diff --git "a/5373.jsonl" "b/5373.jsonl" new file mode 100644--- /dev/null +++ "b/5373.jsonl" @@ -0,0 +1,641 @@ +{"seq_id":"298776410","text":"\"\"\"\nA module implementing utilities for working with different filesystems\n\nCredits:\nCopyright (c) 2017-2020 Matej Aleksandrov, Matej Batič, Grega Milčinski, Matic Lubej, Devis Peresutti (Sinergise)\nCopyright (c) 2017-2020 Nejc Vesel, Jovan Višnjić, Anže Zupanc (Sinergise)\n\nThis source code is licensed under the MIT license found in the LICENSE\nfile in the root directory of this source tree.\n\"\"\"\nimport fs\nfrom fs_s3fs import S3FS\n\nfrom sentinelhub import SHConfig\n\n\ndef get_filesystem(path, create=False, **kwargs):\n \"\"\" A utility function for initializing any type of filesystem object with PyFilesystem2 package\n\n :param path: A filesystem path\n :type path: str\n :param create: If the filesystem path doesn't exist this flag indicates to either create it or raise an error\n :type create: bool\n :param kwargs: Any keyword arguments to be passed forward\n :return: A filesystem object\n :rtype: fs.FS\n \"\"\"\n if path.startswith('s3://'):\n return load_s3_filesystem(path, *kwargs)\n\n return fs.open_fs(path, create=create, **kwargs)\n\n\ndef load_s3_filesystem(path, strict=False, config=None):\n \"\"\" Loads AWS s3 filesystem from a path\n\n :param path: A path to a folder on s3 bucket that will be the base folder in this filesystem\n :type path: str\n :param strict: If `True` the filesystem will be making additional checks to the s3. Default is `False`.\n :type strict: bool\n :param config: A configuration object with AWS credentials. By default is set to None and in this case the default\n configuration will be taken.\n :type config: SHConfig or None\n :return: A S3 filesystem object\n :rtype: fs_s3fs.S3FS\n \"\"\"\n if not path.startswith('s3://'):\n raise ValueError(\"AWS path has to start with s3:// but found '{}'\".format(path))\n\n if config is None:\n config = SHConfig()\n\n path_chunks = path.split('/', 3)[2:]\n bucket_name = path_chunks[0]\n dir_path = path_chunks[1] if len(path_chunks) > 1 else '/'\n\n return S3FS(\n bucket_name=bucket_name,\n dir_path=dir_path,\n aws_access_key_id=config.aws_access_key_id if config.aws_access_key_id else None,\n aws_secret_access_key=config.aws_secret_access_key if config.aws_secret_access_key else None,\n strict=strict\n )\n","sub_path":"core/eolearn/core/fs_utils.py","file_name":"fs_utils.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"356091356","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, TimestampType, DoubleType\n\n# Initializing SparkSession\nspark = SparkSession.builder.appName(\"DataIngestionAndRefine\").master(\"local[*]\").getOrCreate()\n\n# Reading from landing Zone\n\nlandingFileSchema = StructType([\n StructField('Sale_ID', StringType(), True),\n StructField('Product_ID', StringType(), True),\n StructField('Quantity_Sold', IntegerType(), True),\n StructField('Vendor_ID', StringType(), True),\n StructField('Sale_Date', TimestampType(), True),\n StructField('Sale_Amount', DoubleType(), True),\n StructField('Sale_Currency', StringType(), True)\n])\n\nlandingFileDF = spark.read.schema(landingFileSchema)\\\n .option(\"delimiter\", \"|\")\\\n .csv(\"C:\\\\Users\\\\Jaya\\\\PycharmProjects\\\\GKC_StoresPipeline\\\\Data\\\\Inputs\\\\Sales_Landing\\\\SalesDump_04062020\")\n\nlandingFileDF.show()\n","sub_path":"src/main/python/Creating Schema.py","file_name":"Creating Schema.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"390276072","text":"from ftw.upgrade import UpgradeStep\nfrom ftw.upgrade.placefulworkflow import PlacefulWorkflowPolicyActivator\nfrom plone import api\n\n\nclass ActivatePlacefulWorkflowForPrivateArea(UpgradeStep):\n \"\"\"Activate placeful workflow for private area.\n \"\"\"\n\n def __call__(self):\n portal = api.portal.get()\n private_root = portal.unrestrictedTraverse('private', None)\n if private_root is None:\n return\n\n activator = PlacefulWorkflowPolicyActivator(private_root)\n activator.activate_policy(\n 'opengever_private_policy',\n review_state_mapping={\n ('opengever_document_workflow', 'opengever_private_document_workflow'): {\n 'document-state-draft': 'document-state-draft',\n 'document-state-shadow': 'document-state-shadow'},\n ('opengever_mail_workflow', 'opengever_private_mail_workflow'): {\n 'mail-state-active': 'mail-state-active'}})\n","sub_path":"opengever/core/upgrades/20180131124231_activate_placeful_workflow_for_private_area/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"40285230","text":"import robin_stocks.robinhood as r\nimport pandas as pd\nimport numpy as np\nimport ta as ta\nfrom pandas.plotting import register_matplotlib_converters\nfrom ta import *\nfrom misc import *\nfrom tradingstats import *\nfrom config import *\n\n# Log in to Robinhood\n# Put your username and password in a config.py file in the same directory (see sample file)\nlogin = r.login(rh_username,rh_password)\n\n# Safe divide by zero division function\ndef safe_division(n, d):\n return n / d if d else 0\n\ndef get_historicals(ticker, intervalArg, spanArg, boundsArg):\n # If it's a ticker in this program, then it must be a crypto ticker\n history = r.get_crypto_historicals(ticker,interval=intervalArg,span=spanArg,bounds=boundsArg)\n return history\n\ndef get_watchlist_symbols():\n \"\"\"\n Returns: the symbol for each stock in your watchlist as a list of strings\n \"\"\"\n my_list_names = set()\n symbols = set()\n\n watchlistInfo = r.get_all_watchlists()\n for watchlist in watchlistInfo['results']:\n listName = watchlist['display_name']\n my_list_names.add(listName)\n\n for listName in my_list_names:\n watchlist = r.get_watchlist_by_name(name=listName)\n for item in watchlist['results']:\n symbol = item['symbol']\n symbols.add(symbol)\n\n return symbols\n\ndef get_portfolio_symbols():\n \"\"\"\n Returns: the symbol for each stock in your portfolio as a list of strings\n \"\"\"\n symbols = []\n holdings_data = r.get_open_stock_positions()\n for item in holdings_data:\n if not item:\n continue\n instrument_data = r.get_instrument_by_url(item.get('instrument'))\n symbol = instrument_data['symbol']\n symbols.append(symbol)\n return symbols\n\ndef get_position_creation_date(symbol, holdings_data):\n \"\"\"Returns the time at which we bought a certain stock in our portfolio\n\n Args:\n symbol(str): Symbol of the stock that we are trying to figure out when it was bought\n holdings_data(dict): dict returned by r.get_open_stock_positions()\n\n Returns:\n A string containing the date and time the stock was bought, or \"Not found\" otherwise\n \"\"\"\n instrument = r.get_instruments_by_symbols(symbol)\n url = instrument[0].get('url')\n for dict in holdings_data:\n if(dict.get('instrument') == url):\n return dict.get('created_at')\n return \"Not found\"\n\ndef get_modified_holdings():\n \"\"\" Retrieves the same dictionary as r.build_holdings, but includes data about\n when the stock was purchased, which is useful for the read_trade_history() method\n in tradingstats.py\n\n Returns:\n the same dict from r.build_holdings, but with an extra key-value pair for each\n position you have, which is 'bought_at': (the time the stock was purchased)\n \"\"\"\n holdings = r.build_holdings()\n holdings_data = r.get_open_stock_positions()\n for symbol, dict in holdings.items():\n bought_at = get_position_creation_date(symbol, holdings_data)\n bought_at = str(pd.to_datetime(bought_at))\n holdings[symbol].update({'bought_at': bought_at})\n return holdings\n\ndef sell_holdings(symbol, holdings_data):\n \"\"\" Place an order to sell all holdings of a stock.\n\n Args:\n symbol(str): Symbol of the stock we want to sell\n holdings_data(dict): dict obtained from get_modified_holdings() method\n \"\"\"\n shares_owned = int(float(holdings_data[symbol].get(\"quantity\")))\n if not debug:\n r.order_sell_market(symbol, shares_owned)\n print(\"####### Selling \" + str(shares_owned) + \" shares of \" + symbol + \" #######\")\n\ndef buy_holdings(potential_buys, profile_data, holdings_data):\n \"\"\" Places orders to buy holdings of stocks. This method will try to order\n an appropriate amount of shares such that your holdings of the stock will\n roughly match the average for the rest of your portfoilio. If the share\n price is too high considering the rest of your holdings and the amount of\n buying power in your account, it will not order any shares.\n\n Args:\n potential_buys(list): List of strings, the strings are the symbols of stocks we want to buy\n symbol(str): Symbol of the stock we want to sell\n holdings_data(dict): dict obtained from r.build_holdings() or get_modified_holdings() method\n \"\"\"\n cash = float(profile_data.get('cash'))\n portfolio_value = float(profile_data.get('equity')) - cash\n ideal_position_size = (safe_division(portfolio_value, len(holdings_data))+cash/len(potential_buys))/(2 * len(potential_buys))\n prices = r.get_latest_price(potential_buys)\n for i in range(0, len(potential_buys)):\n stock_price = float(prices[i])\n if(ideal_position_size < stock_price < ideal_position_size*1.5):\n num_shares = int(ideal_position_size*1.5/stock_price)\n elif (stock_price < ideal_position_size):\n num_shares = int(ideal_position_size/stock_price)\n else:\n print(\"####### Tried buying shares of \" + potential_buys[i] + \", but not enough buying power to do so#######\")\n break\n print(\"####### Buying \" + str(num_shares) + \" shares of \" + potential_buys[i] + \" #######\")\n if not debug:\n r.order_buy_market(potential_buys[i], num_shares)\n\n\n\ndef scan_stocks():\n if debug:\n print(\"----- DEBUG MODE -----\\n\")\n print(\"----- Starting scan... -----\\n\")\n register_matplotlib_converters()\n watchlist_symbols = get_watchlist_symbols()\n portfolio_symbols = get_portfolio_symbols()\n holdings_data = get_modified_holdings()\n potential_buys = []\n sells = []\n print(\"Current Portfolio: \" + str(portfolio_symbols) + \"\\n\")\n print(\"Current Watchlist: \" + str(watchlist_symbols) + \"\\n\")\n print(\"----- Scanning portfolio for assets to sell -----\\n\")\n # Add your own selling logic here\n\n profile_data = r.build_user_profile()\n print(\"\\n----- Scanning watchlist for assets to buy -----\\n\")\n # Add your own buying logic here\n\n if(len(potential_buys) > 0):\n buy_holdings(potential_buys, profile_data, holdings_data)\n if(len(sells) > 0):\n update_trade_history(sells, holdings_data, \"tradehistory.txt\")\n print(\"----- Scan over -----\\n\")\n if debug:\n print(\"----- DEBUG MODE -----\\n\")\n\n# Execute the scan\n# scan_stocks()\n# get_historicals(\"DOGE\", \"15second\", \"month\", \"24_7\")\n# print(r.get_crypto_historicals(symbol=\"DOGE\",interval=\"15second\",span=\"month\",bounds=\"24_7\"))\n\n\n\n\n\n# Organize cash and DOGE into tiers\n\n# if-statements for buying\n# if tier_buy_price >= actual_price:\n# if cash in tier > 0:\n# limit_buy_order() for amount of cash in tier\n# if-statements for selling\n# if tier_sell_price >= actual_price:\n# if DOGE in tier:\n# imit_sell_order() for amount of DOGE in tier\n\ndef jm_trading_strategy(): # Here is my own trading strategy code --Jonathan McCormick:\n actively_trading = True\n while actively_trading == True:\n\n # Gather price info on DOGE.\n doge_quote = r.get_crypto_quote(\"DOGE\")\n doge_ask_price, doge_bid_price = doge_quote[\"ask_price\"], doge_quote[\"bid_price\"]\n print(\"DOGE ask price:\", doge_ask_price, \"\\nDOGE bid price:\", doge_bid_price)\n\n # Check my USD available for trading.\n my_theoretical_buying_power = r.load_account_profile()[\"buying_power\"]\n savings_amount = 20 # This is off-limits for trading. Value is measured in USD.\n my_usd_to_trade = float(my_theoretical_buying_power) - savings_amount # My real tradable buying power.\n print(\"My USD trading supply: $\", my_usd_to_trade)\n\n # Check my DOGE available for trading.\n my_crypto_positions = r.get_crypto_positions()\n my_doge_to_trade = float(my_crypto_positions[2][\"quantity_available\"])\n print(\"My DOGE trading supply: Ð\", my_doge_to_trade)\n\n # Create tiers.\n num_of_tiers = 100\n tiers = []\n tier_increment_size = 0.01 # Value in USD\n tier_buy_price = 0.01 # The lowest price I expect DOGE to go (for these purposes)\n tier_sell_price = tier_buy_price + tier_increment_size\n\n tier_counter = 0\n\n while num_of_tiers > tier_counter:\n tiers.append(\"Tier \" + str(tier_counter))\n tier_counter += 1\n\n tier_dictionary = {}\n for tier in tiers:\n\n tier_doge_supply = my_doge_to_trade / num_of_tiers\n tier_usd_supply = my_usd_to_trade / num_of_tiers\n\n\n tier_dictionary[tier] = [tier_buy_price, tier_sell_price, tier_doge_supply, tier_usd_supply]\n tier_buy_price += tier_increment_size\n tier_sell_price += tier_increment_size\n\n\n\n\n print(tier_dictionary)\n print(\"DOGE supply per tier: \" + str(tier_doge_supply) + \"\\nUSD supply per tier:\" + str(tier_usd_supply))\n\n for tier in tier_dictionary:\n\n # Math.\n def doge_buy(amountInDollars, limitPrice):\n r.order_buy_crypto_limit_by_price('DOGE', amountInDollars, limitPrice, timeInForce='gfd', jsonify=True)\n\n def doge_sell(amountInDollars, limitPrice):\n r.order_sell_crypto_limit_by_price('DOGE', amountInDollars, limitPrice, timeInForce='gfd', jsonify=True)\n\n # if seller price is less than your buying price, then place a limit buy order for 1 DOGE\n if doge_ask_price <= tier[0]:\n amount_of_doge_to_buy = 1 / float(tier[0])\n print(amount_of_doge_to_buy)\n #doge_buy(tier_dictionary[tier_usd_supply], tier_buy_price)\n\n # if buyer price is more than your selling price, then place a limit sell order for 1 DOGE\n \"\"\"if doge_bid_price > tier[1]:\n\n doge_sell(doge, ___)\"\"\"\n # Assign USD to tiers.\n #usd_per_tier = my_usd_to_trade / num_of_tiers\n\n # Assign DOGE to tiers.\n\n # Execute orders\n \n \"\"\"\n Consider whether or not to have some sort of emergency stop switch which will trigger if the net account value falls x% within x amount of time.\n You can always resume the bot manually. \n \"\"\"\n\n # Record data\n if(len(sells) > 0):\n update_trade_history(sells, holdings_data, \"tradehistory.txt\")\n\n return \"Exited trading for now.\"\njm_trading_strategy()\n# This is a comment\n","sub_path":"robinhoodbot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"560808404","text":"def solution(n):\n arr = []\n result = 0\n while 0 < n:\n n, mod = divmod(n, 3)\n arr.append(mod)\n \n num = 1\n \n for i in range(len(arr)-1, -1, -1):\n result += arr[i] * num\n num *= 3\n return result","sub_path":"3진법 뒤집기.py","file_name":"3진법 뒤집기.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"447334449","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nfrom biokbase.workspace.client import Workspace as _Workspace\nimport time as _time\nfrom collections import defaultdict as _defaultdict\n\n# Q&D method to summarize KBase reference data workspaces.\n# CSV of object id, name, md5 for assemblies. Last version only.\n\n#_URL = 'https://ci.kbase.us/services/ws'\n_URL = 'https://kbase.us/services/ws'\n#_REF_WS = 15792\n_REF_WS = 19217\n_TYPE = 'KBaseGenomeAnnotations.Assembly'\n_OUT_FILE = 'output.csv'\n\ndef main():\n ws = _Workspace(_URL)\n wsinfo = ws.get_workspace_info({'id': _REF_WS})\n ws_size = wsinfo[4]\n print('Processing workspace {} ({}) with {} objects'.format(wsinfo[1], _REF_WS, ws_size))\n print()\n types = _defaultdict(int)\n with open(_OUT_FILE, 'w') as output:\n for i in xrange(0, ws_size, 10000):\n print('Processing objects from {} to {}'.format(i, i + 9999))\n start = _time.time()\n objs = ws.list_objects({'ids': [_REF_WS], 'minObjectID': i, 'maxObjectID': i + 9999})\n end = _time.time()\n print('Got {} objects back in {} sec'.format(len(objs), end - start))\n for o in objs:\n type = o[2]\n types[type] += 1\n ref = str(o[6]) + '/' + str(o[0]) + '/' + str(o[4])\n if type.split('-')[0] != _TYPE:\n print('Skipping {}, {}'.format(ref, type))\n else:\n md5 = o[8]\n name = o[1]\n output.write('{} {} {} {}\\n'.format(ref, name, md5, type))\n print()\n print('Saw types:')\n for type, count in types.items():\n print('{} {}'.format(type, count))\n\nif __name__ == \"__main__\":\n main()","sub_path":"summarize_ref_assemblies.py","file_name":"summarize_ref_assemblies.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"474245689","text":"from keras.layers import Dense, SeparableConv1D, LSTM\nfrom keras.layers import GlobalMaxPooling1D, Masking\nfrom keras.layers import Lambda, Subtract, Concatenate, Reshape\n\nimport keras.backend as K\n\n\ndef dnn_build(embed_input1, embed_input2, embed_input3):\n mean = Lambda(lambda a: K.mean(a, axis=1), name='mean')\n da1 = Dense(200, activation='relu', name='encode1')\n da2 = Dense(200, activation='relu', name='encode2')\n norm = Lambda(lambda a: K.sqrt(K.sum(K.square(a), axis=-1)))\n x = mean(embed_input1)\n x = da1(x)\n x = da2(x)\n y = mean(embed_input2)\n y = da1(y)\n y = da2(y)\n z = mean(embed_input3)\n z = da1(z)\n z = da2(z)\n pos = norm(Subtract()([x, y]))\n neg = norm(Subtract()([x, z]))\n delta = Subtract()([neg, pos])\n return Reshape((1,))(delta)\n\n\ndef dnn_cache(embed_input):\n mean = Lambda(lambda a: K.mean(a, axis=1), name='mean')\n da1 = Dense(200, activation='relu', name='encode1')\n da2 = Dense(200, activation='relu', name='encode2')\n x = mean(embed_input)\n x = da1(x)\n return da2(x)\n\n\ndef cnn_build(embed_input1, embed_input2, embed_input3):\n ca1 = SeparableConv1D(filters=64, kernel_size=1, padding='same', activation='relu', name='conv1')\n ca2 = SeparableConv1D(filters=64, kernel_size=2, padding='same', activation='relu', name='conv2')\n ca3 = SeparableConv1D(filters=64, kernel_size=3, padding='same', activation='relu', name='conv3')\n mp = GlobalMaxPooling1D()\n concat = Concatenate()\n da = Dense(200, activation='relu', name='encode')\n norm = Lambda(lambda a: K.sqrt(K.sum(K.square(a), axis=-1)))\n x1 = ca1(embed_input1)\n x1 = mp(x1)\n x2 = ca2(embed_input1)\n x2 = mp(x2)\n x3 = ca3(embed_input1)\n x3 = mp(x3)\n x = concat([x1, x2, x3])\n x = da(x)\n y1 = ca1(embed_input2)\n y1 = mp(y1)\n y2 = ca2(embed_input2)\n y2 = mp(y2)\n y3 = ca3(embed_input2)\n y3 = mp(y3)\n y = concat([y1, y2, y3])\n y = da(y)\n z1 = ca1(embed_input3)\n z1 = mp(z1)\n z2 = ca2(embed_input3)\n z2 = mp(z2)\n z3 = ca3(embed_input3)\n z3 = mp(z3)\n z = concat([z1, z2, z3])\n z = da(z)\n pos = norm(Subtract()([x, y]))\n neg = norm(Subtract()([x, z]))\n delta = Subtract()([neg, pos])\n return Reshape((1,))(delta)\n\n\ndef cnn_cache(embed_input):\n ca1 = SeparableConv1D(filters=64, kernel_size=1, padding='same', activation='relu', name='conv1')\n ca2 = SeparableConv1D(filters=64, kernel_size=2, padding='same', activation='relu', name='conv2')\n ca3 = SeparableConv1D(filters=64, kernel_size=3, padding='same', activation='relu', name='conv3')\n mp = GlobalMaxPooling1D()\n da = Dense(200, activation='relu', name='encode')\n x1 = ca1(embed_input)\n x1 = mp(x1)\n x2 = ca2(embed_input)\n x2 = mp(x2)\n x3 = ca3(embed_input)\n x3 = mp(x3)\n x = Concatenate()([x1, x2, x3])\n return da(x)\n\n\ndef rnn_build(embed_input1, embed_input2, embed_input3):\n mask = Masking()\n ra = LSTM(200, activation='tanh', name='encode')\n norm = Lambda(lambda a: K.sqrt(K.sum(K.square(a), axis=-1)))\n x = mask(embed_input1)\n x = ra(x)\n y = mask(embed_input2)\n y = ra(y)\n z = mask(embed_input3)\n z = ra(z)\n pos = norm(Subtract()([x, y]))\n neg = norm(Subtract()([x, z]))\n delta = Subtract()([neg, pos])\n return Reshape((1,))(delta)\n\n\ndef rnn_cache(embed_input):\n ra = LSTM(200, activation='tanh', name='encode')\n x = Masking()(embed_input)\n return ra(x)\n","sub_path":"nn_arch.py","file_name":"nn_arch.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"293334084","text":"tree1 = [1,2,3,4,5,6,7,8,9,10,11,20,50,561,651,53165]\r\n\r\ndef binary_search_recursive(tree, key):\r\n\treturn bsr(tree,key,0,len(tree))\r\n\t\t\r\ndef bsr(a, key, left, right):\r\n\tif left>right:return None\r\n\tmid = (left + right) // 2\r\n\te = a[mid]\r\n\tif e == key: return mid\r\n\tif e > key: return bsr(a,key,left,mid)\r\n\telse: return bsr(a,key,mid,right)\r\n\r\nprint(binary_search_recursive(tree1,10))","sub_path":"binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"547177416","text":"from IPython.display import clear_output\nfrom keras.callbacks import Callback\nclass PlotLearning(Callback):\n\n def on_train_begin(self, logs={}):\n self.i = 0\n self.x = []\n self.loss = []\n self.val_loss = []\n self.acc = []\n self.val_acc = []\n self.fig = plt.figure()\n \n self.logs = []\n\n def on_epoch_end(self, epoch, logs={}):\n \n self.logs.append(logs)\n self.x.append(self.i)\n self.loss.append(logs.get('loss'))\n self.acc.append(logs.get('dice_coef'))\n \n self.val_loss.append(logs.get('val_loss')) \n self.val_acc.append(logs.get('val_dice_coef'))\n \n self.i += 1\n f, ax = plt.subplots(1, 2, figsize=(12,4), sharex=True)\n ax = ax.flatten()\n clear_output(wait=True)\n \n ax[0].plot(self.x, self.loss, label=\"loss\", lw=2)\n ax[0].plot(self.x, self.val_loss, label=\"val loss\")\n #ax[0].set_ylim(bottom=0.)\n ax[0].legend()\n ax[0].grid(True)\n \n ax[1].plot(self.x, self.acc, label=\"Dice coef\", lw=2)\n ax[1].plot(self.x, self.val_acc, label=\"val Dice coef\")\n #ax[1].set_ylim(bottom=0.)\n ax[1].legend()\n ax[1].grid(True)\n \n plt.show();\n \nplotLoss = PlotLearning()","sub_path":"PlotLearningModels.py","file_name":"PlotLearningModels.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"250851122","text":"import glob,os,ntpath\r\nwith open('classes.txt') as cl:\r\n classes = cl.read().splitlines()\r\n for cc in classes:\r\n read_files = glob.glob(\"Location\"+\"*.txt\")\r\n for f in read_files:\r\n path=ntpath.basename(f)\r\n head,tail=ntpath.split(path)\r\n print(tail)\r\n with open(f, \"r\") as infile:\r\n with open(\"Location\"+cc+'/'+tail, \"w\") as outfile:\r\n for line in infile:\r\n line=line.replace('.',\"\")\r\n print(line)\r\n outfile.write(line)","sub_path":"scripts/remove_dots_from_files.py","file_name":"remove_dots_from_files.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"228578574","text":"\n\nfrom xai.brain.wordbase.nouns._viol import _VIOL\n\n#calss header\nclass _VIOLS(_VIOL, ):\n\tdef __init__(self,): \n\t\t_VIOL.__init__(self)\n\t\tself.name = \"VIOLS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"viol\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_viols.py","file_name":"_viols.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"481729006","text":"\"\"\"\nWhen building classes and inheritances, the time will come where you will have to mix all the @staticmethod, @classmethod and @abc.abstractmethod decorators. the following are tips when you need to mix them.\n\"\"\"\n\n\"\"\"\nabstract methods can be implemented in many ways\n\nKeep in mind that declaring a method as being abstract, doesn't freeze the prototype of that method.\n\nThat means that the abstract method must be implemented, but it can be implemented with any argument list, or implemented as being a class or a static method,\n\"\"\"\n\n\"\"\"\n@abc.abstractmethod\n\"\"\"\n\nimport abc\n\n\nclass BasePizza(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def get_radius(self):\n \"\"\"Method that should do something.\"\"\"\n\n\nBasePizza() # TypeError: Can't instantiate abstract class BasePizza with abstract methods get_radius\n\n\"\"\"\nCalzone class is valid, since Calzone fulfills the interface requirement we defined for BasePizza objects.\n\nDietPizza class is also correct and fulfills the contract we have with our abstract BasePizza class. The fact that the get_ingredients method doesn't need to know about the object to return result is an implementation detail, not a criteria to have our contract fulfilled. Therefore, you can't force an implementation of your abstract method to be a regular, class or static method, and arguably you shouldn't.\n\"\"\"\n","sub_path":"src/language_ref/class/method/abstract/abstract_method_2_mixed_1.py","file_name":"abstract_method_2_mixed_1.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"123434605","text":"import os\nimport os.path as osp\nimport re\nimport datetime\nimport argparse\n\nimport xml.etree.ElementTree as ET\nimport tifffile as tif\nimport yaml\n\n\ndef read_ome_meta(path: str):\n with open(path, 'r') as s:\n gathered_meta = yaml.safe_load(stream=s)\n\n return gathered_meta\n\n\ndef read_slicer_meta(slicer_meta: dict):\n\n acq_meta = {\"region_width\": slicer_meta['nblocks']['x'],\n \"region_height\": slicer_meta['nblocks']['y'],\n \"tile_width\": slicer_meta['block_shape_no_overlap']['x'],\n \"tile_height\": slicer_meta['block_shape_no_overlap']['y'],\n \"tile_overlap_x\": slicer_meta['overlap']['x'],\n \"tile_overlap_y\": slicer_meta['overlap']['y'],\n \"tiling_mode\": slicer_meta['tiling_mode']\n }\n return acq_meta\n\n\ndef generate_processor_meta(acquisition_meta: dict, submission: dict):\n\n num_z_planes = acquisition_meta['num_z_planes']\n ngpus = submission['ngpus']\n best_focus_channel = submission['best_focus_channel']\n drift_compensation_channel = submission['drift_compensation_channel']\n nuclei_channel = submission['nuclei_channel']\n\n if drift_compensation_channel is not None:\n run_drift_comp = True\n drift_compensation = {'drift_compensation': {'channel': drift_compensation_channel}}\n else:\n run_drift_comp = False\n drift_compensation = {}\n if num_z_planes > 1:\n run_best_focus = True\n best_focus = {'best_focus': {'channel': best_focus_channel}}\n z_plane = 'best'\n else:\n run_best_focus = False\n best_focus = {}\n z_plane = 'all'\n\n gpus = list(range(0, ngpus))\n\n processor_meta = {\n \"processor\": {\n \"args\": {\n \"gpus\": gpus,\n \"run_crop\": False,\n \"run_tile_generator\": True,\n \"run_drift_comp\": run_drift_comp,\n \"run_cytometry\": True,\n \"run_best_focus\": run_best_focus\n },\n \"deconvolution\": {\"n_inter\": 25, \"scale_factor\": 0.5},\n \"tile_generator\": {\"raw_file_type\": \"keyence_mixed\"}\n }\n }\n processor_meta['processor'].update(best_focus)\n processor_meta['processor'].update(drift_compensation)\n\n cytometry = {\n \"cytometry\": {\n \"z_plane\": z_plane,\n \"target_shape\": [acquisition_meta[\"tile_width\"] + acquisition_meta[\"tile_overlap_x\"],\n acquisition_meta[\"tile_height\"] + acquisition_meta[\"tile_overlap_y\"]],\n \"nuclei_channel_name\": nuclei_channel,\n \"segmentation_params\": {\"memb_min_dist\": 8, \"memb_sigma\": 5, \"memb_gamma\": 0.25, \"marker_dilation\": 3},\n \"quantification_params\": {\"nucleus_intensity\": True, \"cell_graph\": True}\n }\n }\n processor_meta['processor'].update(cytometry)\n return processor_meta\n\n\ndef main(collected_meta_path: str, cytokit_config_path: str):\n\n with open(collected_meta_path, 'r') as s:\n collected_meta = yaml.safe_load(s)\n\n slicer_meta = read_slicer_meta(collected_meta['slicer_meta'])\n ome_meta = collected_meta['ome_meta']\n\n # same as acquisition_meta but without key - acquisition\n acq_meta = dict()\n acq_meta.update(slicer_meta)\n acq_meta.update(ome_meta)\n\n submission = collected_meta['submission']\n\n head_meta = {\"name\": submission['experiment_name'],\n \"date\": str(datetime.datetime.now()),\n \"environemnt\": {\"path_formats\": \"keyence_multi_cycle_v01\"}}\n\n processor_meta = generate_processor_meta(acq_meta, submission)\n acquisition_meta = {'acquisition': acq_meta}\n\n cytokit_config = dict()\n cytokit_config.update(head_meta)\n cytokit_config.update(acquisition_meta)\n cytokit_config.update(processor_meta)\n\n with open(cytokit_config_path, 'w') as s:\n yaml.safe_dump(cytokit_config, stream=s, default_flow_style=False, indent=4, sort_keys=False)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--collected_meta_path', type=str, help='path to collected metadata')\n parser.add_argument('--cytokit_config_path', type=str, help='path to output cytokit config file')\n\n args = parser.parse_args()\n\n main(args.collected_meta_path, args.cytokit_config_path)\n","sub_path":"bin/generate_cytokit_config.py","file_name":"generate_cytokit_config.py","file_ext":"py","file_size_in_byte":4337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"290095264","text":"import yaml\nfrom os import remove\nfrom os.path import isfile\nfrom datetime import datetime\nfrom utils.shell_io import byte_style\n\ndef _wait(lfile):\n if isfile(lfile):\n msg = 'Wait for '\n msg += byte_style(f\"'{lfile}'\", '3')\n msg += '\\n (Locked at '\n with open(lfile) as fr:\n for line in fr:\n msg += line.split('.')[0]\n msg += ') Unlock? [Y or any key to exit] '\n if input(msg) != 'Y':\n # print('\\nexited')\n exit()\n remove(lfile)\n\ndef _block(lfile):\n with open(lfile, 'w') as fw:\n fw.write(str(datetime.now()))\n\ndef _unblock(lfile):\n if isfile(lfile):\n remove(lfile)\n return True\n return False\n\ndef save_yaml(status, mfile, lfile, wait_lock = True):\n if lfile:\n if wait_lock:\n _wait(lfile)\n _block(lfile)\n\n finished = False\n do_exit = None\n while not finished:\n try:\n with open(mfile, 'w') as fw:\n fw.write(f'# {datetime.now()}\\n')\n yaml.dump(status, fw, default_flow_style = False)\n finished = True\n except KeyboardInterrupt as e:\n do_exit = e\n print('suppress', e, 'for saving', mfile)\n # release\n if wait_lock:\n _unblock(lfile)\n if do_exit is not None:\n raise do_exit\n else:\n with open(mfile, 'a+') as fw:\n fw.write(f'# {datetime.now()}\\n')\n yaml.dump(status, fw, default_flow_style = False)\n return True\n\ndef load_yaml(mfile, lfile, block = False, wait_lock = True):\n if isfile(mfile):\n if wait_lock:\n _wait(lfile)\n if block:\n _block(lfile)\n else:\n save_yaml({}, mfile, lfile)\n with open(mfile, 'r') as fr:\n status = yaml.load(fr, Loader = yaml.FullLoader)\n if not status:\n status = {}\n if wait_lock and block:\n return status, lambda : _unblock(lfile)\n return status","sub_path":"utils/yaml_io.py","file_name":"yaml_io.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"509048256","text":"#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport scipy\nfrom data_handler import gen_graphs\nfrom pte_theano import PTE\nimport logging\n\n\nclass train_pte(object):\n\n '''\n class to train the pte model on the given corpus.\n '''\n\n def __init__(self):\n '''\n define model paramters.\n '''\n self.graphs = gen_graphs()\n self.graphs.contruct_graphs(\"graph\")\n # Generate nnz matrices with data (i, j, w)\n self.nnz_ww = []\n self.nnz_wd = []\n self.nnz_wl = []\n self.ndims = 40\n self.lr = 0.05\n self.batch_size = 100\n self.window_size = 10\n self.k = 5\n self.nepochs = 1\n\n def train(self):\n '''\n run training (first pre-training and than fine tuning on graph with\n parameters defined in constructor.\n '''\n # setting up logger\n logger = logging.getLogger(\"graph2vec\")\n logger.setLevel(logging.INFO)\n logger.setLevel(logging.DEBUG)\n fh = logging.FileHandler(\"word2graph2vec.log\")\n formatter = logging.Formatter('%(asctime)s %(message)s')\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n p, v1, v2 = self.graphs.gen_edgeprob()\n logger.info(\"Setting up the model\")\n E = self.graphs.nedge\n V = self.graphs.nvertex\n D = self.graphs.ndocs\n L = self.graphs.nlabels\n d = len(self.graphs.w2d)\n l = len(self.graphs.w2l)\n pte = PTE(V, self.ndims, self.graphs.ndocs, self.graphs.nlabels)\n pte.ww_model()\n pte.wd_model()\n pte.wl_model()\n logger.info(\"Training started\")\n for epoch in xrange(0, self.nepochs):\n # Pre-training\n np.random.shuffle(p)\n c = 0\n try:\n # Pre-training on word 2 word model.\n for i in xrange(0, E, self.batch_size):\n sample = np.random.choice(p.shape[0], self.batch_size, p=p)\n c = 0\n for j in xrange(0, sample.shape[0]):\n indm = v1[sample[j]]\n indc = v2[sample[j]]\n indr = np.asarray(\n np.random.randint(V, size=self.k), dtype=np.int32)\n cost = pte.pretraining_ww(indm, indc, indr)\n c += cost\n logger.info(\"Cost after training one sample (batch) is %f\" % c)\n # Pre-training on word-doc graph\n logger.info(\"Pre-training on word-word graph done\")\n #for i in xrange(0, d):\n # indw = nnz_wd[i, 0]\n # indd = nnz_wd[i, 1]\n # indr = np.asarray(\n # np.random.randint(V, size=self.k), dtype=np.int32)\n # if i % 5000 == 0:\n # logger.info(\"cost is %f\" % c)\n # c = 0\n # cost = pte.pretraining_wd(indw, indd, indr, nnz_wd[i, 2])\n # c += cost\n # Fine-tuning on word-label graph\n #logger.info(\"Pre-training on word-doc done\")\n #for i in xrange(0, l):\n # indw = nnz_wl[i, 0]\n # indl = nnz_wl[i, 1]\n # indr = np.asarray(\n # np.random.randint(V, size=self.k), dtype=np.int32)\n # if i % 5000 == 0:\n # logger.info(\"cost is %f\" % c)\n # c = 0\n # cost = pte.finetuning(indw, indl, indr, nnz_wl[i, 2])\n # c += cost\n except Exception as e:\n logger.exception(\"Following exception occured %s\" % e)\n logger.info(\"Pre-training on word-label done\")\n logger.info(\"training done, saving model\")\n pte.save_model()\n\nif __name__ == \"__main__\":\n pte = train_pte()\n pte.train()\n","sub_path":"word2graph2vec/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"140662925","text":"# Wykonaj wykres funkcji:\n# • f(x) = x/(-3) + a dla x <= 0,\n# • f(x) = x*x/3 dla x >= 0,\n# • gdzie x = <-10;10> z krokiem 0.5.\n\nimport matplotlib.pyplot as plt\nimport pylab as p\n\na = int(input(\"Podaj a: \"))\nx = y = 0\nlx = [0]\nly = [0]\nr = 1\nfor i in range(0, a):\n rad = float(p.randint(0, 360)) * p.pi / 180\n x = x + r * p.cos(rad)\n y = y + r * p.sin(rad)\n\n lx.append(x)\n ly.append(y)\nplt.plot(lx, ly, \"o:\", color=\"green\", linewidth=2, alpha=0.5)\nplt.plot([0, x], [0, y], color=\"blue\")\n\ns = p.fabs(p.sqrt(x**2 + y**2))\nprint(\"Wektor przesunięcia:\", s)\n\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Wykres\")\nplt.legend([\"Dane x, y\\nPrzemieszczenie: \" + str(s)], loc=\"upper left\")\n\nplt.grid(True)\nplt.show()\n\ninput(\"\\n\\nAby zakończyć wciśnij Enter\")\n","sub_path":"zaj3/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"215481784","text":"from photoInfo import *\nfrom flickrapi import FlickrAPI\nfrom pprint import pprint\nimport urllib.request\nimport os\n\nclass PhotoAdmin:\n\tdef __init__(self):\n\t\tself._photosInfo = []\n\t\tself._photoPaths = []\n\t\tself._photoNumber= 0\n\n\t#Saves all images.\n\tdef saveImages(self):\n\n\t\tfor photo in self._photosInfo:\n\n\t\t\tpath = \"./imgs/img{n}.jpg\".format(n=self._photoNumber)\n\n\t\t\turllib.request.urlretrieve(photo.getUrl(), path)\n\n\t\t\tself._photoNumber += 1\n\n\t\t\tself._photoPaths.append(path)\n\n\t#Erases file in given path.\n\tdef erasePhoto(self,path):\n\t\tos.remove(path)\n\n\n\t#Connects with Flickr API,gets n number of random photos and saves id and url from each photo.\n\t# 0 < n =< 500\n\tdef getPhotosFromFlickr(self, amount):\n\t\t#Setting keys\n\t\tFLICKR_PUBLIC = '066a9fcaede67bc720f66f75ed20a970'\n\t\tFLICKR_SECRET = 'e95c436ea4863f6c'\n\n\t\t#Connecting to flickrAPI\n\t\tflickr = FlickrAPI(FLICKR_PUBLIC, FLICKR_SECRET, format='parsed-json')\n\t\textras='url_c, url_sq, url_t, url_s, url_q, url_n, url_z, url_l'\n\n\t\t#Searching random photos.\n\t\trandomPhotos = flickr.photos.getRecent(per_page=amount,extras=extras)\n\t\tphotos = randomPhotos['photos']\n\t\tphotos= photos['photo'] \n\n\t\t#Handling data and saving data.\n\t\tfor photo in photos:\n\n\t\t\tid = photo[u'id']\n\t\t\turl= self.getUrlFromPhoto(photo)\n\n\t\t\t\n\t\t\tphotoInfo = PhotoInfo(id,url)\n\n\t\t\tself._photosInfo.append(photoInfo)\n\n\t#Gets url from photo and returns it. \n\tdef getUrlFromPhoto(self,photo):\n\n\t\textras = ['url_c', 'url_sq', 'url_t', 'url_s', 'url_q', 'url_n', 'url_z', 'url_l']\n\n\t\tfor i in extras:\n\t\t\tif(i in photo):\n\t\t\t\tprint(i)\n\t\t\t\turl=photo[i]\n\t\t\t\tbreak\n\n\t\treturn(url)\n\n\tdef getPhotosInfo(self):\n\t\treturn self._photosInfo\n\n\tdef getPaths(self):\n\t\treturn self._photoPaths\n\n","sub_path":"PhotoAdmin.py","file_name":"PhotoAdmin.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"136032716","text":"class Solution(object):\n def subsetsWithDup(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n if not nums:\n return []\n else:\n nums.sort()\n result = [[]]\n self.subsetRecur(nums, 0, [], result)\n return result\n \n def subsetRecur(self, List, pos, path, result):\n for i in range(pos, len(List)):\n if i == pos:\n result.append(path + [List[i]])\n elif List[i] == List[i - 1]:\n continue\n else:\n result.append(path + [List[i]])\n self.subsetRecur(List, i + 1, path + [List[i]], result)","sub_path":"LeetCode/Subsets_II.py","file_name":"Subsets_II.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"163034778","text":"from base import PrefixPlugin\n\nimport pandas as pd\nimport matplotlib\n\nmatplotlib.use('Agg')\n\nclass RouteStatistics(PrefixPlugin):\n \"\"\"\n Name:\n RouteStatistics\n Author:\n David Barroso \n Description:\n Keeps historical data of which prefixes are added, kept, removed, etc. on every run. The data is\n saved in the backend with the following format::\n\n Time,Total,Kept,Added,Removed,Expired\n\n In addition it will generate a graph for better visualization.\n Requires:\n - prev_pt\n - new_pt\n - time\n Configuration:\n - db_table: Where to store/retrieve the data in the backend\n - png_file: Where to save the graph\n - plot_days: Days to plot\n Example:\n Configuration example::\n\n RouteStatistics:\n db_table: 'route_statistics'\n png_file: '/Users/dbarroso/Documents/workspace/pmacct_data/route_statistics.png'\n plot_days: 2\n\n You can adapt the backend database to use this plugin by using the sql script provided in the folder\n *'/sql/plugins/route_statistics.sql'*\n \"\"\"\n\n skip_simulation = False\n run_once_during_simulations = False\n\n def process_data(self):\n data = dict()\n data['time'] = self.time.strftime('%Y-%m-%d %H:%M:%S')\n data['total'] = len(self.new_pt)\n data['kept'] = len(self.new_pt.common_prefixes(self.prev_pt))\n data['removed'] = len(self.prev_pt.missing_prefixes(self.new_pt)) - self.new_pt.expired_prefixes\n data['added'] = len(self.new_pt.missing_prefixes(self.prev_pt))\n\n self.backend.save_dict(data, self.conf['RouteStatistics']['db_table'])\n\n def plot(self):\n pd.set_option('display.mpl_style', 'default')\n table = self.backend.get_data_from_table(self.conf['RouteStatistics']['db_table'])\n\n raw_data = list()\n\n for row in table[1:]:\n raw_data.append(\n {\n table[0][0]: row[0],\n table[0][1]: row[1],\n table[0][2]: row[2],\n table[0][3]: row[3],\n table[0][4]: row[4],\n }\n )\n time_frame = self.conf['RouteStatistics']['plot_days']*24\n data = pd.DataFrame(raw_data)[-time_frame:]\n plot = data.plot(\n x='time',\n figsize = (9,9),\n grid=True,\n title='Route Statistics, max_routes: %s, history: %s' %\n (self.conf['max_routes'], self.conf['history']),\n legend=True,\n )\n fig = plot.get_figure()\n fig.savefig(self.conf['RouteStatistics']['png_file'])\n\n def run(self):\n self.process_data()\n\n if self.last_run:\n self.plot()\n\n\nclass OffloadedBytes(PrefixPlugin):\n \"\"\"\n Name:\n OffloadedBytes\n Author:\n David Barroso \n Description:\n Keeps historical data of how much data is send and how much is offloaded. We consider that data is\n offloaded when a prefix in raw_pt was present in prev_pt. The data saved on the backend has the\n following format::\n\n Time,Total,Offloaded,%\n\n In addition it will generate a graph for better visualization.\n Requires:\n - raw_pt\n - prev_pt\n - time\n Configuration:\n - db_table: Where to store/retrieve the data in the backend\n - png_file: Where to save the graph\n - plot_days: Days to plot\n Example:\n Configuration example::\n\n OffloadedBytes:\n db_table: 'offloaded_bytes'\n png_file: '/Users/dbarroso/Documents/workspace/pmacct_data/offloaded_bytes.png'\n plot_days: 2\n\n You can adapt the backend database to use this plugin by using the sql script provided in the folder\n *'/sql/plugins/offloaded_bytes.sql'*\n\n \"\"\"\n\n skip_simulation = False\n run_once_during_simulations = False\n\n def plot(self):\n pd.set_option('display.mpl_style', 'default')\n\n table = self.backend.get_data_from_table(self.conf['OffloadedBytes']['db_table'])\n\n raw_data = list()\n\n for row in table[1:]:\n raw_data.append(\n {\n table[0][0]: row[0],\n table[0][1]: row[1],\n table[0][2]: float(row[2]),\n table[0][3]: row[3],\n }\n )\n time_frame = self.conf['OffloadedBytes']['plot_days']*24\n data = pd.DataFrame(raw_data)[-time_frame:]\n\n plot = data.plot(\n x='time',\n secondary_y=['percentage'],\n figsize = (9,9),\n grid=True,\n title='Data Offloaded, max_routes: %s, history: %s' %\n (self.conf['max_routes'], self.conf['history']),\n legend=True,\n )\n fig = plot.get_figure()\n fig.savefig(self.conf['OffloadedBytes']['png_file'])\n\n def process(self):\n data = dict()\n data['time'] = self.time.strftime('%Y-%m-%d %H:%M:%S')\n data['total_bytes'] = self.raw_pt.get_total_bytes()\n data['offloaded'] = sum(p.get_bytes() for p in self.raw_pt if self.prev_pt.prefix_present(p))\n\n data['percentage'] = float(data['offloaded'])*100/float(data['total_bytes'])\n\n self.backend.save_dict(data, self.conf['OffloadedBytes']['db_table'])\n\n def run(self):\n self.process()\n\n if self.last_run:\n self.plot()\n","sub_path":"bgp_controller/plugins/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":5525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"551230559","text":"from django.urls import path\n\nfrom .views import *\n\nurlpatterns = [\n\tpath('website-design-and-development/', website_development_view, name=\"web-development\"),\n\tpath('seo-company-in-punjab/', seo_view, name=\"seo\"),\n\tpath('smo-company-in-punjab/', smo_view, name=\"smo\"),\n\tpath('ppc-company-in-punjab/', ppc_view, name=\"ppc\"),\n\tpath('outdoor-advertising/', outdoor_advertisment_view, name=\"outdoor-advertisment\"),\n\tpath('brand-management/', brand_management_view, name=\"brand\"),\n\tpath('software-development/', software_development_view, name=\"software\"),\n\tpath('android-ios-development/', application_development_view, name=\"application\"),\n\tpath('logo-design/', logo_design_view, name=\"logo\"),\n\tpath('video-editing/', video_editing_view, name=\"video\"),\n]","sub_path":"services/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"184956453","text":"# -*- coding:utf-8 -*-\n'''\n@author: jwang\n@license: (C) Copyright 2018-2019, Nokia Sbell Tech Corporation Limited.\n@contact: jianfeng.2.wang@nokia-sbell.com\n@software: Pycharm\n@file: 3_garagy.py\n@time: 2019/1/7 14:14\n@desc:\n'''\n\n\n'''\nIts a parking issue, need find the least movement to reach the goal\nstart = [1,2,3,0,4] , 0 is no car ,and 1234 are diffent car\nend = [0,3,2,1,4]\n\nSo the step of move car is :\n[0,2,3,1,4] ,change 1 to 0\n[2,0,3,1,4] ,change 2 to 0\n[2,3,0,1,4] ,change 3 to 0\n[0,3,2,1,4] ,change 2 to o \nNeed step 4\n'''\n\n\ndef garage(initial, final):\n\n init = initial # prevent changes in original 'initial'\n seq = [] # list of each step in sequence\n steps = 0\n while init != final:\n # 获取当前init列表中0的位置\n zero = init.index(0)\n if zero != final.index(0): #\n car_to_move = final[zero] # 查看对应在final中的位置的值\n pos = init.index(car_to_move) # 获取fina位置的值在init中的位置\n init[zero], init[pos] = init[pos], init[zero] #将init中0所在位置与fina中对应位置的值两个值进行位置调换\n else:\n # 将从头开始往下获取到的不相等的值与init中0所在位置进行兑换\n for i in range(len(init)):\n if init[i] != final[i]:\n init[zero], init[i] = init[i], init[zero]\n break\n seq.append(init[::])\n #seq.append(init)\n steps += 1\n\n return steps, seq\n\n\n'''\n思路:从尾到头进行数字调换,且只能与0进行调换 //错误,因为每次获取的固定是final的0的位置,替换位置的时候可能并非是0进行交换的\n1. 先找到0的在开始列表的位置,对比结果列表,不相同则进行替换,相同则进行前一位的对比\n'''\ndef fake_garage(initial,final):\n\n init = initial # make a copy to prevent init change , not nesserary?\n steps = 0\n seq = []\n\n # 优先判断两则不相同,则循环\n while init != final:\n # 首先获取0所在的位置,即空停车位的地址\n zero = final.index(0)\n if zero != initial.index(0): # 如果两则的0位置不同,则xx\n car_to_move = init[zero] # 找对应final 中 0 对应final所在位置应该挪动的车\n pos = final.index(car_to_move) # 找到init中对应final应该移动车的位置\n init[zero] , init[pos] = init[pos] , init[zero]\n else:\n for i in range(len(init)):\n if init[i] != final[i]:\n init[zero], init[i] = init[i], init[zero]\n break\n # 只能append当前list的copy,因为list是可变的,因此不能直接用本体\n seq.append(initial[::])\n # 每交换一次则记录一次次数\n steps += 1\n return steps , seq\n\n\n\nif __name__ == '__main__':\n start = [1,3,2,4,6,0]\n end = [3,6,4,1,2,0]\n\n #steps , seq = fake_garage(start,end)\n steps, seq = garage(start, end)\n\n print(\"step:{0},seq:{1}\".format(steps , seq))\n","sub_path":"Awesome_Python/Algorithms and Design Patterns/Algorithms/3_garagy.py","file_name":"3_garagy.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"595940021","text":"class Solution(object):\n def findRadius(self, houses, heaters):\n \"\"\"\n :type houses: List[int]\n :type heaters: List[int]\n :rtype: int\n \"\"\"\n heaters.sort()\n radius = 0\n for house in houses:\n index = bisect.bisect_left(heaters, house)\n dist1 = house - heaters[index-1] if index > 0 else sys.maxint\n dist2 = heaters[index] - house if index < len(heaters) else sys.maxint\n radius = max(radius, min(dist1, dist2))\n return radius\n","sub_path":"python_solutions/475-heaters.py","file_name":"475-heaters.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"574754435","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom multiping import MultiPing\nfrom statistics import mean\nfrom statistics import stdev\n\n# function pings a host\ndef ping(host):\n # Create a MultiPing object to test hosts / addresses\n mp = MultiPing([host])\n\n # Send the pings to those addresses\n mp.send()\n\n # With a 1 second timout, wait for responses (may return sooner if all\n # results are received).\n responses, no_responses = mp.receive(1)\n\n for addr, rtt in responses.items():\n RTT = rtt*1000\n\n if no_responses:\n # Sending pings once more\n mp.send()\n responses, no_responses = mp.receive(1)\n RTT = -1\n #returns rtt in miliseconds\n return RTT\n\n# Returns array with 'n' pings to 'host'\ndef get_pings(n, host):\n data = [0]*n\n load = n/10\n print(\"Collecting %d Pings...\" %n)\n for i in range(n):\n if(i == load):\n print(\"%d pings obtained...\" %load )\n load = load + n/10\n data[i] = ping(host)\n #redundancy\n if(data[i] == -1):\n data[i] = ping(host)\n return data\n \n# Writes 1 dimensional array 'data' on 'data.txt'\ndef write_array(array, name):\n text_file = open(\"%s.txt\" %name, \"w\")\n for i in range(len(array)):\n text_file.write(\"%0.5f \\n\" % array[i])\n text_file.close()\n\n# Gets data from txt files DevRTT, EstimatedRTT, SampleRTT\ndef get_arrayData():\n text_file = open(\"SampleRTT.txt\" , \"r\")\n SampleRTT = []\n for i in range(500):\n SampleRTT.append(float(text_file.readline()))\n text_file.close()\n text_file = open(\"EstimatedRTT.txt\" , \"r\")\n EstimatedRTT = []\n for i in range(500):\n EstimatedRTT.append(float(text_file.readline()))\n text_file.close()\n text_file = open(\"DevRTT.txt\" , \"r\")\n DevRTT = []\n for i in range(500):\n DevRTT.append(float(text_file.readline()))\n text_file.close()\n text_file = open(\"TimeoutInterval.txt\" , \"r\")\n TimeoutInterval = []\n for i in range(500):\n TimeoutInterval.append(float(text_file.readline()))\n text_file.close()\n return SampleRTT, EstimatedRTT, DevRTT, TimeoutInterval\n \n \n\n return EstimatedRTT, DevRTT, TimeoutInterval\n\n# Iterates the data in 'SampleRTT' to generate new data arrays\n# 'estimatedRTT' and 'devRTT' given coeficients alfa and beta\n# ref values (RFC6298) : alfa = 1/8 beta = 1/4\ndef iterateData(SampleRTT, alfa, beta):\n size = len(SampleRTT)\n EstimatedRTT = [0]*size\n DevRTT = [0]*size\n TimeoutInterval = [0]*size\n #Initial values of EstimatedRTT is the same as SampleRTT \n EstimatedRTT[0] = SampleRTT[0]\n #Initial values of DevRTT is maintained as zero\n #Initial valies of TimeoutInterval set to first sample\n TimeoutInterval[0] = SampleRTT[0]\n for i in range(1,size):\n EstimatedRTT[i] = (1-alfa)*EstimatedRTT[i-1] + alfa*SampleRTT[i]\n DevRTT[i] = (1-beta)*DevRTT[i-1] + beta*abs(EstimatedRTT[i] - SampleRTT[i])\n TimeoutInterval[i] = EstimatedRTT[i] + 4*DevRTT[i]\n return EstimatedRTT, DevRTT, TimeoutInterval\n\n#plots data \ndef printData(SampleRTT, EstimatedRTT, DevRTT, TimeoutInterval):\n size = len(SampleRTT)\n x = np.arange(0, size , 1)\n # red dashes, blue squares and green triangles \n plt.plot(x, SampleRTT,'-')\n plt.plot(x, EstimatedRTT, '-')\n plt.plot(x, DevRTT, '-')\n plt.plot(x, TimeoutInterval, '-')\n \n TimeoutInterval\n plt.xlabel(\"Pings\")\n plt.ylabel(\"Time [ms]\")\n plt.legend(('SampleRTT', 'EstimatedRTT', 'DevRTT', 'TimeoutInterval'),\n loc='upper left')\n plt.title('RTT and Estimation Parameters - 500 samples')\n plt.show()\n\n#calculates mean and average of data\ndef analyseData(SampleRTT, EstimatedRTT, DevRTT, TimeoutInterval):\n print(\"Mean of SampleRTT: %0.5f ms\" %mean(SampleRTT))\n print(\"Std Deviation of SampleRTT: %0.5f ms\" %stdev(SampleRTT))\n print(\"Mean of EstimatedRTT: %0.5f ms\" %mean(EstimatedRTT))\n print(\"Std Deviation of EstimatedRTT: %0.5f ms\" %stdev(EstimatedRTT))\n print(\"Mean of DevRTT: %0.5f ms\" %mean(DevRTT))\n print(\"Std Deviation of DevRTT: %0.5f ms\" %stdev(DevRTT))\n print(\"Mean of TimeoutInterval: %0.5f ms\" %mean(TimeoutInterval))\n print(\"Std Deviation of TimeoutInterval: %0.5f ms\" %stdev(TimeoutInterval))\n \n \n\n\nalfa = 1/8\nbeta = 1/4\nprint(\"Do you want to acquire data or process data already stored?\")\nchoice = input(\"1: acquire \\n2: process\\nChoice: \")\nif (choice == '1'):\n host = input(\"Enter a valid host name: \")\n print(\"Trying to reach host...\\n\")\n SampleRTT = get_pings(500, host)\n print(\"Pings - OK!\\n\")\n write_array(SampleRTT, \"SampleRTT\")\n print(\"Write SampleRTT - OK!\")\n EstimatedRTT, DevRTT, TimeoutInterval = iterateData(SampleRTT,alfa,beta)\n print(\"EstimatedRTT and DevRTT - OK!\")\n write_array(EstimatedRTT, \"EstimatedRTT\")\n print(\"Write EstimatedRTT - OK!\")\n write_array(DevRTT, \"DevRTT\")\n print(\"Write DevRTT - OK!\")\n write_array(TimeoutInterval, \"TimeoutInterval\")\n print(\"Write TimeoutInterval - OK!\")\n analyseData(SampleRTT, EstimatedRTT, DevRTT, TimeoutInterval)\n printData(SampleRTT, EstimatedRTT, DevRTT, TimeoutInterval)\nif (choice == '2'):\n print(\"Processing data stored at folder files\")\n SampleRTT, EstimatedRTT ,DevRTT, TimeoutInterval = get_arrayData()\n analyseData(SampleRTT, EstimatedRTT, DevRTT, TimeoutInterval)\n printData(SampleRTT, EstimatedRTT, DevRTT, TimeoutInterval)\nelse:\n print(\"Invalid Input\\nClosing program...\")\n \n\n\n\n\n\n\n","sub_path":"ping_to_data.py","file_name":"ping_to_data.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"72327772","text":"#!/usr/bin/eny python\n# Kyle Fitzsimmons, 2020\nimport psycopg2\nimport psycopg2.extras\n\nimport config\nimport serialize_xforms\n\n\n## Fetch Itinerum survey from Postgres database\nconn = psycopg2.connect(**config.DB)\ncur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\nsurvey_id = 261\n\n# get survey metadata record for display language attribute\nquery = f'SELECT language FROM surveys WHERE id={survey_id};'\ncur.execute(query)\nsurvey_language = cur.fetchone()['language']\n\n# retrieve all questions for a survey from Itinerum database\nquery = f'SELECT * FROM survey_questions WHERE survey_id={survey_id} ORDER BY question_num ASC;'\ncur.execute(query)\nquestions = [dict(q) for q in cur.fetchall()]\n\n# retrieve all question choices for a list of questions from Itinerum database\nquestion_ids = tuple([q['id'] for q in questions])\ncur.execute('SELECT * FROM survey_question_choices WHERE question_id IN %s;', (question_ids,))\nchoices = [dict(c) for c in cur.fetchall()]\n\n# merge questions and choices into list of dicts object\nfor q in questions:\n for c in choices:\n if c['question_id'] == q['id']:\n q.setdefault('choices', []).append(c)\n\n\nserialize_xforms.serialize(survey_id, survey_language, questions)\n","sub_path":"itinerum_to_xforms.py","file_name":"itinerum_to_xforms.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"342905978","text":"\nimport os\nimport pkg_resources\nimport nose\nimport unittest\nfrom .test_calculator import CalculatorTest\n\nclass loadTestcases():\n\n def __init__(self,customer_id):\n self.customer_id=customer_id\n print('test')\n\n\n def load_Test_Cases(self):\n print(\"Get T\")\n #print os.getcwd()\n dir= pkg_resources.resource_filename('core.calculator_app', 'core/calculator_app')\n #directory='C:\\\\centerdev\\\\rest-automation\\\\core\\\\calculator_app\\\\core\\\\calculator_app'\n #print pkg_resources.resource_isdir('core.calculator_app')\n print(pkg_resources.resource_listdir('core.calculator_app'))\n directory='C://centerdev//rest - automation//core//calculator_app'\n test_loader=nose.loader.TestLoader(workingDir=os.getcwd())\n print(dir(CalculatorTest))\n print(test_loader.loadTestsFromDir(os.getcwd()))\n nose.run(test_loader)\n\n loader = unittest.TestLoader()\n start_dir = 'path/to/your/test/files'\n suite = loader.discover(os.getcwd())\n\n #runner = unittest.TextTestRunner().run(suite)\n #print runner.testsRun\n\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(CalculatorTest))\n result = unittest.TestResult()\n #result=suite.run(result)\n print(result)\n\n\n #print type(result)\n #res=result.getTestsReport()\n #print res\n\n\n\n\n\n\ntest=loadTestcases('1')\ntest.load_Test_Cases()\n","sub_path":"centerdev/execute_suites/load_test_cases.py","file_name":"load_test_cases.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"354705026","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 9 11:27:04 2019\n\n@author: eo\n\"\"\"\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Add local path\n\nimport os\nimport sys\n\ndef find_path_to_local(target_folder = \"local\"):\n \n # Skip path finding if we successfully import the dummy file\n try:\n from local.dummy import dummy_func; dummy_func(); return\n except ImportError:\n print(\"\", \"Couldn't find local directory!\", \"Searching for path...\", sep=\"\\n\")\n \n # Figure out where this file is located so we can work backwards to find the target folder\n file_directory = os.path.dirname(os.path.abspath(__file__))\n path_check = []\n \n # Check parent directories to see if we hit the main project directory containing the target folder\n prev_working_path = working_path = file_directory\n while True:\n \n # If we find the target folder in the given directory, add it to the python path (if it's not already there)\n if target_folder in os.listdir(working_path):\n if working_path not in sys.path:\n tilde_swarm = \"~\"*(4 + len(working_path))\n print(\"\\n{}\\nPython path updated:\\n {}\\n{}\".format(tilde_swarm, working_path, tilde_swarm))\n sys.path.append(working_path)\n break\n \n # Stop if we hit the filesystem root directory (parent directory isn't changing)\n prev_working_path, working_path = working_path, os.path.dirname(working_path)\n path_check.append(prev_working_path)\n if prev_working_path == working_path:\n print(\"\\nTried paths:\", *path_check, \"\", sep=\"\\n \")\n raise ImportError(\"Can't find '{}' directory!\".format(target_folder))\n \nfind_path_to_local()\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Imports\n\nimport cv2\n\nfrom local.configurables.core.pixel_filter.reference_pixelfilter import Reference_Pixel_Filter\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Define classes\n\nclass Configurable(Reference_Pixel_Filter):\n \n # .................................................................................................................\n \n def __init__(self, location_select_folder_path, camera_select, input_wh):\n \n # Inherit reference functionality\n super().__init__(location_select_folder_path, camera_select, input_wh, file_dunder = __file__)\n \n # Allocate space for derived variables\n self._blur_kernel = None\n \n # Allocate storage for the background image, which is needed to find shadows\n self.current_background_bgr = None\n self.current_background_hsv = None\n \n # Allocate storage for the filter mask, mainly for visualization purposes\n self.filter_mask = None\n \n # . . . . . . . . . . . . . . . . Control Group 1 . . . . . . . . . . . . . . . .\n \n self.ctrl_spec.new_control_group(\"Main Controls\")\n \n self.enable_filter = \\\n self.ctrl_spec.attach_toggle(\n \"enable_filter\",\n label = \"Enable filtering\",\n default_value = True)\n \n self.invert_filter = \\\n self.ctrl_spec.attach_toggle(\n \"invert_filter\",\n label = \"Invert\",\n default_value = False)\n \n self.blur_size = \\\n self.ctrl_spec.attach_slider(\n \"blur_size\",\n label = \"Blurriness\",\n default_value = 0,\n min_value = 0,\n max_value = 15,\n return_type = int,\n tooltip = \"Amount of blurring to apply to a frame before filtering out shadows.\")\n \n self.lower_shadow_threshold = \\\n self.ctrl_spec.attach_slider(\n \"lower_shadow_threshold\",\n label = \"Lower Shadow Threshold\",\n default_value = 0,\n min_value = 0,\n max_value = 255,\n return_type = int)\n \n self.upper_shadow_threshold = \\\n self.ctrl_spec.attach_slider(\n \"upper_shadow_threshold\",\n label = \"Upper Shadow Threshold\",\n default_value = 10,\n min_value = 0,\n max_value = 255,\n return_type = int)\n \n # .................................................................................................................\n \n def reset(self):\n self.filter_mask = None\n \n # .................................................................................................................\n \n def setup(self, variables_changed_dict):\n \n blur_kernel_size = 3 + 2*self.blur_size\n self._blur_kernel = (blur_kernel_size, blur_kernel_size)\n \n # .................................................................................................................\n \n def apply_pixel_filtering(self, binary_frame_1ch, color_frame):\n \n try:\n \n \n hsv_frame = cv2.cvtColor(color_frame, cv2.COLOR_BGR2HSV_FULL)\n diff_frame = cv2.absdiff(hsv_frame, self.current_background_hsv)\n gray_frame = diff_frame[:,:,2]#cv2.cvtColor(diff_frame[:,:,2], cv2.COLOR_BGR2GRAY)\n blur_frame = cv2.blur(gray_frame, self._blur_kernel)\n \n _, lower_thresh_frame = cv2.threshold(blur_frame, self.lower_shadow_threshold, 255, cv2.THRESH_BINARY)\n _, upper_thresh_frame = cv2.threshold(blur_frame, self.upper_shadow_threshold, 255, cv2.THRESH_BINARY_INV)\n thresh_frame = cv2.bitwise_and(lower_thresh_frame, upper_thresh_frame)\n \n return thresh_frame\n \n # Skip masking if not enabled\n if not self.enable_filter:\n return binary_frame_1ch\n \n # Generate filter mask\n scaled_color_frame = cv2.resize(color_frame, dsize = self.input_wh)\n self.filter_mask = self._color_filter(scaled_color_frame)\n \n # Apply color mask to existing binary frame\n new_binary_frame_1ch = cv2.bitwise_and(self.filter_mask, binary_frame_1ch)\n \n return new_binary_frame_1ch\n \n except cv2.error as err:\n self.log(\"ERROR FILTERING ({})\".format(self.script_name))\n if self.configure_mode:\n raise err\n \n return binary_frame_1ch\n \n # .................................................................................................................\n \n def update_background(self, preprocessed_background_frame, bg_update):\n \n # Store backgrounds\n if bg_update or (self.current_background_bgr is None):\n \n # Store the 'clean' background for reference\n self.current_background_bgr = preprocessed_background_frame\n self.current_background_hsv = cv2.cvtColor(self.current_background_bgr, cv2.COLOR_BGR2HSV_FULL)\n \n # .................................................................................................................\n \n def _color_filter(self, bgr_color_frame):\n \n # Filter out lower/upper bounds from the color frame\n binary_filter_1d = cv2.inRange(bgr_color_frame, self._lower_tuple, self._upper_tuple)\n \n # Invert the filter if needed\n return cv2.bitwise_not(binary_filter_1d) if self.invert_filter else binary_filter_1d \n \n # .................................................................................................................\n # .................................................................................................................\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Define functions\n\n# .....................................................................................................................\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Demo\n \nif __name__ == \"__main__\":\n pass\n \n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Scrap\n\n\n\n ","sub_path":"local/configurables/core/pixel_filter/shadow_pixelfilter.py","file_name":"shadow_pixelfilter.py","file_ext":"py","file_size_in_byte":8879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"546329264","text":"#! /usr/bin/env python3\n\n# Adapted from http://kitchingroup.cheme.cmu.edu/blog/2013/02/18/Nonlinear-curve-fitting/\n\nimport glob\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import leastsq\nfrom pymatgen.io.vasp import Vasprun\nfrom vasppy import Poscar\nfrom vasppy.summary import find_vasp_calculations\n\ndef read_data( verbose=True ):\n dir_list = find_vasp_calculations()\n data = []\n for d in dir_list:\n try:\n vasprun = Vasprun( d + 'vasprun.xml', parse_potcar_file=False )\n except:\n continue\n poscar = Poscar.from_file( d + 'POSCAR' )\n data.append( np.array( [ poscar.scaling, vasprun.final_structure.volume, vasprun.final_energy ] ) )\n df = pd.DataFrame( data, columns=[ 'scaling', 'volume', 'energy' ] ).sort_values( by='scaling' )\n df = df.reset_index( drop=True )\n df['scaling_factor'] = df.volume / df.scaling**3\n scaling_factor_round = 5\n if verbose:\n print( df )\n if len( set( df.scaling_factor.round( scaling_factor_round ) ) ) != 1:\n raise ValueError( \"POSCAR scaling factors and volumes are inconsistent\" )\n return df\n\ndef murnaghan( vol, e0, b0, bp, v0 ):\n \"\"\"\n Calculate the energy as a function of volume, using the Murnaghan equation of state\n [Murnaghan, Proc. Nat. Acad. Sci. 30, 244 (1944)]\n https://en.wikipedia.org/wiki/Murnaghan_equation_of_state\n cf. Fu and Ho, Phys. Rev. B 28, 5480 (1983).\n\n Args:\n vol (float): this volume.\n e0 (float): energy at the minimum-energy volume, E0.\n b0 (float): bulk modulus at the minimum-energy volume, B0.\n bp (float): pressure-derivative of the bulk modulus at the minimum-energy volume, B0'.\n v0 (float): volume at the minimum-energy volume, V0.\n \n Returns:\n (float): The energy at this volume. \n \"\"\"\n energy = e0 + b0 * vol / bp * (((v0 / vol)**bp) / (bp - 1) + 1) - v0 * b0 / (bp - 1.0)\n return energy\n\ndef objective( pars, x, y ):\n err = y - murnaghan( x, *pars )\n return err\n\ndef fit( volumes, energies ):\n e_min = energies.min()\n v_min = volumes[ np.argwhere( energies == e_min )[0][0] ]\n x0 = [ e_min, 2.0, 10.0, v_min ] #initial guess of parameters\n plsq = leastsq( objective, x0, args=( volumes, energies ) )\n return plsq\n\nif __name__ == '__main__':\n df = read_data()\n e0, b0, bp, v0 = fit( np.array( df.volume ), np.array( df.energy ) )[0]\n print( \"E0: {:.4f}\".format( e0 ) )\n print( \"V0: {:.4f}\".format( v0 ) )\n print( \"opt. scaling: {:.5f}\".format( ( v0 / df.scaling_factor.mean() )**(1/3) ) )\n","sub_path":"scripts/murnfit.py","file_name":"murnfit.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"70621085","text":"# -*- coding: utf-8 -*-\n# center점으로부터 상하선분에 접하는 선분을 찾아서 거리측정\nimport numpy as np\nimport cv2 as cv\nimport math\nimport imutils\nimport logging\n\n\nlogging.basicConfig(filename='ImageProcessing.log',\n level=logging.DEBUG, format='%(asctime)s:%(message)s')\n\n\nFOCAL_LENGTH = 1410\nWIDTH = 8\n\ntop_line_x1, top_line_y1, top_line_x2, top_line_y2 = 0, 0, 0, 0\nbottom_line_x1, bottom_line_y1, bottom_line_x2, bottom_line_y2 = 0, 0, 0, 0\nleft_top_line_x1, left_top_line_y1, left_top_line_x2, left_top_line_y2 = 0, 0, 0, 0\ncurve_start_line_x1, curve_start_line_y1, curve_start_line_x2, curve_start_line_y2 = 0, 0, 0, 0\n\nkernel = np.ones((3, 1), np.uint8)\nkernel1 = np.ones((1, 3), np.uint8)\n\n\ndef distance_calculate(pixel):\n d = WIDTH * FOCAL_LENGTH / pixel\n return d\n\n\ndef line_point(line_list):\n\n for i in range(len(line_list[1:])):\n a1 = line_list[i][3] - line_list[i][1]\n b1 = line_list[i][0] - line_list[i][2]\n c1 = a1*line_list[i][0] + b1*line_list[i][1]\n a2 = line_list[i+1][3] - line_list[i+1][1]\n b2 = line_list[i+1][0] - line_list[i+1][2]\n c2 = a2*line_list[i+1][0] + b2*line_list[i+1][1]\n deteminate = a1*b2 - a2*b1\n try:\n t_X = int((b2*c1 - b1*c2)/deteminate)\n t_Y = int((a1*c2 - a2*c1)/deteminate)\n except ZeroDivisionError:\n t_X = int((b2*c1 - b1*c2)/1)\n t_Y = int((a1*c2 - a2*c1)/1)\n\n return t_X, t_Y\n\n\ndef threshold_func(img):\n\n frame_HSV = cv.cvtColor(img, cv.COLOR_BGR2HSV)\n threshold = cv.inRange(frame_HSV, (60, 0, 0), (179, 255, 255))\n threshold2 = cv.inRange(img, (0, 0, 146), (179, 255, 255))\n threshold2 = cv.bitwise_not(threshold2)\n result1 = cv.erode(threshold, kernel, iterations=3)\n result1 = cv.dilate(result1, kernel, iterations=5)\n threshold_result = cv.bitwise_and(threshold, threshold2)\n threshold_result2 = cv.bitwise_and(result1, threshold_result)\n threshold_result2 = cv.dilate(threshold_result2, kernel1, iterations=5)\n return threshold_result2\n\n\ndef detect_center(roi_thres):\n cnts = cv.findContours(\n roi_thres.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n for c in cnts:\n c = max(cnts, key=cv.contourArea)\n M = cv.moments(c)\n try:\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n except ZeroDivisionError:\n cX = int(M[\"m10\"] / 1)\n cY = int(M[\"m01\"] / 1)\n return cX, cY\n\n\ndef main(PATH):\n img = cv.imread(PATH)\n img = cv.resize(img, dsize=(0, 0), fx=0.5, fy=0.5,\n interpolation=cv.INTER_LINEAR)\n img = cv.rotate(img, cv.ROTATE_90_CLOCKWISE)\n if img is not None:\n depth, pipe_depth, degree, pipe_type = object_detect(img)\n return depth, pipe_depth, degree, pipe_type\n else:\n logging.warning(\"There is No Image\")\n return 0, 0, 0, 0\n\n\ndef object_detect(img):\n pipe_type = 0\n\n global left_top_line_x1, left_top_line_y1, left_top_line_x2, left_top_line_ygray2\n global top_line_x1, top_line_y1, top_line_x2, top_line_y2\n\n global bottom_line_x1, bottom_line_y1, bottom_line_x2, bottom_line_y2\n global curve_start_line_x1, curve_start_line_y1, curve_start_line_x2, curve_start_line_y2\n top_line_x1, top_line_y1, top_line_x2, top_line_y2 = 0, 0, 0, 0\n bottom_line_x1, bottom_line_y1, bottom_line_x2, bottom_line_y2 = 0, 0, 0, 0\n left_top_line_x1, left_top_line_y1, left_top_line_x2, left_top_line_y2 = 0, 0, 0, 0\n curve_start_line_x1, curve_start_line_y1, curve_start_line_x2, curve_start_line_y2 = 0, 0, 0, 0\n\n threshold_result2 = threshold_func(img)\n cnts = cv.findContours(\n threshold_result2.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n c = max(cnts, key=cv.contourArea)\n x, y, w, h = cv.boundingRect(c)\n # DEFINE: x,y좌표가 0일 경우에 좌표를 더 늘리거나 추가하는 작업에서 오류가 발생하여서 분개함\n if x is 0 and y is 0:\n roi_image = img[1:1+h, 1:1+w]\n else:\n roi_image = img[y-10:y+h+10, x:x+w]\n\n roi_thres = threshold_func(roi_image)\n cX, cY = detect_center(roi_thres)\n cv.circle(roi_image, (cX, cY), 7, (255, 0, 255), -1)\n edges = cv.Canny(roi_thres, 100, 200, apertureSize=3)\n lines = cv.HoughLinesP(edges, 1, np.pi/180, 100,\n minLineLength=0, maxLineGap=500)\n line_list = list()\n try:\n for line in lines:\n x1, y1, x2, y2 = line[0]\n if y1 < cY and y2 < cY and x1 < cX:\n top_line_x1, top_line_y1, top_line_x2, top_line_y2 = x1, y1, x2, y2\n elif y1 > cY and y2 > cY and x1 < cX:\n bottom_line_x1, bottom_line_y1, bottom_line_x2, bottom_line_y2 = x1, y1, x2, y2\n\n elif (y2-y1)/(x2-x1) < 0:\n curve_start_line_x1, curve_start_line_y1, curve_start_line_x2, curve_start_line_y2 = x1, y1, x2, y2\n cv.line(roi_image, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\n line_list.append([bottom_line_x1, bottom_line_y1,\n bottom_line_x2, bottom_line_y2])\n\n line_list.append([curve_start_line_x1, curve_start_line_y1,\n curve_start_line_x2, curve_start_line_y2])\n\n if curve_start_line_x1 is not 0:\n t_X, t_Y = line_point(line_list)\n cv.circle(roi_image, (t_X, t_Y), 7, (0, 255, 255), -1)\n top_degree_height = math.atan2(\n (bottom_line_x1 - t_X), (bottom_line_y1 - t_Y))\n top_degree_bottom = math.atan2(\n (t_X-curve_start_line_x1), (t_Y-curve_start_line_y1))\n degree = (top_degree_height-top_degree_bottom)*180/math.pi\n print(degree)\n if degree < 0:\n print(\"asdfasdfsdf\")\n degree = abs(degree)\n if degree > 180:\n degree = degree-180\n if degree < 170:\n pipe_type = 1\n if degree > 175:\n degree = 0\n # if degree > 175:\n # pipe_type = 1\n # degree = 0\n\n else:\n degree = 0\n pipe_type = 0\n print(\"degree\", degree)\n\n pixel = bottom_line_y1 - top_line_y1\n distance = distance_calculate(pixel)\n print(distance, pixel, degree, pipe_type)\n logging.debug({\n 'DepthToPipe': distance,\n 'PixelDistance': pixel,\n 'Type': pipe_type,\n 'Degree': degree\n })\n if pipe_type is 0:\n return distance, pixel, degree, pipe_type\n else:\n return 0, 0, degree, pipe_type\n except:\n logging.debug(\"There's no Line\")\n return 0, 0, 0, 0\n","sub_path":"api_server/caliber_pipe/project_algorithm.py","file_name":"project_algorithm.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"99677971","text":"#\n# file: rastrigin.py\n#\n# Minimum of the Rastrigin function (f(0,...,0) = 0)\n#\n# RTK, 29-Dec-2019\n# Last update: 07-Aug-2020\n#\n################################################################\n\nimport sys\nimport time\n\nsys.path.append(\"../\")\n\nfrom PSO import *\nfrom DE import *\nfrom RO import *\nfrom GWO import *\nfrom Jaya import *\nfrom GA import *\n\nfrom RandomInitializer import *\nfrom SphereInitializer import *\nfrom QuasirandomInitializer import *\nfrom Bounds import *\nfrom LinearInertia import *\n\n################################################################\n# dist\n#\ndef dist(p):\n \"\"\"Return the distance from p to the true minimum\"\"\"\n\n m = np.zeros(len(p))\n return np.sqrt(((p-m)**2).sum())\n\n\n################################################################\n# Objective\n#\nclass Objective:\n \"\"\"The objective function\"\"\"\n\n def __init__(self):\n \"\"\"Constructor\"\"\"\n self.fcount = 0\n \n def Evaluate(self, p):\n \"\"\"Evaluate a position\"\"\"\n self.fcount += 1\n return 10*len(p) + (p**2 - 10*np.cos(2*np.pi*p)).sum()\n \n\n\n################################################################\n# main\n#\ndef main():\n \"\"\"Rastrigin\"\"\"\n\n if (len(sys.argv) == 1):\n print()\n print(\"rastrigin RI|SI|QI\")\n print()\n print(\" - dimensionality\")\n print(\" - number of swarm particles\")\n print(\" - number of iterations\")\n print(\" - algorithm: PSO,DE,RO,GWO,JAYA,GA\")\n print(\" RI|SI|QI - RI=random, SI=sphere, QI=quasi initializer\")\n print()\n return\n\n ndim = int(sys.argv[1])\n npart = int(sys.argv[2])\n max_iter = int(sys.argv[3])\n alg = sys.argv[4].upper()\n itype = sys.argv[5].upper()\n\n b = Bounds([-2]*ndim,[2]*ndim)\n\n if (itype == \"SI\"):\n i = SphereInitializer(npart, ndim, bounds=b)\n elif (itype == \"QI\"):\n i = QuasirandomInitializer(npart, ndim, bounds=b)\n else:\n i = RandomInitializer(npart, ndim, bounds=b)\n\n obj = Objective()\n\n if (alg == \"PSO\"):\n swarm = PSO(obj=obj, npart=npart, ndim=ndim, init=i, max_iter=max_iter, bounds=b, inertia=LinearInertia())\n elif (alg == \"DE\"):\n swarm = DE(obj=obj, npart=npart, ndim=ndim, init=i, max_iter=max_iter, bounds=b)\n elif (alg == \"RO\"):\n swarm = RO(obj=obj, npart=npart, ndim=ndim, init=i, max_iter=max_iter, bounds=b)\n elif (alg == \"CSO\"):\n swarm = CSO(obj=obj, npart=npart, ndim=ndim, init=i, max_iter=max_iter, bounds=b)\n elif (alg == \"GWO\"):\n swarm = GWO(obj=obj, npart=npart, ndim=ndim, init=i, max_iter=max_iter, bounds=b)\n elif (alg == \"JAYA\"):\n swarm = Jaya(obj=obj, npart=npart, ndim=ndim, init=i, max_iter=max_iter, bounds=b)\n elif (alg == \"GA\"):\n swarm = GA(obj=obj, npart=npart, ndim=ndim, init=i, max_iter=max_iter, bounds=b)\n else:\n raise ValueError(\"Unknown algorithm: %s\" % alg)\n\n st = time.time()\n swarm.Optimize()\n en = time.time()\n\n res = swarm.Results()\n b = res[\"gbest\"][-1]\n p = res[\"gpos\"][-1]\n count = swarm.obj.fcount\n\n print()\n print(\"fmin = %0.16e at:\" % (b,))\n print(\"distance from minimum = %0.16e\" % dist(p))\n print()\n for i in range(ndim):\n print(\" {: .16e}\".format(p[i]))\n print()\n print(\"(%d swarm best updates, %d function evals, time: %0.3f seconds)\" % (len(res[\"gbest\"]), count, en-st))\n print()\n\n\nif (__name__ == \"__main__\"):\n main()\n\n","sub_path":"test_functions/rastrigin.py","file_name":"rastrigin.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"597545090","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 10/1/2018\n\n# Copyright 2018 XingHuan\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom sins.module.sqt import *\nfrom sins.utils.res import resource\nfrom sins.ui.widgets.data_view.utils.status import get_entity_status_icon\n\nOBJECT_ICON_SIZE = 17\n\n\nclass EntityItemWidget(QWidget):\n choose = Signal(object)\n\n def __init__(self, entity, parent_entity=None, *args, **kwargs):\n super(EntityItemWidget, self).__init__(*args, **kwargs)\n\n self.entity = entity\n self.parent_entity = parent_entity\n self.type = entity.__class__.__name__\n\n self.init_ui()\n\n if hasattr(self.entity, 'icon'):\n self.iconLabel.setPixmap(resource.get_pixmap(self.entity.icon, scale=OBJECT_ICON_SIZE))\n self.nameLabel.setText(self.entity.label_name)\n if hasattr(self.entity, 'status'):\n status_icon = get_entity_status_icon(self.entity)\n self.statusLabel.setPixmap(resource.get_pixmap(status_icon, scale=OBJECT_ICON_SIZE))\n\n def init_ui(self):\n\n self.masterLayout = QHBoxLayout()\n self.setLayout(self.masterLayout)\n self.masterLayout.setContentsMargins(0, 0, 0, 0)\n\n self.iconLabel = QLabel()\n self.iconLabel.setFixedSize(QSize(OBJECT_ICON_SIZE, OBJECT_ICON_SIZE))\n self.nameLabel = QLabel()\n self.statusLabel = QLabel()\n\n self.masterLayout.addSpacing(5)\n self.masterLayout.addWidget(self.iconLabel)\n self.masterLayout.addWidget(self.nameLabel)\n self.masterLayout.addWidget(self.statusLabel)\n\n self.setFixedHeight(30)\n\n def mouseReleaseEvent(self, *args, **kwargs):\n self.choose.emit(self)\n\n\n\n","sub_path":"sins/ui/widgets/entity_browser/item_widget/item_widget.py","file_name":"item_widget.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"577563162","text":"import tkinter as tk\n#import numpy as np\nimport random\n\nroll = tk.Tk()\nroll.title('ROLL THE DICE')\nroll.geometry('400x400')\nl = tk.Label(roll,\n text='Roll the dice',\n bg='white',\n font=('Times New Roman', 20),\n width=400, height=2\n )\nl.pack()\n\nvar=tk.StringVar()\nroll_number = tk.Label(roll,\n textvariable=var,\n font=('Times New Roman', 20),\n bg='white',\n width=400,height=2\n )\nroll_number.pack()\n\ndef roll_button():\n number = random.randint(0,99)\n var.set(str(number))\n \nroll_b = tk.Button(roll,\n text='Roll',\n width=15,height=2,\n command=roll_button)\n\nroll_b.place(x=120,y=200)\n\n\n\nroll.mainloop()\n","sub_path":"roll.py","file_name":"roll.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"401669521","text":"import requests\n\nurl = 'http://localhost:5000/voucher'\nmyobj = {\n \"customer_id\": 123,\n \"country_code\": \"Peru\",\n \"last_order_ts\": \"2020-10-03 00:00:00\",\n \"segment_name\": \"recency_segment\",\n \"total_orders\":3\n}\n\nx = requests.post(url, json=myobj)\n\nprint(x.text)\n# print(x)\n","sub_path":"api_endpoint/postgres_api/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"280531564","text":"import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport math\nimport numpy as np\nimport os\nimport imageio\nfrom matplotlib.pyplot import cm\n\n# TODO: 1. Change N_Fourier to 2, 4, 8, 16, 32, 64, 128, get visualization results with differnet number of Fourier Series\nN_Fourier = 64\n\n# TODO: optional, implement visualization for semi-circle\nsignal_name = \"square\" # \"semicircle\"\nPI_2 = 2 * np.pi\n\n# TODO: 2. Please implement the function that calculates the Nth fourier coefficient\n# Note that n starts from 0\n# For n = 0, return a0; n = 1, return b1; n = 2, return a1; n = 3, return b2; n = 4, return a2 ...\n# n = 2 * m - 1(m >= 1), return bm; n = 2 * m(m >= 1), return am. \ndef fourier_coefficient(n):\n if signal_name == \"square\":\n return fourier_square(n)\n elif signal_name == \"semicircle\":\n return fourier_semicircle(n)\n else:\n raise Exception(\"Unknown Signal\")\n\ndef fourier_square(n):\n if n == 0:\n return 0.5\n if n % 2 == 0:\n return 0.0\n else:\n temp = (n+1) // 2\n return 2. / (temp * np.pi) if temp % 2 else 0.0\n\ndef fourier_semicircle(n):\n def f(t, m):\n return np.sqrt((PI_2 - t) * t) * np.cos(m*t)\n if n == 0:\n return (np.pi / 2) ** 2\n if n % 2 == 0:\n n = n // 2 # an\n split = 1000\n delta = PI_2 / split\n xs = np.linspace(0, PI_2, split+1)\n ys = f(xs, n)\n value = np.sum((ys[:-1] + ys[1:])) * delta # 梯形积分法\n return value / PI_2\n else:\n return 0.0\n\n# TODO: 3. implement the signal function\ndef square_wave(t):\n return 0.5 * (1.0 + np.sign(np.sin(t)))\n\n# TODO: optional. implement the semi circle wave function\ndef semi_circle_wave(t):\n offset = t - int(t / (2*np.pi)) * (2*np.pi)\n return np.sqrt((2*np.pi - offset) * offset)\n\ndef function(t):\n if signal_name == \"square\":\n return square_wave(t)\n elif signal_name == \"semicircle\":\n return semi_circle_wave(t)\n else:\n raise Exception(\"Unknown Signal\")\n\n\ndef visualize():\n if not os.path.exists(signal_name):\n os.makedirs(signal_name)\n\n frames = 100\n\n # x and y are for drawing the original function\n x = np.linspace(0, 2 * math.pi, 1000)\n y = np.zeros(1000, dtype = float)\n for i in range(1000):\n y[i] = function(x[i])\n\n for i in range(frames):\n figure, axes = plt.subplots()\n color=iter(cm.rainbow(np.linspace(0, 1, 2 * N_Fourier + 1)))\n\n time = 2 * math.pi * i / frames\n point_pos_array = np.zeros((2 * N_Fourier + 2, 2), dtype = float)\n radius_array = np.zeros((2 * N_Fourier + 1), dtype = float)\n\n point_pos_array[0, :] = [0, 0]\n radius_array[0] = fourier_coefficient(0)\n point_pos_array[1, :] = [0, radius_array[0]]\n\n circle = patches.Circle(point_pos_array[0], radius_array[0], fill = False, color = next(color))\n axes.add_artist(circle)\n\n f_t = function(time)\n for j in range(N_Fourier):\n # calculate circle for a_{n}\n radius_array[2 * j + 1] = fourier_coefficient(2 * j + 1)\n point_pos_array[2 * j + 2] = [point_pos_array[2 * j + 1][0] + radius_array[2 * j + 1] * math.cos((j + 1) * time), # x axis\n point_pos_array[2 * j + 1][1] + radius_array[2 * j + 1] * math.sin((j + 1) * time)] # y axis\n circle = patches.Circle(point_pos_array[2 * j + 1], radius_array[2 * j + 1], fill = False, color = next(color))\n axes.add_artist(circle)\n \n # calculate circle for b_{n}\n radius_array[2 * j + 2] = fourier_coefficient(2 * j + 2)\n point_pos_array[2 * j + 3] = [point_pos_array[2 * j + 2][0] + radius_array[2 * j + 2] * math.sin((j + 1) * time), # x axis\n point_pos_array[2 * j + 2][1] + radius_array[2 * j + 2] * math.cos((j + 1) * time)] # y axis\n circle = patches.Circle(point_pos_array[2 * j + 2], radius_array[2 * j + 2], fill = False, color = next(color))\n axes.add_artist(circle)\n \n # print(radius_array)\n plt.plot(point_pos_array[:, 0], point_pos_array[:, 1], 'o-')\n plt.plot(x, y, '-')\n plt.plot([time, point_pos_array[-1][0]], [f_t, point_pos_array[-1][1]], '-', color = 'r')\n plt.gca().set_aspect('equal', adjustable='box')\n plt.savefig(os.path.join(signal_name, \"{}.png\".format(i)))\n # plt.show()\n plt.close()\n \n images = []\n for i in range(frames):\n images.append(imageio.imread(os.path.join(signal_name, \"{}.png\".format(i))))\n imageio.mimsave('{}.mp4'.format(signal_name + str(N_Fourier)), images)\n\n\nif __name__ == \"__main__\":\n visualize()\n","sub_path":"Fourier-Transform/exp1.py","file_name":"exp1.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"448180591","text":"import pymongo\nfrom pymongo import MongoClient\nfrom django.shortcuts import render\nfrom django.core.context_processors import csrf\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import *\nimport json \nfrom sets import Set\n\ndatabase_name = \"VOSSM\"\ncollection_name = \"raw_data\"\ncollection_name_parse = \"parsed_data\"\ndatabase_name_R_cran = \"test\"\ncollection_name_R_cran = \"package_details\"\ncollection_name_tag_list=\"tags\"\ncollection_name_tag_mapping=\"tag_mapping\"\n\n@csrf_exempt\ndef summary(request):\n\tdata = {}\n\tcount = 0\n\tversion = []\n\tconnection = MongoClient()\n\tdb = connection.VOSSM\n\tcollection = db[collection_name_tag_list]\n\tdataCursor = collection.find()\n\n\tcount = 1\n\tfor record in dataCursor:\n\t\tdata[count] = record\n\t\tcount+= 1\n\n\treturn render(request, 'summarybyprojecttag.html', {\"data\" : data})","sub_path":"vossm_websiteApp/summarybyprojecttag.py","file_name":"summarybyprojecttag.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"645446936","text":"import re\nimport glob\nimport os\nimport sys\nimport sublime\n\nfrom stoplight.tools import ProtoComplition\n\nclass Form(ProtoComplition):\n\n\tdef __init__(self):\n\t\tsuper(Form, self).__init__()\n\n\tdef list(self, view, fName):\n\t\tfolder = os.path.dirname(sublime.active_window().active_view().file_name())\n\t\tif not folder:\n\t\t\treturn False\n\t\tfolder = re.sub('application.*', '', folder)\n\n\t\tres = []\n\t\tfor x in [re.findall(r'\\s*public\\s*function\\s*(.*)\\(', open(folder + 'application/core/Form/' + fName + '.php').read())][0]:\n\t\t\tx = re.sub('\\(.*', '', x)\n\t\t\tres.append((x + ' \\t' + 'method', x + '($1)$0'))\n\n\t\tfor x in [re.findall(r'\\s*public\\s*function\\s*(.*)\\(', open(folder + 'library/Core/Form.php').read())][0]:\n\t\t\tx = re.sub('\\(.*', '', x)\n\t\t\tres.append((x + ' \\t' + 'method', x + '($1)$0'))\n\n\t\treturn res\n","sub_path":"modules/methods/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"248411156","text":"def dictionary(dictio):\r\n print(\"I am in year\",dictio['Fourth year'],\"in college\")\r\n\r\n\r\ndictio = {\"First year\":1,\r\n \"Second year\":2,\r\n \"Third year\":3,\r\n \"Fourth year\":4\r\n }\r\n\r\ndictionary(dictio)\r\n\r\ndef get_dictionary(diction,getValue):\r\n print(\"one is \",diction.get(\"one\"))\r\n\r\ndiction = {\"one\":1,\r\n \"two\":2,\r\n \"three\":3\r\n }\r\n\r\ngetValue = \"one\"\r\nget_dictionary(diction,getValue)\r\n\r\ndef show_keys(keysdict):\r\n print(\"keys are: \")\r\n for index in keysdict:\r\n print(index,end= \" \")\r\n\r\nkeysdict = {\"four\":4,\r\n \"five\":5,\r\n \"six\":6\r\n }\r\n\r\nshow_keys(keysdict)\r\nprint(\"\")\r\n\r\ndef show_values(valuesdict):\r\n print(\"values in this dictionary are\")\r\n for index in valuesdict:\r\n print(valuesdict[index],end=\" \")\r\n\r\n\r\nvaluesdict = {\"seven\":7,\r\n \"eight\":8,\r\n \"nine\":9\r\n }\r\n\r\nshow_values(valuesdict)\r\nprint(\"\")\r\n\r\ndef check_dicionary(checkdict,checkdictvalue):\r\n if checkdictvalue in checkdict:\r\n print(checkdictvalue,\"is in the dictionary\")\r\n else:\r\n print(\"not found!\")\r\n \r\n\r\n\r\ncheckdict = {\"ten\":10,\r\n \"eleven\":11,\r\n \"twelve\":12\r\n }\r\n\r\ncheckdictvalue = \"twelve\"\r\n\r\ncheck_dicionary(checkdict,checkdictvalue)\r\n\r\n\r\ndef change_dictionary(defaultdict,changeValue,changeKey):\r\n defaultdict[changeValue] = changeKey\r\n print(\"new value for\",changeValue,\"is\",defaultdict[changeValue])\r\n\r\n\r\ndefaultdict = {\"eleven\":11,\r\n \"twelve\":12,\r\n \"thirteen\":13\r\n }\r\n\r\nchangeValue = \"eleven\"\r\nchangeKey = 11\r\n\r\nchange_dictionary(defaultdict,changeValue,changeKey)\r\n\r\n\r\ndef remove_element(removedict,removeKey):\r\n removedict.pop(removeKey)\r\n print(\"The dictionary is now \",removedict)\r\n\r\n\r\nremovedict = {\"twenty\": 20,\r\n \"thirty\": 30,\r\n \"forty\": 40\r\n }\r\n\r\nremoveKey = \"twenty\"\r\n\r\nremove_element(removedict,removeKey)\r\n\r\n\r\ndef remove_last_item(lastdict,response):\r\n if response == \"yes\":\r\n lastdict.popitem()\r\n print(\"dicitonary is now\",lastdict)\r\n else:\r\n print(\"dictionary is untouched\")\r\n\r\n\r\nlastdict = {\"ten\": 10,\r\n \"twenty\": 20,\r\n \"thirty\": 30\r\n }\r\n\r\nresponse = \"yes\"\r\nremove_last_item(lastdict,response)\r\n\r\n\r\ndef clear_dictionary(cleardict,clear):\r\n if clear == \"yes\":\r\n cleardict.clear()\r\n print(\"dictionary is now empty\")\r\n else:\r\n print(\"dictionary untouched\",cleardict)\r\n\r\ncleardict = {\"fourty\":40,\r\n \"fifty\":50,\r\n \"sixty\":60\r\n }\r\n\r\nclear = \"yes\"\r\n\r\nclear_dictionary(cleardict,clear)\r\n\r\ndef copy_dict(firstdict,copy):\r\n if copy == \"yes\":\r\n seconddict = firstdict.copy()\r\n print(\"second duplicate dictionary is now \",seconddict)\r\n else:\r\n print(\"no duplicate dictionary made.\")\r\n\r\n\r\nfirstdict = {\"one hundred\":100,\r\n \"two hundred\":200,\r\n \"three hundred\":30\r\n }\r\n\r\ncopy = \"yes\"\r\n\r\ncopy_dict(firstdict,copy)","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"531270418","text":"from source.task_queues.publishers.sqs_publisher import SQSTaskQueuePublisher\nfrom source.task_runner.submitter_interface import MultipleSubmittersTaskSubmitter, QueueBasedTaskSubmitter\n\n\nclass TaskSubmitterComponent(object):\n def __init__(self, env_config, feature_flags, io_handler):\n self._task_submitter = self.get_task_submitter(env_config, feature_flags)\n\n @staticmethod\n def get_task_submitter(env_config, feature_flags):\n task_submitter = MultipleSubmittersTaskSubmitter()\n if feature_flags.get('use_rc', False):\n task_publisher = SQSTaskQueuePublisher(env_config['environment_name'], feature_flags)\n base_submitter = QueueBasedTaskSubmitter(task_publisher)\n task_submitter.add_submitter(base_submitter)\n return task_submitter\n","sub_path":"source/task_runner/task_submitter_component.py","file_name":"task_submitter_component.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"368182542","text":"import mock\n\nfrom bfg9000.path import abspath, Path, Root\nfrom bfg9000.environment import Environment\n\n\ndef make_env(platform=None, clear_variables=False):\n args = (Path('bfgdir', Root.srcdir), None, None, abspath('srcdir'),\n abspath('builddir'), {}, (False, False), None)\n if platform:\n with mock.patch('bfg9000.platforms.host.platform_name',\n return_value=platform):\n env = Environment(*(args + (platform,)))\n else:\n env = Environment(*args)\n\n if clear_variables:\n env.variables = {}\n return env\n","sub_path":"test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"405462589","text":"\n\"\"\" 该文件为数据记录文件 \"\"\"\n\nimport random\nimport json\nimport logging\nfrom Common import logger\nfrom TestDatas.account_data import account_list\nfrom Common.path_config import testdatas_path\n\n\"\"\" 获取登录账号方式一:指定账号 \"\"\"\nuser = \"cfruit.mxn02\"\npasswd = \"Aa123456\"\n\n\"\"\" 获取登录账号方式二 :随机抽取一个 \"\"\"\n# def random_account():\n# test_code = random.sample(account_list,1)\n# return test_code[0]\n\n# user = random_account()[\"user\"]\n# passwd = random_account()[\"passwd\"]\n\n\n# ------------- 回归测试,救命清单 IM发送消息功能相关文本 -------------------\nIM_chat_send_text1 = \"哈哈哈\"\n\n\n# ------------- 【聊天】模块相关用例使用测试数据-------------------\n# 讯息页-搜索关键词\nmessage_search_text = \"test\"\n\n# 讯息页创建群组-群组命名\ncreate_group_name = \"test高级群\"\n\n# 创建群组-添加联络人数\ncreate_group_user_times = 3\n\n# 個人頁分享自己帖子,文本\nshare_personal_text = \"我自己的帖子自己分享咯\"\n\n# 聊天輸入與輸出\nchat_data = [{\"text\": \"測試中文\", \"result\": \"測試中文\"},\n {\"text\": \"test input\", \"result\": \"test input\"},\n {\"text\": \"789\", \"result\": \"789\"},\n {\"text\": \"[xxl01](user://66666618)\", \"result\": \"xxl01\"},\n {\"text\": \"[xxl01]\", \"result\": \"[xxl01]\"},\n {\"text\": \"[Fist][Pinky][RockOn][Beckon]\", \"result\": \"[Fist][Pinky][RockOn][Beckon]\"},\n {\"text\": \"https://www.taobao.com/\", \"result\": \"https://www.taobao.com/\"},\n {\"text\": \"[zu88](crm://4000029818)\", \"result\": \"zu88\"}]\n\n# keycode 对照表\nkeycode = {'a':29,'b':30,'c':31,'d':32,'e':33,'f':34,'g':35,'h':36,'i':37,'j':38,'k':39,'l':40,'m':41,\n 'n':42,'o':43,'p':44,'q':45,'r':46,'s':47,'t':48,'u':49,'v':50,'w':51,'x':52,'y':53,'z':54,\n '0':7,'1':8,'2':9,'3':10,'4':11,'5':12,'6':13,'7':14,'8':15,'9':16}\n\n# 個人頁面「設定昵稱和標簽」輸入暱稱文本\nname_label_data = \"這是一個標準暱稱\"\n\n# 個人頁面[查找聊天内容]-输入文本信息\nfind_chat_text = \"mirtest\"\n\n# ------------- 【最新动态】模块相关用例使用测试数据-------------------\n# 最新动态-搜索关键词\nsearch_test = \"test\"\n\n# 最新动态-搜索用戶关键词\nsearch_user_test = \"cfruit\"\n\n# [建立群組]名稱文本\ncreate_group_text = \"123\"\n\n# 發帖內容\npost_fend_text = \"發帖內容-\"\n\n#發帖內容多种组合字符\npost_send_texts = \"这是一个神奇的帖子@#¥&sdsd-\"\n\n# 动态留言-文本\nsend_message = \"来都来了,说点什么吧!+1\"\n\n# 個人tab發帖文本\npersonal_post_text = \"個人帖子-\"\n\n# 投標標題\nvote_title = \"來投個票吧-\"\n\n# 投票內容\nvote_text = \"這個字你會念嗎?-\"\n\n# 动态留言回复前置,创建一个留言-文本\nsend_message_data = \"我来创建一个留言吧zzz\"\n\n# 分享动态文本\nshare_post_text = \"来神秘人的转发!\"\n\n# 对评论的回复文本\nsend_message_reply = \"小可爱!!来了也不打声招呼\"\n\n# 动态留言-回复文本\nreply_message = \"别点我,我只是来回复的...+2\"\n\n# 分享动态,编辑文本\nshare_text = \"来着神秘的分享\"\n\n# 設定暱稱\nuser_name = \"備註名-\"\n\nvote_title_str = \"这是一个投票标题\"\nvote_content_str = \"这是一个投票内容\"","sub_path":"TestDatas/COMMON_DATA.py","file_name":"COMMON_DATA.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"30262672","text":"import urllib.request\nimport urllib.parse\nimport random\nimport re,csv\n \n\nclass DoubanSpyder():\n def __init__(self):\n headers_list = [{\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50\"},\n {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1\"}]\n headers = random.choice(headers_list)\n self.headers = headers\n self.offset=0\n baseurl = \"https://maoyan.com/board/4\"\n self.baseurl = baseurl\n \n # 页面读取\n def loadPage(self,url):\n req = urllib.request.Request(url,headers=self.headers)\n res = urllib.request.urlopen(req)\n html = res.read().decode(\"utf-8\")\n # print(html)\n self.parsePage(html)\n \n \n # 页面解析\n def parsePage(self,html):\n str ='
.*?title=\"(.*?)\".*?class=\"star\">.*?主演:(.*?)

.*?上映时间:(.*?)

'\n p = re.compile(str,re.S)\n r_list =p.findall(html)\n self.writePage(r_list)\n \n # 文件写入\n def writePage(self,r_list):\n # print(r_list)\n if self.offset == 0:\n with open (\"猫眼.csv\",\"a\",newline=\"\") as f:\n w = csv.writer(f)\n w.writerow([\"电影名称\",\"主演\",\"上映时间\"])\n for i in r_list:\n with open(\"猫眼.csv\",\"a\",newline=\"\") as f:\n writer = csv.writer(f)\n # L = list(i)\n L=[i[0].strip(),i[1].strip(),i[2].strip(),]\n writer.writerow(L) \n\n \n # 主函数\n def workOn(self):\n self.loadPage(self.baseurl)\n while True:\n c = input(\"爬取成功,是否继续(y/n):\")\n if c.strip().lower()==\"y\":\n self.offset += 10\n url = self.baseurl+\"?offset=\"+str(self.offset)\n self.loadPage(url)\n else:\n print(\"停止爬取\") \n break\n print(\"*\"*30) \n \n\n \nif __name__ == \"__main__\":\n D = DoubanSpyder()\n D.workOn()\n ","sub_path":"猫眼CSV测试.py","file_name":"猫眼CSV测试.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"98277094","text":"from pydub import AudioSegment\nsounds = AudioSegment.from_wav(\"output.wav\")\nsounds = sounds.set_channels(1)\nsounds.export(\"out2.wav\", format = \"wav\")\n\ndef transcribe_file(speech_file):\n \"\"\"Transcribe the given audio file.\"\"\"\n from google.cloud import speech\n from google.cloud.speech import enums\n from google.cloud.speech import types\n import io\n import json\n client = speech.SpeechClient()\n\n with io.open(speech_file, 'rb') as audio_file:\n content = audio_file.read()\n\n audio = types.RecognitionAudio(content=content)\n config = types.RecognitionConfig(\n encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=44100,\n language_code='en-US')\n\n response = client.recognize(config, audio)\n # Print the first alternative of all the consecutive results.\n # print(json.dumps(response))\n for result in response.results:\n print('Transcript: {}'.format(result.alternatives[0].transcript))\n\ntranscribe_file(\"out2.wav\")\n\n#key ya29.GlzqBHVSZ965WcJ-9btV6BxbgkbrZNFasUIgwl_h2S8W8x836prUwWqQh5FEC3PFAUckN7aIwcZHa4ve7IKDJ55jf0kck0VW4VeN6QXMcnWQMpW5S4j-h06Ctecptw","sub_path":"testCloudConn.py","file_name":"testCloudConn.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"127800298","text":"# Class object stores the movie related information\nclass Movie():\n # Constructor for initiating the value of variables\n def __init__(self,\n movie_name,\n movie_storyline,\n movie_poster,\n movie_trailer):\n \"\"\"\n :param movie_title: string\n :param movie_storyline: string\n :param poster_image: string\n :param trailer_youtube: string\n \"\"\"\n self.title = movie_name\n self.storyline = movie_storyline\n self.poster_image_url = movie_poster\n self.trailer_youtube_url = movie_trailer\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"603251359","text":"from django.shortcuts import render,redirect\nfrom .models import Book, Genres\nfrom .forms import NewUserForm\n\nfrom django.core.paginator import Paginator\n\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import logout, authenticate, login\nfrom django.contrib import messages\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport tensorflow as tf\nimport keras\nimport numpy as np\nimport pandas as pd\nfrom keras.models import Model\nfrom keras.models import model_from_json\nfrom keras import backend as K\n\nK.clear_session()\n\nwith open('scripts/model.json', 'r') as json_file:\n loaded_model_json = json_file.read()\n\nloaded_model = model_from_json(loaded_model_json)\nloaded_model.load_weights(\"scripts/model.h5\")\nprint(\"Loaded model from disk\")\nloaded_model.compile('adam', 'mean_squared_error')\n\ngenres = ['Fiction', 'Fantasy', 'Romance', 'Young Adult', 'Historical', 'Paranormal', 'Mystery', 'Nonfiction', 'Science Fiction', \n'Historical Fiction', 'Classics', 'Contemporary', 'Childrens', 'Cultural', 'Literature', 'Sequential Art', 'Thriller', 'European Literature', \n'Religion', 'History', 'Biography', 'Humor', 'Horror', 'Novels', 'Adventure', 'Crime', 'Contemporary Romance', 'Autobiography', 'Philosophy', \n'War', 'Short Stories', 'Christian', 'Paranormal Romance', 'Vampires', 'Comics', 'Womens Fiction', 'Memoir', 'Chick Lit', 'Erotica', 'Science']\n\n\n\nclass Home:\n def home(request):\n print (\"**************Going to the Home Page**************\")\n return render(request, 'books/home.html', {})\n\nclass Search:\n def search_books(request):\n return render(request, 'books/search.html', {})\n\n def search(request):\n query = request.GET.get('search_value')\n book_list = Book.objects.filter(title__contains=query)\n genres = Genres.objects.all()\n\n page = request.GET.get('page', 1)\n\n paginator = Paginator(book_list, 1000)\n try:\n books = paginator.page(page)\n except PageNotAnInteger:\n books = paginator.page(1)\n except EmptyPage:\n books = paginator.page(paginator.num_pages)\n\n return render(request, 'books/all_books.html', {'books':books,'genres':genres,'focus_genre':\"False\",'search_header':f\"Search Results For: {query}\"})\n\nclass Find_Books:\n def all_books(request):\n book_list = Book.objects.all()\n genres = Genres.objects.all()\n \n page = request.GET.get('page', 1)\n\n paginator = Paginator(book_list, 1000)\n try:\n books = paginator.page(page)\n except PageNotAnInteger:\n books = paginator.page(1)\n except EmptyPage:\n books = paginator.page(paginator.num_pages)\n\n return render(request, 'books/all_books.html', {'books':books,'genres':genres,'focus_genre':\"False\"})\n\n def sort_books_genre(request,request_genre):\n if request_genre in genres:\n book_list = Book.objects.filter(genres__contains=request_genre)\n genre = Genres.objects.all()\n\n page = request.GET.get('page', 1)\n\n paginator = Paginator(book_list, 1000)\n try:\n books = paginator.page(page)\n except PageNotAnInteger:\n books = paginator.page(1)\n except EmptyPage:\n books = paginator.page(paginator.num_pages)\n\n return render(request, 'books/all_books.html', {'books':books,'genres':genre,'focus_genre':request_genre})\n else:\n return redirect('all_books')\n\nclass Book_Functions:\n def about_book(request,pk,status=False):\n book = Book.objects.get(pk=pk)\n return render(request, 'books/about_books.html', {'book':book})\n\n def add_to_wishlist(request,pk,status=False):\n book = Book.objects.get(pk=pk)\n book.status = \"To Read\"\n book.current_page = 0\n book.save()\n book.publish()\n print (book.pk)\n return redirect('about_book', pk=book.pk)\n\n def remove_from_wishlist(request,pk,status=False):\n book = Book.objects.get(pk=pk)\n book.status = \"Not Read\"\n book.current_page = 0\n book.save()\n book.publish()\n print (book.pk)\n return redirect('about_book', pk=book.pk)\n\n\n def currently_reading(request,pk,status=False):\n book = Book.objects.get(pk=pk)\n book.status = \"Reading\"\n book.save()\n book.publish()\n print (book.pk)\n return redirect('about_book', pk=book.pk)\n\n def change_current_page(request,pk,status=\"In Progress\"):\n\n if status==\"In Progress\":\n book = Book.objects.get(pk=pk)\n return render(request, 'books/about_books.html', {'book':book,'flag':\"In Progress\"})\n else:\n book = Book.objects.get(pk=pk)\n book.current_page = request.GET.get('new_page')\n book.save()\n book.publish()\n print (book.pk)\n return redirect('about_book', pk=book.pk)\n\nclass Services:\n def services(request):\n return render(request, 'books/services.html', {})\n\nclass Registration:\n def register(request):\n if request.method == \"POST\":\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f\"New account created: {username}\")\n login(request, user)\n return redirect(\"home\")\n\n else:\n for msg in form.error_messages:\n messages.error(request, f\"{msg}: {form.error_messages[msg]}\")\n\n return render(request = request,\n template_name = \"registration/signup.html\",\n context={\"form\":form})\n\n form = UserCreationForm\n return render(request = request,\n template_name = \"registration/signup.html\",\n context={\"form\":form})\n\n def login_request(request):\n if request.method == 'POST':\n form = AuthenticationForm(request=request, data=request.POST)\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n messages.info(request, f\"You are now logged in as {username}\")\n return redirect('home')\n else:\n messages.error(request, \"Invalid username or password.\")\n else:\n messages.error(request, \"Invalid username or password.\")\n form = AuthenticationForm()\n return render(request = request,\n template_name = \"registration/login.html\",\n context={\"form\":form})\n def logout_request(request):\n logout(request)\n messages.info(request, \"Logged out successfully!\")\n return redirect(\"home\")\n\n\n\nclass User_Book_Data:\n def select_user_preferences(request):\n book_list = Book.objects.all()\n \n page = request.GET.get('page', 1)\n\n paginator = Paginator(book_list, 1000)\n try:\n books = paginator.page(page)\n except PageNotAnInteger:\n books = paginator.page(1)\n except EmptyPage:\n books = paginator.page(paginator.num_pages)\n\n return render(request, 'books/user_select_books.html', {\"books\":books})\n\n @csrf_exempt\n def handle_selected_books(request):\n selected_books = request.POST.getlist(\"selected[]\")\n print(selected_books)\n return HttpResponse('Success')\n\nclass Read_Books:\n def read_books(request):\n books = Book.objects.all()[:500]\n return render(request, 'books/read_books.html', {'books':books})\n\n def select_read_books(request):\n books = Book.objects.all()[:500]\n return render(request, 'books/read_books.html', {'books':books})\n\n \nclass Recommend_Books:\n def predictions(request):\n #get user_data\n user_data = np.array([1 for i in range(10000)])\n\n dataset = pd.read_csv('scripts/goodbooks-10k-master/ratings.csv')\n book_data = np.array(list(set(dataset.book_id)))\n books = pd.read_csv('scripts/goodbooks-10k-master/books.csv')\n\n user = np.array(user_data) #[1,1,0,1,0,0,0......0,1,1]\n predictions = loaded_model.predict([user, book_data])\n predictions = np.array([a[0] for a in predictions])\n recommended_book_ids = (-predictions).argsort()[:100]\n\n output = books[books['book_id'].isin(recommended_book_ids)]\n\n K.clear_session()\n\n books = Book.objects.filter(goodreads_book_id__in = list(output.goodreads_book_id))\n\n\n return render(request, 'books/all_books.html', {'books':books,'search_header':\"Your Recommendations\"})\n\n \n#{% url 'sort_books_genre' request_genre=gen.genre %}\n\n\n\n\n\n\n\n\n\n\n# Create your views here.\n","sub_path":"books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"251924014","text":"__author__ = 'Martin'\n\nfrom django.conf.urls import patterns, include, url\nfrom MedicalHistory import views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = patterns('',\n url(r'^appointments/$', views.appointments, name='appointments'),\n url(r'^appointments/new/$', views.appointment_add, name='appointment_new'),\n url(r'^appointments/(?P\\d+)/edit/$', views.appointment_edit, name='appointment_edit'),\n url(r'^appointments/(?P\\d+)/remove/$', views.appointment_remove, name='appointment_remove'),\n ##########\n #Calendar#\n ##########\n url(r'^appointments/month/(\\d+)/(\\d+)/(prev|next)/$', views.appointments, name=\"month\"),\n url(r'^appointments/month/(\\d+)/(\\d+)/$', views.appointments, name=\"month\"),\n url(r'^appointments/month$', views.appointments, name=\"month\"),\n url(r'^appointments/day/(\\d+)/(\\d+)/(\\d+)/$', views.day, name=\"day\"),\n\n url(r'^(?P\\w+)/prescriptions/$', views.prescriptions, name='prescriptions'),\n url(r'^(?P\\w+)/prescriptions/new/$', views.prescription_add, name='prescription_new'),\n url(r'^(?P\\w+)/prescriptions/(?P\\d+)/edit/$', views.prescription_edit, name='prescription_edit'),\n url(r'^(?P\\w+)/prescriptions/(?P\\d+)/remove/$', views.prescription_remove, name='prescription_remove'),\n\n url(r'^(?P\\w+)/insurance/$', views.insurance, name='insurance'),\n url(r'^(?P\\w+)/insurance/edit/$', views.insurance_edit, name='insurance_edit'),\n url(r'^(?P\\w+)/insurance/create/$', views.insurance_new, name='insurance_new'),\n\n url(r'^(?P\\w+)/conditions/$', views.conditions, name='conditions'),\n url(r'^(?P\\w+)/conditions/(?P\\d+)/edit/$', views.conditions_edit, name='conditions_edit'),\n url(r'^(?P\\w+)/conditions/new/$', views.conditions_new, name='conditions_new'),\n\n url(r'^(?P\\w+)/tests/$', views.test_results, name='tests'),\n url(r'^(?P\\w+)/tests/(?P\\d+)/remove/$', views.test_remove, name='test_remove'),\n url(r'^(?P\\w+)/tests/(?P\\d+)/toggle/$', views.test_release_toggle, name='test_toggle'),\n url(r'^(?P\\w+)/tests/(?P\\d+)/edit/$', views.test_edit, name='test_edit'),\n url(r'^(?P\\w+)/tests/new/$', views.test_create, name='test_new'),\n\n url(r'^(?P\\w+)/export/$', views.export, name='export'),\n )","sub_path":"HealthNet/Team-A_HealthNetR2/MedicalHistory/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"70546695","text":"# coding: utf-8\n\n\"\"\"\n DocuSign REST API\n\n The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.\n\n OpenAPI spec version: v2\n\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport os\nimport unittest\n\nfrom docusign_esign.client.api_client import ApiClient\nfrom docusign_esign.client.auth.oauth import OAuthToken\n\n\nclass TestConfig(object):\n def __init__(self, user_name=None, client_secret =None, user_id=None, password=None, integrator_key=None, host=None, recipient_email=None,\n recipient_name=None, template_role_name=None, template_id=None, return_url=None, redirect_uri=None):\n self.user_name = user_name if user_name else \"node_sdk@mailinator.com\"\n self.password = password if password else \"qweqweasd\"\n self.client_secret = client_secret if client_secret else \"3b61ffcf-8f76-4cf8-b541-d49f7d82cb55\"\n self.integrator_key = integrator_key if integrator_key else \"ae30ea4e-3959-4d1c-b867-fcb57d2dc4df\"\n self.host = host if host else \"https://demo.docusign.net/restapi\"\n self.recipient_email = recipient_email if recipient_email else \"node_sdk@mailinator.com\"\n self.recipient_name = recipient_name if recipient_name else \"node_sdk@mailinator.com\"\n self.template_role_name = template_role_name if template_role_name else \"node_sdk@mailinator.com\"\n self.template_id = template_id if template_id else \"cf2a46c2-8d6e-4258-9d62-752547b1a419\"\n self.return_url = return_url if return_url else \"node_sdk@mailinator.com\"\n self.user_id = user_id if user_id else \"fcc5726c-cd73-4844-b580-40bbbe6ca126\"\n self.redirect_uri = redirect_uri if redirect_uri else \"http://38a36d7b.ngrok.io\"\n\n self.oauth_host_name = \"account-d.docusign.com\"\n self.private_key_file_name = \"{}/keys/private.pem\".format(os.path.dirname(os.path.abspath(__file__)))\n self.expires_in_hours = 1\n\n # this.IntegratorKeyNoConsent = \"66750331-ee4b-4ab8-b8ee-6c1a413a6096\";\n # this.PrivateKeyNoConsentFilename = \"../../docs/privateKeyConsentReq.pem\";\n\n\nclass TestOauth(unittest.TestCase):\n \"\"\" AccountBillingPlan unit test stubs \"\"\"\n\n def setUp(self):\n self.test_config = TestConfig()\n self.api_client = ApiClient(oauth_host_name=self.test_config.oauth_host_name)\n self.api_client.set_base_path(\"https://demo.docusign.net\")\n self.api_client.set_oauth_host_name(self.test_config.oauth_host_name)\n\n def test_oauth_uri(self):\n self.api_client.get_oauth_host_name()\n uri = self.api_client.get_authorization_uri(client_id=self.test_config.integrator_key,\n redirect_uri=self.test_config.redirect_uri,\n scopes=[\"signature\", \"impersonation\"],\n response_type='code')\n self.assertTrue(isinstance(uri, str))\n self.api_client.rest_client.pool_manager.clear()\n\n def test_jwt_application(self):\n with open(self.test_config.private_key_file_name, 'r') as private_key:\n token_obj = self.api_client.request_jwt_application_token(client_id=self.test_config.integrator_key,\n oauth_host_name=self.test_config.oauth_host_name,\n private_key_bytes=private_key.read(),\n expires_in=self.test_config.expires_in_hours)\n self.assertTrue(isinstance(token_obj, OAuthToken))\n self.api_client.rest_client.pool_manager.clear()\n\n def test_jwt_user(self):\n with open(self.test_config.private_key_file_name, 'r') as private_key:\n token_obj = self.api_client.request_jwt_user_token(client_id=self.test_config.integrator_key,\n user_id=self.test_config.user_id,\n oauth_host_name=self.api_client.get_oauth_host_name(),\n private_key_bytes=private_key.read(),\n expires_in=self.test_config.expires_in_hours\n )\n self.assertTrue(isinstance(token_obj, OAuthToken))\n self.api_client.rest_client.pool_manager.clear()\n\n def test_authorization_code_login(self):\n self.api_client.get_oauth_host_name()\n uri = self.api_client.get_authorization_uri(client_id=self.test_config.integrator_key,\n redirect_uri=self.test_config.redirect_uri,\n scopes=[\"signature\"],\n response_type='code')\n self.assertTrue(isinstance(uri, str))\n\n # import webbrowser\n # from docusign_esign.client.auth.oauth.user_info import UserInfo\n # webbrowser.open(uri)\n #\n # # IMPORTANT: after the login, DocuSign will send back a fresh\n # # authorization code as a query param of the redirect URI.\n # # You should set up a route that handles the redirect call to get\n # # that code and pass it to token endpoint as shown in the next\n # # lines:\n # #\n # code = \"code\"\n # token_obj = self.api_client.generate_access_token(self.test_config.integrator_key, self.test_config.client_secret, code)\n # self.assertTrue(isinstance(token_obj, OAuthToken))\n #\n # self.api_client.set_access_token(token_obj)\n # user_info = self.api_client.get_user_info(token_obj.access_token)\n # self.assertTrue(isinstance(user_info, UserInfo))\n self.api_client.rest_client.pool_manager.clear()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_oauth.py","file_name":"test_oauth.py","file_ext":"py","file_size_in_byte":6056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"54216362","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport tweepy\nimport datetime as dt\nfrom configparser import ConfigParser\nimport pandas as pd\nimport csv\n\nconfig = ConfigParser()\nconfig.read('twitter.conf')\n\nusernames = ['cardinals_pbp',\n 'bears_pbp',\n 'packers_pbp',\n 'giants_pbp',\n 'lions_pbp',\n 'redskins_pbp',\n 'eagles_pbp',\n 'steelers_pbp',\n 'rams_pbp',\n '49ers_pbp',\n 'browns_pbp',\n 'colts_pbp',\n 'cowboys_pbp',\n 'chiefs_pbp',\n 'chargers_pbp',\n 'broncos_pbp',\n 'jets_pbp',\n 'patriots_pbp',\n 'raiders_pbp',\n 'titans_pbp',\n 'bills_pbp',\n 'vikings_pbp',\n 'falcons_pbp',\n 'dolphins_pbp',\n 'saints_pbp',\n 'bengals_pbp',\n 'seahawks_pbp',\n 'bucs_pbp',\n 'panthers_pbp',\n 'jaguars_pbp',\n 'ravens_pbp',\n 'texans_pbp']\n\ndef get_all_tweets(screen_name):\n #Twitter only allows access to a users most recent 3240 tweets with this method\n\n #authorize twitter, initialize tweepy\n auth = tweepy.OAuthHandler(consumer_key=config['TWITTER']['CONSUMER_KEY'],\n consumer_secret=config['TWITTER']['CONSUMER_SECRET'])\n auth.set_access_token(key=config['TWITTER']['ACCESS_TOKEN'],\n secret=config['TWITTER']['ACCESS_SECRET'])\n api = tweepy.API(auth)\n\n #initialize a list to hold all the tweepy Tweets\n alltweets = []\n\n #make initial request for most recent tweets (200 is the maximum allowed count)\n new_tweets = api.user_timeline(screen_name = screen_name,count=200)\n\n #save most recent tweets\n alltweets.extend(new_tweets)\n\n #save the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n\n #keep grabbing tweets until there are no tweets left to grab\n while len(new_tweets) > 0:\n print(\"getting tweets before {}\".format(oldest))\n\n #all subsiquent requests use the max_id param to prevent duplicates\n new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)\n\n #save most recent tweets\n alltweets.extend(new_tweets)\n\n #update the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n\n print(\"...{} tweets downloaded so far\".format(len(alltweets)))\n\n #transform the tweepy tweets into a 2D array that will populate the csv\n outtweets = [[tweet.id_str,\n tweet.created_at,\n tweet.text.replace(',','').replace(';',''),\n tweet.user.screen_name,\n tweet.user.location,\n tweet.user.time_zone,\n tweet.source,\n tweet.retweet_count,\n tweet.favorite_count] for tweet in alltweets]\n\n #write the csv\n with open('{}_tweets.csv'.format(screen_name), 'w') as f:\n writer = csv.writer(f)\n writer.writerow([\"id\",\n \"created_at\",\n \"text\",\n \"screen_name\",\n \"location\",\n \"time_zone\",\n \"source\",\n \"retweet_count\",\n \"favorite_count\"])\n writer.writerows(outtweets)\n\n pass\n\nfor username in usernames:\n get_all_tweets(screen_name=username)\n","sub_path":"notebooks/Scrape_Twitter_Posts/Scrape_Twitter_Play_by_Play.py","file_name":"Scrape_Twitter_Play_by_Play.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"483079370","text":"from ppo_algorithm import *\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\nimport optuna\nfrom optuna.visualization import plot_optimization_history\n\n\n# %% The function to train and tune hyperparameters\n\n# Help function to plot experiments of the Q-Learning training\ndef visualise_training(all_iterations, all_avg_rewards, all_var_rewards, all_avg_action_counts, best_params):\n # Crete dataframe\n df = pd.DataFrame(zip(all_iterations, all_avg_rewards, all_var_rewards, all_avg_action_counts),\n columns=['iteration', 'avg_reward', 'var_reward', 'avg_action_count'])\n\n # Define the optimal parameters from tuning\n best_n_layers = best_params['n_layers']\n best_hidden_size = best_params['hidden_size']\n best_learning_rate = best_params['learning_rate']\n best_gamma = best_params['gamma']\n best_multiplier = best_params['multiplier']\n\n # Plot the PPO training graphs (the values from running experiments 100 times at every 10 iterations)\n fig, axs = plt.subplots(3, 1, sharex=True, figsize=(12, 10))\n fig.suptitle('PPO Learning Plots with the Optimal Hyperparameters', fontsize=22)\n\n axs[0].plot(df['iteration'], df['avg_reward'])\n axs[0].set_title(f'(Hidden Layers: {best_n_layers}, Hidden Size: {best_hidden_size}, '\n f'Learning Rate: {best_learning_rate:.4f}, Gamma: {best_gamma:.4f}, '\n f'Multiplier: {best_multiplier})', fontsize=14)\n axs[0].set_ylabel('Avg. Reward', fontsize=14)\n\n axs[1].plot(df['iteration'], df['var_reward'])\n axs[1].set_ylabel('Var. Reward', fontsize=14)\n\n axs[2].plot(df['iteration'], df['avg_action_count'])\n axs[2].set_ylabel('Avg. Action C.', fontsize=14)\n axs[2].set_xlabel('Iterations', fontsize=14)\n fig.tight_layout()\n plt.show()\n\n\nif __name__ == '__main__':\n\n # Define an objective function to tune hyperparameters by Optuna framework\n # (similar to random search but it's better)\n def objective(trial):\n # Define tuning parameters\n params = {\n 'n_layers': trial.suggest_int('n_layers', 1, 2),\n 'hidden_size': trial.suggest_categorical('hidden_size', [64, 128, 256, 512]),\n 'learning_rate': trial.suggest_loguniform('learning_rate', 1e-4, 1e-2),\n 'gamma': trial.suggest_uniform('gamma', 0.2, 0.8),\n 'multiplier': trial.suggest_int('multiplier', 3, 5)\n }\n\n best_avg_reward_per_action, _, _, _, _ = PPO(dungeon, params).learning(save_model=False)\n\n return best_avg_reward_per_action\n\n # Define the environment\n dungeon = IceDungeonPO(10)\n dungeon.reset()\n\n # Save the environment for evaluating the results\n FILENAME_ENV = open('dungeon_' + str(dungeon.size) + '.p', 'wb')\n pickle.dump(dungeon, FILENAME_ENV)\n FILENAME_ENV.close()\n\n # Create a study object and optimise the objective function\n study = optuna.create_study(direction='maximize')\n\n # Limit tuning iteration at 5 times\n study.optimize(objective, n_trials=5)\n\n print('\\nBest trial:')\n trial_ = study.best_trial\n\n print('Best parameters:', trial_.params)\n\n # Training with the optimal hyperparameters\n _, iter_lst, avg_r_lst, var_r_lst, avg_ac_lst = PPO(dungeon, trial_.params).learning(save_model=True)\n\n # Visualise the optimisation history\n plot_optimization_history(study)\n\n # Visualise experiments of the Q-Learning training\n visualise_training(iter_lst, avg_r_lst, var_r_lst, avg_ac_lst, trial_.params)\n","sub_path":"4_Deep_Reinforcement_Learning/Task3/.ipynb_checkpoints/training_evaluating-checkpoint.py","file_name":"training_evaluating-checkpoint.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"88538993","text":"import time\r\nimport random\r\nimport requests\r\nimport telepot\r\n\r\nfrom telepot.loop import MessageLoop\r\n\r\nsh = [\"هههههههههههههههههههههههههههههههههههههه\",\"كسمك يلا\",\"احا\",\"كسمك يطيز يهبل\",\"خ ـؤد يڪسم ـڪ فينڪ ڪدآ ♡\",\"ڪسم ـڪ يڪلب\",\"رد يعلق\",\"زبي\",\"يكسمك مص\",\"زبي اهو ياض\",\"كسمك ياض\",\"كسمك وكسم الكسم\",\"رد\",\"رد بس يت فينك\",\"احا\",\"عبرني يعرص\",\"كسمك رد\",\"كسمين امك رد\",\"زبي زبي\",\"في طيزك يعرص\",\"كسم كدا\",\"نا زهقت\",\"احا\",\"كسمك يبز\",\"كسمك يطيز يهبل\",\"ڪسم ـڪ يڪلب\",\"ههكسكك\",\"كسمك\",\"كسك وردي\",\"ايوا وري كسسمك\",\"كسسسمين امك\",\"رد يبز\",\"يطيز\",\"يكتساه\",\"كسمك نا زهقت\",\"كسمك لاجل كيمو\",\"كسمك لاجل زبي\",\"كسمك لاجل الفيس\",\"كسمك لاجل الواتس\",\"كسمك لاجل حببتي\",\"ههههههههههههههههههههههههههههههههههههه\",\"كسمك لاجل انك خورم\",\"كسمك لاجل وسام اخبا\",\"سكس يكسمك\"]\r\n\r\n\r\ndef substr(string, start, length = None):\r\n if start < 0:\r\n start = start + len(string)\r\n if not length:\r\n return string[start:]\r\n elif length > 0:\r\n return string[start:start + length]\r\n else:\r\n return string[start:length]\r\n\r\n\r\n\r\ndef bot_msg(msg):\r\n chat_user = msg['from']['username']\r\n command = msg['text']\r\n a = msg['text']\r\n command = msg['text']\r\n a = msg['text']\r\n chat_id = msg['chat']['id']\r\n one = a.find('-i ')+3\r\n one2 = a.find('-u') - one - 1\r\n one3 = substr(a, one, one2)\r\n two = a.find('-u ')+3\r\n two2 = a.find('-m') - two - 1\r\n two3 = substr(a, two, two2)\r\n three = a.find('-m ')+3\r\n three2 = a.find(';') - three \r\n three3 = substr(a, three, three2)\r\n string = '/start -i '+one3+' -u '+two3+' -m '+three3+';'\r\n \r\n if a.find('-i ') == 7:\r\n if chat_user == 'KEMO3309':\r\n if string in a:\r\n for a in range(int(three3)):\r\n l = random.randint(0, 43)\r\n ta = sh[l]\r\n a = ta+' {}'.format(two3)\r\n requests.post('https://api.telegram.org/bot1493300654:AAGqGYdVALdO9zoPRLUiCPtrchMYfwGhGyU/sendMessage', {'chat_id':one3, 'text':a})\r\n time.sleep(2)\r\n else:\r\n bot.sendMessage(chat_id, 'wrong syntax')\r\n\r\n elif chat_user == 'Y_n_w':\r\n if string in a:\r\n for a in range(int(three3)):\r\n l = random.randint(0, 43)\r\n ta = sh[l]\r\n a = ta+' {}'.format(two3)\r\n requests.post('https://api.telegram.org/bot1493300654:AAGqGYdVALdO9zoPRLUiCPtrchMYfwGhGyU/sendMessage', {'chat_id':one3, 'text':a})\r\n time.sleep(2)\r\n else:\r\n bot.sendMessage(chat_id, 'wrong syntax')\r\n\r\n\r\n elif chat_user == 'V_3_X':\r\n if string in a:\r\n for a in range(int(three3)):\r\n l = random.randint(0, 43)\r\n ta = sh[l]\r\n a = ta+' {}'.format(two3)\r\n requests.post('https://api.telegram.org/bot1493300654:AAGqGYdVALdO9zoPRLUiCPtrchMYfwGhGyU/sendMessage', {'chat_id':one3, 'text':a})\r\n time.sleep(2)\r\n else:\r\n bot.sendMessage(chat_id, 'wrong syntax')\r\n else:\r\n bot.sendMessage(chat_id, 'Hi There \\nsorry you are not admin')\r\n\r\n else:\r\n if command == '/group':\r\n types = msg['chat']['type']\r\n group = msg['chat']['title']\r\n types = msg['chat']['type']\r\n replay='Hi There ! \\nchat name : {}\\nchat type : {}\\nchat id : {}\\nsee you soon @{}' .format(group, types, chat_id, chat_user)\r\n bot.sendMessage(chat_id, replay)\r\n elif command == '/personal':\r\n chats = msg['from']['id']\r\n replay='Hi There ! \\nyour id : {}\\nsee you soon @{}' .format(chats, chat_user)\r\n bot.sendMessage(chat_id, replay)\r\n\r\n\r\n elif command == '/start':\r\n chats = msg['from']['id']\r\n alls = str(chats)+' from '+chat_user\r\n replay='Hi There'\r\n bot.sendMessage(chat_id, replay)\r\n requests.post('https://api.telegram.org/bot1493300654:AAGqGYdVALdO9zoPRLUiCPtrchMYfwGhGyU/sendMessage', {'chat_id':'-1001338645871', 'text':alls})\r\n \r\n elif command == '/admins':\r\n replay=' admins: \\n@HQQQ0 && @KEMO3309'\r\n bot.sendMessage(chat_id, replay)\r\n \r\n if command == '/group@te7feelbot':\r\n group = msg['chat']['title']\r\n types = msg['chat']['type']\r\n replay='Hi There ! \\nchat name : {}\\nchat type : {}\\nchat id : {}\\nsee you soon @{}' .format(group, types, chat_id, chat_user)\r\n bot.sendMessage(chat_id, replay)\r\n\r\n elif command == '/personal@te7feelbot':\r\n chats = msg['from']['id']\r\n replay='Hi There ! \\nyour id : {}\\nsee you soon @{}' .format(chats, chat_user)\r\n bot.sendMessage(chat_id, replay)\r\n\r\n elif command == '/start@te7feelbot':\r\n chats = msg['from']['id']\r\n alls = str(chats)+' from @'+chat_user\r\n replay='Hi There'\r\n bot.sendMessage(chat_id, replay)\r\n requests.post('https://api.telegram.org/bot1493300654:AAGqGYdVALdO9zoPRLUiCPtrchMYfwGhGyU/sendMessage', {'chat_id':'-1001338645871', 'text':alls})\r\n\r\n elif command == '/admins@te7feelbot':\r\n replay=' admins: \\n@HQQQ0 && @KEMO3309'\r\n bot.sendMessage(chat_id, replay)\r\n\r\n\r\nbot = telepot.Bot('1493300654:AAGqGYdVALdO9zoPRLUiCPtrchMYfwGhGyU')\r\n\r\nMessageLoop(bot, bot_msg).run_as_thread()\r\nwhile 1:\r\n\r\n time.sleep(1)\r\n","sub_path":"kamal4.py","file_name":"kamal4.py","file_ext":"py","file_size_in_byte":6084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"570373409","text":"# -*- coding: utf-8 -*- #\n# Copyright 2016 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utilities for the cloudbuild API.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport re\nfrom apitools.base.protorpclite import messages as proto_messages\nfrom apitools.base.py import encoding as apitools_encoding\nfrom googlecloudsdk.api_lib.util import apis\nfrom googlecloudsdk.core import exceptions\nfrom googlecloudsdk.core import yaml\nfrom googlecloudsdk.core.resource import resource_property\nfrom googlecloudsdk.core.util import files\n\nimport six\n\n_API_NAME = 'cloudbuild'\n_API_VERSION = 'v1'\n_ALPHA_API_VERSION = 'v1alpha2'\n\nWORKERPOOL_NAME_MATCHER = r'projects/.*/workerPools/.*'\nWORKERPOOL_NAME_SELECTOR = r'projects/.*/workerPools/(.*)'\n\n\ndef GetMessagesModule():\n return apis.GetMessagesModule(_API_NAME, _API_VERSION)\n\n\ndef GetClientClass():\n return apis.GetClientClass(_API_NAME, _API_VERSION)\n\n\ndef GetClientInstance(use_http=True):\n return apis.GetClientInstance(_API_NAME, _API_VERSION, no_http=(not use_http))\n\n\ndef GetMessagesModuleAlpha():\n return apis.GetMessagesModule(_API_NAME, _ALPHA_API_VERSION)\n\n\ndef GetClientClassAlpha():\n return apis.GetClientClass(_API_NAME, _ALPHA_API_VERSION)\n\n\ndef GetClientInstanceAlpha(use_http=True):\n return apis.GetClientInstance(\n _API_NAME, _ALPHA_API_VERSION, no_http=(not use_http))\n\n\ndef EncodeSubstitutions(substitutions, messages):\n if not substitutions:\n return None\n substition_properties = []\n # TODO(b/35470611): Use map encoder function instead when implemented\n for key, value in sorted(six.iteritems(substitutions)): # Sort for tests\n substition_properties.append(\n messages.Build.SubstitutionsValue.AdditionalProperty(\n key=key, value=value))\n return messages.Build.SubstitutionsValue(\n additionalProperties=substition_properties)\n\n\ndef EncodeTriggerSubstitutions(substitutions, messages):\n if not substitutions:\n return None\n substition_properties = []\n for key, value in sorted(six.iteritems(substitutions)): # Sort for tests\n substition_properties.append(\n messages.BuildTrigger.SubstitutionsValue.AdditionalProperty(\n key=key, value=value))\n return messages.BuildTrigger.SubstitutionsValue(\n additionalProperties=substition_properties)\n\n\nclass ParserError(exceptions.Error):\n \"\"\"Error parsing YAML into a dictionary.\"\"\"\n\n def __init__(self, path, msg):\n msg = 'parsing {path}: {msg}'.format(\n path=path,\n msg=msg,\n )\n super(ParserError, self).__init__(msg)\n\n\nclass ParseProtoException(exceptions.Error):\n \"\"\"Error interpreting a dictionary as a specific proto message.\"\"\"\n\n def __init__(self, path, proto_name, msg):\n msg = 'interpreting {path} as {proto_name}: {msg}'.format(\n path=path,\n proto_name=proto_name,\n msg=msg,\n )\n super(ParseProtoException, self).__init__(msg)\n\n\ndef SnakeToCamelString(snake):\n \"\"\"Change a snake_case string into a camelCase string.\n\n Args:\n snake: str, the string to be transformed.\n\n Returns:\n str, the transformed string.\n \"\"\"\n parts = snake.split('_')\n if not parts:\n return snake\n\n # Handle snake with leading '_'s by collapsing them into the next part.\n # Legit field names will never look like this, but completeness of the\n # function is important.\n leading_blanks = 0\n for p in parts:\n if not p:\n leading_blanks += 1\n else:\n break\n if leading_blanks:\n parts = parts[leading_blanks:]\n if not parts:\n # If they were all blanks, then we over-counted by one because of split\n # behavior.\n return '_' * (leading_blanks - 1)\n parts[0] = '_' * leading_blanks + parts[0]\n\n return ''.join(parts[:1] + [s.capitalize() for s in parts[1:]])\n\n\ndef SnakeToCamel(msg, skip=None):\n \"\"\"Recursively transform all keys and values from snake_case to camelCase.\n\n If a key is in skip, then its value is left alone.\n\n Args:\n msg: dict, list, or other. If 'other', the function returns immediately.\n skip: contains dict keys whose values should not have camel case applied.\n\n Returns:\n Same type as msg, except all strings that were snake_case are now CamelCase,\n except for the values of dict keys contained in skip.\n \"\"\"\n if skip is None:\n skip = []\n if isinstance(msg, dict):\n return {\n SnakeToCamelString(key):\n (SnakeToCamel(val, skip) if key not in skip else val)\n for key, val in six.iteritems(msg)\n }\n elif isinstance(msg, list):\n return [SnakeToCamel(elem, skip) for elem in msg]\n else:\n return msg\n\n\ndef MessageToFieldPaths(msg):\n \"\"\"Produce field paths from a message object.\n\n The result is used to create a FieldMask proto message that contains all field\n paths presented in the object.\n https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto\n\n Args:\n msg: An user defined message object that extends the messages.Message class.\n https://github.com/google/apitools/blob/master/apitools/base/protorpclite/messages.py\n\n Returns:\n The list of field paths.\n \"\"\"\n fields = []\n for field in msg.all_fields():\n v = msg.get_assigned_value(field.name)\n if field.repeated and not v:\n # Repeated field is initialized as an empty list.\n continue\n if v is not None:\n name = resource_property.ConvertToSnakeCase(field.name)\n if hasattr(v, 'all_fields'):\n # message has sub-messages, constructing subpaths.\n for f in MessageToFieldPaths(v):\n fields.append('{}.{}'.format(name, f))\n else:\n fields.append(name)\n return fields\n\n\ndef _UnpackCheckUnused(obj, msg_type):\n \"\"\"Stuff a dict into a proto message, and fail if there are unused values.\n\n Args:\n obj: dict(), The structured data to be reflected into the message type.\n msg_type: type, The proto message type.\n\n Raises:\n ValueError: If there is an unused value in obj.\n\n Returns:\n Proto message, The message that was created from obj.\n \"\"\"\n msg = apitools_encoding.DictToMessage(obj, msg_type)\n\n def _CheckForUnusedFields(obj):\n \"\"\"Check for any unused fields in nested messages or lists.\"\"\"\n if isinstance(obj, proto_messages.Message):\n unused_fields = obj.all_unrecognized_fields()\n if unused_fields:\n if len(unused_fields) > 1:\n # Because this message shows up in a dotted path, use braces.\n # eg .foo.bar.{x,y,z}\n unused_msg = '{%s}' % ','.join(sorted(unused_fields))\n else:\n # For single items, omit the braces.\n # eg .foo.bar.x\n unused_msg = unused_fields[0]\n raise ValueError('.%s: unused' % unused_msg)\n for used_field in obj.all_fields():\n try:\n field = getattr(obj, used_field.name)\n _CheckForUnusedFields(field)\n except ValueError as e:\n raise ValueError('.%s%s' % (used_field.name, e))\n if isinstance(obj, list):\n for i, item in enumerate(obj):\n try:\n _CheckForUnusedFields(item)\n except ValueError as e:\n raise ValueError('[%d]%s' % (i, e))\n\n _CheckForUnusedFields(msg)\n\n return msg\n\n\ndef LoadMessageFromStream(stream,\n msg_type,\n msg_friendly_name,\n skip_camel_case=None,\n path=None):\n \"\"\"Load a proto message from a stream of JSON or YAML text.\n\n Args:\n stream: file-like object containing the JSON or YAML data to be decoded.\n msg_type: The protobuf message type to create.\n msg_friendly_name: A readable name for the message type, for use in error\n messages.\n skip_camel_case: Contains proto field names or map keys whose values should\n not have camel case applied.\n path: str or None. Optional path to be used in error messages.\n\n Raises:\n ParserError: If there was a problem parsing the stream as a dict.\n ParseProtoException: If there was a problem interpreting the stream as the\n given message type.\n\n Returns:\n Proto message, The message that got decoded.\n \"\"\"\n if skip_camel_case is None:\n skip_camel_case = []\n # Turn the data into a dict\n try:\n structured_data = yaml.load(stream, file_hint=path)\n except yaml.Error as e:\n raise ParserError(path, e.inner_error)\n if not isinstance(structured_data, dict):\n raise ParserError(path, 'Could not parse as a dictionary.')\n\n return _YamlToMessage(structured_data, msg_type, msg_friendly_name,\n skip_camel_case, path)\n\n\ndef LoadMessagesFromStream(stream,\n msg_type,\n msg_friendly_name,\n skip_camel_case=None,\n path=None):\n \"\"\"Load multiple proto message from a stream of JSON or YAML text.\n\n Args:\n stream: file-like object containing the JSON or YAML data to be decoded.\n msg_type: The protobuf message type to create.\n msg_friendly_name: A readable name for the message type, for use in error\n messages.\n skip_camel_case: Contains proto field names or map keys whose values should\n not have camel case applied.\n path: str or None. Optional path to be used in error messages.\n\n Raises:\n ParserError: If there was a problem parsing the stream.\n ParseProtoException: If there was a problem interpreting the stream as the\n given message type.\n\n Returns:\n Proto message list of the messages that got decoded.\n \"\"\"\n if skip_camel_case is None:\n skip_camel_case = []\n # Turn the data into a dict\n try:\n structured_data = yaml.load_all(stream, file_hint=path)\n except yaml.Error as e:\n raise ParserError(path, e.inner_error)\n\n return [\n _YamlToMessage(item, msg_type, msg_friendly_name, skip_camel_case, path)\n for item in structured_data\n ]\n\n\ndef _YamlToMessage(structured_data,\n msg_type,\n msg_friendly_name,\n skip_camel_case=None,\n path=None):\n \"\"\"Load a proto message from a file containing JSON or YAML text.\n\n Args:\n structured_data: Dict containing the decoded YAML data.\n msg_type: The protobuf message type to create.\n msg_friendly_name: A readable name for the message type, for use in error\n messages.\n skip_camel_case: Contains proto field names or map keys whose values should\n not have camel case applied.\n path: str or None. Optional path to be used in error messages.\n\n Raises:\n ParseProtoException: If there was a problem interpreting the file as the\n given message type.\n\n Returns:\n Proto message, The message that got decoded.\n \"\"\"\n\n # Transform snake_case into camelCase.\n structured_data = SnakeToCamel(structured_data, skip_camel_case)\n\n # Then, turn the dict into a proto message.\n try:\n msg = _UnpackCheckUnused(structured_data, msg_type)\n except Exception as e:\n # Catch all exceptions here because a valid YAML can sometimes not be a\n # valid message, so we need to catch all errors in the dict to message\n # conversion.\n raise ParseProtoException(path, msg_friendly_name, '%s' % e)\n\n return msg\n\n\ndef LoadMessageFromPath(path,\n msg_type,\n msg_friendly_name,\n skip_camel_case=None):\n \"\"\"Load a proto message from a file containing JSON or YAML text.\n\n Args:\n path: The path to a file containing the JSON or YAML data to be decoded.\n msg_type: The protobuf message type to create.\n msg_friendly_name: A readable name for the message type, for use in error\n messages.\n skip_camel_case: Contains proto field names or map keys whose values should\n not have camel case applied.\n\n Raises:\n files.MissingFileError: If the file does not exist.\n ParserError: If there was a problem parsing the file as a dict.\n ParseProtoException: If there was a problem interpreting the file as the\n given message type.\n\n Returns:\n Proto message, The message that got decoded.\n \"\"\"\n with files.FileReader(path) as f: # Returns user-friendly error messages\n return LoadMessageFromStream(f, msg_type, msg_friendly_name,\n skip_camel_case, path)\n\n\ndef LoadMessagesFromPath(path,\n msg_type,\n msg_friendly_name,\n skip_camel_case=None):\n \"\"\"Load a proto message from a file containing JSON or YAML text.\n\n Args:\n path: The path to a file containing the JSON or YAML data to be decoded.\n msg_type: The protobuf message type to create.\n msg_friendly_name: A readable name for the message type, for use in error\n messages.\n skip_camel_case: Contains proto field names or map keys whose values should\n not have camel case applied.\n\n Raises:\n files.MissingFileError: If the file does not exist.\n ParseProtoException: If there was a problem interpreting the file as the\n given message type.\n\n Returns:\n Proto message list of the messages that got decoded.\n \"\"\"\n with files.FileReader(path) as f: # Returns user-friendly error messages\n return LoadMessagesFromStream(f, msg_type, msg_friendly_name,\n skip_camel_case, path)\n\n\ndef WorkerPoolShortName(resource_name):\n \"\"\"Turn a worker pool's full resource name into its short name (the ID).\n\n For example, this turns \"projects/abc/workerPools/def\" into \"def\".\n\n Args:\n resource_name: A Worker pool's full resource name.\n\n Raises:\n ValueError: If the full resource name was not well-formatted.\n\n Returns:\n The worker pool's short name.\n \"\"\"\n match = re.search(WORKERPOOL_NAME_SELECTOR, resource_name)\n if match:\n return match.group(1)\n raise ValueError('The worker pool resource name must match \"%s\"' %\n (WORKERPOOL_NAME_MATCHER,))\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/api_lib/cloudbuild/cloudbuild_util.py","file_name":"cloudbuild_util.py","file_ext":"py","file_size_in_byte":14361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"48362872","text":"from bs4 import BeautifulSoup as BS\nfrom urllib import urlopen\nimport pandas as pd\nlinks=[]\n\nteams=['ATL','BOS','BRK','CHO','CHI','CLE','DAL','DEN',\n 'DET','GSW', 'HOU','IND', 'LAC','LAL','MEM','MIA','MIL',\n 'MIN','NOP','NYK', 'OKC','ORL','PHI','PHO','POR','SAC','SAS','TOR','UTA',\n 'WAS']\nurl_template=\"http://www.basketball-reference.com/teams/{team}/2016_games.html\"\n\ngame_three_percentage=pd.DataFrame()\n\nfor team in teams:\n\n url=url_template.format(team=team)\n\n html=urlopen(url)\n\n soup=BS(html, \"html5lib\")\n\n soup_rows=soup.findAll('tbody', limit=1)[0].findAll('tr')\n\n \n \n for i in range(0,len(soup_rows)):\n \n \n if i!=20 and i!=41 and i!=62 and i!=83:\n tds=soup_rows[i]\n td=tds.findAll(\"td\")\n link=td[4].findAll('a')[0]['href']\n links.append(link)\n \n\nurl_template_two=\"http://www.basketball-reference.com/{link}\"\nfor link in links:\n row=[]\n url=url_template_two.format(link=link)\n html=urlopen(url)\n soup=BS(html,\"html5lib\")\n team_name=soup.findAll('h2')\n foot= soup.findAll('tfoot')\n \n \n row.append(team_name[0].getText())\n row.append(foot[0].findAll('td')[7].getText())\n row.append(team_name[1].getText())\n row.append(foot[2].findAll('td')[7].getText())\n \n \n df2=pd.DataFrame([row],columns=['team','3pt%','team','3pt%'])\n \n game_three_percentage=game_three_percentage.append(df2, ignore_index=True)\n\ngame_three_percentage.head()\n","sub_path":"3pt% game by game.py","file_name":"3pt% game by game.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"133545434","text":"from django.conf.urls.defaults import patterns, url\n\n\n\nurlpatterns = patterns('web.notes.views',\n url(r'^$', 'show', name='show'),\n url(r'^list', 'list', name='list'),\n url(r'^create', 'create', name='create'),\n url(r'^(?P\\d)/read', 'read', name='read'),\n url(r'^(?P\\d)/update', 'update', name='update'),\n url(r'^(?P\\d)/delete', 'delete', name='delete'),\n)\n\n","sub_path":"notes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"548688937","text":"#!/usr/bin/env python3\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom time import sleep\n\nimport neural_networks as mynn\nimport tools as t\n\ndef simulate(i, x_test, y_test):\n\n if i % 100 == 0:\n plt.clf()\n plt.title(\"Simulation, step: {}\".format(i))\n\n plt.scatter(x_test, y_test)\n\n plt.draw()\n plt.pause(0.001)\n\ndef main():\n type = \"square\"\n \n if type == \"square\":\n X = np.linspace(-50, 50, 26)\n\n y = np.array([[z**2] for z in X ])\n x = np.array([[z, 1.0] for z in X ])\n\n X_test = np.linspace(-50, 50, 101)\n x_test = np.array([[z, 1.0] for z in X_test])\n\n nn = mynn.NeuralNetworkSquare(x, y)\n simulation = True\n for i in range(100000):\n\n nn.feedforward()\n nn.backprop()\n\n if simulation:\n simulate(i, X_test, nn.predict(x_test))\n\n if simulation == False:\n plt.title(\"Comparision\")\n plt.scatter(X_test, X_test**2, label=\"Original\")\n plt.scatter(X_test, nn.predict(x_test), label=\"Predicted\")\n plt.legend()\n plt.show()\n\n elif type == \"sin\":\n x = np.linspace(0, 2, 21).reshape(21, 1)\n y = np.sin((3*np.pi/2) * x)\n x_test = np.linspace(0, 2, 161).reshape(161, 1)\n\n nn = mynn.NeuralNetworkSin(x, y)\n simulation = True\n for i in range(100000):\n\n nn.feedforward()\n nn.backprop()\n\n if simulation:\n simulate(i, x_test, nn.predict(x_test))\n\n if simulation == False:\n plt.title(\"Comparision\")\n plt.scatter(x_test, np.sin((3*np.pi/2) * x_test), label=\"Original\")\n plt.scatter(x_test, nn.predict(x_test), label=\"Predicted\")\n plt.legend()\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lista6/zad2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"532505289","text":"from driver import base\nfrom driver import tuchemnitz\n\nclass Config:\n def __init__ ( self ):\n self.driver = None\n self.files = []\n self.availableDrivers = []\n self.mysql_user = \"ideal-user\"\n self.mysql_passwd = \"ideal-password\"\n self.mysql_host = \"localhost\"\n self.mysql_db = \"ideal-enigma\"\n self.verbose = False\n self.table_flip = False\n self.recursive = False\n self.directory = False\n self.directory_path = \"\"\n \n self.discoverDrivers()\n \n \n def discoverDrivers ( self ):\n sc = base.BaseDriver.__subclasses__()\n for c in sc :\n driverInfo = { \"name\": c.name, \"driver\": c }\n self.availableDrivers.append ( driverInfo )\n\n def loadDriver ( self ):\n for d in self.availableDrivers:\n if d[\"name\"] == self.driver :\n result = d[\"driver\"].__new__(d[\"driver\"])\n result.__init__()\n return (result)\n return None\n \n def __str__ ( self ):\n result = \"\"\n for a in dir(self):\n if ( type(getattr(self,a)) is int ):\n result = result + \"%s = %d\\n\"%(a, getattr(self,a))\n elif ( type(getattr(self,a)) is str ):\n result = result + \"%s = %s\\n\"%(a, getattr(self,a))\n elif ( callable(getattr(self,a)) ):\n pass\n else:\n result = result + \"%s = %s\\n\"%(a, getattr(self, a))\n return (result) \n","sub_path":"parser/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"354821349","text":"import os\nimport sys\nimport time\nimport logging\nimport argparse\nimport pandas as pd\n\ndef pca_parser():\n parser = argparse.ArgumentParser('pca', description='Y-haplogroup tracker @ver-1.0 BY ChenHao')\n parser.add_argument('phy',\n help='Run to plot phylotree plot.')\n parser.add_argument('-i', '--input', required=True, type=str, nargs='+',\n help='input: Input hap or extra file.')\n parser.add_argument('-o', '--output', required=False, type=str, nargs=1, action='store',\n help='output: Output haplogroup file.')\n parser.add_argument('-m', '--mode', required=False, type=str, nargs=1, default=['smart'], choices=['rough', 'smart', 'accurate'],\n help='missing rate: Set missing rate to filter female samples, default is 0.4')\n parser.add_argument('-t', '--type', required=False, type=str, nargs=1, default='key', choices=['key', 'final'],\n help='notes: Set whether keep the haplogroup attatching (Notes), defualt not setting.')\n parser.add_argument('-f', '--filter', required=False, action='store_true',\n help='filter: filter samples without key mutation.')\n parser.add_argument('--info', required=True, type=str, nargs=1, action='store',\n help='input: Input info file.')\n parser.add_argument('--freq', required=False, action='store_true',\n help='pcaplot: Output a pca plot.')\n\n args = parser.parse_args()\n\n return args\n","sub_path":"PhyloFileIO.py","file_name":"PhyloFileIO.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"628110307","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\nfrom news import views as news_views#It is better offically\nurlpatterns = [\n # Examples:\n # url(r'^$', 'swu.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^column/(?P[^/]+)/$', news_views.column_show, name='list_column'),\n #url(r'^subcolumn/(?P[^/]+)/$', news_views.subcolumn_show, name='list_subcolumn'),\n url(r'^(?P[^/]+)/article/(?P(\\d{1,2}))/$', news_views.article_show, name='list_article'),\n url(r'^like/$',news_views.like,name=\"like\"),\n url(r'^comment/$',news_views.comment,name=\"comment\"),\n url(r'^accounts/', include('users.urls')),\n url(r'^register/$',news_views.register,name=\"register\"),\n url(r'^login/$',news_views.login,name=\"login\"),\n\turl(r'^$',news_views.home,name=\"home\"),\n url(r'^admin/', include(admin.site.urls)),\n]\n","sub_path":"swu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"355999195","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Multilayer Perceptron implementation.\n\"\"\"\n\nfrom math import exp\nfrom copy import deepcopy\ntry:\n from doc_inherit import method_doc_inherit\nexcept ImportError:\n # Dummy decorator (docstrings will not be inherited)\n def method_doc_inherit(func):\n return func\n\nfrom neuro.base.net import Net, BIAS_KEY\n\n# Input cells basename\nNAME_I = 'x'\n# Output cells basename\nNAME_O = 'y'\n# Hidden cells basename\nNAME_H = 'z'\n\n\nclass MLPerceptron(Net):\n \"\"\"Multilayer Perceptron class.\n\n Attributes:\n name (str): Perceptron instance name.\n sizein (int): Input layer size.\n sizeout (int): Output layer size.\n hsizes (list): Hidden layers sizes.\n \"\"\"\n\n name = None\n sizein = None\n sizeout = None\n hsizes = None\n _hnames = None\n\n def __init__(self, name, sizein, sizeout, hsizes):\n if not hsizes:\n raise ValueError('Invalid hidden layers sizes.')\n super().__init__(name)\n self.sizein = sizein\n self.sizeout = sizeout\n self.hsizes = hsizes\n self._hnames = []\n # For each hidden layer\n for i in range(len(hsizes)):\n # Create base name\n self._hnames.append(NAME_H * (i + 1))\n # Add hidden cells\n self.add_cells(self._hnames[i], hsizes[i])\n # Add synapses with previous hidden layer\n if i > 0:\n self.add_synapses(self._hnames[i-1], self._hnames[i],\n 0, n=hsizes[i-1], m=hsizes[i])\n # Add input layer cells\n self.add_cells(NAME_I, sizein, type='in')\n # Add output layer cells\n self.add_cells(NAME_O, sizeout, type='out')\n # Add input synapses\n self.add_synapses(NAME_I, self._hnames[0], 0, n=sizein, m=hsizes[0])\n # Add output synapses\n self.add_synapses(self._hnames[i], NAME_O, 0, n=hsizes[i], m=sizeout)\n\n def train(self, datain, dataout, learn, epochs, normalize=False):\n # Check that data sizes match\n if len(datain) != len(dataout):\n raise ValueError('Input and output instance counts do not match.')\n # Check learning rate range\n if not 0 < learn <= 1:\n raise ValueError(\n 'Learning rate must be within the interval (0, 1].')\n # Print initial progress\n print('Training... 0%', end='\\r')\n # Normalize input if required\n if normalize:\n self.normalize(datain)\n # Create list for MSE\n mse = list()\n # Initialize stop condition to false\n stop = False\n # Initialize current epoch to zero\n epoch = 0\n # Run epochs until stop conditions are met\n while not stop and epoch < epochs:\n # Assume stop condition\n stop = True\n # For each training pair in data\n for s, t in zip(datain, dataout):\n # Check that output sizes match\n if len(self._y) != len(t):\n raise ValueError(\n 'Instance {} does not match output layer size ({}).'.format(t, len(self._y)))\n # Create dict for new synapses\n synapses = deepcopy(self._synapses)\n # Create history dict\n hist = dict()\n # Populate history dict and get output values\n y = self.test_instance(s, hist=hist)\n # Initialize list of input deltas\n δ_in = [t[j] - y[j] for j in range(len(y))]\n # Create lists for retropropagation\n names = [NAME_O] + self._hnames[::-1] + [NAME_I]\n sizes = [self.sizeout] + self.hsizes[::-1] + [self.sizein]\n # Retropropagation\n for k in range(len(names) - 1):\n # Initialize list for previous layer δ_in\n _δ_in = [0] * sizes[k + 1]\n # For each cell in current layer\n for j in range(sizes[k]):\n # If correction is needed\n if δ_in[j] != 0:\n _zz = '{}{}'.format(names[k], j)\n # Get input value from history\n zz_in = hist[_zz][0]\n # Compute current delta\n δ = δ_in[j] * self.df(zz_in)\n # Save bias weight correction\n synapses[_zz][BIAS_KEY] += learn * δ\n # For each cell in previous layer\n for i in range(sizes[k + 1]):\n _z = '{}{}'.format(names[k + 1], i)\n # Get output value from history\n z = hist[_z][1]\n # Save synaptic weight correction\n synapses[_zz][_z] += learn * δ * z\n # Accumulate δ_in\n _δ_in[i] += δ * self._synapses[_zz][_z]\n # Clear stop condition\n stop = False\n # Set input deltas for previous layer\n δ_in = _δ_in\n # Update synapses\n self._synapses = synapses\n # Test dataset at the end of current epoch\n Y = self.test(datain)\n # Compute residual sum of squares\n rss = sum([sum([(dataout[i][j] - Y[i][j]) **\n 2 for j in range(len(Y[i]))]) / len(Y[0]) for i in range(len(Y))])\n # Append MSE value after current epoch\n mse.append(rss / len(Y))\n # Move to next epoch\n epoch += 1\n # Print current progress\n print('Training... {}%'.format(\n int(100 * epoch / epochs)), end='\\r', flush=True)\n # Print end of line\n print()\n # Return MSE list\n return mse\n\n def f(self, y):\n # Watch out for overflows\n try:\n return 2 / (1 + exp(-y)) - 1\n # If exponential overflow\n except OverflowError:\n # Saturate accordingly\n if y < 0:\n return -1.0\n else:\n return 1.0\n\n\n def df(self, y):\n \"\"\"Net-wide transfer function derivative.\n\n Args:\n y (float): Input signal.\n\n Returns:\n float: Output.\n \"\"\"\n\n return (1 + self.f(y)) * (1 - self.f(y)) / 2\n","sub_path":"p3/neuro/ml_perceptron.py","file_name":"ml_perceptron.py","file_ext":"py","file_size_in_byte":6560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"19240701","text":"#For draw simple graphic\n\nimport matplotlib.pyplot as plt\n\n\nclass Graph:\n\n def save_graph(self, tweets_labelled, hashtag):\n\n pos = 0\n neg = 0\n neutral = 0\n\n for opinion in tweets_labelled:\n if opinion[1] == 1:\n pos += 1\n elif opinion[1] == 0:\n neg += 1\n else:\n neutral += 1\n\n labels = 'Positive', 'Negative', 'Neutral'\n sizes = [pos, neg, neutral]\n explode = (0.1, 0, 0)\n fig1, ax1 = plt.subplots()\n ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',\n shadow=True, startangle=10)\n ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n ax1.set_title(\"#{}\".format(hashtag))\n\n plt.savefig(\"Statistics of hashtag - {}\".format(hashtag))\n","sub_path":"Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"137250529","text":"\"\"\"stripe_example URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^charge_card/$', 'main.views.charge_card', name=\"charge_card\"),\n url(r'^read_csv/$', 'main.views.read_csv', name=\"read_csv\"),\n url(r'^item_list_view/$', 'main.views.item_list_view', name=\"item_list_view\"),\n url(r'^json_item_list/$', 'main.views.json_item_list', name=\"json_item_list\"),\n url(r'^ups_shipping/$', 'main.views.ups_shipping', name=\"ups_shipping\"),\n url(r'^fedex_shipping/$', 'main.views.fedex_shipping', name=\"fedex_shipping\"),\n]\n\n","sub_path":"stripe_example/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"28221156","text":"from testInput import input\n\nfor _ in range(int(input())):\n n, m = map(int, input().split())\n l = []\n for i in range(n):\n l.append(input())\n maxx = 0\n\n for i in range(n):\n count = 0\n count1 = 0\n for j in range(m):\n if l[i][j] == '#' and ((i - 1) < 0 or l[i - 1][j] == '.'):\n count += 1\n else:\n count = 0\n if l[i][j] == '#' and ((i + 1) >= n or l[i + 1][j] == '.'):\n count1 += 1\n else:\n count1 = 0\n maxx = max(maxx, count, count1)\n\n for j in range(1, m):\n count = 0\n count1 = 0\n for i in range(n):\n if l[i][j] == '#' and ((j - 1) < 0 or l[i][j - 1] == '.'):\n count += 1\n else:\n count = 0\n if l[i][j] == '#' and ((j + 1) >= m or l[i][j + 1] == '.'):\n count1 += 1\n else:\n count1 = 0\n maxx = max(maxx, count, count1)\n print(maxx)","sub_path":"HESEPCircuit/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"413139693","text":"#dec_tree.ppy\r\nimport sys\r\nimport csv\r\nimport re\r\n\r\n# read in the arguments of the tree file and csv file\r\ntxt_file = sys.argv[1]\r\ncsv_file = sys.argv[2]\r\n\r\n# data holds the data from the csv file\r\ndata = []\r\n\r\n# tree is the decision tree\r\n# each level of the decision tree will be a dictionary\r\ntree = {}\r\n\r\n# return depth, attribute_type, attribute, classification \r\ndef parse_line(line):\r\n\r\n\t# increment depth until the first character that is not '|'\r\n\t# or a space\r\n\tdepth = 0\r\n\twhile line[depth] == '|' or hex(ord(line[depth])) == hex(0x20):\r\n\t\tdepth += 1\r\n\r\n\t# bug: for some reason the while loop increments depth 1 more than necessary\r\n\tif depth > 3:\r\n\t\tdepth-= 1\r\n\r\n\tif depth > 3:\r\n\t\tdepth-= 1\r\n\r\n\t# split the line by space\r\n\tline = line.split(\" \")\r\n\r\n\t# assign the attribute and its type\r\n\tattribute_type = line[depth]\r\n\tattribute = line[depth+1]\r\n\r\n\t# if the line ends in 'good' or 'bad', include it in the return as classification\r\n\tif (attribute[len(attribute)-1]) == ':':\r\n\t\tclassification = line[depth+2]\r\n\t\tattribute = attribute[:-1]\t#remove the ':' from the attribute string\r\n\telse:\r\n\t\t# if the line does not end with 'good' or 'bad' return None as the classification\r\n\t\tclassification = None\r\n\r\n\t# print (line)\r\n\t# print ('depth:',depth, '\tattribute_type:', attribute_type, '\t\tattribute:', attribute, '\t\tclassification:',classification)\r\n\r\n\treturn depth, attribute_type, attribute, classification\r\n\r\n# function which adds a branch to the tree dictionary\r\ndef add_path(parent,attribute_type,classification):\r\n\tif parent.get(attribute_type):\r\n\t\t1\r\n\telse:\r\n\t\tif classification == None:\r\n\t\t\tparent[attribute] = {}\r\n\t\t\treturn parent[attribute]\r\n\t\telse:\r\n\t\t\tparent[attribute] = classification +' (0)'\r\n\t\t\treturn parent\r\n\r\n# recursively traverses the tree until all the 'good' and 'bad' counts are returned\r\ndef get_results(tree):\r\n\tresults = []\r\n\tfor key in tree:\r\n\t\tif type(tree[key]) == dict:\r\n\t\t\tresults.extend(get_results(tree[key]))\r\n\t\telse:\r\n\t\t\tresults.append(tree[key])\r\n\r\n\treturn results\r\n\r\n# increments a string of the good or bad count\r\n# ex. good(3) -> good(4)\r\ndef increment_count(string):\r\n\tstr_arr = string.split(\" \")\r\n\r\n\tcount = int(str_arr[1][1:-1])\r\n\tnew_count = count + 1\r\n\r\n\tnew_count = '(' + str(new_count) + ')'\r\n\r\n\tstring = str_arr[0] + ' ' + new_count\r\n\treturn string\r\n\r\n# recursively gets the classification of data\r\ndef get_classification(parent,attributes):\r\n\tfor i in range(0,len(attributes)):\r\n\t\ta = attributes[i].replace('\"', \"\")\r\n\t\ta = a.replace(\" \",\"\")\r\n\r\n\t\tresult = parent.get(a)\r\n\t\tif type(result) == str:\r\n\t\t\tparent[a] = increment_count(result)\r\n\t\t\treturn parent[a]\r\n\t\telif type(result) == dict:\r\n\t\t\treturn get_classification(result,attributes)\r\n\r\n\r\n############\r\n### MAIN ###\r\n############\r\n\r\n\r\n# read in the csv file \r\nwith open('test.csv') as csv_file:\r\n\tcsv_reader = csv.reader(csv_file, delimiter=',')\r\n\tline_count = 0\r\n\tfor row in csv_reader:\r\n\t\tdata.append(row)\r\n\t\tline_count+=1\r\n\r\n\r\n#read in the tree txt file\r\nwith open(txt_file) as tree_file:\r\n\trow = tree_file.readlines()\r\n\trow = [x.rstrip() for x in row if x.rstrip()] # Remove newline characters\r\n\r\n\r\n\r\n# CREATE THE TREE\r\nprev_depth = 0\r\nparent = tree\r\nprev_attribute_type = None\r\nprev_parent = None\r\n\r\nfor line in row:\r\n\tdepth, attribute_type,attribute,classification = (parse_line(line))\r\n\t\r\n\t# if the depth is 0, this path stems from root\r\n\t# if the depth is greater than the previous path, this path stems from the previous\r\n\t# if the depth is less than the previous path but not 0, it stems from the next level up\r\n\tif depth == 0:\r\n\t\tparent = tree\r\n\telif depth > prev_depth:\r\n\t\tprev_parent = parent\r\n\t\tparent = prev_attribute_type\r\n\telif 0 < depth < prev_depth:\r\n\t\tparent = prev_parent\r\n\r\n\t# add a path from the parent dictionary\r\n\tprev_attribute_type = add_path(parent,attribute_type,classification)\r\n\tprev_depth = depth\r\n\r\n\r\nprint(tree)\r\n\r\n# classify each data type in the csv file\r\n# keep track of how many are unmatched\r\nattribute_names = []\r\nline_count = 0\r\nNone_count = 0\r\nfor attributes in data:\r\n\tif (get_classification(tree, attributes)) == None and line_count > 0:\r\n\t\tNone_count+=1\r\n\tline_count+=1\r\n\r\nprint(tree)\r\n\r\n# get an array of the results (good count, bad count)\r\nresults = (get_results(tree))\r\n\r\n\r\nprint ('\\n\\n')\r\n# print the results to console\r\nwith open(txt_file) as tree_file:\r\n\treplace_count = 0\r\n\trow = tree_file.readlines()\r\n\tfor line in row:\r\n\t\tline = line.split(\" \")\r\n\t\tchar = line[len(line) - 2]\r\n\r\n\t\t# if the tree ends with 'good(x)' or 'bad(x)', replace it with the results\r\n\t\tif char[0] == '(':\r\n\t\t\tline[len(line) - 2] = results[replace_count][-3:]\r\n\t\t\treplace_count += 1\r\n\r\n\t\t# if statment so the lines that are \"\\n\" are not printed\r\n\t\tif len(line) > 1: \r\n\t\t\tprint (\" \".join(line), end =\"\")\r\n\r\n# print the number of unmatched items\r\nprint('\\nUNMATCHED:', None_count)","sub_path":"CS 1656/project5/dec_tree.py","file_name":"dec_tree.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"488123249","text":"from datetime import date, datetime\nfrom functools import partial\nfrom json import dump, dumps, load\nfrom logging import debug, error\n\nfrom marshmallow import fields, post_load, pre_load, Schema\nfrom marshmallow.validate import Length\nfrom requests_oauthlib import OAuth2Session\n\n# all the fields have the option for not being set\n# dates have an extra option of being 0 or a real date\n\n# states for this field are:\n# a GMT timestamp with the time set to noon\n# unset, represented by API as 0\nclass ToodledoDate(fields.Field):\n\tdef _serialize(self, value, attr, obj):\n\t\tif value is None:\n\t\t\treturn 0\n\t\treturn datetime(year=value.year, month=value.month, day=value.day).timestamp()\n\n\tdef _deserialize(self, value, attr, obj):\n\t\tif value == 0:\n\t\t\treturn None\n\t\treturn date.fromtimestamp(float(value))\n\n# states for this field are:\n# a GMT timestamp\n# unset, represented by API as 0\nclass ToodledoDatetime(fields.Field):\n\tdef _serialize(self, value, attr, obj):\n\t\tif value is None:\n\t\t\treturn 0\n\t\treturn value.timestamp()\n\n\tdef _deserialize(self, value, attr, obj):\n\t\tif value == 0:\n\t\t\treturn None\n\t\treturn datetime.fromtimestamp(float(value))\n\nclass ToodledoTags(fields.Field):\n\tdef _serialize(self, value, attr, obj):\n\t\tassert isinstance(value, list)\n\t\treturn \", \".join(sorted(value))\n\n\tdef _deserialize(self, value, attr, obj):\n\t\tassert isinstance(value, str)\n\t\tif value == \"\":\n\t\t\treturn []\n\t\treturn [x.strip() for x in value.split(\",\")]\n\nclass Task:\n\tdef __init__(self, **data):\n\t\tfor name, item in data.items():\n\t\t\tsetattr(self, name, item)\n\n\tdef __repr__(self):\n\t\tattributes = sorted([\"{}={}\".format(name, item) for name, item in self.__dict__.items()])\n\t\treturn \"\".format(\", \".join(attributes))\n\n\tdef IsComplete(self):\n\t\treturn self.completedDate is not None\n\nclass ToodledoError(Exception):\n\terrorCodeToMessage = {\n\t\t 1: \"No access token was given\",\n\t\t 2: \"The access token was invalid\",\n\t\t 3: \"Too many API requests\",\n\t\t 4: \"The API is offline for maintenance\",\n\t\t601: \"Your task must have a title.\",\n\t\t602: \"Only 50 tasks can be added/edited/deleted at a time.\",\n\t\t603: \"The maximum number of tasks allowed per account (20000) has been reached\",\n\t\t604: \"Empty id\",\n\t\t605: \"Invalid task\",\n\t\t606: \"Nothing was added/edited. You'll get this error if you attempt to edit a task but don't pass any parameters to edit.\",\n\t\t607: \"Invalid folder id\",\n\t\t608: \"Invalid context id\",\n\t\t609: \"Invalid goal id\",\n\t\t610: \"Invalid location id\",\n\t\t611: \"Malformed request\",\n\t\t612: \"Invalid parent id\",\n\t\t613: \"Incorrect field parameters\",\n\t\t614: \"Parent was deleted\",\n\t\t615: \"Invalid collaborator\",\n\t\t616: \"Unable to reassign or share task\"\n\t}\n\n\tdef __init__(self, errorCode):\n\t\terrorMessage = ToodledoError.errorCodeToMessage.get(errorCode, \"Unknown error\")\n\t\tsuper().__init__(errorMessage, errorCode)\n\nclass TaskSchema(Schema):\n\tid_ = fields.Integer(dump_to=\"id\", load_from=\"id\")\n\ttitle = fields.String(validate=Length(max=255))\n\ttags = ToodledoTags(dump_to=\"tag\", load_from=\"tag\")\n\tstartDate = ToodledoDate(dump_to=\"startdate\", load_from=\"startdate\")\n\tdueDate = ToodledoDate(dump_to=\"duedate\", load_from=\"duedate\")\n\tmodified = ToodledoDatetime()\n\tcompletedDate = ToodledoDate(dump_to=\"completed\", load_from=\"completed\")\n\n\t@post_load\n\tdef MakeTask(self, data):\n\t\treturn Task(**data)\n\nclass Account:\n\tdef __init__(self, lastEditTask, lastDeleteTask):\n\t\tself.lastEditTask = lastEditTask\n\t\tself.lastDeleteTask = lastDeleteTask\n\n\tdef __repr__(self):\n\t\treturn \"\".format(self.lastEditTask, self.lastDeleteTask)\n\nclass AccountSchema(Schema):\n\tlastEditTask = ToodledoDatetime(dump_to=\"lastedit_task\", load_from=\"lastedit_task\")\n\tlastDeleteTask = ToodledoDatetime(dump_to=\"lastdelete_task\", load_from=\"lastdelete_task\")\n\n\t@post_load\n\tdef MakeAccount(self, data):\n\t\treturn Account(data[\"lastEditTask\"], data[\"lastDeleteTask\"])\n\ndef DumpTaskList(taskList):\n\t# TODO - pass many=True to the schema instead of this custom stuff\n\tschema = TaskSchema()\n\treturn [schema.dump(task).data for task in taskList]\n\ndef GetAccount(session):\n\taccountInfo = session.get(Toodledo.getAccountUrl)\n\taccountInfo.raise_for_status()\n\treturn AccountSchema().load(accountInfo.json()).data\n\ndef GetTasks(session, params):\n\tallTasks = []\n\tlimit = 1000 # single request limit\n\tstart = 0\n\twhile True:\n\t\tdebug(\"Start: {}\".format(start))\n\t\tparams[\"start\"] = start\n\t\tparams[\"num\"] = limit\n\t\tresponse = session.get(Toodledo.getTasksUrl, params=params)\n\t\tresponse.raise_for_status()\n\t\ttasks = response.json()\n\t\tif \"errorCode\" in tasks:\n\t\t\terror(\"Toodledo error: {}\".format(tasks))\n\t\t\traise ToodledoError(tasks[\"errorCode\"])\n\t\t# the first field contains the count or the error code\n\t\tallTasks.extend(tasks[1:])\n\t\tdebug(\"Retrieved {} tasks\".format(len(tasks[1:])))\n\t\tif len(tasks[1:]) < limit:\n\t\t\tbreak\n\t\tstart += limit\n\tschema = TaskSchema()\n\treturn [schema.load(x).data for x in allTasks]\n\ndef EditTasks(session, taskList):\n\tif len(taskList) == 0:\n\t\treturn\n\tdebug(\"Total tasks to edit: {}\".format(len(taskList)))\n\tlimit = 50 # single request limit\n\tstart = 0\n\twhile True:\n\t\tdebug(\"Start: {}\".format(start))\n\t\tlistDump = DumpTaskList(taskList[start: start + limit])\n\t\tresponse = session.post(Toodledo.editTasksUrl, params={\"tasks\":dumps(listDump)})\n\t\tresponse.raise_for_status()\n\t\tdebug(\"Response: {},{}\".format(response, response.text))\n\t\ttaskResponse = response.json()\n\t\tif \"errorCode\" in taskResponse:\n\t\t\traise ToodledoError(taskResponse[\"errorCode\"])\n\t\tif len(taskList[start: start + limit]) < limit:\n\t\t\tbreak\n\t\tstart += limit\n\ndef AddTasks(session, taskList):\n\tif len(taskList) == 0:\n\t\treturn\n\tlimit = 50 # single request limit\n\tstart = 0\n\twhile True:\n\t\tdebug(\"Start: {}\".format(start))\n\t\tlistDump = DumpTaskList(taskList[start: start + limit])\n\t\tresponse = session.post(Toodledo.addTasksUrl, params={\"tasks\":dumps(listDump)})\n\t\tresponse.raise_for_status()\n\t\tif \"errorCode\" in response.json():\n\t\t\traise ToodledoError(tasks[\"errorCode\"])\n\t\tif len(taskList[start: start + limit]) < limit:\n\t\t\tbreak\n\t\tstart += limit\n\ndef DeleteTasks(session, taskList):\n\tif len(taskList) == 0:\n\t\treturn\n\ttaskIdList = [task.id_ for task in taskList]\n\tlimit = 50 # single request limit\n\tstart = 0\n\twhile True:\n\t\tdebug(\"Start: {}\".format(start))\n\t\tresponse = session.post(Toodledo.deleteTasksUrl, params={\"tasks\":dumps(taskIdList[start: start + limit])})\n\t\tresponse.raise_for_status()\n\t\tif \"errorCode\" in response.json():\n\t\t\traise ToodledoError(tasks[\"errorCode\"])\n\t\tif len(taskIdList[start: start + limit]) < limit:\n\t\t\tbreak\n\t\tstart += limit\n\nclass TokenStorageFile:\n\tdef __init__(self, path):\n\t\tself.path = path\n\n\tdef Save(self, token):\n\t\twith open(self.path, \"w\") as f:\n\t\t\tdump(token, f)\n\n\tdef Load(self):\n\t\ttry:\n\t\t\twith open(self.path, \"r\") as f:\n\t\t\t\treturn load(f)\n\t\texcept FileNotFoundError:\n\t\t\treturn None\n\nclass Toodledo:\n\ttokenUrl = \"https://api.toodledo.com/3/account/token.php\"\n\tgetAccountUrl = \"https://api.toodledo.com/3/account/get.php\"\n\tgetTasksUrl = \"https://api.toodledo.com/3/tasks/get.php\"\n\tdeleteTasksUrl = \"https://api.toodledo.com/3/tasks/delete.php\"\n\taddTasksUrl = \"https://api.toodledo.com/3/tasks/add.php\"\n\teditTasksUrl = \"https://api.toodledo.com/3/tasks/edit.php\"\n\n\tdef __init__(self, clientId, clientSecret, tokenStorage, scope):\n\t\tself.tokenStorage = tokenStorage\n\t\tself.clientId = clientId\n\t\tself.clientSecret = clientSecret\n\t\tself.scope = scope\n\t\tself.session = self.Session()\n\n\tdef Authorize(self):\n\t\tauthorizationBaseUrl = \"https://api.toodledo.com/3/account/authorize.php\"\n\t\tsession = OAuth2Session(client_id=self.clientId, scope=self.scope)\n\t\tauthorizationUrl, _ = session.authorization_url(authorizationBaseUrl)\n\t\tprint(\"Go to the following URL and authorize the app:\" + authorizationUrl)\n\n\t\ttry:\n\t\t\tfrom pyperclip import copy\n\t\t\tcopy(authorizationUrl)\n\t\t\tprint(\"URL copied to clipboard\")\n\t\texcept ImportError:\n\t\t\tpass\n\n\t\tredirectResponse = input(\"Paste the full redirect URL here:\")\n\n\t\ttoken = session.fetch_token(Toodledo.tokenUrl, client_secret=self.clientSecret, authorization_response=redirectResponse, token_updater=self.tokenStorage.Save)\n\t\tself.tokenStorage.Save(token)\n\t\treturn token\n\n\tdef Session(self):\n\t\ttoken = self.tokenStorage.Load()\n\t\tif token is None:\n\t\t\ttoken = self.Authorize()\n\n\t\treturn OAuth2Session(\n\t\t\tclient_id=self.clientId,\n\t\t\ttoken=token,\n\t\t\tauto_refresh_kwargs={\"client_id\": self.clientId, \"client_secret\": self.clientSecret},\n\t\t\tauto_refresh_url=Toodledo.tokenUrl,\n\t\t\ttoken_updater=self.tokenStorage.Save)\n\n\tdef ReauthorizeIfNecessary(self, func):\n\t\ttry:\n\t\t\treturn func(self.session)\n\t\texcept ToodledoError:\n\t\t\t# this can happen if the refresh token has expired\n\t\t\tself.session = self.Authorize()\n\t\t\treturn func(self.session)\n\n\tdef GetAccount(self):\n\t\tself.ReauthorizeIfNecessary(partial(GetAccount))\n\n\tdef GetTasks(self, params):\n\t\tself.ReauthorizeIfNecessary(partial(GetTasks, params=params))\n\n\tdef EditTasks(self, params):\n\t\tself.ReauthorizeIfNecessary(partial(EditTasks, params=params))\n\n\tdef AddTasks(self, taskList):\n\t\tself.ReauthorizeIfNecessary(partial(AddTasks, taskList=taskList))\n\n\tdef DeleteTasks(self, params):\n\t\tself.ReauthorizeIfNecessary(partial(DeleteTasks, params=params))\n","sub_path":"toodledo/toodledo.py","file_name":"toodledo.py","file_ext":"py","file_size_in_byte":9144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"186233384","text":"\n#\n# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration\n#\n\ndef TRTMonitoringRun3Cfg(flags):\n from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\n from .TRTMonitoringRun3ESD_Alg import TRTMonitoringRun3ESD_AlgConfig\n from .TRTMonitoringRun3RAW_Alg import TRTMonitoringRun3RAW_AlgConfig\n\n result = ComponentAccumulator()\n\n # do not run in RAW->ESD (if two step) or AOD-only\n if flags.DQ.Environment not in ('tier0Raw', 'AOD'):\n result.merge(TRTMonitoringRun3ESD_AlgConfig(flags))\n \n # only when input is RAW\n if flags.DQ.Environment in ('online', 'tier0', 'tier0Raw'):\n result.merge(TRTMonitoringRun3RAW_AlgConfig(flags))\n\n return result\n","sub_path":"InnerDetector/InDetMonitoring/TRTMonitoringRun3/python/TRTMonitoringRun3Config.py","file_name":"TRTMonitoringRun3Config.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"140088235","text":"# created by https://github.com/ithg\n\nimport requests\nimport json\nimport os\nimport urllib.request\nimport glob\nfrom urllib import parse\n\n\ndef get_file_list():\n url = \"https://api.github.com/repos/babgozd/camporter96-custom/contents/grid\"\n data = requests.get(url)\n tmp_info = json.loads(data.text)\n # steam_dir=PATH\n print(\"\"\"\n \n ______ ______ __ __ ______ __ __ ______ __ \n / \\ / \\ | \\ | \\ / \\ | \\ | \\ / \\ | \\ \n| $$$$$$\\| $$$$$$\\| $$ | $$| $$$$$$\\| $$\\ | $$| $$$$$$\\| $$ \n| $$ \\$$| $$ \\$$| $$ | $$| $$ __\\$$| $$$\\| $$| $$___\\$$| $$ \n| $$ | $$ \\$$\\ / $$| $$| \\| $$$$\\ $$ \\$$ \\ | $$ \n| $$ __ | $$ __ \\$$\\ $$ | $$ \\$$$$| $$\\$$ $$ _\\$$$$$$\\| $$ \n| $$__/ \\| $$__/ \\ \\$$ $$ | $$__| $$| $$ \\$$$$| \\__| $$| $$_____ \n \\$$ $$ \\$$ $$ \\$$$ \\$$ $$| $$ \\$$$ \\$$ $$| $$ \\\\\n \\$$$$$$ \\$$$$$$ \\$ \\$$$$$$ \\$$ \\$$ \\$$$$$$ \\$$$$$$$$\n Camporter96\\'s Custom Vertical Grids for New Steam Library\"\"\")\n if 1 == len(glob.glob('C:/Program Files (x86)/Steam/userdata/*')):\n steam_dir = glob.glob('C:/Program Files (x86)/Steam/userdata/*')[0] + '/config/grid/'\n else:\n steam_dir = input(\n \"Enter your Steam dir(like: E:/Program Files (x86)/Steam/userdata/****** ):\") + '/config/grid/'\n print(\"\")\n if os.path.exists(steam_dir):\n current_file = os.listdir(steam_dir)\n else:\n os.mkdir(steam_dir)\n current_file = os.listdir(steam_dir)\n f_current = open('oldfilenames.txt', mode='w', encoding='utf-8')\n for i in range(len(current_file)):\n f_current.write(str(current_file[i])+'\\n')\n f_current.close()\n f_github = open('newfilenames.txt', mode='w', encoding='utf-8')\n for i in range(len(tmp_info)):\n f_github.write(tmp_info[i]['name'] + '\\n')\n f_github.close()\n return steam_dir\n\n\ndef pic_download():\n steam_dir = get_file_list()\n str1 = []\n str2 = []\n str_dump = []\n fa = open('newfilenames.txt', 'r')\n fb = open('oldfilenames.txt', 'r')\n str1 = fa.read().splitlines()\n str2 = fb.read().splitlines()\n fa.close()\n fb.close()\n os.remove('newfilenames.txt')\n os.remove('oldfilenames.txt')\n for i in str1:\n if i in str2:\n str_dump.append(i)\n for i in str_dump:\n if i in str1:\n str1.remove(i)\n if len(str1) != 0:\n for i in list(str1):\n f_newpic = open(steam_dir+i, mode='wb')\n newi = parse.quote(i).replace(\"\\+\", \"%20\")\n picurl = \"https://raw.githubusercontent.com/babgozd/camporter96-custom/master/grid/\"+newi\n newpic = urllib.request.urlopen(picurl)\n f_newpic.write(newpic.read())\n f_newpic.flush()\n f_newpic.close()\n print(\"[INFO]Download/Update is complete.\\n[INFO]If have any questions,please report issues on github.\")\n else:\n print(\"[INFO]Your files seem to be up to date.\\n[INFO]If have any questions,please report issues on github.\")\n\n\nif __name__ == \"__main__\":\n pic_download()\n print(\"\")\n print(\"Github Page: https://github.com/babgozd/camporter96-custom\")\n print(\"Artworks: camporter96 (https://www.reddit.com/user/camporter96)\")\n print(\"Arrangement: djandDK (https://www.reddit.com/user/djandDK)\") \n print(\"Script: ithg (https://github.com/ithg)\")\n print(\"Repository: babgozd (https://github.com/babgozd)\")\n print(\"\")\n input(\"press enter to exit\")\n os._exit(0)\n","sub_path":"CustomGrids-old.py","file_name":"CustomGrids-old.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"277646258","text":"# import timing to get execution time\nimport sys\nsys.path.append('../')\nimport timing\n\nfrom qiskit import QuantumProgram\nfrom qiskit.tools.visualization import plot_histogram, plot_circuit\nfrom math import pi\n\nbackend = \"local_qasm_simulator\"\n\nqp = QuantumProgram()\n\nnq = 3 # number of qubits\nq = qp.create_quantum_register(\"q\", nq)\nc = qp.create_classical_register(\"c\", nq)\n\ncircuits = ['qc']\nqc = qp.create_circuit(circuits[0], [q], [c])\n\n# Create superposition\nqc.h(q[0])\nqc.h(q[1])\nqc.h(q[2])\n\n# Grover iteration\niteration = 2\nfor num in range(iteration):\n # Oracle\n qc.cx(q[1],q[0])\n qc.tdg(q[0])\n qc.cx(q[2],q[0])\n qc.t(q[0])\n qc.cx(q[1],q[0])\n qc.tdg(q[0])\n qc.cx(q[2],q[0])\n qc.t(q[0])\n qc.t(q[1])\n qc.cx(q[2],q[1])\n qc.tdg(q[1])\n qc.cx(q[2],q[1])\n qc.t(q[2])\n\n # Diffusion operator\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n qc.x(q[0])\n qc.x(q[1])\n qc.x(q[2])\n\n qc.cx(q[1],q[0])\n qc.tdg(q[0])\n qc.cx(q[2],q[0])\n qc.t(q[0])\n qc.cx(q[1],q[0])\n qc.tdg(q[0])\n qc.cx(q[2],q[0])\n qc.t(q[0])\n qc.t(q[1])\n qc.cx(q[2],q[1])\n qc.tdg(q[1])\n qc.cx(q[2],q[1])\n qc.t(q[2])\n\n qc.x(q[0])\n qc.x(q[1])\n qc.x(q[2])\n qc.h(q[0])\n qc.h(q[1])\n qc.h(q[2])\n\n# Measurement\nqc.measure(q[0], c[0])\nqc.measure(q[1], c[1])\nqc.measure(q[2], c[2])\n\n# Execution\nresults = qp.execute(circuits, backend=backend, shots=8192, seed=1) \n\n# Show result\n# data = results.get_counts(circuits[0])\n# plot_histogram(data)\n# plot_circuit(qc)\n# print(results.get_data(circuits[0]))","sub_path":"grovers_algorithm/3qubit_grover/sim_3qubit_grover_same_circuit_as_real.py","file_name":"sim_3qubit_grover_same_circuit_as_real.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"308620149","text":"\"\"\"\n zoom.site\n\"\"\"\n\nimport logging\nimport os\n\nimport zoom.config\nimport zoom.helpers\nfrom zoom.context import context\n\n\nDEFAULT_OWNER_URL = 'https://www.dynamic-solutions.com'\n\nclass Site(object):\n \"\"\"a Zoom site\"\"\"\n # pylint: disable=too-many-instance-attributes, too-few-public-methods\n\n def __init__(self, request):\n\n self.request = request\n instance = request.instance\n self.name = name = request.domain\n\n # TODO: consider getting site to do this calculation instead of reqeust\n site_path = request.site_path\n if os.path.exists(site_path):\n\n self.name = name\n self.path = site_path\n self.config = zoom.config.Config(site_path, 'site.ini')\n\n get = self.config.get\n self.url = get('site', 'url', '')\n self.title = get('site', 'name', self.name)\n self.link = '{}'.format(self.url, self.name)\n self.csrf_validation = True\n self.tracking_id = get('site', 'tracking_id', '')\n\n self.owner = get('site', 'owner', 'Company Name')\n self.owner_name = get('site', 'owner', 'Company Name')\n self.owner_url = get('site', 'owner_url', DEFAULT_OWNER_URL)\n self.owner_email = get('site', 'owner_email', 'info@testco.com')\n self.admin_email = get('site', 'admin_email', 'admin@testco.com')\n\n self.smtp_host = get('mail', 'smtp_host', '')\n self.smtp_port = get('mail', 'smtp_port', '')\n self.smtp_user = get('mail', 'smtp_user', '')\n self.smtp_passwd = get('mail', 'smtp_passwd', '')\n self.mail_logo = get('mail', 'logo', '')\n self.mail_from_addr = get('mail', 'from_addr', '')\n self.mail_from_name = get('mail', 'from_name', self.title + ' Support')\n self.mail_delivery = get('mail', 'delivery', '')\n\n self.guest = get('users', 'default', 'guest')\n self.administrators_group = get(\n 'users', 'administrator_group', 'administrators'\n )\n self.developers_group = get(\n 'users', 'developer_group', 'developers'\n )\n\n self.secure_cookies = (\n request.protocol == 'https' and\n get('sessions', 'secure_cookies', True)\n )\n\n theme_dir = get('theme', 'path', os.path.join(instance, 'themes'))\n self.themes_path = theme_dir\n self.theme = get('theme', 'name', 'default')\n self.theme_path = os.path.join(theme_dir, self.theme)\n\n logger = logging.getLogger(__name__)\n logger.debug('site path: %r', site_path)\n logger.debug('theme path: %r', self.theme_path)\n\n else:\n raise Exception('site {!r} does not exist'.format(site_path))\n\n @property\n def tracker(self):\n if self.tracking_id:\n path = os.path.join(os.path.dirname(__file__), 'views', 'google_tracker.html')\n with open(path) as reader:\n return reader.read() % self.tracking_id\n return ''\n\n @property\n def abs_url(self):\n request = self.request\n port = (request.port not in ['80', '443']) and ':' + request.port or ''\n return '{}://{}{}'.format(\n request.protocol,\n request.server,\n port,\n )\n\n @property\n def apps_paths(self):\n isdir = os.path.isdir\n apps_paths = self.config.get('apps', 'path').split(';')\n return apps_paths\n return filter(isdir, apps_paths)\n\n def get_template(self, name=None):\n template = name or 'default'\n filename = os.path.join(self.theme_path, template + '.html')\n with open(filename) as reader:\n return reader.read()\n\n def get_owner_link(self):\n \"\"\"Returns a link for the site owner.\"\"\"\n if self.owner_url:\n return link_to(self.owner_name, self.owner_url)\n if self.owner_email:\n return mail_to(self.owner_name, self.owner_email)\n return name\n\n def helpers(self):\n \"\"\"provide helpers\"\"\"\n return dict(\n site_name=self.title,\n site_url=self.url,\n abs_site_url=self.abs_url,\n owner_name=self.owner_name,\n owner_url=self.owner_url,\n owner_email=self.owner_email,\n admin_email=self.admin_email,\n theme=self.theme,\n theme_uri='/themes/' + self.theme,\n request_path=self.request.path,\n tracker=self.tracker,\n )\n\n def __repr__(self):\n from zoom.utils import pretty\n return ''.format(self.abs_url, self.path)\n\n def __str__(self):\n return zoom.utils.pretty(self)\n\ndef handler(request, handler, *rest):\n \"\"\"install site object\"\"\"\n request.site = context.site = Site(request)\n return handler(request, *rest)\n","sub_path":"zoom/site.py","file_name":"site.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"236361682","text":"#encoding: utf-8\n\nfrom nose.tools import *\nimport sys\nsys.path.append('../lib')\n\nfrom filters import exclude\n\n@raises(TypeError)\ndef test_takes_a_list_and_object_as_argument():\n exclude(1337, 45)\n exclude()\n exclude(\"kjkj\")\n exclude([1, 2, 3])\n\ndef test_should_return_list():\n result = exclude([1, 2, 3], 4)\n\n # result should be a list\n assert_true(isinstance(result, list))\n\n\ndef test_should_return_list_without_items():\n result = exclude([\"bosse\", \"daniel\", \"edvard\", \"bosse\", \"bosse\"], \"bosse\")\n\n length = len(result) # should be 2\n\n\n for name in result:\n assert_true(name != \"bosse\")\n\n assert_equal(length, 2)","sub_path":"test/testexclude.py","file_name":"testexclude.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"606725708","text":"import sys\nassert sys.version_info >= (3, 5) # make sure we have Python 3.5+\n\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.sql import SparkSession, functions as f, types\nspark = SparkSession.builder.appName('read_stream').getOrCreate()\nassert spark.version >= '2.4' # make sure we have Spark 2.4+\nspark.sparkContext.setLogLevel('WARN')\nsc = spark.sparkContext\n\n\ndef main(topic):\n messages = spark.readStream.format('kafka') \\\n .option('kafka.bootstrap.servers', '199.60.17.210:9092,199.60.17.193:9092') \\\n .option('subscribe', topic).load()\n values = messages.select(messages['value'].cast('string'))\n values=values.withColumn('tmp', f.split(values['value'], \" \"))\n xy=values.select(values['tmp'].getItem(0).alias('x'),values['tmp'].getItem(1).alias('y'))\n sums = xy.select(f.sum('x').alias('sum_x'), f.sum('y').alias('sum_y'), (f.sum(xy['x']*xy['y'])).alias('sum_xy'), \\\n f.count('x').alias('n'), f.sum(f.pow(xy['x'],2)).alias('sum_x_square'))\n results = sums.withColumn('slope' ,((sums['sum_xy']-(1/sums['n'])*sums['sum_x']*sums['sum_y'])/(sums['sum_x_square']-(1/sums['n'])*(f.pow(sums['sum_x'],2)))))\n results = results.withColumn('intercept', (results['sum_y']/results['n'])-results['slope']*(results['sum_x']/results['n']))\n final = results.drop('sum_x','sum_y','sum_xy','n','sum_x_square')\n stream = final.writeStream.format('console').option(\"truncate\", \"false\").outputMode('complete').start()\n stream.awaitTermination(60)\n\nif __name__ == \"__main__\":\n topic = sys.argv[1]\n main(topic)\n\n \n\n\n","sub_path":"cmpt732_assignment6/read_stream.py","file_name":"read_stream.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"178557072","text":"#!/usr/bin/env python\n# daniel.svensson at purplescout.se 2008\n# Thomas Nagy 2016-2018 (ita)\n\"\"\"\nSupport for Ruby extensions. A C/C++ compiler is required::\n\n\tdef options(opt):\n\t\topt.load('compiler_c ruby')\n\tdef configure(conf):\n\t\tconf.load('compiler_c ruby')\n\t\tconf.check_ruby_version((1,8,0))\n\t\tconf.check_ruby_ext_devel()\n\t\tconf.check_ruby_module('libxml')\n\tdef build(bld):\n\t\tbld(\n\t\t\tfeatures = 'c cshlib rubyext',\n\t\t\tsource = 'rb_mytest.c',\n\t\t\ttarget = 'mytest_ext',\n\t\t\tinstall_path = '${ARCHDIR_RUBY}')\n\t\tbld.install_files('${LIBDIR_RUBY}', 'Mytest.rb')\n\"\"\"\nimport os\n\nfrom waflib import Errors\nfrom waflib import Options\nfrom waflib import Task\nfrom waflib import Utils\nfrom waflib.Configure import conf\nfrom waflib.TaskGen import before_method\nfrom waflib.TaskGen import extension\nfrom waflib.TaskGen import feature\n\n\n@feature(\"rubyext\")\n@before_method(\"apply_incpaths\", \"process_source\", \"apply_bundle\", \"apply_link\")\ndef init_rubyext(self):\n \"\"\"\n Add required variables for ruby extensions\n \"\"\"\n self.install_path = \"${ARCHDIR_RUBY}\"\n self.uselib = self.to_list(getattr(self, \"uselib\", \"\"))\n if not \"RUBY\" in self.uselib:\n self.uselib.append(\"RUBY\")\n if not \"RUBYEXT\" in self.uselib:\n self.uselib.append(\"RUBYEXT\")\n\n\n@feature(\"rubyext\")\n@before_method(\"apply_link\", \"propagate_uselib_vars\")\ndef apply_ruby_so_name(self):\n \"\"\"\n Strip the *lib* prefix from ruby extensions\n \"\"\"\n self.env.cshlib_PATTERN = self.env.cxxshlib_PATTERN = self.env.rubyext_PATTERN\n\n\n@conf\ndef check_ruby_version(self, minver=()):\n \"\"\"\n Checks if ruby is installed.\n If installed the variable RUBY will be set in environment.\n The ruby binary can be overridden by ``--with-ruby-binary`` command-line option.\n \"\"\"\n\n ruby = self.find_program(\"ruby\", var=\"RUBY\", value=Options.options.rubybinary)\n\n try:\n version = self.cmd_and_log(\n ruby + [\"-e\", \"puts defined?(VERSION) ? VERSION : RUBY_VERSION\"]\n ).strip()\n except Errors.WafError:\n self.fatal(\"could not determine ruby version\")\n self.env.RUBY_VERSION = version\n\n try:\n ver = tuple(map(int, version.split(\".\")))\n except Errors.WafError:\n self.fatal(\"unsupported ruby version %r\" % version)\n\n cver = \"\"\n if minver:\n cver = \"> \" + \".\".join(str(x) for x in minver)\n if ver < minver:\n self.fatal(\"ruby is too old %r\" % ver)\n\n self.msg(\"Checking for ruby version %s\" % cver, version)\n\n\n@conf\ndef check_ruby_ext_devel(self):\n \"\"\"\n Check if a ruby extension can be created\n \"\"\"\n if not self.env.RUBY:\n self.fatal(\"ruby detection is required first\")\n\n if not self.env.CC_NAME and not self.env.CXX_NAME:\n self.fatal(\"load a c/c++ compiler first\")\n\n version = tuple(map(int, self.env.RUBY_VERSION.split(\".\")))\n\n def read_out(cmd):\n return Utils.to_list(\n self.cmd_and_log(self.env.RUBY + [\"-rrbconfig\", \"-e\", cmd])\n )\n\n def read_config(key):\n return read_out(\"puts RbConfig::CONFIG[%r]\" % key)\n\n cpppath = archdir = read_config(\"archdir\")\n\n if version >= (1, 9, 0):\n ruby_hdrdir = read_config(\"rubyhdrdir\")\n cpppath += ruby_hdrdir\n if version >= (2, 0, 0):\n cpppath += read_config(\"rubyarchhdrdir\")\n cpppath += [os.path.join(ruby_hdrdir[0], read_config(\"arch\")[0])]\n\n self.check(\n header_name=\"ruby.h\",\n includes=cpppath,\n errmsg=\"could not find ruby header file\",\n link_header_test=False,\n )\n\n self.env.LIBPATH_RUBYEXT = read_config(\"libdir\")\n self.env.LIBPATH_RUBYEXT += archdir\n self.env.INCLUDES_RUBYEXT = cpppath\n self.env.CFLAGS_RUBYEXT = read_config(\"CCDLFLAGS\")\n self.env.rubyext_PATTERN = \"%s.\" + read_config(\"DLEXT\")[0]\n\n # ok this is really stupid, but the command and flags are combined.\n # so we try to find the first argument...\n flags = read_config(\"LDSHARED\")\n while flags and flags[0][0] != \"-\":\n flags = flags[1:]\n\n # we also want to strip out the deprecated ppc flags\n if len(flags) > 1 and flags[1] == \"ppc\":\n flags = flags[2:]\n\n self.env.LINKFLAGS_RUBYEXT = flags\n self.env.LINKFLAGS_RUBYEXT += read_config(\"LIBS\")\n self.env.LINKFLAGS_RUBYEXT += read_config(\"LIBRUBYARG_SHARED\")\n\n if Options.options.rubyarchdir:\n self.env.ARCHDIR_RUBY = Options.options.rubyarchdir\n else:\n self.env.ARCHDIR_RUBY = read_config(\"sitearchdir\")[0]\n\n if Options.options.rubylibdir:\n self.env.LIBDIR_RUBY = Options.options.rubylibdir\n else:\n self.env.LIBDIR_RUBY = read_config(\"sitelibdir\")[0]\n\n\n@conf\ndef check_ruby_module(self, module_name):\n \"\"\"\n Check if the selected ruby interpreter can require the given ruby module::\n\n def configure(conf):\n conf.check_ruby_module('libxml')\n\n :param module_name: module\n :type module_name: string\n \"\"\"\n self.start_msg(\"Ruby module %s\" % module_name)\n try:\n self.cmd_and_log(self.env.RUBY + [\"-e\", \"require '%s';puts 1\" % module_name])\n except Errors.WafError:\n self.end_msg(False)\n self.fatal(\"Could not find the ruby module %r\" % module_name)\n self.end_msg(True)\n\n\n@extension(\".rb\")\ndef process(self, node):\n return self.create_task(\"run_ruby\", node)\n\n\nclass run_ruby(Task.Task):\n \"\"\"\n Task to run ruby files detected by file extension .rb::\n\n def options(opt):\n opt.load('ruby')\n\n def configure(ctx):\n ctx.check_ruby_version()\n\n def build(bld):\n bld.env.RBFLAGS = '-e puts \"hello world\"'\n bld(source='a_ruby_file.rb')\n \"\"\"\n\n run_str = \"${RUBY} ${RBFLAGS} -I ${SRC[0].parent.abspath()} ${SRC}\"\n\n\ndef options(opt):\n \"\"\"\n Add the ``--with-ruby-archdir``, ``--with-ruby-libdir`` and ``--with-ruby-binary`` options\n \"\"\"\n opt.add_option(\n \"--with-ruby-archdir\",\n type=\"string\",\n dest=\"rubyarchdir\",\n help=\"Specify directory where to install arch specific files\",\n )\n opt.add_option(\n \"--with-ruby-libdir\",\n type=\"string\",\n dest=\"rubylibdir\",\n help=\"Specify alternate ruby library path\",\n )\n opt.add_option(\n \"--with-ruby-binary\",\n type=\"string\",\n dest=\"rubybinary\",\n help=\"Specify alternate ruby binary\",\n )\n","sub_path":"docs/.mywaflib/waflib/Tools/ruby.py","file_name":"ruby.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"398175401","text":"# Copyright (c) 2021 Mira Geoscience Ltd.\n#\n# This file is part of geoapps.\n#\n# geoapps is distributed under the terms and conditions of the MIT License\n# (see LICENSE file at the root of this source code package).\n\nimport numpy as np\nimport pytest\nfrom geoh5py.objects import Grid2D, Points\nfrom geoh5py.workspace import Workspace\n\nfrom geoapps.drivers.components import InversionMesh\nfrom geoapps.drivers.components.locations import InversionLocations\nfrom geoapps.io.MVI import MVIParams, default_ui_json\nfrom geoapps.utils.testing import Geoh5Tester\n\nworkspace = Workspace(\"./FlinFlon.geoh5\")\n\n\ndef setup_params(tmp):\n geotest = Geoh5Tester(workspace, tmp, \"test.geoh5\", default_ui_json, MVIParams)\n geotest.set_param(\"mesh\", \"{e334f687-df71-4538-ad28-264e420210b8}\")\n geotest.set_param(\"topography_object\", \"{ab3c2083-6ea8-4d31-9230-7aad3ec09525}\")\n return geotest.make()\n\n\ndef test_mask(tmp_path):\n ws, params = setup_params(tmp_path)\n window = params.window()\n locations = InversionLocations(ws, params, window)\n test_mask = [0, 1, 1, 0]\n locations.mask = test_mask\n assert isinstance(locations.mask, np.ndarray)\n assert locations.mask.dtype == bool\n test_mask = [0, 1, 2, 3]\n with pytest.raises(ValueError) as excinfo:\n locations.mask = test_mask\n assert \"Badly formed\" in str(excinfo.value)\n\n\ndef test_get_locations(tmp_path):\n ws, params = setup_params(tmp_path)\n window = params.window()\n locs = np.ones((10, 3), dtype=float)\n points_object = Points.create(ws, name=\"test-data\", vertices=locs)\n locations = InversionLocations(ws, params, window)\n dlocs = locations.get_locations(points_object.uid)\n np.testing.assert_allclose(locs, dlocs)\n\n xg, yg = np.meshgrid(np.arange(5) + 0.5, np.arange(5) + 0.5)\n locs = np.c_[xg.ravel(), yg.ravel(), np.zeros(25)]\n grid_object = Grid2D.create(\n ws,\n origin=[0, 0, 0],\n u_cell_size=1,\n v_cell_size=1,\n u_count=5,\n v_count=5,\n rotation=0.0,\n dip=0.0,\n )\n dlocs = locations.get_locations(grid_object.uid)\n np.testing.assert_allclose(dlocs, locs)\n\n\ndef test_filter(tmp_path):\n ws, params = setup_params(tmp_path)\n window = params.window()\n locations = InversionLocations(ws, params, window)\n test_data = np.array([0, 1, 2, 3, 4, 5])\n locations.mask = np.array([0, 0, 1, 1, 1, 0])\n filtered_data = locations.filter(test_data)\n assert np.all(filtered_data == [2, 3, 4])\n\n test_data = {\"key\": test_data}\n filtered_data = locations.filter(test_data)\n assert np.all(filtered_data[\"key\"] == [2, 3, 4])\n\n\ndef test_rotate(tmp_path):\n # Basic test since rotate_xy already tested\n ws, params = setup_params(tmp_path)\n window = params.window()\n locations = InversionLocations(ws, params, window)\n test_locs = np.array([[1.0, 2.0, 3.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])\n locs_rot = locations.rotate(test_locs)\n assert locs_rot.shape == test_locs.shape\n\n\ndef test_z_from_topo(tmp_path):\n ws, params = setup_params(tmp_path)\n window = params.window()\n locations = InversionLocations(ws, params, window)\n locations.locs = np.array([[315674, 6070832, 0]])\n locs = locations.set_z_from_topo(locations.locs)\n assert locs[0, 2] == 326\n","sub_path":"tests/locations_test.py","file_name":"locations_test.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"324875405","text":"from scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nimport time,pymysql\n\nclass Wy_Spider(CrawlSpider):\n name = 'hy_163'\n allowed_domains = ['163.com']\n start_urls = ['https://tech.163.com/']\n page = 0\n #更新设置--------------------------------------------------\n # start_time = time.time()\n # up_time = 600 # 更新 秒\n custom_settings = {\n #设置爬取算法模式\n # 'SCHEDULER_DISK_QUEUE' : 'scrapy.squeues.PickleFifoDiskQueue',\n # 'SCHEDULER_MEMORY_QUEUE' : 'scrapy.squeues.FifoMemoryQueue',\n # 'DEPTH_PRIORITY': 1, #0表示深度优先,1表示广度优先\n # 'DEPTH_LIMIT' : 5 #最大深度值\n # 'CONCURRENT_REQUESTS':32,\n # 'DOWNLOAD_DELAY':1,\n # 'CONCURRENT_REQUESTS_PER_DOMAIN' :32,\n #'LOG_LEVEL':'DEBUG'\n }\n #-默认入库,入FTP,入分类设置,更新时长---------------------------\n table_name = 'hy_cn_tech' #mysql表名\n default_category='tech' #默认分类\n #--------------------------------------------------------\n rules = (Rule(LinkExtractor(allow=r'^https://www.163.com/(?!keywords)(?!photoview).*html$'), callback='parse_item', follow=False),\n Rule(LinkExtractor(allow=r'https://tech.163.com/(?!keywords).*'),follow=True),)\n\n def __init__(self):\n super(Wy_Spider, self).__init__(name='hy_163')\n # mysql------------------------------------------\n self.conn = pymysql.Connect(\n host='154.212.112.247',\n port=13006,\n # 数据库名:\n db='seo-hy',\n user=\"root\",\n passwd='itfkgsbxf3nyw6s1',\n charset='utf8')\n self.cur = self.conn.cursor()\n\n def parse_item(self, response):\n # 后续更新:启动10分钟后关闭\n # if time.time() - self.start_time >= self.up_time:\n # self.crawler.engine.close_spider(self, \"更新10分钟完成!!\")\n item = {}\n url=response.url\n item['url'] = url\n # 标题\n try:\n item['title'] = response.xpath(\"//meta[@property='og:title']/@content\").extract_first()\n if item['title'] == None:\n item['title'] = ''\n except Exception:\n item['title'] = ''\n # 关键字\n try:\n item['keyword'] = response.xpath(\"//meta[@name='keywords']/@content\").extract_first()\n if item['keyword'] ==None or len(item['keyword'])<1:\n item['keyword'] = item['title'].replace(' ',',')\n except Exception:\n item['keyword'] = item['title'].replace(' ',',')\n # 摘要\n try:\n item['description'] = response.xpath(\"//meta[@name='description']/@content\").extract_first()\n if item['description'] == None:\n item['description'] = response.xpath(\"//meta[@property='og:description']/@content\").extract_first()\n if item['description'] == None:\n item['description'] = item['title']\n except Exception:\n item['description'] = item['title']\n # 图片\n try:\n img_url=response.xpath(\"//div[@class='post_body']//img/@src\").extract_first()\n if 'logo' in img_url or img_url == None:\n item['img_src'] = ''\n else:item['img_src']=img_url\n except Exception:\n item['img_src'] = ''\n # 正文\n try:\n item['content'] ='\\n'.join(response.xpath(\"//div[@class='post_body']//p/text() | //div[@class='post_body']//p/a/text()\").extract())\n except Exception:\n item['content'] = ''\n\n # 作者\n item['author'] = '马铃薯科技'\n\n # 发行时间\n try:\n item['release_time'] = response.xpath(\"//div[@class='post_info']/text()\").extract_first().replace('\\n','').strip()[0:19]\n except Exception:\n item['release_time'] = time.strftime('%Y-%m-%d %H:%M:%S')\n #分类\n try:\n item['category']='tech'\n except Exception:\n item['category']='tech'\n # 来源\n item['be_from'] ='tech.163.com'\n\n\n #生成器返回:\n if len(item['title']) >=1 and len(item['content']) >= 50 and item['category'] != '':\n #-----------入库去重--------------------------------------\n find_ex = \"select id,url from {} where title= %s \".format(self.table_name)\n self.cur.execute(find_ex, (item[\"title\"]))\n if not self.cur.fetchone():\n news = \"insert into {}(title,content,author,release_time,keyword,description,url,img_src,category,create_time,be_from) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\".format(self.table_name)\n self.cur.execute(news, (item['title'], item['content'], item['author'], item['release_time'], item['keyword'],item['description'], item['url'],item['img_src'], item['category'], time.time(),item['be_from']))\n self.conn.commit()\n self.page += 1\n print(time.strftime('%Y.%m.%d-%H:%M:%S'), '第', self.page, '条抓取成功:', item['url'])\n else:print('**数据重复:',item['url'])\n else:\n print('##数据不匹配:标题长度:',len(item['title']),'文本长度:',len(item['content']),'category:',item['category'],response.url)\n\n\n def close(self, reason):\n print(reason,'共抓取:',self.page,'条数据')\n self.conn.close()\n ##self.crawler.engine.close_spider(self, \"关闭spider\")\n #scrapy crawl hy_163\n","sub_path":"li_news_spider/spiders/hy_cn_tech_163.py","file_name":"hy_cn_tech_163.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"528298595","text":"#\n# MembraneTestCase Membrane\n#\n\nimport os, sys\nimport unittest\n\nfrom Testing import ZopeTestCase\nfrom Products.membrane.tests import base\nfrom Products.CMFPlone.utils import _createObjectByType\n\nfrom Products.membrane.plugins.userfactory import MembraneUser\nfrom Products.membrane.interfaces import IMembraneUserAuth\n\nclass MembraneUserFactoryTestBase:\n\n def _getTargetClass( self ):\n\n from Products.membrane.plugins.userfactory \\\n import MembraneUserFactory\n\n return MembraneUserFactory\n\n def _makeOne( self, id='test', *args, **kw ):\n\n return self._getTargetClass()( id=id, *args, **kw )\n \n\nclass TestMembraneUserFactory( base.MembraneTestCase\n , MembraneUserFactoryTestBase):\n\n def afterSetUp(self):\n self.portal.pmm = self._makeOne('pmm')\n self.addUser()\n\n def testUserCreation(self):\n username = self.member.getUserName()\n user = self.portal.pmm.createUser(self.userid, username)\n self.failUnless(user)\n self.failUnless(isinstance(user, MembraneUser))\n\n def testUserCreationFromPAS(self):\n user = self.portal.acl_users.getUserById(self.userid)\n self.failUnless(user)\n self.failUnless(isinstance(user, MembraneUser))\n\n def testLogin(self):\n self.login(self.userid)\n\n\nclass TestMembraneUserReferenceable( base.MembraneTestCase\n , MembraneUserFactoryTestBase):\n\n def afterSetUp(self):\n self.portal.pmm = self._makeOne('pmm')\n self.addUser()\n\n def testUID(self):\n user = self.portal.acl_users.getUserById(self.userid)\n self.failUnlessEqual(user.getProperty('uid'), self.member.UID())\n self.failUnlessEqual(user.UID(), self.member.UID())\n\n def testGetMembraneObject(self):\n user = self.portal.acl_users.getUserById(self.userid)\n self.failUnlessEqual(user._getMembraneObject(), self.member)\n\n def testAddAndGetRefs(self):\n user = self.portal.acl_users.getUserById(self.userid)\n folder = _createObjectByType('Folder', self.portal, 'document')\n\n user.addReference(folder)\n\n self.failUnless(user.hasRelationshipTo(folder))\n self.failUnless(self.member.hasRelationshipTo(folder))\n\n refs = user.getRefs()\n self.failUnlessEqual(refs, self.member.getRefs())\n self.failUnlessEqual(len(refs), 1)\n\n self.failUnlessEqual(refs, user.getReferences())\n\n ref = refs[0]\n self.failUnlessEqual(ref, folder)\n\n brefs = folder.getBRefs()\n self.failUnlessEqual(len(brefs), 1)\n\n bref = brefs[0]\n self.failUnlessEqual(bref, self.member)\n\n refimpl = user.getReferenceImpl()\n self.failUnless(refimpl)\n self.failUnlessEqual(refimpl, self.member.getReferenceImpl())\n\n brefimpl = folder.getBackReferenceImpl()\n self.failUnless(brefimpl)\n \n self.failUnlessEqual(user.reference_url(), self.member.reference_url())\n\n user.deleteReference(folder)\n self.failIf(user.getRefs())\n self.failIf(self.member.getRefs())\n \n\ndef test_suite():\n from unittest import TestSuite, makeSuite\n suite = TestSuite()\n suite.addTest(makeSuite(TestMembraneUserFactory))\n suite.addTest(makeSuite(TestMembraneUserReferenceable))\n return suite\n","sub_path":"products/membrane/tests/testMembraneUserFactory.py","file_name":"testMembraneUserFactory.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"76526497","text":"#!/usr/bin/env python3\nimport sys\nimport re\nimport subprocess\nfrom enum import Enum\nimport gi\ngi.require_version('Notify', '0.7')\nfrom gi.repository import Notify\n\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QSystemTrayIcon, QMenu, QAction, qApp, QMessageBox\nfrom PyQt5.QtCore import QSize, QThread, pyqtSignal\nfrom PyQt5.QtGui import QIcon\n\n\nPROTONVPN_APPLET_VERSION = 0.1\n\n\nclass VPNStatusException(Exception):\n pass\n\n\nclass VPNCommand(Enum):\n status = 'sudo protonvpn s'\n connect_fastest = 'sudo protonvpn c -f'\n disconnect = 'sudo protonvpn d'\n version = 'sudo protonvpn -v'\n\n\ndef check_single_instance():\n\n pid = None\n\n try:\n pid = subprocess.check_output('pgrep protonvpn-applet'.split()).decode(sys.stdout.encoding)\n except subprocess.CalledProcessError:\n try:\n pid = subprocess.check_output('pgrep protonvpn-applet.py'.split()).decode(sys.stdout.encoding)\n except subprocess.CalledProcessError:\n pass\n\n if pid is not None:\n print('There is an instance already running.')\n sys.exit(1)\n\n return\n\n\nclass Polling(QThread):\n def __init__(self, PApplet):\n QThread.__init__(self)\n self.PApplet = PApplet\n return\n\n def __del__(self):\n self.wait()\n return\n\n def run(self):\n while(self.PApplet.is_polling()):\n try:\n statusmsg = subprocess.check_output(\n VPNCommand.status.value.split()).decode(sys.stdout.encoding)\n if (re.search('Connected', statusmsg)):\n self.PApplet.tray_icon.setIcon(QIcon('icons/16x16/protonvpn-connected.png'))\n elif (re.search('Disconnected', statusmsg)):\n self.PApplet.tray_icon.setIcon(QIcon('icons/16x16/protonvpn-disconnected.png'))\n else:\n raise VPNStatusException('Cannot parse protonvpn-cli status output.')\n except subprocess.CalledProcessError:\n self.PApplet.tray_icon.setIcon(QIcon('icons/16x16/protonvpn-disconnected.png'))\n self.sleep(1)\n return\n\n\nclass ConnectVPN(QThread):\n def __init__(self, PApplet):\n QThread.__init__(self)\n self.PApplet = PApplet\n return\n\n def __del__(self):\n self.wait()\n return\n\n def run(self):\n subprocess.run(VPNCommand.connect_fastest.value.split())\n self.PApplet.status_vpn('dummy')\n return\n\n\nclass DisconnectVPN(QThread):\n def __init__(self, PApplet):\n QThread.__init__(self)\n self.PApplet = PApplet\n return\n\n def __del__(self):\n self.wait()\n return\n\n def run(self):\n subprocess.run(VPNCommand.disconnect.value.split())\n self.PApplet.status_vpn('dummy')\n return\n\n\nclass CheckStatus(QThread):\n def __init__(self, PApplet):\n QThread.__init__(self)\n self.PApplet = PApplet\n return\n\n def __del__(self):\n self.wait()\n return\n\n def run(self):\n result = subprocess.check_output(VPNCommand.status.value.split()).decode(sys.stdout.encoding)\n result = result.split('\\n')\n\n print(result)\n\n if 'Disconnected' in result[0]:\n if self.PApplet.show_notifications():\n Notify.Notification.new(f'VPN disconnected').show()\n self.PApplet.tray_icon.setIcon(QIcon('icons/16x16/protonvpn-disconnected.png'))\n elif 'Connected' in result[0]:\n if self.PApplet.show_notifications():\n Notify.Notification.new('\\n'.join(result)).show()\n self.PApplet.tray_icon.setIcon(QIcon('icons/16x16/protonvpn-connected.png'))\n else:\n raise VPNStatusException(f'VPN status could not be parsed: {result}')\n\n return\n\n\nclass CheckProtonVPNVersion(QThread):\n\n protonvpn_version_ready = pyqtSignal(str)\n\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.parent = parent\n self.version = 'None'\n\n def __del__(self):\n self.wait()\n return\n\n def run(self):\n self.version = subprocess.check_output(VPNCommand.version.value.split()).decode(sys.stdout.encoding)\n self.protonvpn_version_ready.emit(self.version)\n return\n\n\nclass PVPNApplet(QMainWindow):\n\n tray_icon = None\n polling = True\n\n # Override the class constructor\n def __init__(self):\n\n QMainWindow.__init__(self)\n\n self.setMinimumSize(QSize(480, 80)) # Set sizes\n self.setWindowTitle('ProtonVPN Qt') # Set a title\n central_widget = QWidget(self) # Create a central widget\n self.setCentralWidget(central_widget) # Set the central widget\n\n # Init QSystemTrayIcon\n self.tray_icon = QSystemTrayIcon(self)\n self.tray_icon.setIcon(QIcon('icons/16x16/protonvpn-disconnected.png'))\n\n # Init libnotify\n Notify.init('ProtonVPN')\n\n # Menu actions\n connect_action = QAction('Connect', self)\n disconnect_action = QAction('Disconnect', self)\n status_action = QAction('Status', self)\n quit_action = QAction('Exit', self)\n show_protonvpn_applet_version_action = QAction('About ProtonVPN-Applet', self)\n show_protonvpn_version_action = QAction('About ProtonVPN', self)\n self.show_notifications_action = QAction('Show Notifications')\n self.show_notifications_action.setCheckable(True)\n self.show_notifications_action.setChecked(False)\n\n # Triggers\n quit_action.triggered.connect(qApp.quit)\n connect_action.triggered.connect(self.connect_vpn)\n disconnect_action.triggered.connect(self.disconnect_vpn)\n status_action.triggered.connect(self.status_vpn)\n show_protonvpn_applet_version_action.triggered.connect(self.show_protonvpn_applet_version)\n show_protonvpn_version_action.triggered.connect(self.get_protonvpn_version)\n\n # Draw menu\n tray_menu = QMenu()\n tray_menu.addAction(show_protonvpn_applet_version_action)\n tray_menu.addAction(show_protonvpn_version_action)\n tray_menu.addAction(self.show_notifications_action)\n tray_menu.addAction(connect_action)\n tray_menu.addAction(disconnect_action)\n tray_menu.addAction(status_action)\n tray_menu.addAction(quit_action)\n self.tray_icon.setContextMenu(tray_menu)\n self.tray_icon.show()\n\n # Polling thread\n self.start_polling()\n\n return\n\n def is_polling(self):\n return self.polling\n\n def kill_polling(self):\n self.polling = False\n return\n\n def start_polling(self):\n self.polling = True\n self.pollingThread = Polling(self)\n self.pollingThread.start()\n return\n\n def connect_vpn(self, event):\n self.kill_polling()\n self.connectThread = ConnectVPN(self)\n self.connectThread.finished.connect(self.start_polling)\n self.connectThread.start()\n return\n\n def disconnect_vpn(self, event):\n self.disconnectThread = DisconnectVPN(self)\n self.disconnectThread.start()\n return\n\n def status_vpn(self, event):\n self.statusThread = CheckStatus(self)\n self.statusThread.start()\n return\n\n # Override closeEvent to intercept the window closing event\n def closeEvent(self, event):\n event.ignore()\n self.hide()\n return\n\n def show_notifications(self):\n return self.show_notifications_action.isChecked()\n\n def show_protonvpn_applet_version(self):\n \"\"\"Show the protonvpn-applet version.\n \"\"\"\n\n name = '© 2019 Dónal Murray'\n email = 'dmurray654@gmail.com'\n github = 'https://github.com/seadanda/protonvpn-applet'\n\n info = [f'
Version: {PROTONVPN_APPLET_VERSION}',\n f'{name}',\n f\"{email}\",\n f\"{github}
\"]\n\n centered_text = f'
{\"
\".join(info)}
'\n\n QMessageBox.information(self, 'protonvpn-applet', centered_text)\n\n return\n\n def get_protonvpn_version(self):\n \"\"\"Start the CheckProtonVPNVersion thread; when it gets the version, it will call `self.show_protonvpn_version`\n \"\"\"\n print('called get_protonvpn_version')\n self.check_protonvpn_version_thread = CheckProtonVPNVersion(self)\n self.check_protonvpn_version_thread.protonvpn_version_ready.connect(self.show_protonvpn_version)\n self.check_protonvpn_version_thread.start()\n return\n\n def show_protonvpn_version(self, version):\n \"\"\"Show the ProtonVPN version in a QMessageBox.\n\n Parameters\n ----------\n version : str\n Version number to be shown.\n \"\"\"\n print('called show_protonvpn_version')\n QMessageBox.information(self, 'ProtonVPN Version', f'Version: {version}')\n return\n\n\nif __name__ == '__main__':\n check_single_instance()\n app = QApplication(sys.argv)\n mw = PVPNApplet()\n sys.exit(app.exec())\n","sub_path":"protonvpn-applet.py","file_name":"protonvpn-applet.py","file_ext":"py","file_size_in_byte":9115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"279270904","text":"class Solution(object):\n def findLadders(self, beginWord, endWord, wordList):\n \"\"\"\n :type beginWord: str\n :type endWord: str\n :type wordList: List[str]\n :rtype: List[List[str]]\n \"\"\"\n wordList = set(wordList)\n res = []\n layer = {}\n layer[beginWord] = [[beginWord]]\n while layer:\n new_layer = collections.defaultdict(list)\n for word in layer:\n if word == endWord:\n res.extend(k for k in layer[word])\n else:\n for i in range(len(word)):\n for c in 'abcdefghijklmnopqrstuvwxyz':\n new_word = word[:i] + c + word[i+1:]\n if new_word in wordList:\n new_layer[new_word] += [j+[new_word] for j in layer[word]]\n wordList -= set(new_layer.keys())\n layer = new_layer\n return res","sub_path":"LeetCode/Algorithm/Python/126-Word Ladder II.py","file_name":"126-Word Ladder II.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"428355365","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# In[2]:\n\n\ngrey = cv2.imread('../data/Lena.png', 0)\ncv2.imshow('original grey', grey)\ncv2.waitKey()\ncv2.destroyAllWindows()\n\n\n# In[3]:\n\n\ngrey_eq = cv2.equalizeHist(grey)\n\n\n# In[4]:\n\n\nhist, bins = np.histogram(grey_eq, 256, [0, 255])\nplt.fill_between(range(256), hist, 0)\nplt.xlabel('pixel value')\nplt.show()\n\n\n# In[5]:\n\n\ncv2.imshow('equalized grey', grey_eq)\ncv2.waitKey()\ncv2.destroyAllWindows()\n\n\n# In[6]:\n\n\ncolor = cv2.imread('../data/Lena.png')\nhsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV)\n\n\n# In[8]:\n\n\nhsv[..., 2] = cv2.equalizeHist(hsv[..., 2])\ncolor_eq = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\ncv2.imshow('original color', color)\n\n\n# In[9]:\n\n\ncv2.imshow('original color', color)\n\n\n# In[10]:\n\n\ncv2.imshow('equalized color', color_eq)\ncv2.waitKey()\ncv2.destroyAllWindows()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Chapter02/09 Equalizing image histogram.py","file_name":"09 Equalizing image histogram.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"222293880","text":"\n# coding: utf-8\n\n# In[2]:\n\nget_ipython().magic(u'matplotlib inline')\n\n\n# In[3]:\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport scipy\n\nfrom os import path\nfrom sys import argv\n\n\n# ### DEFINE FUNCTIONS\n\n# In[4]:\n\ndef load_data(data_filename):\n # load data file\n fields = np.genfromtxt(data_filename, delimiter=',',unpack=True,usecols=(0))\n ID = np.genfromtxt(data_filename, delimiter=',',unpack=True,usecols=(1),dtype=np.str)\n lorri_m = np.genfromtxt(data_filename, delimiter=',',unpack=True,usecols=(2))\n S, S_err = np.genfromtxt(data_filename, delimiter=',',unpack=True,usecols=(3,4))\n m, m_err = np.genfromtxt(data_filename, delimiter=',',unpack=True,usecols=(5,6))\n \n return (fields,ID,lorri_m,S,S_err,m,m_err)\n\ndef find_weighted_average(data,err):\n weight = 1.0/(err**2.0) # weight the data points by their errors. Smaller error = more weight\n weight = weight/np.sum(weight) # normalize the weight\n \n mean = np.average(data, weights=weight) \n #calculate the unbiased variance of the mean\n mean_var_1 = np.sum(weight*(data-mean)**2.0)\n mean_var_2 = np.sum(weight)/((np.sum(weight))**2.0-np.sum(weight*weight))\n mean_var = mean_var_1*mean_var_2\n #error = sqrt of the variance\n mean_err = mean_var**(1.0/2)\n \n return (mean,mean_err)\n\ndef find_average(data): \n mean = np.average(data)\n err = np.std(data)\n \n return (mean,err)\n \ndef find_flux(lorri_m,S,S_err):\n a = 10**(-lorri_m/2.5)\n flux = a / S # unit: DN\n flux_err = np.sqrt(a*a*S_err*S_err/(S**4.0)) # unit: DN\n \n #convert DN to Jy in R_L band\n flux = flux*3050\n flux_err = flux_err*3050\n \n #return flux in microJy\n flux = flux*(10**6.0)\n flux_err = flux_err*(10**6.0)\n \n return (flux,flux_err)\n\n\n# ### LOAD DATA\n\n# In[5]:\n\nall_fields_data = 'ALL_FIELDS.csv'\ngood_fields_data = 'GOOD_FIELDS.csv'\n\nALL_fields,ALL_ID,ALL_lorri_m,ALL_S,ALL_S_err,ALL_m,ALL_m_err = load_data(all_fields_data)\nGOOD_fields,GOOD_ID,GOOD_lorri_m,GOOD_S,GOOD_S_err,GOOD_m,GOOD_m_err = load_data(good_fields_data)\n\n#Values from Cheng et al. to compare our numbers to\nCHENG_m = 18.86 \nCHENG_flux = 10**(-CHENG_m/2.5)*3050*(10**(6.0)) #assume a count of 1 per sec, then mag measured = ref mag = 18.86\n #3050 is to convert to Jy, 10^6 is to convert to microJy\nprint('Cheng et al. mag: %0.3f' % CHENG_m)\nprint('Cheng et al. flux: %0.3f [microJy]' % CHENG_flux)\n\n\n# ### COMPUTE MEAN MAG AND FLUX\n\n# In[6]:\n\n#MAGNITUDE\n#only good fields\nGOOD_m_mean, GOOD_m_mean_err = find_weighted_average(GOOD_m,GOOD_m_err)\nprint(\"Mean mag of 4 best fields: %0.3f +/- %0.3f\" % (GOOD_m_mean,GOOD_m_mean_err))\n\n#all fields\nALL_m_mean, ALL_m_mean_err = find_average(ALL_m)\nprint(\"Mean mag of all fields: %0.3f +/- %0.3f\" % (ALL_m_mean,ALL_m_mean_err))\n\n\n# In[7]:\n\n#FLUX\n# a = 10^(-lorri_m/2.5)\n# F = 3050*a/s\n# = /, = <10^(-lorri_m/2.5)> ~ = 10^(-/2.5)\n# is the average of lorri_m of EACH star, with associated stdev\n# so = lorri_m reported here\n# = S reported here, so the flux of each star will then be:\n# = 3050*a/S\n# error of each point is (use derivative to get the average):\n# = sqrt(a_err*a_err + a*a/(S_err*S_err)*S_err)/S\n\n# THEN use this F_err to find the weighted mean\n\n#only good fields\nGOOD_flux,GOOD_flux_err = find_flux(GOOD_lorri_m,GOOD_S,GOOD_S_err)\nGOOD_flux_mean,GOOD_flux_mean_err = find_weighted_average(GOOD_flux,GOOD_flux_err)\nprint(\"Mean flux of 4 best fields: %0.3f +/- %0.3f [microJy]\" % (GOOD_flux_mean,GOOD_flux_mean_err))\n\n#all fields\nALL_flux,ALL_flux_err = find_flux(ALL_lorri_m,ALL_S,ALL_S_err)\nALL_flux_mean,ALL_flux_mean_err = find_average(ALL_flux)\nprint(\"Mean flux of all fields: %0.3f +/- %0.3f [microJy]\" % (ALL_flux_mean,ALL_flux_mean_err))\n\n\n# ### MAKING FIGURES\n\n# In[8]:\n\n#EXTRACT THE POINTS OF FOUR BEST FIELDS FOR PLOT\nFIELD_3 = np.asarray([1,2])\nFIELD_5 = np.asarray([3,4])\nFIELD_6 = np.asarray([5,6])\nFIELD_7 = np.asarray([7,8])\nstar = np.arange(1,9,1)\n\nFIELD_3_m = GOOD_m[0:2]\nFIELD_5_m = GOOD_m[2:4]\nFIELD_6_m = GOOD_m[4:6]\nFIELD_7_m = GOOD_m[6:]\n\nFIELD_3_m_err = GOOD_m_err[0:2]\nFIELD_5_m_err = GOOD_m_err[2:4]\nFIELD_6_m_err = GOOD_m_err[4:6]\nFIELD_7_m_err = GOOD_m_err[6:]\n\nFIELD_3_flux = GOOD_flux[0:2]\nFIELD_5_flux = GOOD_flux[2:4]\nFIELD_6_flux = GOOD_flux[4:6]\nFIELD_7_flux = GOOD_flux[6:]\n\nFIELD_3_flux_err = GOOD_flux_err[0:2]\nFIELD_5_flux_err = GOOD_flux_err[2:4]\nFIELD_6_flux_err = GOOD_flux_err[4:6]\nFIELD_7_flux_err = GOOD_flux_err[6:]\n\n\n# In[10]:\n\n#PLOT\nfig,(ax1,ax2) = plt.subplots(1,2,figsize=(9,4.5))\n\n#MAGNITUDE\nstar_number = np.arange(0,10,1) # x-coordinate for some points to use fill_between\n\n#Cheng et al.\nax1.axhline(CHENG_m,color='#fe9929',linestyle='-',linewidth=0.75,zorder=0,label='Cheng et al.')\n\n#all stars average\nax1.axhline(ALL_m_mean,color='#1d91c0',linestyle=':',linewidth=1,zorder=1,label='All fields')\n\n#four fields average\nax1.axhline(GOOD_m_mean,color='#41ae76',linestyle='-',linewidth=2,label='4 best fields',zorder=2,alpha=0.7)\nax1.fill_between(star_number,GOOD_m_mean+GOOD_m_mean_err,GOOD_m_mean-GOOD_m_mean_err, color='#66c2a4',alpha=0.15,zorder=2)\n\n#individual stars\nax1.errorbar(FIELD_3,FIELD_3_m,yerr=FIELD_3_m_err,fmt='o',color='#c51b7d',ms=4,zorder=6,linewidth=0.7)\nax1.errorbar(FIELD_5,FIELD_5_m,yerr=FIELD_5_m_err,fmt='^',color='#c51b7d',ms=5,zorder=6,linewidth=0.7)\nax1.errorbar(FIELD_6,FIELD_6_m,yerr=FIELD_6_m_err,fmt='s',color='#c51b7d',ms=4,zorder=6,linewidth=0.7)\nax1.errorbar(FIELD_7,FIELD_7_m,yerr=FIELD_7_m_err,fmt='*',color='#c51b7d',ms=4,zorder=6,linewidth=0.7)\n\nax1.set_xlabel('Star ID',labelpad=8)\nax1.set_ylabel(r'Reference magnitude $R_{{\\rm L},0}$')\nax1.set_xlim(0,9)\nax1.set_ylim(18.1,19.1)\nax1.set_xticks(star) # set the ticks to star number\nax1.set_xticklabels(GOOD_ID,rotation=90) # match star to star ID\nax1.legend(loc='lower left',frameon=False, prop={'size':10})\n\n\n#FLUX\nF_mean_star_plot = np.arange(0,9,0.5)\n\n#Cheng et al.\nax2.axhline(CHENG_flux,color='#fe9929',linestyle='-',linewidth=0.75,zorder=0,label='Cheng et al.')\n\n#all stars average\nax2.axhline(ALL_flux_mean,color='#1d91c0',linestyle=':',linewidth=1,zorder=1,label='All fields')\n\n#four fields average\nax2.axhline(GOOD_flux_mean,color='#41ae76',linestyle='-',linewidth=2,label='4 best fields',zorder=2,alpha=0.7)\nax2.fill_between(star_number,GOOD_flux_mean+GOOD_flux_mean_err,GOOD_flux_mean-GOOD_flux_mean_err, color='#66c2a4',alpha=0.15,zorder=2)\n\n#individual stars\nax2.errorbar(FIELD_3,FIELD_3_flux,yerr=FIELD_3_flux_err,fmt='o',color='#c51b7d',ms=4,zorder=6,linewidth=0.7)\nax2.errorbar(FIELD_5,FIELD_5_flux,yerr=FIELD_5_flux_err,fmt='^',color='#c51b7d',ms=5,zorder=6,linewidth=0.7)\nax2.errorbar(FIELD_6,FIELD_6_flux,yerr=FIELD_6_flux_err,fmt='s',color='#c51b7d',ms=4,zorder=6,linewidth=0.7)\nax2.errorbar(FIELD_7,FIELD_7_flux,yerr=FIELD_7_flux_err,fmt='*',color='#c51b7d',ms=4,zorder=6,linewidth=0.7)\n\nax2.set_xlabel('Star ID',labelpad=8)\nax2.set_ylabel(r'Reference flux $F_{{\\rm L}, 0}$ [$\\mu$Jy]')\nax2.set_xlim(0,9)\nax2.set_ylim(55,155)\nax2.set_xticks(star)\nax2.set_xticklabels(GOOD_ID,rotation=90)\nax2.legend(loc='lower right',frameon=False, prop={'size':10})\n\n\n\nplt.subplots_adjust(bottom=0.3)\nplt.tight_layout(w_pad=5.0)\nplt.savefig('aperture_calibration.pdf')\nplt.show()\n\n","sub_path":"py/ebl_paper/nh_plot_aperture_calibration.py","file_name":"nh_plot_aperture_calibration.py","file_ext":"py","file_size_in_byte":7359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"295968610","text":"# Django settings for starfish project.\nimport logging\nimport os\n\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\n# 11s\nMAX_QUERY_EXECUTION_TIME = 11000\n\nMAX_ORG_ID = 3\n\nDEFAULT_CHARSET = 'utf-8'\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'Asia/Shanghai'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'zh_CN'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = False\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/var/www/example.com/media/\"\nMEDIA_ROOT = ''\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://example.com/media/\", \"http://media.example.com/\"\nMEDIA_URL = ''\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/var/www/example.com/static/\"\nSTATIC_ROOT = '/opt/mos/codebase/starfish-ws/static'\n\n# URL prefix for static files.\n# Example: \"http://example.com/static/\", \"http://static.example.com/\"\nSTATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'xs65g!tcydduzyez877)nz$3egahz87h-w4t_@@2f*t2_*be@o'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nROOT_URLCONF = 'starfish.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'starfish.wsgi.application'\n\nSETTINGS_DIR = os.path.dirname(__file__)\nPROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)\nPROJECT_PATH = os.path.abspath(PROJECT_PATH)\n\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_PATH, 'templates'),\n)\n\n\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n 'django.core.context_processors.request',\n)\n\nINSTALLED_APPS = (\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'corsheaders',\n 'oauth2_provider',\n 'apps.chat',\n 'apps.org',\n 'apps.mail',\n 'apps.project',\n 'apps.i18n',\n 'apps.message',\n 'apps.version',\n 'apps.fs',\n 'apps.bfs',\n 'apps.acl',\n 'apps.application',\n 'apps.account',\n 'apps.search',\n 'apps.misc',\n 'apps.oauth2',\n 'yxt',\n)\n\nOAUTH2_PROVIDER = {\n 'SCOPES': {\n 'read': '读取你的信息',\n 'write': '修改你的信息(包括发送消息)',\n },\n}\n\nDEFAULT_SCOPES = ['read', 'write']\n\nAUTH_USER_MODEL = 'account.User'\n\nSMTP_HOST = ['in-100-bj', 'in-101-bj', 'in-105-bj']\nSMPT_FAKE_PWD = 'some pwd'\n\nSERVICE_MAIL_CONF = {\n 'from': 'service@bitfamily.com',\n}\n\nSENDFILE_BACKEND = 'sendfile.backends.nginx'\nSENDFILE_URL = '/protected'\n\nMAIN_DOMAIN = 'api.starfish.im'\nMAIN_DOMAIN_YXT = 'qdim.yunxuetang.cn'\n\nUSER_AVATAR_URL_PREFIX_YXT = 'https://qdim.yunxuetang.cn/v1/user-avatars'\nORG_AVATAR_URL_PREFIX_YXT = 'https://qdim.yunxuetang.cn/v1/org-avatars'\nUSER_AVATAR_URL_PREFIX_STARFISH = 'https://api.starfish.im/v1/user-avatars'\nORG_AVATAR_URL_PREFIX_STARFISH = 'https://api.starfish.im/v1/org-avatars'\n\nPROJECT_DETAIL_URL_PATTERN = 'https://api.starfish.im/v1/app_url/?app_params=%2Fpages%2Ftask-detail%2Findex.html%3Fproject_id%3D{project_id}%26task_id%3D{task_id}&app={PROJECT_APP_ID}'\n\nPROJECT_APP_ICON = 'https://api.starfish.im/v1/app_icons/task_app_icon.png'\nFILE_APP_ICON = 'https://api.starfish.im/v1/app_icons/file_app_icon.png'\n\nAPI_URL = 'https://%s/v1' % MAIN_DOMAIN\nAPI_URL_YXT = 'https://%s/v1' % MAIN_DOMAIN_YXT\n\nINVITATION_URL = 'http://www.starfish.im/pages/invite/index.html?inviteId={invitation_id}&orgId={org_id}&phone={phone}'\n\nDOWNLOADS_URL_PREFIX = 'https://pkg.starfish.im/downloads'\n\nNOT_FOUND_PAGE = 'https://pkg.starfish.im/not-found'\n\nWECHAT_OPEN_PLATFORM_APP_ID = 'wx1689381406fcc40f'\nWECHAT_OPEN_PLATFORM_APP_SECRET = '755d8d89d439171b5a8478db32d1ec5d'\n\nWECHAT_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code={code}&grant_type=authorization_code' % (\n WECHAT_OPEN_PLATFORM_APP_ID, WECHAT_OPEN_PLATFORM_APP_SECRET\n)\n\nWECHAT_REFRESH_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token={refresh_token}' % (\n WECHAT_OPEN_PLATFORM_APP_ID\n)\n\nWECHAT_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}'\n\nSESSION_COOKIE_NAME = 'session_id'\n\nAGENT_AGE = 30 * 86400\n\nSTARFISH_TOKEN_QUEUE_NAME = 'new_starfish_token'\nSTARFISH_WECHAT_BIND_QUEUE_NAME = 'new_starfish_wechat_bind'\nSTARFISH_MESSAGE_QUEUE_NAME = 'new_starfish_message'\nSTARFISH_MESSAGE_ORG_QUEUE_NAME = 'new_starfish_org_message'\nSTARFISH_SAVE_USER_MESSAGE_QUEUE_NAME = 'new_starfish_save_user_message'\nSTARFISH_OFFLINE_QUEUE_NAME = 'new_starfish_offline'\nSTARFISH_CONVERSATION_UPDATED_MESSAGE_QUEUE_NAME = 'new_starfish_conversation_updated'\nSTARFISH_EMAIL_QUEUE_NAME = 'new_starfish_email'\nSTARFISH_AUTO_CLEAN_TABLES_QUEUE_NAME = 'new_starfish_auto_clean_tables'\nSTARFISH_INDEX_QUEUE_NAME = 'starfish_index'\nSTARFISH_ORG_DOMAIN_UPDATED_QUEUE = 'new_starfish_org_domain_updated'\nSTARFISH_APNS_QUEUE = 'maxwell_apns'\n\nSTARFISH_OPERATION_INFO_QUEUE = 'starfish_operation_info_queue'\nSTARFISH_SAVE_USER_MESSAGE_PROCESSES = (4, 2) # tuple(fast process count, slow process count)\nSTARFISH_SAVE_USER_MESSAGE_LIMIT = 100\n\nIMAGE_RESIZE_SPEC = {\n 'mobile': (400, 400),\n 'mobile_avatar': (200, 200),\n 'pc': (400, 400),\n}\n\nIMAGE_RESIZE_MIN_SIZE = {\n (400, 400): 80,\n (200, 200): 40,\n (70, 70): 10,\n (90, 90): 10,\n (64, 64): 10,\n (34, 34): 10,\n (32, 32): 10,\n}\n\nSMS_GATEWAY_URL = 'https://sms-gateway.starfish.im/messages'\nSMS_GATEWAY_SECRET_CODE = 'b0144c503fe928716c73726acfc53ef0'\nSMS_GATEWAY_TIMEOUT = 15\nSMS_TYPE_TOKEN = 'token'\nSMS_TYPE_INVITATION = 'invitation'\n\nOPENSIPS_GATEWAY = 'https://opensips-gateway.starfish.im/subscribers'\n\nMAIL_MESSAGE_ID_SUFFIX = 'starfish.im'\n\nWECHAT_CROP_TOKEN = \"CdukYVWy7bcOwTeOeqGuXS9Nxk\"\nWECHAT_CROP_ENCODING_AES_KEY = \"xn8vjJAS4buzk17saOIgR5SwQcwEldSmUCHVH3TpDPt\"\nWECHAT_CROP_CORP_ID = \"wx6cc875eb6aabdb03\"\n\nSMTP_MX_RECORDS = ('mx1.starfish.im.', 'mx2.starfish.im.')\n\nBFS_HOSTS_YXT = ['120.132.70.134', '123.59.67.127', '123.59.66.50']\nBFS_HOSTS = ['123.56.41.201', '123.57.156.96', '182.92.212.220']\n\nCORS_ORIGIN_ALLOW_ALL = False\nCORS_ALLOW_CREDENTIALS = True\n\nCORS_ORIGIN_REGEX_WHITELIST = (\n '^(?:http|https)s?://starfish.im',\n '^(?:http|https)s?://.*\\.starfish.im',\n '^(?:http|https)s?://getstarfish.com',\n '^(?:http|https)s?://.*\\.getstarfish.com',\n '^(?:http|https)s?://localhost:.*',\n '^(?:http|https)s?://192\\.168\\..*',\n)\n\nCORS_ALLOW_HEADERS = (\n 'x-requested-with',\n 'content-type',\n 'accept',\n 'origin',\n 'authorization',\n 'x-csrftoken',\n 'x-session-id',\n)\n\nIS_YXT_ENV = False\n\nenv = os.environ.get('DJANGO_ENV', None)\nvalid_envs = (\n 'unittest-sqlite3',\n 'dev',\n 'prod',\n 'script',\n 'test',\n 'script_test',\n 'prod_yxt',\n 'test_yxt',\n 'script_yxt')\nif env not in valid_envs:\n raise ValueError('invalid env: %s', env)\n\nif env == 'dev':\n from .settings_dev import *\n\nif env == 'unittest-sqlite3':\n from .settings_unittest_sqlite3 import *\n\nif env == 'prod':\n from .settings_prod import *\n\nif env == 'script':\n from .settings_script import *\n\nif env == 'test':\n from .settings_test import *\n\nif env == 'script_test':\n from .settings_script_test import *\n\nif env == 'prod_yxt':\n from .settings_prod_yxt import *\n IS_YXT_ENV = True\n\nif env == 'test_yxt':\n from .settings_test_yxt import *\n IS_YXT_ENV = True\n\nif env == 'script_yxt':\n from .settings_script_yxt import *\n IS_YXT_ENV = True\n\nos.environ['PGOPTIONS'] = '-c statement_timeout=%s' % MAX_QUERY_EXECUTION_TIME\nos.environ['PYTHON_EGG_CACHE'] = '/tmp'\n\nlogging._defaultFormatter = logging.Formatter(u\"%(message)s\")\n\nREST_FRAMEWORK = {\n 'EXCEPTION_HANDLER': 'common.exceptions.final_exception_handler'\n}\n\nSEARCH_HIGHLIGHT_TAGS = {\n 0: ([\"\"], [\"\"]),\n 1: ([''], ['']),\n 2: ([''], [''])\n}\n\nRABBIT_MQ_CONF = {\"host\": '123.57.59.182',\n \"port\": 5672,\n \"username\": \"wanglijun\",\n \"password\": \"wanglijun\"}\n\nREQUEST_TIME_LIMIT_LEVELS = (200, 500, 800)\n\n\n# settings for maxwell master endpoints for all deployments #\nMAXWELL_MASTER_STARFISH = 1 # maxwell starfish\nMAXWELL_MASTER_YXT = 100 # mawell yxt\n\n# set CURRENT_MAXWELL_MASTER by IS_YXT_ENV(DJANGO_ENV==prod_yxt or script_yxt)\nCURRENT_MAXWELL_MASTER = MAXWELL_MASTER_STARFISH\nif IS_YXT_ENV:\n CURRENT_MAXWELL_MASTER = MAXWELL_MASTER_YXT\n\nALL_MAXWELL_MASTER_ENDPOINTS = {\n MAXWELL_MASTER_STARFISH:\n ('tcp://en-101-bj:2012', 'tcp://en-102-bj:2012', 'tcp://en-105-bj:2012'),\n MAXWELL_MASTER_YXT:\n ('tcp://en-203-gd:2012', 'tcp://en-204-gd:2012', 'tcp://en-210-gd:2012'),\n}\n\nif not IS_YXT_ENV:\n ALL_MAXWELL_MASTER_ENDPOINTS[MAXWELL_MASTER_STARFISH] = MAXWELL_MASTER_ENDPOINT\n","sub_path":"starfish-ws/starfish/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":10247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"44059631","text":"import requests, json, datetime as dt, os\n\ndirname = os.path.dirname(__file__)\nfolder = os.path.join(dirname, 'coinapi/')\n\nnow = dt.datetime.now()\nyear = str(now.year)\nlastyear = str(now.year-1)\nyearbeforethat = str(now.year-2)\n\nif now.day < 10:\n day = \"0\"+str(now.day)\nelse:\n day = str(now.day)\nif now.month < 10:\n month = \"0\"+str(now.month)\nelse:\n month = str(now.month)\n\nurlpart1 = 'https://www.cryptocurrencychart.com/api/coin/history/'\nurlpart2 = '/'+lastyear+'-'+month+'-'+day+'/'+year+'-'+month+'-'+day+'/price/USD'\nurl2part1 = 'https://www.cryptocurrencychart.com/api/coin/history/'\nurl2part2 = '/'+yearbeforethat+'-'+month+'-'+day+'/'+lastyear+'-'+month+'-'+day+'/price/USD'\nheaders = dict(\n Key=\"cdbb52cebef377eb7edac0a0f89142ca\",\n Secret=\"70977d1fd58b5fca8a3be4b1697346fd\"\n)\n\nwith open(os.path.join(folder, 'data.json')) as d:\n coinNames = json.loads(d)\ncoinIDs = []\nfor entry in coinNames['id']:\n coinIDs.append(entry)\n\ni = 0\nwhile i < len(coinIDs):\n url = urlpart1+coinIDs[i]+urlpart2\n resp = requests.get(url=url, headers=headers)\n data = resp.json()\n writeTo = 'coinapi/price/'+coinIDs[i]+'.json'\n with open(writeTo, 'w') as outfile:\n json.dump(data, outfile)\n i+=1","sub_path":"getPrice.py","file_name":"getPrice.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"398941714","text":"import cgi\nimport datetime\nimport os\nfrom urllib2 import Request, urlopen\nimport json\nimport requests\nimport logging\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import users\nfrom google.appengine.api import urlfetch\n\nbooks_key = ndb.Key('Book', 'default_books')\n\nclass MediaItem(object):\n type = ''\n name = ''\n poster = ''\n synopsis = ''\n length = ''\n creator = ''\n released = ''\n date = ''\n count = ''\n\nclass Book(ndb.Model):\n name = ndb.StringProperty()\n author = ndb.StringProperty()\n pages = ndb.IntegerProperty()\n cover = ndb.StringProperty()\n published = ndb.StringProperty()\n date = ndb.DateTimeProperty(auto_now_add=True)\n userID = ndb.StringProperty()\n count = ndb.IntegerProperty()\n\ndef booksDB(offset, user):\n books = Book.query(Book.userID == user).order(-Book.date).fetch(limit=20, offset=offset)\n\n bookData = []\n\n for book in books:\n row = MediaItem()\n row.name = book.name\n row.poster = book.cover\n row.creator = book.author\n row.length = book.pages\n row.count = book.count\n row.date = book.published\n current = { 'type': 'book', 'name': row.name, 'count': row.count, 'poster': row.poster, 'released': row.date, 'pages': row.length, 'creator': row.creator }\n bookData.append(current)\n\n return bookData\n\n\ndef bookByID(id, user, count):\n headers = {'Accept': 'application/json'}\n bookID = id\n book = Book(parent=books_key)\n #user = users.get_current_user().user_id()\n\n googleBookVol = \"https://www.googleapis.com/books/v1/volumes/ID\"\n\n url = googleBookVol.replace(\"ID\", bookID)\n url = url + \"?key=AIzaSyD9o4jKfQvvCAr8glvom4llEAssu8ojmgk&country=US\"\n request = Request(url, headers=headers)\n\n response_body = json.loads(urlopen(request).read())\n book.pages = int(response_body['volumeInfo']['pageCount'])\n\n if response_body['volumeInfo']['imageLinks']:\n try:\n book.cover = response_body['volumeInfo']['imageLinks']['thumbnail']\n except:\n book.cover = response_body['volumeInfo']['imageLinks']['smallThumbnail']\n else:\n book.cover = ''\n\n book.name = response_body['volumeInfo']['title']\n book.published = response_body['volumeInfo']['publishedDate']\n book.author = response_body['volumeInfo']['authors'][0]\n book.userID = user\n book.count = count\n book.put()\n\n return int(response_body['volumeInfo']['pageCount'])\n\ndef getResults(term, user):\n books = Book.query(Book.userID == user).fetch()\n results = []\n\n for book in books:\n if term.lower() in book.name.lower():\n row = MediaItem()\n row.name = book.name\n row.poster = book.cover\n row.date = book.date\n row.count = book.count\n row.date = book.published\n #row.key = book.key\n current = {'type': 'book', 'name': row.name, 'count': row.count, 'poster': row.poster, 'released': row.date}\n results.append(current)\n\n return results","sub_path":"pyhelpers/books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"121369138","text":"import zmq\nimport pyaudio\nfrom cv2 import VideoCapture\nfrom util import SMOOTH,Filter,SHARPEN\nimport cv2\nimport numpy as np\nimport struct\nimport bz2\nimport time\nimport sys\n\nip = \"127.0.0.1\"\nport = 8000\n\ntry:\n ip = sys.argv[1] \n port = sys.argv[2]\nexcept:\n print(\"Please include the server IP and port\")\n exit()\n\ncontext = zmq.Context()\nSubscribeSocket = context.socket(zmq.SUB)\nSubscribeSocket.connect(\"tcp://\"+ip+\":%s\" % port) #Connect to server\nSubscribeSocket.setsockopt(zmq.SUBSCRIBE, b\"\")\n\ndef AddFPS(frame1,string):\n cv2.putText(frame1,string,(0,25),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2, cv2.LINE_AA)\n return frame1\n\nframes = 0\nfps = 30\ntimea = time.time() \n\nwhile True:\n \n compressed = SubscribeSocket.recv() #Receive packet\n buffer = bz2.decompress(compressed)\n shape = struct.unpack(\"HH\",buffer[1:5])\n frameBytes = buffer[5:] #Get Frame Bytes\n frame = np.frombuffer(frameBytes,dtype = np.uint8) #Convert bytes to frame array\n frame = np.unpackbits(np.asarray(frame,dtype=np.uint8))\n frame.shape = shape\n frame = (frame*255)\n frame = cv2.resize(frame,(int(640*1.5),int(480*1.5))) #Upscale Frame \n frame = Filter(frame,SMOOTH)\n frames += 1\n if(time.time() - timea > 5):\n timea = time.time()\n fps = frames//5\n frames = 0\n \n cv2.imshow(\"Video\",AddFPS(frame,str(fps)+\" FPS\")) #Display the frame\n cv2.waitKey(1)\n ","sub_path":"Receiver_black_and_white_packed.py","file_name":"Receiver_black_and_white_packed.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"317087682","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/auth.py\n# Compiled at: 2017-06-06 22:44:39\n# Size of source mod 2**32: 184 bytes\n\n\nclass NoAuthRequired:\n method_code = 0\n\n\nacceptable_auth_methods = [\n NoAuthRequired]\nacceptable_auth_method_codes = [method.method_code for method in acceptable_auth_methods]","sub_path":"pycfiles/asocks-0.1.0-py3.4/auth.cpython-34.py","file_name":"auth.cpython-34.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"507236216","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/profitbricks/__init__.py\n# Compiled at: 2018-07-12 06:04:26\n# Size of source mod 2**32: 733 bytes\n__doc__ = 'ProfitBricks API Client Library for Python'\n__version__ = '4.1.3'\nAPI_HOST = 'https://api.profitbricks.com/cloudapi/v4'\nAPI_VERSION = '4.0'","sub_path":"pycfiles/profitshare-0.1.tar/__init__.cpython-36.py","file_name":"__init__.cpython-36.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"309151155","text":"import json\nimport numpy as np \nimport matplotlib.pyplot as pt\n\npt.figure(figsize=(4.25,4.5))\nbg = (.9,.9,.9)\nfg = (.1,.1,.1)\n\nvariant = [\"max\",\"filter\",\"rfilter\"]\ntitles = [\"Max\", \"Cut-off\", \"Cut-off (repeats)\"]\n\nfor sp, vari in enumerate(variant):\n\n # filetoload = vari+\"avggen.json\"\n filetoload = vari+\"avgrwd.json\"\n \n full = {}\n with open(\"data/\" + filetoload, \"r\") as file:\n result = json.load(file)\n full[sp] = []\n for k,val in result.items():\n avgr = np.array(val)\n full[sp].append(val)\n full[sp]=np.array(full[sp])\n \n num_reps = len(full[sp])\n\n pt.subplot(len(variant),1,sp+1)\n pt.plot(full[sp].T, c=bg, zorder=0)\n pt.plot(full[sp].mean(axis=0), c=fg, zorder=1, label=\"Avg. over %d trials\" % num_reps)\n if sp == 0:\n pt.title(\"Testing set rewards\")\n pt.legend(loc=\"lower right\")\n pt.ylabel(titles[sp])\n \npt.tight_layout()\npt.savefig(\"filter_curves.eps\")\n# pt.show()\n \n","sub_path":"plot_filters.py","file_name":"plot_filters.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"183771841","text":"import numpy as np\n\nfrom scipy.ndimage.measurements import label\n\nimport matplotlib.image as mpimg\n\nimport matplotlib.pyplot as plt\n\n# Class that process heatmap and stores bounding boxes from heatmap of previous frame\nclass HeatMap():\n\n def __init__(self, img):\n self.heatmap = np.zeros_like(img[:,:,0]).astype(np.float)\n self.cold = 1\n self.hot = 1\n self.saturation = 10\n self.boundingBoxes = []\n self.threshold = 3\n\n # Heats every pixel in bounding box by one increment of self.hot. Begins by chilling all pixels\n #\n def add_heat(self, bbox_list):\n self.chill()\n if len(self.boundingBoxes) == 0:\n for box in bbox_list:\n self.heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += self.hot\n self.heatmap[np.where(self.heatmap > self.saturation)] = self.saturation\n else:\n for box in bbox_list:\n heat = 0\n self.heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += self.hot\n for box_exist in self.boundingBoxes:\n if box == box_exist:\n self.heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += self.hot\n heat = 1\n break\n\n self.heatmap[np.where(self.heatmap > self.saturation)] = self.saturation\n self.boundingBoxes = bbox_list\n return self.heatmap\n\n # Reduce all pixels in heatmap by 1 factor of self.cold and revert anything below 0 to 0\n def chill(self):\n self.heatmap -= self.cold\n self.heatmap[np.where(self.heatmap < 0)] = 0\n\n # Returns self.heatmap\n def get_heat(self):\n return np.copy(self.heatmap)\n\n # Zero out pixels below the threshold and returns threshold map\n def apply_threshold(self):\n self.heatmap[self.heatmap <= self.threshold] = 0\n return self.heatmap\n\n def set_threshold(self, threshold):\n self.threshold = threshold\n\n def get_boxes(self):\n return self.boundingBoxes\n","sub_path":"heat_map.py","file_name":"heat_map.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"503064960","text":"import pandas as pd\nimport sqlite3\nfrom sqlite3 import Error\n\nconn = sqlite3.connect(\"/Users/casa/Documents/sqlite-tools-osx-x86-3260000/ff.db\")\n\n#outfile='/Users/casa/Documents/FF/ranks.csv'\n#f = open(outfile,\"w+\")\ndf = pd.read_csv('/Users/casa/Documents/FF/locpairs.csv')\ndtf = pd.DataFrame({}, columns=['value','rank'])\nposf=0\nfor i in range(0,df.shape[0]):\n s1 = df.loc[i,'s1']\n s2 = df.loc[i,'s2']\n print(str(s1)+\"-\"+str(s2))\n sql=\"select value,quad,pquad from scoresAgg where s1=\"+str(s1)+\" and s2=\"+str(s2)+\" order by pquad desc;\"\n dfr=pd.read_sql(sql,conn)\n #rank=dfr.shape[0]\n rank=1\n pos=0\n dfr['rank']=0\n\n for name, row in dfr.iterrows():\n #dfr.loc[pos,'rank']=rank\n dtf.loc[posf,'value']=dfr.loc[pos,'value']\n dtf.loc[posf,'rank']=rank \n rank=rank+1\n pos=pos+1\n posf=posf+1\ndtf.to_csv(r'/Users/casa/Documents/FF/ranks.csv')\n \n","sub_path":"rankMax.py","file_name":"rankMax.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"418713604","text":"#encoding:utf-8\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nimport pymongo\n\nclient = pymongo.MongoClient('localhost',27017)\nganji = client['ganji']\nurl_list = ganji['url_list']\nurl_list_vip = ganji['url_list_vip']\nitem_info = ganji['item_info']\nitem_info_vip = ganji['item_info_vip']\n\n# 爬虫1:获取全部的抓取页面的url地址\ndef get_links_from(channel,pages,who_sells='o'):\n list_view = '{}{}{}'.format(channel,who_sells,str(pages))\n wb_content = requests.get(list_view)\n time.sleep(3)\n soup = BeautifulSoup(wb_content.text,'lxml')\n if soup.find('div','pageBox'):\n for link in soup.select('a.ft-tit'):\n item_link = link.get('href')\n if(who_sells=='o'):\n url_list.insert_one({'url':item_link})\n elif(who_sells=='a'):\n url_list_vip.insert_one({'url':item_link})\n\ndef get_item_info_from(url):\n wb_content = requests.get(url)\n time.sleep(3)\n soup = BeautifulSoup(wb_content.text,'lxml')\n no_longer_exist = soup.find('div.error')\n if no_longer_exist:\n pass\n else:\n title = soup.select('h1.title-name')[0].text\n publish_time = soup.select('i.pr-5')[0].text.split('发布')[0].split() if soup.find_all('i','pr-5') else None\n item_type = soup.select('ul.det-infor li span a')[0].text.split()\n price = soup.select('i.f22.fc-orange.f-type')[0].text\n area = list(soup.select('ul.det-infor li:nth-of-type(3)')[0].stripped_strings)[1:10]\n seller_types = soup.select('span.fc-orange')[0].text\n if '个人' in seller_types:\n seller_type = '个人'\n item_info.insert_one({'title':title,'time':publish_time,'itype':item_type,'price':price,'area':area,'stype':seller_type})\n else:\n seller_type = '商家'\n item_info_vip.insert_one({'title':title,'time':publish_time,'itype':item_type,'price':price,'area':area,'stype':seller_type})\n\nif __name__==\"__main__\":\n get_links_from('http://bj.ganji.com/rirongbaihuo/',3)\n get_links_from('http://bj.ganji.com/rirongbaihuo/',3,'a')\n get_item_info('http://bj.ganji.com/rirongbaihuo/1437873732x.htm')","sub_path":"week2大作业提交/huyongsheng/page_parsing.py","file_name":"page_parsing.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"164843570","text":"import openpyxl,random,math\r\nwb = openpyxl.load_workbook('criteriavalidation.xlsx')\r\nsheet1=wb.get_sheet_by_name('Sheet1')\r\nsheet2 = wb.get_sheet_by_name('Sheet2')\r\nsheet3 = wb.get_sheet_by_name('Sheet3')\r\n\r\n\r\n\r\n\r\ndistance_matrix=[[sheet2.cell(row=i,column=j).value for j in range (2,6)] for i in range(5,9)]\r\ncost_matrix=[[sheet2.cell(row=i,column=j).value for j in range (7,11)] for i in range(5,9)]\r\nstorage_cost_arr=[sheet2.cell(row=i,column=12).value for i in range (5,9)]\r\nprocessing_cost_arr=[sheet2.cell(row=i,column=13).value for i in range (5,9)]\r\nreceiving_cost_arr=[sheet2.cell(row=i,column=14).value for i in range (5,9)]\r\ntardiness_cost_arr=[sheet2.cell(row=i,column=15).value for i in range (5,9)]\r\nwarehouse_storage_limit_arr=[sheet2.cell(row=i,column=16).value for i in range (5,9)]\r\nvehicle_limit_arr=[sheet2.cell(row=i,column=17).value for i in range (5,9)]\r\nvehicle_limit_arr_temp=[sheet2.cell(row=i,column=17).value for i in range (5,9)]\r\n\r\n\r\nbreak_even_matrix=[[sheet2.cell(row=i,column=j).value for j in range (2,6)] for i in range(13,17)]\r\n\r\nprint('how many customers?')\r\nnum_customers=int(input())\r\n\r\n\r\nno_of_units=[sheet1.cell(row=i,column=2).value for i in range (2,num_customers+2)]\r\n#print(no_of_units)\r\nweight=[sheet1.cell(row=i,column=3).value for i in range (2,num_customers+2)]\r\nvolume=[sheet1.cell(row=i,column=4).value for i in range (2,num_customers+2)]\r\nware_house_number=[sheet1.cell(row=i,column=5).value for i in range (2,num_customers+2)]\r\ndestination=[sheet1.cell(row=i,column=6).value for i in range (2,num_customers+2)]\r\nprocessing_time=[sheet1.cell(row=i,column=7).value for i in range (2,num_customers+2)]\r\ndelivery_time=[sheet1.cell(row=i,column=8).value for i in range (2,num_customers+2)]\r\ndue_time=[sheet1.cell(row=i,column=9).value for i in range (2,num_customers+2)]\r\nis_order_Stored=[sheet1.cell(row=i,column=10).value for i in range (2,num_customers+2)]\r\nlate_vehicles=[sheet1.cell(row=i,column=11).value for i in range (2,num_customers+2)]\r\nstart_date=[sheet1.cell(row=i,column=12).value for i in range (2,num_customers+2)]\r\nend_date=[sheet1.cell(row=i,column=14).value for i in range (2,num_customers+2)]\r\nt=[sheet1.cell(row=i,column=15).value for i in range (2,num_customers+2)]\r\nt1=[sheet1.cell(row=i,column=16).value for i in range (2,num_customers+2)]\r\nk=[sheet3.cell(row=i,column=1).value for i in range (2,22)]\r\ncp=[sheet3.cell(row=i,column=2).value for i in range (2,22)]\r\nprop1=[sheet3.cell(row=i,column=3).value for i in range (2,22)]\r\nk1=[sheet3.cell(row=i,column=5).value for i in range (2,18)]\r\ncp1=[sheet3.cell(row=i,column=6).value for i in range (2,18)]\r\nprop2=[sheet3.cell(row=i,column=7).value for i in range (2,18)]\r\nware_dest_vehicles_limit=[[0 for i in range(4)] for j in range(4)]\r\nspace_left_arr=[[0 for i in range(4)] for j in range(4)]\r\n\r\nvolume_check_arr=[0,0,0,0]\r\nvehicles_check=[0,0,0,0]\r\nfor i in range(num_customers):\r\n\t#print(i,volume_check_arr[ware_house_number[i]-1],volume[i])\r\n\tvolume_check_arr[ware_house_number[i]-1]+=volume[i]\r\n\tvehicles_check[ware_house_number[i]-1]+=weight[i]\r\nfor i in range(4):\r\n\tvehicles_check[i]=int(vehicles_check[i]/10)+1\r\n\r\n\r\nreturn_vehciles_data=[[0 for i in range(31)] for j in range(4)]\r\n\r\n\r\ncurr_customer=0\r\n\r\n\r\nprobability=0.7\r\nis_new_order={}\r\nvolume_check_arr=[0,0,0,0]\r\nfor i in range(num_customers):\r\n\tvolume_check_arr[ware_house_number[i]-1]+=volume[i]\r\nfor i in range(2,num_customers+2):\r\n\tnew_order_flag=False\r\n\twarehouse_customer=ware_house_number[curr_customer]\r\n\tif warehouse_customer not in is_new_order:\r\n\t\tis_new_order[warehouse_customer]=1\r\n\t\tnew_order_flag=True\r\n\r\n\t\r\n\r\n\r\n\ttemp_vehicles_left=vehicle_limit_arr_temp[warehouse_customer-1]\r\n\tif ware_dest_vehicles_limit[warehouse_customer-1][destination[curr_customer]-1] - weight[curr_customer] < 0:\r\n\t\tware_dest_vehicles_limit[warehouse_customer-1][destination[curr_customer]-1]=abs(10-weight[curr_customer])\r\n\t\t#print('1',ware_dest_vehicles_limit[warehouse_customer-1][destination[curr_customer]-1])\r\n\t\tno_of_vehicles_customer=int(weight[curr_customer]/10)+1\r\n\t\tvehicle_limit_arr_temp[warehouse_customer-1]-=no_of_vehicles_customer\r\n\t\t#print(vehicle_limit_arr_temp)\r\n\telse:\r\n\t\tware_dest_vehicles_limit[warehouse_customer-1][destination[curr_customer]-1]-=weight[curr_customer]\r\n\tvehicles_new_temp=temp_vehicles_left-vehicle_limit_arr_temp[warehouse_customer-1]\r\n\t#print('new vehicles variable',vehicles_new_temp)\r\n\tspace_left=ware_dest_vehicles_limit[warehouse_customer-1][destination[curr_customer]-1]\r\n\t#print('space left',space_left)\r\n\tnew_space_temp=10 - space_left\r\n\tprint(new_space_temp)\r\n\t#print('new space temp',new_space_temp)\r\n\tvehicles_left=vehicle_limit_arr_temp[warehouse_customer-1]\r\n\t#print('vehicles left',vehicle_limit_arr_temp[warehouse_customer-1])\r\n\r\n\t\r\n\t#no_of_vehicles_customer=int(weight[curr_customer]/10)+1\r\n\tdestination_customer=destination[curr_customer]\t","sub_path":"criteriafinal.py","file_name":"criteriafinal.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"291932506","text":"from pymongo import collection\nfrom pymongo.message import insert\nimport requests\nfrom bs4 import BeautifulSoup\nimport os \nimport random\nimport time\nimport datetime\nimport pymongo\n\nurl = 'https://www.ptt.cc/bbs/stock/index.html'\nuserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'\nheaders = {'User-Agent' : userAgent}\ncookies = {'over18':'1'}\ntoday = datetime.datetime.today().strftime('%Y-%m-%d')\n#Mongodb\nclient = pymongo.MongoClient(host='localhost',port=27017)\nmydb = client.erictest\ncollection = mydb.pttstock\nif collection.find_one() != None:\n for r in collection.find().sort(\"_id\",-1).limit(1):\n mongo_id = r['_id']\nelse:\n mongo_id = 0\n\nfor i in range(3): \n print(f'-------第{i+1}頁開始--------')\n res = requests.get(url = url , headers = headers , cookies = cookies) \n soup = BeautifulSoup(res.text)\n clums = soup.select('div.r-ent') #文章格\n y = 0\n for clum in clums :\n date = {}\n try:\n y =y+1\n title = clum.find('a').text.replace('\\w','')\n for a in ('/','?','.','*','>','<',':'):\n title = title.replace(a ,'')\n href ='https://www.ptt.cc'+clum.find('a')['href']\n time.sleep(random.randint(1,3))\n post_res = requests.get(url = href , headers=headers , cookies = cookies)\n post_soup = BeautifulSoup(post_res.text)\n post_title = post_soup.title.text.split(' - ')[0]\n post_author = post_soup.findAll('div' , class_='article-metaline')[0].find('span' , 'article-meta-value').text\n post_time = post_soup.findAll('div' , class_='article-metaline')[2].find('span' , 'article-meta-value').text\n post_reply = post_soup.findAll('div' , class_='push')\n n = 0\n good = 0\n bad = 0\n for r in range(0, len(post_reply)):\n n = n+1\n if len(post_reply[r].find('span')['class']) == 2:\n good = good +1\n elif len(post_reply[r].find('span')['class']) == 3:\n if '噓 ' in post_reply[r].find('span' , class_='f1 hl push-tag'):\n bad =bad + 1\n print(title)\n\n if collection.find_one({'文章標題':post_title}) == None :\n mongo_id = mongo_id + 1\n date['_id']=mongo_id\n date['爬蟲時間']=today\n date['文章標題']=post_title\n date['作者']=post_author\n date['發文時間']=post_time\n date['回文數']=n\n date['讚數']=good\n date['噓數']=bad\n collection.insert(date)\n else:\n print('此資料已經存在')\n except:\n print('水桶文章')\n time.sleep(random.randint(1,3))\n print(f'共{y}個文章被下載')\n print('-------結束--------')\n url = 'https://www.ptt.cc'+soup.find('div', class_='btn-group btn-group-paging').findAll('a')[1]['href']","sub_path":"Mogodbpython/pytelmon.py","file_name":"pytelmon.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110594816","text":"import pytest\nfrom selenium import webdriver\n\n\n@pytest.fixture(scope=\"session\")\ndef setup(request):\n print(\"initiating chrome driver\")\n driver = webdriver.Chrome(executable_path=\"C:\\\\Users\\\\malin.nemergut\\\\PycharmProjects\\\\drivers\\\\chromedriver.exe\")\n session = request.node\n for item in session.items:\n cls = item.getparent(pytest.Class)\n setattr(cls.obj, \"driver\", driver)\n driver.get(\"http://seleniumeasy.com/test\")\n driver.maximize_window()\n\n yield driver\n driver.close()","sub_path":"parallel/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"475244560","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\n# 画像のネガポジ反転 2016/08/22 masaniwa\n\nimport cv2 as cv\nimport ProcessingTimer as pt\n\n# 画像のネガポジ反転\n# @param frame 入力画像\n# @return ネガポジ反転画像\ndef getInverseFrame(frame):\n\treturn 255 - frame\n\nif __name__ == \"__main__\":\n\tcv.namedWindow(\"InputFrame\")\n\tcv.namedWindow(\"InverseFrame\")\n\t\n\t# USBカメラ非接続でもVideoCapture.isOpened()でTrueが返ってくるので、まともにエラー処理してないです。\n\t# USBカメラ非接続でVideoCapture.read()すると落ちるので注意。\n\tcapture = cv.VideoCapture(0)\n\t\n\twhile True:\n\t\t_, inputFrame = capture.read()\n\t\t\n\t\twith pt.ProcessingTimer(\"getInverseFrame\"):\n\t\t\tinverseFrame = getInverseFrame(inputFrame)\n\t\t\t\n\t\tcv.imshow(\"InputFrame\", inputFrame)\n\t\tcv.imshow(\"InverseFrame\", inverseFrame)\n\t\t\n\t\t# ESCキーが押されると終了\n\t\t# waitKey()で取得できるキーコードがおかしいので応急処置\n\t\tif (cv.waitKey(60) % 256) == 27:\n\t\t\tbreak\n\t\t\t\n\tcapture.release()\n\tcv.destroyAllWindows()\n","sub_path":"getInverseFrame.py","file_name":"getInverseFrame.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"229583923","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 24 11:19:51 2018\n\n@author: Sotheanith Sok\n\nPurpose: Pseudorandom number generator tutorial\n\"\"\"\nimport math\n#Below the parameters in the formula are assigned their values. \n\nM = 41\nA = 31\nN = 100\n\n#Below is a prompt for the user to enter their seed.\nS=int(input(\"Enter the value of your seed.\\n\"))\n\n#Below is the formula for the pseudorandom generator\nfor i in range(15):\n S=(M*S+A)%N\n #Make it between [0,1)\n r=S/N\n #print (\"%.3f\"%r)\n number=math.floor(r*6+1)\n print(number);\n \n","sub_path":"Lab/Lab1.py","file_name":"Lab1.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"420617934","text":"from django.shortcuts import render, redirect, render_to_response\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom .forms import ImageUploadForm, ExcelUploadForm\nfrom .models import Document\nfrom django.urls import reverse\nfrom django.core.files.storage import default_storage\nfrom django.core.files.base import ContentFile\nfrom django.conf import settings\nfrom django.template import RequestContext\nfrom detector.detector import model_init, TRANSFORM_IMG_TEST\nfrom django.core.cache import cache\n\nimport os\nimport cv2\nimport glob\nimport random\nimport seaborn as sns\nfrom datetime import datetime\nimport scipy.misc\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom anova.views import read_excel, t_test, tukeys\n\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\n\ndef directory_path():\n # file will be uploaded to MEDIA_ROOT/user_/\n today = datetime.today()\n cur_date = datetime(today.year, today.month, today.day).strftime('%y_%m_%d')\n return 'uploads/{0}/{1}/'.format(cur_date,random.randint(1000,9999))\n\ndef basic(request):\n # model = model_init()\n if request.method == 'POST':\n\n if request.POST.get('t_test') == 't_test':\n try:\n cache_key = 'my_heavy_view_cache_key'\n df, dfr, dict_pos, uniq_names = cache.get(cache_key)\n newDF, num_pairs = t_test(df, dfr, dict_pos, uniq_names)\n return render(request, 'main/basic.html', {'result':newDF.to_html(), 'num_pairs':num_pairs})\n except:\n return render(request, 'main/basic.html', {'num_pairs':1})\n\n elif request.POST.get('t_test') == 'anova':\n try:\n cache_key = 'my_heavy_view_cache_key'\n df, dfr, dict_pos, uniq_names = cache.get(cache_key)\n return render(request, 'main/basic.html', {'result':dfr.to_html(), 'num_pairs':1})\n except:\n return render(request, 'main/basic.html', {'num_pairs':1})\n\n elif request.POST.get('t_test') == 'tukeys':\n try:\n cache_key = 'my_heavy_view_cache_key'\n df, dfr, dict_pos, uniq_names = cache.get(cache_key)\n result = tukeys(df, dfr, dict_pos, uniq_names)\n return render(request, 'main/basic.html', {'result':1, 'num_pairs':1, 'qwe':result})\n except:\n return render(request, 'main/basic.html', {'num_pairs':1})\n\n elif request.POST['type_of_analysis'] == 'opisthorchiasis':\n form = ImageUploadForm(request.POST, request.FILES)\n if form.is_valid():\n image_name, full_path = handle_uploaded_image(request.FILES['image'])\n prediction = detect_image(full_path)\n form = ImageUploadForm()\n image_name2 = 'outfile.jpg'\n context = {'photo_url': image_name, 'photo_url2':image_name2}\n return render(request, 'main/basic.html', context)\n else:\n form = ImageUploadForm()\n return render(request, 'main/basic.html')\n\n elif request.POST['type_of_analysis'] == 'anova':\n try:\n myfile = request.FILES['image']\n except:\n form = ImageUploadForm()\n return render(request, 'main/basic.html',{'num_pairs':1})\n path = directory_path()\n fs = FileSystemStorage(path)\n filename = fs.save(myfile.name, myfile)\n uploaded_file_url = fs.url(filename)\n\n form = ImageUploadForm()\n dfr, dict_pos, uniq_names, df = read_excel(os.path.join(settings.BASE_DIR, path + 'sample.xlsx'))\n result = [df, dfr, dict_pos, uniq_names]\n cache_key = 'my_heavy_view_cache_key'\n cache.set(cache_key, result, 720)\n # pic = sns.heatmap(dfr.round(5), annot=True, fmt=\"g\", cmap='viridis')\n # return render(request, 'main/basic.html', {'result':pic.get_figure()})\n return render(request, 'main/basic.html', {'result':dfr.to_html(), 'num_pairs':1})\n\n else:\n form = ImageUploadForm()\n return render(request, 'main/basic.html', {'num_pairs':1})\n # Save via models and forms\n # form = ExcelUploadForm(request.POST, request.FILES)\n # if form.is_valid():\n # newdoc = Document(docfile = request.FILES['image'])\n # # tmp = dir(newdoc)\n # # for i in tmp:\n # # print(eval('newdoc.{}'.format(i)))\n # # print('--'*10)\n # newdoc.save()\n # data = request.FILES['image']\n # print(data)\n # # full_path = handle_uploaded_excel(request.FILES['image'])\n # return HttpResponse('q')\n # else:\n # form = ImageUploadForm()\n # return render(request, 'main/basic.html')\n form = ImageUploadForm()\n return render(request, 'main/basic.html', {'num_pairs':1})\n\n\n\ndef handle_uploaded_image(image):\n # save image in to static/media - Nginx/Gunicorn\n image = image.read()\n path = default_storage.save('', ContentFile(image))\n full_path = os.path.join(settings.MEDIA_ROOT, path)\n image_name = 'media/' + path\n return image_name, full_path\n\n\ndef detect_image(full_path):\n model = model_init()\n img = TRANSFORM_IMG_TEST(cv2.imread(full_path)[...,::-1]).unsqueeze(0)\n res = model(img)\n res_FOR_VISUAL = res[0][0].data.numpy()\n scipy.misc.imsave('static/outfile.jpg', res_FOR_VISUAL) # for web-server\n # scipy.misc.imsave('main/static/outfile.jpg', res_FOR_VISUAL) # for local-server\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"356265117","text":"from __future__ import annotations\n\nimport asyncio\nimport logging\nimport random\nfrom heapq import nsmallest\nfrom itertools import chain\nfrom typing import List, Union, Optional, Tuple, Iterator, Callable, Dict\n\nfrom . import rpc\nfrom .config import asize, ksize\nfrom .node import ID, Node, Addr\n\nlog = logging.getLogger(__name__)\n\n\nclass KBucket(List[Node]):\n def __init__(self, range: Tuple[int, int]) -> None:\n self.range = range\n super().__init__()\n\n def __repr__(self) -> str:\n return f''\n\n def covers(self, node: Node) -> bool:\n return self.range[0] <= node.id < self.range[1]\n\n def full(self) -> bool:\n return len(self) >= ksize\n\n def divide(self, mask: int) -> Tuple[KBucket, KBucket]:\n mid = (self.range[0] + self.range[1]) // 2\n left = KBucket((self.range[0], mid))\n right = KBucket((mid, self.range[1]))\n for node in self:\n if node.id & mask:\n right.append(node)\n else:\n left.append(node)\n return left, right\n\n\nclass LookupQueue(asyncio.Queue):\n def __init__(self, xor: Callable[[Node], int], nodes: Iterator[Node]):\n self._xor = xor\n self._queue = nsmallest(ksize, nodes, key=xor)\n # reversed to get better pop() performance\n self._queue.reverse()\n super().__init__()\n\n def _init(self, maxsize):\n pass\n\n def _put(self, node: Node):\n lo, hi = 0, len(self._queue)\n distance = self._xor(node)\n while lo < hi:\n mid = (lo + hi) // 2\n if distance > self._xor(self._queue[mid]):\n hi = mid\n else:\n lo = mid + 1\n self._queue.insert(lo, node)\n self._queue = self._queue[-ksize:]\n\n def _get(self):\n return self._queue.pop()\n\n\nclass ValueFound(Exception):\n pass\n\n\nclass NodeFound(Exception):\n pass\n\n\ndef xor_key(id: ID) -> Callable[[Node], int]:\n return lambda n: n.id ^ id\n\n\nclass Server:\n def __init__(self, addr: Addr, id: Optional[ID] = None) -> None:\n if id is None:\n id = ID(random.getrandbits(160))\n self.node = Node(id, addr)\n self.node_level = 0\n self.routing_table: List[KBucket] = [KBucket((0, 2 ** 160))]\n self.storage: Dict[ID, bytes] = {}\n\n async def start(self, bootstrap: Optional[List[Node]] = None):\n self.rpc = await rpc.start(self.node, on_rpc=self.update_routing_table)\n register = self.rpc.register\n\n @register\n def ping() -> str:\n return 'pong'\n\n @register\n def store(key: ID, value: bytes) -> None:\n self.storage[key] = value\n\n @register\n def find_node(id: ID) -> List[Node]:\n return self.get_closest_nodes(id)\n\n @register\n def find_value(id: ID) -> Union[List[Node], bytes]:\n try:\n return self.storage[id]\n except KeyError:\n return find_node(id)\n\n # join the network\n if bootstrap is None:\n return\n\n tasks = (self.rpc.find_node(node.addr, self.node.id)\n for node in bootstrap)\n res = await asyncio.gather(*tasks, return_exceptions=True)\n for idx, new_nodes in enumerate(res):\n if isinstance(new_nodes, Exception):\n log.error(f'failed to connect.')\n continue\n await self.update_routing_table(bootstrap[idx])\n for node in new_nodes:\n await self.update_routing_table(node)\n\n def __repr__(self):\n return f''\n\n async def update_routing_table(self, new: Node):\n if new == self.node:\n log.debug('Ignoring this node.')\n return\n bucket = next(bucket for bucket in self.routing_table\n if bucket.covers(new))\n\n if new in bucket:\n bucket.remove(new)\n bucket.append(new)\n return\n\n if not bucket.full():\n bucket.append(new)\n return\n\n if bucket.covers(self.node):\n mask = (1 << self.node_level) & self.node.id\n self.node_level += 1\n self.routing_table.remove(bucket)\n self.routing_table += bucket.divide(mask)\n await self.update_routing_table(new)\n return\n\n oldest = bucket[0]\n try:\n await self.rpc.ping(oldest.addr)\n except asyncio.TimeoutError:\n bucket.remove(oldest)\n bucket.append(new)\n\n # the new node is dropped\n\n def get_closest_nodes(self, id: ID) -> List[Node]:\n return nsmallest(ksize, chain(*self.routing_table), xor_key(id))\n\n async def _lookup_node(self, id: ID, rpc_func: str) -> List[Node]:\n \"\"\"Locate the k closest nodes to the given node ID.\n \"\"\"\n xor = xor_key(id)\n nodes = self.get_closest_nodes(id)\n queue = LookupQueue(xor, nodes)\n queried = set()\n\n async def query():\n while not queue.empty():\n node = await queue.get()\n queried.add(node)\n new_nodes = await self.rpc.call(node.addr, rpc_func, id)\n if isinstance(new_nodes, bytes):\n raise ValueFound(new_nodes)\n for node in new_nodes:\n if node == self.node:\n continue\n if node.id == id:\n raise NodeFound(node)\n if node not in queried:\n queue.put_nowait(node)\n\n try:\n await asyncio.gather(*(query() for _ in range(asize)))\n except NodeFound as exc:\n return [exc.args[0]]\n return nsmallest(ksize, queried, key=xor)\n\n async def set(self, key: ID, value: bytes) -> None:\n self.storage[key] = value\n nodes = await self._lookup_node(key, 'find_node')\n await asyncio.gather(\n *(self.rpc.store(node.addr, key, value) for node in nodes))\n\n async def get(self, key: ID) -> bytes:\n try:\n return self.storage[key]\n except KeyError:\n try:\n await self._lookup_node(key, 'find_value')\n except ValueFound as exc:\n return exc.args[0]\n else:\n raise KeyError(f'key {key} not found')\n\n async def close(self):\n self.rpc.close()\n","sub_path":"kademlia/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"437730437","text":"class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n def __repr__(self):\n return str(self.value)\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def __str__(self):\n cur_head = self.head\n out_string = \"\"\n while cur_head:\n out_string += str(cur_head.value) + \" -> \"\n cur_head = cur_head.next\n return out_string[0:len(out_string)-3]\n\n\n def append(self, value):\n\n if self.head is None:\n self.head = Node(value)\n return\n\n node = self.head\n while node.next:\n node = node.next\n\n node.next = Node(value)\n\n def size(self):\n size = 0\n node = self.head\n while node:\n size += 1\n node = node.next\n\n return size\n\n\ndef unique_elements(llist_1, llist_2):\n unique_set1 = set()\n unique_set2 = set()\n\n current = llist_1.head\n while current is not None:\n unique_set1.add(current.value)\n current = current.next\n\n current = llist_2.head\n\n while current is not None:\n unique_set2.add(current.value)\n current = current.next\n\n return unique_set1, unique_set2\n\n\ndef union(llist_1, llist_2):\n # Your Solution Here\n if llist_1.head is None:\n return llist_2\n if llist_2 .head is None:\n return llist_1\n\n result = unique_elements(llist_1, llist_2)\n union_res = result[0].union(result[1])\n\n resultll = LinkedList()\n\n for val in union_res:\n resultll.append(val)\n\n return resultll\n\n\ndef intersection(llist_1, llist_2):\n # Your Solution Here\n if llist_1 is None or llist_2 is None:\n return []\n\n result = unique_elements(llist_1, llist_2)\n intersection_res = result[0].intersection(result[1])\n\n resultll = LinkedList()\n\n for val in intersection_res:\n resultll.append(val)\n\n return resultll\n\n\n# Test case 1\n\nlinked_list_1 = LinkedList()\nlinked_list_2 = LinkedList()\n\nelement_1 = [3,2,4,35,6,65,6,4,3,21]\nelement_2 = [6,32,4,9,6,1,11,21,1]\n\nfor i in element_1:\n linked_list_1.append(i)\n\nfor i in element_2:\n linked_list_2.append(i)\n\nprint (union(linked_list_1,linked_list_2))\nprint (intersection(linked_list_1,linked_list_2))\n\n# Test case 2\n\nlinked_list_3 = LinkedList()\nlinked_list_4 = LinkedList()\n\nelement_1 = [3,2,4,35,6,65,6,4,3,23]\nelement_2 = [1,7,8,9,11,21,1]\n\nfor i in element_1:\n linked_list_3.append(i)\n\nfor i in element_2:\n linked_list_4.append(i)\n\nprint (union(linked_list_3,linked_list_4))\nprint (intersection(linked_list_3,linked_list_4))\n\n# Test case 3\n\nlinked_list_3 = LinkedList()\nlinked_list_4 = LinkedList()\n\nelement_1 = []\nelement_2 = [1,7,8,9,11,21,1]\n\nfor i in element_1:\n linked_list_3.append(i)\n\nfor i in element_2:\n linked_list_4.append(i)\n\nprint (union(linked_list_3,linked_list_4))\nprint (intersection(linked_list_3,linked_list_4))\n\n# Test case 4\n\nlinked_list_3 = LinkedList()\nlinked_list_4 = LinkedList()\n\nelement_1 = [1,7,8,9,11,21,1]\nelement_2 = []\n\nfor i in element_1:\n linked_list_3.append(i)\n\nfor i in element_2:\n linked_list_4.append(i)\n\nprint (union(linked_list_3,linked_list_4))\nprint (intersection(linked_list_3,linked_list_4))\n\n# Test case 5\n\nlinked_list_3 = LinkedList()\nlinked_list_4 = LinkedList()\n\nelement_1 = []\nelement_2 = []\n\nfor i in element_1:\n linked_list_3.append(i)\n\nfor i in element_2:\n linked_list_4.append(i)\n\nprint(union(linked_list_3,linked_list_4))\nprint(intersection(linked_list_3,linked_list_4))\n\n","sub_path":"Show Me DataStructures/UnionAndIntersection/IntersectionAndUnion.py","file_name":"IntersectionAndUnion.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"15168981","text":"# coding: utf-8\n\n\"\"\"\n Selling Partner API for Reports\n\n The Selling Partner API for Reports lets you retrieve and manage a variety of reports that can help selling partners manage their businesses. # noqa: E501\n\n OpenAPI spec version: 2020-09-04\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass Report(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 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 'marketplace_ids': 'list[str]',\n 'report_id': 'str',\n 'report_type': 'str',\n 'data_start_time': 'datetime',\n 'data_end_time': 'datetime',\n 'report_schedule_id': 'str',\n 'created_time': 'datetime',\n 'processing_status': 'str',\n 'processing_start_time': 'datetime',\n 'processing_end_time': 'datetime',\n 'report_document_id': 'str'\n }\n\n attribute_map = {\n 'marketplace_ids': 'marketplaceIds',\n 'report_id': 'reportId',\n 'report_type': 'reportType',\n 'data_start_time': 'dataStartTime',\n 'data_end_time': 'dataEndTime',\n 'report_schedule_id': 'reportScheduleId',\n 'created_time': 'createdTime',\n 'processing_status': 'processingStatus',\n 'processing_start_time': 'processingStartTime',\n 'processing_end_time': 'processingEndTime',\n 'report_document_id': 'reportDocumentId'\n }\n\n def __init__(self, marketplace_ids=None, report_id=None, report_type=None, data_start_time=None, data_end_time=None, report_schedule_id=None, created_time=None, processing_status=None, processing_start_time=None, processing_end_time=None, report_document_id=None): # noqa: E501\n \"\"\"Report - a model defined in Swagger\"\"\" # noqa: E501\n self._marketplace_ids = None\n self._report_id = None\n self._report_type = None\n self._data_start_time = None\n self._data_end_time = None\n self._report_schedule_id = None\n self._created_time = None\n self._processing_status = None\n self._processing_start_time = None\n self._processing_end_time = None\n self._report_document_id = None\n self.discriminator = None\n if marketplace_ids is not None:\n self.marketplace_ids = marketplace_ids\n self.report_id = report_id\n self.report_type = report_type\n if data_start_time is not None:\n self.data_start_time = data_start_time\n if data_end_time is not None:\n self.data_end_time = data_end_time\n if report_schedule_id is not None:\n self.report_schedule_id = report_schedule_id\n self.created_time = created_time\n self.processing_status = processing_status\n if processing_start_time is not None:\n self.processing_start_time = processing_start_time\n if processing_end_time is not None:\n self.processing_end_time = processing_end_time\n if report_document_id is not None:\n self.report_document_id = report_document_id\n\n @property\n def marketplace_ids(self):\n \"\"\"Gets the marketplace_ids of this Report. # noqa: E501\n\n A list of marketplace identifiers for the report. # noqa: E501\n\n :return: The marketplace_ids of this Report. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._marketplace_ids\n\n @marketplace_ids.setter\n def marketplace_ids(self, marketplace_ids):\n \"\"\"Sets the marketplace_ids of this Report.\n\n A list of marketplace identifiers for the report. # noqa: E501\n\n :param marketplace_ids: The marketplace_ids of this Report. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._marketplace_ids = marketplace_ids\n\n @property\n def report_id(self):\n \"\"\"Gets the report_id of this Report. # noqa: E501\n\n The identifier for the report. This identifier is unique only in combination with a seller ID. # noqa: E501\n\n :return: The report_id of this Report. # noqa: E501\n :rtype: str\n \"\"\"\n return self._report_id\n\n @report_id.setter\n def report_id(self, report_id):\n \"\"\"Sets the report_id of this Report.\n\n The identifier for the report. This identifier is unique only in combination with a seller ID. # noqa: E501\n\n :param report_id: The report_id of this Report. # noqa: E501\n :type: str\n \"\"\"\n if report_id is None:\n raise ValueError(\"Invalid value for `report_id`, must not be `None`\") # noqa: E501\n\n self._report_id = report_id\n\n @property\n def report_type(self):\n \"\"\"Gets the report_type of this Report. # noqa: E501\n\n The report type. # noqa: E501\n\n :return: The report_type of this Report. # noqa: E501\n :rtype: str\n \"\"\"\n return self._report_type\n\n @report_type.setter\n def report_type(self, report_type):\n \"\"\"Sets the report_type of this Report.\n\n The report type. # noqa: E501\n\n :param report_type: The report_type of this Report. # noqa: E501\n :type: str\n \"\"\"\n if report_type is None:\n raise ValueError(\"Invalid value for `report_type`, must not be `None`\") # noqa: E501\n\n self._report_type = report_type\n\n @property\n def data_start_time(self):\n \"\"\"Gets the data_start_time of this Report. # noqa: E501\n\n The start of a date and time range used for selecting the data to report. # noqa: E501\n\n :return: The data_start_time of this Report. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._data_start_time\n\n @data_start_time.setter\n def data_start_time(self, data_start_time):\n \"\"\"Sets the data_start_time of this Report.\n\n The start of a date and time range used for selecting the data to report. # noqa: E501\n\n :param data_start_time: The data_start_time of this Report. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._data_start_time = data_start_time\n\n @property\n def data_end_time(self):\n \"\"\"Gets the data_end_time of this Report. # noqa: E501\n\n The end of a date and time range used for selecting the data to report. # noqa: E501\n\n :return: The data_end_time of this Report. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._data_end_time\n\n @data_end_time.setter\n def data_end_time(self, data_end_time):\n \"\"\"Sets the data_end_time of this Report.\n\n The end of a date and time range used for selecting the data to report. # noqa: E501\n\n :param data_end_time: The data_end_time of this Report. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._data_end_time = data_end_time\n\n @property\n def report_schedule_id(self):\n \"\"\"Gets the report_schedule_id of this Report. # noqa: E501\n\n The identifier of the report schedule that created this report (if any). This identifier is unique only in combination with a seller ID. # noqa: E501\n\n :return: The report_schedule_id of this Report. # noqa: E501\n :rtype: str\n \"\"\"\n return self._report_schedule_id\n\n @report_schedule_id.setter\n def report_schedule_id(self, report_schedule_id):\n \"\"\"Sets the report_schedule_id of this Report.\n\n The identifier of the report schedule that created this report (if any). This identifier is unique only in combination with a seller ID. # noqa: E501\n\n :param report_schedule_id: The report_schedule_id of this Report. # noqa: E501\n :type: str\n \"\"\"\n\n self._report_schedule_id = report_schedule_id\n\n @property\n def created_time(self):\n \"\"\"Gets the created_time of this Report. # noqa: E501\n\n The date and time when the report was created. # noqa: E501\n\n :return: The created_time of this Report. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._created_time\n\n @created_time.setter\n def created_time(self, created_time):\n \"\"\"Sets the created_time of this Report.\n\n The date and time when the report was created. # noqa: E501\n\n :param created_time: The created_time of this Report. # noqa: E501\n :type: datetime\n \"\"\"\n if created_time is None:\n raise ValueError(\"Invalid value for `created_time`, must not be `None`\") # noqa: E501\n\n self._created_time = created_time\n\n @property\n def processing_status(self):\n \"\"\"Gets the processing_status of this Report. # noqa: E501\n\n The processing status of the report. # noqa: E501\n\n :return: The processing_status of this Report. # noqa: E501\n :rtype: str\n \"\"\"\n return self._processing_status\n\n @processing_status.setter\n def processing_status(self, processing_status):\n \"\"\"Sets the processing_status of this Report.\n\n The processing status of the report. # noqa: E501\n\n :param processing_status: The processing_status of this Report. # noqa: E501\n :type: str\n \"\"\"\n if processing_status is None:\n raise ValueError(\"Invalid value for `processing_status`, must not be `None`\") # noqa: E501\n allowed_values = [\"CANCELLED\", \"DONE\", \"FATAL\", \"IN_PROGRESS\", \"IN_QUEUE\"] # noqa: E501\n if processing_status not in allowed_values:\n raise ValueError(\n \"Invalid value for `processing_status` ({0}), must be one of {1}\" # noqa: E501\n .format(processing_status, allowed_values)\n )\n\n self._processing_status = processing_status\n\n @property\n def processing_start_time(self):\n \"\"\"Gets the processing_start_time of this Report. # noqa: E501\n\n The date and time when the report processing started, in ISO 8601 date time format. # noqa: E501\n\n :return: The processing_start_time of this Report. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._processing_start_time\n\n @processing_start_time.setter\n def processing_start_time(self, processing_start_time):\n \"\"\"Sets the processing_start_time of this Report.\n\n The date and time when the report processing started, in ISO 8601 date time format. # noqa: E501\n\n :param processing_start_time: The processing_start_time of this Report. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._processing_start_time = processing_start_time\n\n @property\n def processing_end_time(self):\n \"\"\"Gets the processing_end_time of this Report. # noqa: E501\n\n The date and time when the report processing completed, in ISO 8601 date time format. # noqa: E501\n\n :return: The processing_end_time of this Report. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._processing_end_time\n\n @processing_end_time.setter\n def processing_end_time(self, processing_end_time):\n \"\"\"Sets the processing_end_time of this Report.\n\n The date and time when the report processing completed, in ISO 8601 date time format. # noqa: E501\n\n :param processing_end_time: The processing_end_time of this Report. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._processing_end_time = processing_end_time\n\n @property\n def report_document_id(self):\n \"\"\"Gets the report_document_id of this Report. # noqa: E501\n\n The identifier for the report document. Pass this into the getReportDocument operation to get the information you will need to retrieve and decrypt the report document's contents. # noqa: E501\n\n :return: The report_document_id of this Report. # noqa: E501\n :rtype: str\n \"\"\"\n return self._report_document_id\n\n @report_document_id.setter\n def report_document_id(self, report_document_id):\n \"\"\"Sets the report_document_id of this Report.\n\n The identifier for the report document. Pass this into the getReportDocument operation to get the information you will need to retrieve and decrypt the report document's contents. # noqa: E501\n\n :param report_document_id: The report_document_id of this Report. # noqa: E501\n :type: str\n \"\"\"\n\n self._report_document_id = report_document_id\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(Report, 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, Report):\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","sub_path":"sp_api/api/reports/models/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":14075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"338934798","text":"#!/usr/bin/python\n\nimport lib\nimport lib.interpolation as interpolation\nimport lib.benchmarking as benchmarking\nimport lib.training as training\nimport lib.userio as userio\n\n\"\"\"\nExample specifics:\n\n - Application: Dot Product with 2 Paramters (One Faked)\n - Interpolator: Kriging\n - Initial point selection scheme: linear\n - Trainer: None\n\n - Initial points: 1000\n - Trained points: 0\n\n\"\"\"\n\nexample_name = \"example-c\"\n\n# General setup. 'shell' directs and controls user i/o.\n# 'data' stores all of the points and values.\nshell = userio.Shell()\ndata = interpolation.Data()\n\n# ---------- Set up the benchmarking and point-generation tools ---------- #\napp_name = \"dotprod2\"\napp_tags = [\"N\", \"-\"]\nN_range = [64, 16384]\nZ_range = [64, 16384]\napp_ranges = [N_range, Z_range]\nthings_to_parse = [\"Run Time\"]\nstart_strings = [\"RUNTIME: \"]\nend_strings = [\";r\"]\ncommand = \"samples/dot_serial\"\n\nbench = benchmarking.Benchmarking(app_name, app_tags)\nbench.setup(things_to_parse, start_strings, end_strings, command)\nbench.shell = shell\n\npointgen = benchmarking.PointGenerator(app_ranges)\n\n# ----------------------- Set up the interpolator ------------------------ #\n\nvariogram = { \"type\": \"exponential\",\n \"nugget\": 0.001,\n \"range\": 10.0,\n \"sill\": 1.0 }\npolynomial = 0\nneighbors = 4\n\ninterpol = interpolation.Kriging(data, polynomial, variogram, neighbors)\n\ninitial_points = pointgen.diaglinspace(200)\ntrainer = training.Training(interpol, bench, pointgen, shell)\ntrainer.initialize(initial_points)\n\n# We're done, save the results.\nbench.save_bmark(\"saves/\" + example_name)\nbench.save_csv(\"saves/\" + example_name)\n\n# ------------------------ Evaluate the Results -------------------------- #\n\nbench.load_bmark(\"saves/\" + example_name)\n\nevaluation_points = pointgen.randdiaglinspace(500)\n\nestimates, variances = interpol.interpolate(evaluation_points)\ntrainer.evaluate(evaluation_points, estimates)\n","sub_path":"Benchmarks/Tile_Benchmarks/calibration/interpolator/example-c.py","file_name":"example-c.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"433672597","text":"import argparse\nimport os\nimport shutil\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader,Dataset\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom PIL import Image\nfrom Net import Net\nfrom CenterLoss import CenterLoss\nfrom torch.autograd import Variable\nimport torch.backends.cudnn as cudnn\n\nos.environ['CUDA_VISIBLE_DEVICES']='0'\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\nparser.add_argument('--epochs', default=90, type=int, metavar='N',\n help='number of total epochs to run')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch-size', default=256, type=int,\n metavar='N', help='mini-batch size (default: 256)')\nparser.add_argument('--lr', '--learning-rate', default=0.1, type=float,\n metavar='LR', help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\nparser.add_argument('--loss_weight', default=0.003, type=float, metavar='LW',\n help='loss weight')\nparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,\n metavar='W', help='weight decay (default: 1e-4)')\nparser.add_argument('--print-freq', '-p', default=10, type=int,\n metavar='N', help='print frequency (default: 10)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',\n help='evaluate model on validation set')\nparser.add_argument('--pretrained', dest='pretrained', action='store_true',\n help='use pre-trained model')\n\nbest_prec1 = 0\n\n#=======================================================================================\n#----------------------------------------ready the dataset-----------------------------\n\ndef default_loader(img):\n return Image.open(img)\n\n\ndef default_list_reader(txt_path):\n imgList = []\n with open(txt_path, 'r') as file:\n for line in file.readlines():\n imgPath, label = line.strip().split(' ')\n imgList.append((imgPath, int(label)))\n return imgList\n\nclass MS_Celeb_set(Dataset):\n def __init__(self,\n img_path,\n txt_path,\n img_transform=None,\n normalize=True,\n loader=default_loader):\n self.img_path=img_path\n self.imgList=default_list_reader(txt_path)\n self.img_transform = img_transform\n self.loader = loader\n self.normalize = normalize\n\n def __getitem__(self, index):\n imgPath, label = self.imgList[index]\n img = self.loader(os.path.join(self.img_path, imgPath))\n\n if self.img_transform is not None:\n img = self.img_transform(img)\n\n if self.normalize:\n img = (img - 127.5) / 128.\n return img, label\n\n def __len__(self):\n return len(self.imgList)\n\n#------------------------------------define train-----------------------------------------\ndef train(train_loader, model, criterion, optimizer, epoch, loss_weight, use_cuda):\n print (\"Training... Epoch = %d\" % epoch)\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n softmax_losses = AverageMeter()\n center_losses = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n\n model.train()\n\n end = time.time()\n\n for i,(img, label) in enumerate(train_loader):\n if use_cuda:\n img = img.cuda()\n label = label.cuda()\n\n img, label = Variable(img), Variable(label)\n ip1, pred = model(img)\n softmax_loss = criterion[0](pred, label)\n center_loss = criterion[1](label,ip1)\n\n loss = softmax_loss + loss_weight*center_loss\n\n optimizer[0].zero_grad()\n optimizer[1].zero_grad()\n\n loss.backward()\n\n optimizer[0].step()\n optimizer[1].step()\n\n\n #for param in criterion[1].parameters():\n # param.grad.data *= (1. / loss_weight)\n\n prec1 = accuracy(pred.data,label)\n softmax_losses.update(softmax_loss.data[0], img.size(0))\n center_losses.update(center_loss.data[0], img.size(0))\n losses.update(loss.data[0],img.size(0))\n top1.update(prec1[0], img.size(0))\n \n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\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 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'SoftmaxLoss {softmax_loss.val:.4f} ({softmax_loss.avg:.4f})\\t'\n 'CenterLoss {center_loss.val:.4f} ({center_loss.avg:.4f})\\t'\n 'Prec@ {top1.val:.3f} ({top1.avg:.3f})\\t'.format(\n epoch, i, len(train_loader), batch_time=batch_time,\n data_time=data_time,loss=losses,softmax_loss=softmax_losses, center_loss=center_losses, top1=top1))\n \n#-----------------------------------------define validate--------------------------------\ndef validate(val_loader, model, loss_weight, criterion,use_cuda):\n batch_time = AverageMeter()\n softmax_losses = AverageMeter()\n center_losses = AverageMeter()\n losses = AverageMeter()\n\n top1 = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n for i, (img_var, label_var) in enumerate(val_loader):\n if use_cuda:\n img_var = img_var.cuda()\n label_var = label_var.cuda()\n\n\n # compute output\n img_var, label_var = torch.autograd.Variable(img_var,volatile=True), torch.autograd.Variable(label_var,volatile=True)\n ip1_var, pred_var = model(img_var)\n softmax_loss = criterion[0](pred_var, label_var)\n center_loss = criterion[1](label_var, ip1_var)\n\n loss = softmax_loss + loss_weight*center_loss\n\n\n # measure accuracy and record loss\n prec1 = accuracy(pred_var.data, label_var)\n softmax_losses.update(softmax_loss.data[0], img_var.size(0))\n center_losses.update(center_loss.data[0], img_var.size(0))\n losses.update(loss.data[0], img_var.size(0))\n top1.update(prec1[0], img_var.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n \n if i % args.print_freq == 0:\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Prec@ {top1.val:.3f} ({top1.avg:.3f})'.format(\n i, len(val_loader), batch_time=batch_time, loss=losses,\n top1=top1))\n\n print(' * Prec@1 {top1.avg:.3f}'\n .format(top1=top1))\n\n return top1.avg\n\n#================================================================================================\n#-----------------------------------creat the net and assign optimizer-----------------------------\ndef main():\n global args, best_prec1\n args = parser.parse_args()\n\n if torch.cuda.is_available():\n use_cuda = True\n else: use_cuda = False\n\n\n print(\"=> creating model\")\n model = Net()\n print(model)\n\n# NLLLoss\n nllloss = nn.NLLLoss() # CrossEntropyLoss = log_softmax + NLLLoss\n# CenterLoss\n loss_weight = 0.003\n centerloss = CenterLoss(num_classes=20000,feat_dim=512)\n\n if use_cuda:\n nllloss = nllloss.cuda()\n centerloss = centerloss.cuda()\n model = model.cuda()\n model = model.cuda()\n criterion = [nllloss, centerloss]\n\n optimizer4nn = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=0.0005)\n sheduler= lr_scheduler.StepLR(optimizer4nn, 30, gamma=0.1) #30 0.1\n\n\n optimzer4center = optim.SGD(centerloss.parameters(), lr=0.5)\n \n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_prec1 = checkpoint['best_prec1']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer4nn.load_state_dict(checkpoint['optimizer4nn'])\n optimzer4center.load_state_dict(checkpoint['optimizer4center'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n \n #-------------------------------load data and train------------------------------------------- \n\n train_data = MS_Celeb_set(img_path='/data3/zjxu/DATA/FaceVerification_cleaned/MS_Celeb_transformed_cv2/',\n txt_path='/data2/interns/yxhe/DATA/celeb_1M_picked_grey.txt',\n img_transform=transforms.Compose([transforms.RandomHorizontalFlip(),\n transforms.ToTensor()]))\n train_loader = DataLoader(train_data, batch_size=256, shuffle=True)\n val_data = MS_Celeb_set(img_path='/data3/zjxu/DATA/FaceVerification_cleaned/MS_Celeb_transformed_cv2/',\n txt_path='/data2/interns/yxhe/DATA/valceleb_1M_picked_grey.txt',\n img_transform=transforms.ToTensor())\n val_loader = DataLoader(val_data, batch_size=200, shuffle=False)\n \n cudnn.benchmark = True\n\n\n if args.evaluate:\n validate(val_loader, model, criterion)\n return\n\n for epoch in range(args.start_epoch, args.epochs):\n sheduler.step()\n\n train(train_loader, model, criterion, [optimizer4nn, optimzer4center], epoch + 1, loss_weight, use_cuda) #train\n prec1 = validate(val_loader, model,loss_weight,criterion,use_cuda) #validate\n # remember best prec@1 and save checkpoint\n is_best = prec1 > best_prec1\n best_prec1 = max(prec1, best_prec1)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': 'mobile_cls',\n 'state_dict': model.state_dict(),\n 'best_prec1': best_prec1,\n 'optimizer4nn' : optimizer4nn.state_dict(),\n 'optimzer4center': optimzer4center.state_dict(),\n }, is_best)\n\ndef save_checkpoint(state, is_best, filename='checkpoint_test.pth.tar'):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'model_best_test.pth.tar')\n \n \n#============================================================================================= \n#-----------------------------define some tiny functions----------------------------------\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 val = float(val)\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\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).data)\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\nif __name__ == '__main__':\n main()","sub_path":"main_with_centerloss.py","file_name":"main_with_centerloss.py","file_ext":"py","file_size_in_byte":12117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"586030555","text":"import boto3\n\nclient = boto3.client('ec2')\n\nresponse = client.describe_instance_status()\n#print(response)\n\nfor r in response['InstanceStatuses']:\n #print(r['InstanceId'])\n try:\n value = r['Events']\n except KeyError:\n # Key is not present\n print(\"No event for \" + r['InstanceId'])\n else:\n print(\"There is event for \" + r['InstanceId'] + \"Please Check!\")\n\n\n","sub_path":"aws_events2.py","file_name":"aws_events2.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"25503049","text":"from typing import Optional, Tuple\n\nimport torch\nfrom inferno.io.transform import Transform\n\n\nclass MaskCenter:\n \"\"\"Mask out the 'artifact plane' \"\"\"\n\n def __init__(self, n_mask: int = 1, center: Optional[int] = None, **super_kwargs):\n super().__init__(**super_kwargs)\n assert n_mask > 0\n self.n_mask = n_mask\n self.center = center\n\n def __call__(self, pred: torch.Tensor, tgt: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n assert len(pred.shape) == 5\n mask = torch.ones_like(pred)\n if self.center is None:\n mid_z = round(mask.shape[2] / 2)\n else:\n mid_z = self.center\n # mid_z = self.center if self.center is not None else mask.shape[2] // 2\n mid_z_start = mid_z - self.n_mask // 2\n mid_z_end = mid_z + (self.n_mask + 1) // 2\n mask[:, :, mid_z_start:mid_z_end] = 0\n mask.requires_grad = False\n\n # mask prediction with mask\n masked_prediction = pred * mask\n return masked_prediction, tgt\n\n\nclass MaskBorder(Transform):\n \"\"\"Mask out the borders in x and y (aka in the last two dimensions)\"\"\"\n\n def __init__(self, n_mask: int = 1, **super_kwargs):\n super().__init__(**super_kwargs)\n assert n_mask > 0\n self.n_mask = n_mask\n\n def batch_function(self, tensors):\n prediction, target = tensors\n assert len(prediction.shape) > 3\n mask = torch.zeros_like(prediction)\n mask[..., self.n_mask : -self.n_mask, self.n_mask : -self.n_mask] = 1\n mask.requires_grad = False\n\n # mask prediction with mask\n masked_prediction = prediction * mask\n return masked_prediction, target\n","sub_path":"hylfm/utils/loss_transform.py","file_name":"loss_transform.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"533784150","text":"import pygame\r\nimport arrows, spells\r\n\r\nclass GameObjects(object):\r\n\tdef __init__(self, player, enemies, viewport):\r\n\t\tself.player = player\r\n\t\tself.enemies = enemies\r\n\t\tself.viewport = viewport\r\n\t\tself.spells = pygame.sprite.Group()\r\n\t\tself.arrows = pygame.sprite.Group()\r\n\t\r\n\tdef add_spell(self, target):\r\n\t\tx, y = target.x, target.y + target.height / 2 # x and y are the bottom of the target image\r\n\t\tfireball = spells.Fire(x, y)\r\n\t\tself.spells.add(fireball)\r\n\t\t\r\n\tdef update_spells(self):\r\n\t\tself.spells.update(self.viewport)\r\n\t\tcollideables = pygame.sprite.groupcollide(self.spells, self.enemies, False, False)\t\r\n\t\tfor spell, enemies in collideables.iteritems():\r\n\t\t\tfor enemy in enemies:\r\n\t\t\t\tenemy.damage_taken += spell.damage\r\n\t\r\n\tdef add_arrow(self, target):\r\n\t\tx, y = self.player.rect.center\r\n\t\tnew_x, new_y = self.change_coordinates(target)\r\n\t\ttarget.x, target.y = (new_x, new_y)\r\n\t\tbasicarrow = arrows.TripleFireArrow(x, y, target)\r\n\t\tself.arrows.add(basicarrow)\r\n\t\r\n\tdef update_arrows(self):\r\n\t\tself.arrows.update(self.viewport)\r\n\t\tcollideables = pygame.sprite.groupcollide(self.arrows, self.enemies, False, False)\t\r\n\t\tfor arrow, enemies in collideables.iteritems():\r\n\t\t\tfor enemy in enemies:\r\n\t\t\t\tpygame.sprite.Sprite.kill(arrow)\r\n\t\t\t\tenemy.damage_taken += arrow.damage\r\n\t\t\t\tbreak\r\n\t\r\n\tdef change_coordinates(self, target):\r\n\t\t# update object position after camera moves, so it stays still\r\n\t\t# add viewport x and y to target before passing to here\r\n\t\tworld_x = self.viewport.x + target.x\r\n\t\tworld_y = self.viewport.y + target.y\r\n\t\tmove_x = target.x + self.viewport.x\r\n\t\tmove_y = target.y + self.viewport.y\r\n\t\ttarget_x = world_x - move_x\r\n\t\ttarget_y = move_y - move_y\r\n\t\tnew_x = target_x + target.x\r\n\t\tnew_y = target_y + target.y\r\n\t\treturn new_x, new_y\r\n\t\r\n\tdef update(self):\r\n\t\tself.update_arrows()\r\n\t\tself.update_spells()\r\n\t\t\r\n\tdef draw(self, surface):\r\n\t\tself.spells.draw(surface)\r\n\t\tself.arrows.draw(surface)\r\n\t\t\r\n\t\r\n","sub_path":"sprites/gameobjects.py","file_name":"gameobjects.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"275532825","text":"import sys\r\n\r\nclass SetUp:\r\n\r\n def __init__(self):\r\n pass\r\n\r\n @classmethod\r\n def get_input_filename(cls):\r\n for i in range(len(sys.argv)):\r\n if(sys.argv[i] == '-i' and i < (len(sys.argv) -1)):\r\n inputFileName = sys.argv[i + 1]\r\n\r\n return inputFileName\r\n\r\n @classmethod\r\n def get_output_filename(cls):\r\n\r\n for i in range(len(sys.argv)):\r\n if (sys.argv[i] == '-o' and i < (len(sys.argv) -1)):\r\n outputFileName = sys.argv[i + 1]\r\n\r\n return outputFileName\r\n\r\n\r\n @classmethod\r\n def import_data_file(cls):\r\n\r\n for i in range(len(sys.argv)):\r\n if (sys.argv[i] == '-i' and i < (len(sys.argv) - 1)):\r\n inputFileName = sys.argv[i + 1]\r\n\r\n try:\r\n instructions = [line.rstrip() for line in open(inputFileName, 'r')]\r\n except IOError:\r\n print(\"Could not open input file, is path correct?\")\r\n\r\n return instructions\r\n\r\n @classmethod\r\n def imm_bit_to_32_bit_converter(cls, num, bitsize):\r\n negBitMask = 2**(bitsize - 1) # bit mask to determine if the first digit is a 1 or 0\r\n extendMask = 0\r\n\r\n i = 31\r\n while (i >= bitsize):\r\n extendMask += 2**i\r\n i -= 1\r\n\r\n if (negBitMask & num) > 0:\r\n num = num | extendMask # extend to 32 bits\r\n num = num ^ 0xFFFFFFFF # toggle bits\r\n num = num + 1 # add 1\r\n num = num * -1 # make negative\r\n return num\r\n\r\n @classmethod\r\n def immSignedToTwosConverter(cls, num): #num is assumed to be 32 bits\r\n negBitMask = 0x80000000\r\n bitFlipMask = 0xFFFFFFFF # num xor bitFlipMask toggles all bits except for the first one\r\n #Changed bitFlipMask to mirror method above. prior gave incorrect response. --JFR\r\n if (num & negBitMask) > 0: #if number is negative\r\n # convert to twos complement by flipping bits and adding 1\r\n num = num ^ bitFlipMask\r\n num += 1\r\n num = num * -1\r\n # if num is positive, it is already in twos complement :)\r\n\r\n return num\r\n\r\n @classmethod\r\n def bin2StringSpaced(cls, s):\r\n spacedStr = s[0:8] + \" \" + s[8:11] + \" \" + s[11:16] + \" \" + s[16:21] + \" \" + s[21:26] + \" \" + s[26:32]\r\n return spacedStr\r\n\r\n @classmethod\r\n def bin2StringSpacedD(cls, s):\r\n spacedStr = s[0:11] + \" \" + s[11:20] + \" \" + s[20:22] + \" \" + s[22:27] + \" \" + s[27:32]\r\n return spacedStr\r\n\r\n @classmethod\r\n def bin2StringSpacedIM(cls, s):\r\n spacedStr = s[0:9] + \" \" + s[9:11] + \" \" + s[11:27] + \" \" + s[27:32]\r\n return spacedStr\r\n\r\n @classmethod\r\n def bin2StringSpacedCB(cls, s):\r\n spacedStr = s[0:8] + \" \" + s[8:27] + \" \" + s[27:32]\r\n return spacedStr\r\n\r\n @classmethod\r\n def bin2StringSpacedI(cls, s):\r\n spacedStr = s[0:10] + \" \" + s[10:22] + \" \" + s[22:27] + \" \" + s[27:32]\r\n return spacedStr;\r\n\r\n @classmethod\r\n def bin2StringSpacedR(cls, s):\r\n spacedStr = s[0:11] + \" \" + s[11:16] + \" \" + s[16:22] + \" \" + s[22:27] + \" \" + s[27:32]\r\n return spacedStr\r\n\r\n @classmethod\r\n def bin2StringSpacedB(cls, s):\r\n spacedStr = s[0:6] + \" \" + s[6:32]\r\n return spacedStr\r\n\r\n @classmethod\r\n def imm_32_bit_unsigned_to_32_bit_signed_converter(cls, num):\r\n firstBitOneMask = 0X80000000 #or\r\n firstBitZeroMask = 0X7FFFFFFF #and\r\n if (num < 0):\r\n num = num | firstBitOneMask\r\n else:\r\n num = num & firstBitZeroMask\r\n return num\r\n\r\n @classmethod\r\n def decimalToBinary(cls, num):\r\n if num > 1:\r\n cls.decimalToBinary(num // 2)\r\n print(num % 2, end='')\r\n\r\n @classmethod\r\n def binaryToDecimal(cls, binary):\r\n print(\"\\n\")\r\n print(int(binary, 2))","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"346406842","text":"import base64\nfrom datetime import timedelta\nimport logging\n\nfrom asn1crypto import cms\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef retrieve_signature_signing_time(signature):\n \"\"\" Return the 'signingTime' CMS attribute from the detached PKCS signature.\n\n This parsing depends on the structure of 'ContentInfo' objects defined in\n RFC-5652 (specifically the inner OID 1.2.840.113549.1.9.5):\n https://tools.ietf.org/html/rfc5652#section-11.3\n\n :param signature: Base64 encoded signature data (of a 'ContentInfo' object).\n :type: str\n :return: A datetime object representing the inner 'signingTime' object.\n :rtype: datetime\n :raises: AttributeError if no 'signing_time' object can be found.\n \"\"\"\n data = base64.b64decode(signature)\n content_info = cms.ContentInfo.load(data)\n signer_data = content_info['content']\n signer_infos = signer_data['signer_infos']\n signer_info = signer_infos[0] # We expect only one item in the list.\n signed_attrs = signer_info['signed_attrs']\n for signed_attr in signed_attrs:\n if 'signing_time' == signed_attr['type'].native:\n value = signed_attr['values']\n return value.native[0] # datetime object, only item in the list.\n raise AttributeError('No signing_time attribute found in signature.')\n\n\ndef signing_time_is_valid(signature, current_time, threshold):\n \"\"\" Given a detached top-level CMS signature, validate the 'signingTime'\n attribute against the current time and a time-delta threshold.\n\n If the difference between the current time and the 'signingTime' exceeds\n the threshold, the token should be considered invalid.\n\n :param signature: Base64 encoded detached CMS signature data.\n :type: str\n :param current_time: Current system time to compare the token against.\n :type: offset-aware datetime\n :param threshold: Amount of time to consider the token valid.\n :type: timedelta\n :return: False if the signing time exceeds the threshold, otherwise True\n :rtype: bool\n :raises: AttributeError if no 'signingTime' attribute can be found,\n indicating an invalid token. May also raise if signature data is in an\n unexpected format, inconsistent with the CMS 'ContentInfo' object.\n \"\"\"\n signing_time = retrieve_signature_signing_time(signature)\n is_valid = timedelta(0) <= (current_time - signing_time) <= threshold\n logger.debug((\n \"Signing time is {is_valid}. \"\n \"Signing time: {signing_time:%Y-%m-%d %H:%M:%S %Z}, \"\n \"Current time: {current_time:%Y-%m-%d %H:%M:%S %Z}, \"\n \"Threshold: {threshold}.\").format(\n is_valid='valid' if is_valid else 'invalid',\n signing_time=signing_time,\n current_time=current_time,\n threshold=threshold)\n )\n return is_valid\n","sub_path":"applepay/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"301935858","text":"\"\"\"\nThis class is part of the Robot in a maze game\ninitiated with class variables to use them in the different methods\nall the methods have a quick explanation of their utility and usage\n\"\"\"\n\nimport os\nimport pickle\n\nclass Robot_control:\n \"\"\"This class will control de way the robot is controlled\"\"\"\n\n def __init__(self):\n # returns the path of the current directory (with __file__), then passed again to the same method to go up of a level\n self.directory = os.path.dirname(os.path.dirname(__file__))\n\n # get a list of files in \"maps\" folder\n self.listoffiles = os.listdir(os.path.join(self.directory, \"maps\"))\n\n # global maze in the class\n self.robot_maze = {}\n self.maze_width = 1\n self.maze_height = 1\n self.storedot = False\n \n\n # display winning message\n def message(self):\n print(34 * \"*\")\n print(\"*** Bravo, vous avez gagné !!! ***\")\n print(34 * \"*\")\n \n\n # checks which object is ahead of the robot and updates what's in its trail\n def check_object(self, x, new_x, y, new_y):\n # if a wall ahead, we don't do anything\n if self.robot_maze[new_x, new_y]=='O':\n pass\n # if the door is found, we call for the winning message and start a new game\n elif self.robot_maze[new_x, new_y]=='U':\n self.robot_maze[new_x, new_y] = 'X'\n self.robot_maze[x, y] = ' '\n self.display_map()\n self.message()\n self.get_maps_to_dict()\n \n # if a dot \".\" is ahead we store its existence to display it back again\n # once robot has passed throught this \"gate\"\n elif self.robot_maze[new_x, new_y]=='.':\n self.storedot = True\n self.robot_maze[new_x, new_y] = 'X'\n self.robot_maze[x, y] = ' '\n \n elif self.storedot:\n self.storedot = False\n self.robot_maze[new_x, new_y] = 'X'\n self.robot_maze[x, y] = '.'\n\n else:\n # at the end we update maze with robot movements\n # update the maze with the 'x' into the right case\n self.robot_maze[new_x, new_y] = 'X'\n self.robot_maze[x, y] = ' '\n\n \n # handles key inputs to update maze dict structure according to robot moves\n def move_robot(self, userkey):\n # from the list returned by find_robot, we split into x, y positions\n x = x_new = self.find_robot()[0]\n y = y_new = self.find_robot()[1]\n print(\"\\r\\nActuellement, le robot se trouve dans la case x:{}, y:{}.\".format(x+1, y+1))\n jump = 1\n\n # call to display new game\n if userkey == 'G':\n self.get_maps_to_dict()\n\n # go up\n elif userkey == 'N':\n y_new -= jump\n self.check_object(x, x_new, y, y_new)\n \n # go right\n elif userkey == 'E':\n x_new += jump\n self.check_object(x, x_new, y, y_new)\n\n # go down\n elif userkey == 'S':\n y_new += jump\n self.check_object(x, x_new, y, y_new)\n\n # go left\n elif userkey == 'O':\n x_new -= jump\n self.check_object(x, x_new, y, y_new)\n\n \n # returns position of \"X\", representing the robot\n def find_robot(self):\n for key, value in self.robot_maze.items():\n if value == 'X':\n return key\n\n\n # stores game status to a binary file\n def store_game(self):\n # returns the path of the current directory (with __file__), then passed again to the same method to go up of a level\n # concatenates directory path with all settings to get the proper file\n # games saved into a file in the controls directory\n path_game_file = os.path.join(self.directory, \"controls\", \"games.maz\")\n with open(path_game_file, 'wb') as game_file:\n my_pickler = pickle.Pickler(game_file)\n # store the complete maze into the binary file\n my_pickler.dump(self.robot_maze)\n # and also the status of the storedot variable in case the game has stoped over a dot=gate\n my_pickler.dump(self.storedot)\n \n\n # loads game status of a binary file, if existing\n def load_game(self):\n path_game_file = os.path.join(self.directory, \"controls\", \"games.maz\")\n try:\n with open(path_game_file, 'rb') as game_file:\n my_depickler = pickle.Unpickler(game_file)\n self.robot_maze = my_depickler.load()\n self.storedot = my_depickler.load()\n return True\n except FileNotFoundError:\n self.robot_maze = {} # return empty dict if file doesn't exists\n return False\n\n \n # displays maze to the screen as per current structure in class\n def display_map(self):\n line = 0\n for col in range(self.maze_height+1):\n print('\\r')\n for line in range(self.maze_width+1):\n print(self.robot_maze[line, col], end='')\n line = 0\n print('\\r')\n\n \n # checks if an input is within the range defined\n def checkIntValue(self, stringtodisplay, maze_qty):\n # initiate input choice\n choice = 0\n # if the value is not in the available quantity of files we keep looping\n # and must be a integer\n while choice not in range(1, maze_qty+1):\n try:\n choice = int(input(stringtodisplay))\n except ValueError:\n continue\n # return the picked choice from player\n return choice\n\n\n # finds \"*.txt\" files from a given file list\n def find_txt_files(self):\n listoftxt = []\n # iterate through the list of files in the folder\n for founded_txt in self.listoffiles: \n # if these have .txt we display them\n if founded_txt.endswith(\".txt\"):\n listoftxt.append(founded_txt)\n return listoftxt\n\n\n # loads maze structure to a class dictionnary\n def get_maps_to_dict(self):\n # let's check the files we have in \"maps\" folder are .txt\n print(\"\\r \\nLabyrinthes existants :\")\n\n # find the available maze files\n qty_maze = self.find_txt_files()\n\n # display available maze txt files\n for i, files in enumerate(qty_maze):\n print(\"{} - {}.\".format(i+1, qty_maze[i]))\n \n # we ask for a pick by the user as per the above files found\n choicen = self.checkIntValue(\"Entrez un numéro de labyrinthe pour commencer à jouer : \", len(qty_maze))\n\n # concatenates directory path with all settings to get the proper file\n path_to_file = os.path.join(self.directory, \"maps\", qty_maze[choicen-1])\n \n self.robot_maze = {}\n\n with open(path_to_file, 'r') as file_maps:\n if file_maps.readable:\n # we get all lines of the file into a list\n entry = file_maps.readlines()\n # we iterate through each line of the file to split it to the dict with tuples as keys\n for y, line in enumerate(entry):\n # we iterate through each type of a line\n for x in range(len(line)):\n # ignoring new line code\n if line[x] != \"\\n\":\n # amending coordinates dictionnary with maze structure\n self.robot_maze.update({(x, y): line[x].upper()})\n else:\n print(\"Le fichier est illisible\")\n \n # x and y as width and height of the maze\n self.maze_width = x\n self.maze_height = y","sub_path":"controls/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":7664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"462817708","text":"# Tip Calculator\n\nbill = float(input(\"Enter the total bill and I will show you what you should tip \\\nat 15 or 20%: \"))\n\nprint(\"\\nA tip at 15% would be: \", bill * .15, \"for a total of: \",bill * .15 + bill, \"or at 20% tip would\\\nbe: \", bill * .20, \"or a total of: \", bill * .20 + bill)\n\n\ninput(\"\\n\\nPress the enter key to exit.\")\n\n\n","sub_path":"original/Tip_Calculator.py","file_name":"Tip_Calculator.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"219597326","text":"#-------------------------------------------------------------------------------\n# Part of tweedledum. This file is distributed under the MIT License.\n# See accompanying file /LICENSE for details.\n#-------------------------------------------------------------------------------\nimport ast\nimport _ast\nimport sys\nfrom .. import core\n\nclass ParseError(Exception):\n pass\n\nclass LogicNetwork(ast.NodeVisitor):\n bitops = {_ast.BitAnd: 'create_and',\n _ast.BitOr: 'create_or',\n _ast.BitXor: 'create_xor',\n _ast.And: 'create_and',\n _ast.Or: 'create_or',\n _ast.Not: 'create_not',\n _ast.Invert: 'create_not'\n }\n\n def __init__(self, source):\n self.source = source\n node = ast.parse(source)\n self.scopes = []\n self._network = None\n self.visit(node)\n super().__init__()\n\n @property\n def types(self):\n \"\"\"returns vars ands types in the scope\"\"\"\n ret = []\n for scope in self.scopes:\n ret.append({k: v[0] for k, v in scope.items()})\n return ret\n\n def simulate(self):\n return core.simulate(self._network)\n\n def synthesize(self) -> str:\n return core.synthesize_xag(self._network)\n\n def visit_Module(self, node):\n if len(node.body) != 1 and not isinstance(node.body[0], ast.FunctionDef):\n raise ParseError(\"just functions, sorry!\")\n self.visit(node.body[0])\n\n def visit_FunctionDef(self, node):\n if node.returns is None:\n raise ParseError(\"return type is needed\")\n self.scopes.append({'return': (node.returns.id, None),\n node.returns.id: ('type', None)})\n self._network = core.xag_network()\n self.extend_scope(node.args)\n return super().generic_visit(node)\n\n def visit_Return(self, node):\n _type, signal = self.visit(node.value)\n if _type != self.scopes[-1]['return'][0]:\n raise ParseError(\"return type error\")\n self._network.create_po(signal)\n return\n\n def visit_Assign(self, node):\n type_value, signal_value = self.visit(node.value)\n for target in node.targets:\n self.scopes[-1][target.id] = (type_value, signal_value)\n # _, _ = self.visit(target)\n return (type_value, signal_value)\n\n def bit_binop(self, left, right, op):\n left_type, left_signal = left\n right_type, right_signal = right\n if left_type != 'Bit' or right_type != 'Bit':\n raise ParseError(\"binop type error\")\n bitop = LogicNetwork.bitops.get(type(op))\n if bitop:\n return 'Bit', getattr(self._network, bitop)(left_signal, right_signal)\n else:\n raise ParseError(\"Unknown binop.op %s\" % op)\n\n def visit_BoolOp(self, node):\n \"\"\" node.left=Bit and node.right=Bit return Bit \"\"\"\n return self.bit_binop(self.visit(node.values[0]), self.visit(node.values[1]), node.op)\n\n def visit_BinOp(self, node):\n \"\"\" node.left=Bit and node.right=Bit return Bit \"\"\"\n return self.bit_binop(self.visit(node.left), self.visit(node.right), node.op)\n\n def visit_UnaryOp(self, node):\n operand_type, operand_signal = self.visit(node.operand)\n bitop = LogicNetwork.bitops.get(type(node.op))\n if bitop:\n return 'Bit', getattr(self._network, bitop)(operand_signal)\n else:\n raise ParseError(\"Unknown UntaryOp.op %s\" % node.op)\n\n def visit_Name(self, node):\n if node.id not in self.scopes[-1]:\n raise ParseError('out of scope: %s' % node.id)\n return self.scopes[-1][node.id]\n\n def generic_visit(self, node):\n if isinstance(node, (_ast.arguments, _ast.arg, _ast.Load, _ast.BitAnd,\n _ast.BitOr, _ast.BitXor, _ast.BoolOp, _ast.Or)):\n return super().generic_visit(node)\n raise ParseError(\"Unknown node: %s\" % type(node))\n\n def extend_scope(self, args_node: _ast.arguments) -> None:\n for arg in args_node.args:\n if arg.annotation is None:\n raise ParseError(\"argument type is needed\")\n self.scopes[-1][arg.annotation.id] = ('type', None)\n self.scopes[-1][arg.arg] = (arg.annotation.id, self._network.create_pi())\n","sub_path":"python/tweedledum/parser/logic_network.py","file_name":"logic_network.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"512759289","text":"from __future__ import annotations\n\nimport os\nimport time\nfrom threading import Thread\nfrom typing import List, Iterator, Type\nfrom tempfile import TemporaryDirectory\n\n\nclass GenericInputData:\n def __init__(self, path: str, *args, **kwargs):\n self.path = path\n\n def read(self):\n raise NotImplementedError\n\n @classmethod\n def generate_inputs(cls, config: dict) -> Iterator[GenericInputData]:\n data_dir = config[\"data_dir\"]\n for name in os.listdir(data_dir):\n yield cls(os.path.join(data_dir, name))\n\n\nclass PathInputData(GenericInputData):\n def read(self):\n return open(self.path).read()\n\n\nclass GenericWorker:\n def __init__(self, input_data: GenericInputData):\n self.input_data = input_data\n self.result = 0\n\n def map(self):\n raise NotImplementedError\n\n def reduce(self, other: GenericWorker):\n raise NotImplementedError\n\n @classmethod\n def create_workers(\n cls, input_class: Type[GenericInputData], config: dict\n ) -> List[GenericWorker]:\n workers = []\n for input_data in input_class.generate_inputs(config):\n workers.append(cls(input_data))\n return workers\n\n\nclass LineCountWorker(GenericWorker):\n def map(self):\n data = self.input_data.read()\n self.result = data.count(\"\\n\")\n\n def reduce(self, other: GenericWorker):\n self.result += other.result\n\n\ndef execute(workers: List[GenericWorker]) -> int:\n threads = [Thread(target=w.map) for w in workers]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n first, rest = workers[0], workers[1:]\n for worker in rest:\n first.reduce(worker)\n return first.result\n\n\ndef mapreduce(\n worker_class: Type[GenericWorker],\n input_class: Type[GenericInputData],\n config: dict,\n):\n workers = worker_class.create_workers(input_class, config)\n return execute(workers)\n\n\ndef write_test_files(temp_dir: str):\n with open(os.path.join(temp_dir, \"test_1.txt\"), \"w\") as f:\n f.write(\"qwe\\nqwe\\n\")\n with open(os.path.join(temp_dir, \"test_2.txt\"), \"w\") as f:\n f.write(\"qwe\\nqwe\\n\")\n with open(os.path.join(temp_dir, \"test_3.txt\"), \"w\") as f:\n f.write(\"qwe\\nqwe\\n\")\n\n\nif __name__ == \"__main__\":\n with TemporaryDirectory() as temp_dir:\n write_test_files(temp_dir)\n config = {\"data_dir\": temp_dir}\n result = mapreduce(LineCountWorker, PathInputData, config)\n\n print(f\"result: {result}\")\n","sub_path":"dev/mapreduce/case_2.py","file_name":"case_2.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"583097269","text":"# test driving the ACMEv2 protocol\n\nimport base64\nimport json\nimport os.path\nimport re\nimport pytest\n\nfrom TestEnv import TestEnv\nfrom TestHttpdConf import HttpdConf\nfrom TestCertUtil import CertUtil\n\n\ndef setup_module(module):\n print(\"setup_module: %s\" % module.__name__)\n TestEnv.init()\n TestEnv.check_acme()\n TestEnv.httpd_error_log_clear()\n TestEnv.APACHE_CONF_SRC = \"data/test_drive\"\n HttpdConf().install()\n assert TestEnv.apache_restart() == 0\n\n\ndef teardown_module(module):\n print(\"teardown_module:%s\" % module.__name__)\n assert TestEnv.apache_stop() == 0\n\n\nclass TestDrivev2:\n\n def setup_method(self, method):\n print(\"setup_method: %s\" % method.__name__)\n TestEnv.clear_store()\n HttpdConf().install()\n self.test_domain = TestEnv.get_method_domain(method)\n\n def teardown_method(self, method):\n print(\"teardown_method: %s\" % method.__name__)\n\n # --------- invalid precondition ---------\n\n def test_502_000(self):\n # test case: md without contact info\n domain = self.test_domain\n name = \"www.\" + domain\n assert TestEnv.a2md([\"add\", name])['rv'] == 0\n run = TestEnv.a2md([\"drive\", name])\n assert run['rv'] == 1\n assert re.search(\"No contact information\", run[\"stderr\"])\n\n def test_502_001(self):\n # test case: md with contact, but without TOS\n domain = self.test_domain\n name = \"www.\" + domain\n assert TestEnv.a2md([\"add\", name])['rv'] == 0\n assert TestEnv.a2md( \n [\"update\", name, \"contacts\", \"admin@test1.not-forbidden.org\"]\n )['rv'] == 0\n run = TestEnv.a2md([\"drive\", name])\n assert run['rv'] == 1\n assert re.search(\"the CA requires you to accept the terms-of-service as specified in \", run[\"stderr\"])\n\n # test_102 removed, was based on false assumption\n def test_502_003(self):\n # test case: md with unknown protocol FOO\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name])\n assert TestEnv.a2md(\n [\"update\", name, \"ca\", TestEnv.ACME_URL, \"FOO\"]\n )['rv'] == 0\n run = TestEnv.a2md([\"drive\", name])\n assert run['rv'] == 1\n assert re.search(\"Unknown CA protocol\", run[\"stderr\"])\n\n # --------- driving OK ---------\n\n def test_502_100(self):\n # test case: md with one domain\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name])\n assert TestEnv.apache_start() == 0\n # drive\n prev_md = TestEnv.a2md([\"list\", name])['jout']['output'][0]\n r = TestEnv.a2md([\"-vv\", \"drive\", \"-c\", \"http-01\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n TestEnv.check_md_credentials([name])\n self._check_account_key(name)\n\n # check archive content\n store_md = json.loads(open(TestEnv.store_archived_file(name, 1, 'md.json')).read())\n for f in ['name', 'ca', 'domains', 'contacts', 'renew-mode', 'renew-window', 'must-staple']:\n assert store_md[f] == prev_md[f]\n \n # check file system permissions:\n TestEnv.check_file_permissions(name)\n # check: challenges removed\n TestEnv.check_dir_empty(TestEnv.store_challenges())\n # check how the challenge resources are answered in sevceral combinations \n result = TestEnv.get_meta(domain, \"/.well-known/acme-challenge\", False)\n assert result['rv'] == 0\n assert result['http_status'] == 404\n result = TestEnv.get_meta(domain, \"/.well-known/acme-challenge/\", False)\n assert result['rv'] == 0\n assert result['http_status'] == 404\n result = TestEnv.get_meta(domain, \"/.well-known/acme-challenge/123\", False)\n assert result['rv'] == 0\n assert result['http_status'] == 404\n assert result['rv'] == 0\n cdir = os.path.join(TestEnv.store_challenges(), domain)\n os.makedirs(cdir)\n open(os.path.join(cdir, 'acme-http-01.txt'), \"w\").write(\"content-of-123\")\n result = TestEnv.get_meta(domain, \"/.well-known/acme-challenge/123\", False)\n assert result['rv'] == 0\n assert result['http_status'] == 200\n assert result['http_headers']['Content-Length'] == '14'\n\n def test_502_101(self):\n # test case: md with 2 domains\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name, \"test.\" + domain])\n assert TestEnv.apache_start() == 0\n # drive\n r = TestEnv.a2md([\"-vv\", \"drive\", \"-c\", \"http-01\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n TestEnv.check_md_credentials([name, \"test.\" + domain])\n\n # test_502_102 removed, as accounts without ToS are not allowed in ACMEv2\n\n def test_502_103(self):\n # test case: md with one domain, ACME account and TOS agreement on server\n # setup: create md\n domain = self.test_domain\n name = \"www.\" + domain\n assert TestEnv.a2md([\"add\", name])['rv'] == 0\n assert TestEnv.a2md([\"update\", name, \"contacts\", \"admin@\" + domain])['rv'] == 0\n assert TestEnv.apache_start() == 0\n # setup: create account on server\n run = TestEnv.a2md([\"-t\", \"accepted\", \"acme\", \"newreg\", \"admin@\" + domain], raw=True)\n assert run['rv'] == 0\n acct = re.match(\"registered: (.*)$\", run[\"stdout\"]).group(1)\n # setup: link md to account\n assert TestEnv.a2md([\"update\", name, \"account\", acct])['rv'] == 0\n # drive\n r = TestEnv.a2md([\"-vv\", \"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n TestEnv.check_md_credentials([name])\n\n # test_502_104 removed, order are created differently in ACMEv2\n\n def test_502_105(self):\n # test case: md with one domain, local TOS agreement and ACME account that is deleted (!) on server\n # setup: create md\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name])\n assert TestEnv.apache_start() == 0\n # setup: create account on server\n run = TestEnv.a2md([\"-t\", \"accepted\", \"acme\", \"newreg\", \"test@\" + domain], raw=True)\n assert run['rv'] == 0\n acct = re.match(\"registered: (.*)$\", run[\"stdout\"]).group(1)\n # setup: link md to account\n assert TestEnv.a2md([\"update\", name, \"account\", acct])['rv'] == 0\n # setup: delete account on server\n assert TestEnv.a2md([\"acme\", \"delreg\", acct])['rv'] == 0\n # drive\n r = TestEnv.a2md([\"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n TestEnv.check_md_credentials([name])\n\n def test_502_107(self):\n # test case: drive again on COMPLETE md, then drive --force\n # setup: prepare md in store\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name])\n assert TestEnv.apache_start() == 0\n # drive\n r = TestEnv.a2md([\"-vv\", \"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n TestEnv.check_md_credentials([name])\n orig_cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n\n # drive again\n assert TestEnv.a2md([\"-vv\", \"drive\", name])['rv'] == 0\n TestEnv.check_md_credentials([name])\n cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n # check: cert not changed\n assert cert.same_serial_as(orig_cert)\n\n # drive --force\n assert TestEnv.a2md([\"-vv\", \"drive\", \"--force\", name])['rv'] == 0\n TestEnv.check_md_credentials([name])\n cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n # check: cert not changed\n assert not cert.same_serial_as(orig_cert)\n # check: previous cert was archived\n cert = CertUtil(TestEnv.store_archived_file(name, 2, 'pubcert.pem'))\n assert cert.same_serial_as(orig_cert)\n\n def test_502_108(self):\n # test case: drive via HTTP proxy\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name])\n conf = HttpdConf(proxy=True)\n conf.add_line('LogLevel proxy:trace8')\n conf.install()\n assert TestEnv.apache_restart() == 0\n\n # drive it, with wrong proxy url -> FAIL\n r = TestEnv.a2md([\"-p\", \"http://%s:1\" % TestEnv.HTTPD_HOST, \"drive\", name])\n assert r['rv'] == 1\n assert \"Connection refused\" in r['stderr']\n\n # drive it, working proxy url -> SUCCESS\n proxy_url = \"http://%s:%s\" % (TestEnv.HTTPD_HOST, TestEnv.HTTP_PROXY_PORT)\n r = TestEnv.a2md([\"-vv\", \"-p\", proxy_url, \"drive\", name])\n assert 0 == r['rv'], \"a2md failed: {0}\".format(r['stderr'])\n TestEnv.check_md_credentials([name])\n\n def test_502_109(self):\n # test case: redirect on SSL-only domain\n # setup: prepare config\n domain = self.test_domain\n name = \"www.\" + domain\n conf = HttpdConf()\n conf.add_admin(\"admin@\" + domain)\n conf.add_drive_mode(\"manual\")\n conf.add_md([name])\n conf.add_vhost(name, port=TestEnv.HTTP_PORT, doc_root=\"htdocs/test\")\n conf.add_vhost(name, doc_root=\"htdocs/test\")\n conf.install()\n # setup: create resource files\n self._write_res_file(os.path.join(TestEnv.APACHE_HTDOCS_DIR, \"test\"), \"name.txt\", name)\n self._write_res_file(os.path.join(TestEnv.APACHE_HTDOCS_DIR), \"name.txt\", \"not-forbidden.org\")\n assert TestEnv.apache_restart() == 0\n\n # drive it\n assert TestEnv.a2md([\"drive\", name])['rv'] == 0\n assert TestEnv.apache_restart() == 0\n # test HTTP access - no redirect\n assert TestEnv.get_content(\"not-forbidden.org\", \"/name.txt\", use_https=False) == \"not-forbidden.org\"\n assert TestEnv.get_content(name, \"/name.txt\", use_https=False) == name\n r = TestEnv.get_meta(name, \"/name.txt\", use_https=False)\n assert int(r['http_headers']['Content-Length']) == len(name)\n assert \"Location\" not in r['http_headers']\n # test HTTPS access\n assert TestEnv.get_content(name, \"/name.txt\", use_https=True) == name\n\n # test HTTP access again -> redirect to default HTTPS port\n conf.add_require_ssl(\"temporary\")\n conf.install()\n assert TestEnv.apache_restart() == 0\n r = TestEnv.get_meta(name, \"/name.txt\", use_https=False)\n assert r['http_status'] == 302\n exp_location = \"https://%s/name.txt\" % name\n assert r['http_headers']['Location'] == exp_location\n # should not see this\n assert 'Strict-Transport-Security' not in r['http_headers']\n # test default HTTP vhost -> still no redirect\n assert TestEnv.get_content(\"not-forbidden.org\", \"/name.txt\", use_https=False) == \"not-forbidden.org\"\n r = TestEnv.get_meta(name, \"/name.txt\", use_https=True)\n # also not for this\n assert 'Strict-Transport-Security' not in r['http_headers']\n\n # test HTTP access again -> redirect permanent\n conf.add_require_ssl(\"permanent\")\n conf.install()\n assert TestEnv.apache_restart() == 0\n r = TestEnv.get_meta(name, \"/name.txt\", use_https=False)\n assert r['http_status'] == 301\n exp_location = \"https://%s/name.txt\" % name\n assert r['http_headers']['Location'] == exp_location\n assert 'Strict-Transport-Security' not in r['http_headers']\n # should see this\n r = TestEnv.get_meta(name, \"/name.txt\", use_https=True)\n assert r['http_headers']['Strict-Transport-Security'] == 'max-age=15768000'\n\n def test_502_110(self):\n # test case: SSL-only domain, override headers generated by mod_md \n # setup: prepare config\n domain = self.test_domain\n name = \"www.\" + domain\n conf = HttpdConf()\n conf.add_admin(\"admin@\" + domain)\n conf.add_drive_mode(\"manual\")\n conf.add_require_ssl(\"permanent\")\n conf.add_md([name])\n conf.add_vhost(name, port=TestEnv.HTTP_PORT)\n conf.add_vhost(name)\n conf.install()\n assert TestEnv.apache_restart() == 0\n # drive it\n assert TestEnv.a2md([\"drive\", name])['rv'] == 0\n assert TestEnv.apache_restart() == 0\n\n # test override HSTS header\n conf._add_line(' Header set Strict-Transport-Security \"max-age=10886400; includeSubDomains; preload\"')\n conf.install()\n assert TestEnv.apache_restart() == 0\n r = TestEnv.get_meta(name, \"/name.txt\", use_https=True)\n assert r['http_headers']['Strict-Transport-Security'] == 'max-age=10886400; includeSubDomains; preload'\n\n # test override Location header\n conf._add_line(' Redirect /a /name.txt')\n conf._add_line(' Redirect seeother /b /name.txt')\n conf.install()\n assert TestEnv.apache_restart() == 0\n # check: default redirect by mod_md still works\n exp_location = \"https://%s/name.txt\" % name\n r = TestEnv.get_meta(name, \"/name.txt\", use_https=False)\n assert r['http_status'] == 301\n assert r['http_headers']['Location'] == exp_location\n # check: redirect as given by mod_alias\n exp_location = \"https://%s/a\" % name\n r = TestEnv.get_meta(name, \"/a\", use_https=False)\n assert r['http_status'] == 301 # FAIL: mod_alias generates Location header instead of mod_md\n assert r['http_headers']['Location'] == exp_location\n\n def test_502_111(self):\n # test case: vhost with parallel HTTP/HTTPS, check mod_alias redirects\n # setup: prepare config\n domain = self.test_domain\n name = \"www.\" + domain\n conf = HttpdConf()\n conf.add_admin(\"admin@\" + domain)\n conf.add_drive_mode(\"manual\")\n conf.add_md([name])\n conf._add_line(\" LogLevel alias:debug\")\n conf.add_vhost(name, port=TestEnv.HTTP_PORT)\n conf.add_vhost(name)\n conf.install()\n assert TestEnv.apache_restart() == 0\n # drive it\n r = TestEnv.a2md([\"-v\", \"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n assert TestEnv.apache_restart() == 0\n\n # setup: place redirect rules\n conf._add_line(' Redirect /a /name.txt')\n conf._add_line(' Redirect seeother /b /name.txt')\n conf.install()\n assert TestEnv.apache_restart() == 0\n # check: redirects on HTTP\n exp_location = \"http://%s:%s/name.txt\" % (name, TestEnv.HTTP_PORT)\n r = TestEnv.get_meta(name, \"/a\", use_https=False)\n assert r['http_status'] == 302\n assert r['http_headers']['Location'] == exp_location\n r = TestEnv.get_meta(name, \"/b\", use_https=False)\n assert r['http_status'] == 303\n assert r['http_headers']['Location'] == exp_location\n # check: redirects on HTTPS\n exp_location = \"https://%s:%s/name.txt\" % (name, TestEnv.HTTPS_PORT)\n r = TestEnv.get_meta(name, \"/a\", use_https=True)\n assert r['http_status'] == 302\n assert r['http_headers']['Location'] == exp_location # FAIL: expected 'https://...' but found 'http://...'\n r = TestEnv.get_meta(name, \"/b\", use_https=True)\n assert r['http_status'] == 303\n assert r['http_headers']['Location'] == exp_location\n\n def test_502_120(self):\n # test case: NP dereference reported by Daniel Caminada \n domain = self.test_domain\n name = \"www.\" + domain\n conf = HttpdConf()\n conf.add_admin(\"admin@\" + domain)\n conf.add_drive_mode(\"manual\")\n conf.add_md([name])\n conf.add_vhost(name)\n conf.install()\n assert TestEnv.apache_restart() == 0\n TestEnv.run([\"openssl\", \"s_client\",\n \"-connect\", \"%s:%s\" % (TestEnv.HTTPD_HOST, TestEnv.HTTPS_PORT),\n \"-servername\", \"example.com\", \"-crlf\"\n ], \"GET https:// HTTP/1.1\\nHost: example.com\\n\\n\")\n assert TestEnv.apache_restart() == 0\n # assert that no crash is reported in the log\n assert not TestEnv.httpd_error_log_scan(re.compile(r'^.* child pid \\S+ exit .*$'))\n\n # --------- critical state change -> drive again ---------\n\n def test_502_200(self):\n # test case: add dns name on existing valid md\n # setup: create md in store\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name])\n assert TestEnv.apache_start() == 0\n # setup: drive it\n r = TestEnv.a2md([\"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n old_cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n # setup: add second domain\n assert TestEnv.a2md([\"update\", name, \"domains\", name, \"test.\" + domain])['rv'] == 0\n # drive\n r = TestEnv.a2md([\"-vv\", \"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n # check new cert\n TestEnv.check_md_credentials([name, \"test.\" + domain])\n new_cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n assert not old_cert.same_serial_as(new_cert.get_serial)\n\n @pytest.mark.parametrize(\"renew_window,test_data_list\", [\n (\"14d\", [\n {\"valid\": {\"notBefore\": -5, \"notAfter\": 180}, \"renew\": False},\n {\"valid\": {\"notBefore\": -200, \"notAfter\": 15}, \"renew\": False},\n {\"valid\": {\"notBefore\": -200, \"notAfter\": 13}, \"renew\": True},\n ]),\n (\"30%\", [\n {\"valid\": {\"notBefore\": -0, \"notAfter\": 180}, \"renew\": False},\n {\"valid\": {\"notBefore\": -120, \"notAfter\": 60}, \"renew\": False},\n {\"valid\": {\"notBefore\": -126, \"notAfter\": 53}, \"renew\": True},\n ])\n ])\n def test_502_201(self, renew_window, test_data_list):\n # test case: trigger cert renew when entering renew window \n # setup: prepare COMPLETE md\n domain = self.test_domain\n name = \"www.\" + domain\n conf = HttpdConf()\n conf.add_admin(\"admin@\" + domain)\n conf.add_drive_mode(\"manual\")\n conf.add_renew_window(renew_window)\n conf.add_md([name])\n conf.install()\n assert TestEnv.apache_restart() == 0\n assert TestEnv.a2md([\"list\", name])['jout']['output'][0]['state'] == TestEnv.MD_S_INCOMPLETE\n # setup: drive it\n r = TestEnv.a2md([\"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n cert1 = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n assert TestEnv.a2md([\"list\", name])['jout']['output'][0]['state'] == TestEnv.MD_S_COMPLETE\n\n # replace cert by self-signed one -> check md status\n print(\"TRACE: start testing renew window: %s\" % renew_window)\n for tc in test_data_list:\n print(\"TRACE: create self-signed cert: %s\" % tc[\"valid\"])\n TestEnv.create_self_signed_cert([name], tc[\"valid\"])\n cert2 = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n assert not cert2.same_serial_as(cert1)\n md = TestEnv.a2md([\"list\", name])['jout']['output'][0]\n assert md[\"renew\"] == tc[\"renew\"], \\\n \"Expected renew == {} indicator in {}, test case {}\".format(tc[\"renew\"], md, tc)\n\n @pytest.mark.parametrize(\"key_type,key_params,exp_key_length\", [\n (\"RSA\", [2048], 2048),\n (\"RSA\", [3072], 3072),\n (\"RSA\", [4096], 4096),\n (\"Default\", [], 2048)\n ])\n def test_502_202(self, key_type, key_params, exp_key_length):\n # test case: specify RSA key length and verify resulting cert key \n # setup: prepare md\n domain = self.test_domain\n name = \"www.\" + domain\n conf = HttpdConf()\n conf.add_admin(\"admin@\" + domain)\n conf.add_drive_mode(\"manual\")\n conf.add_private_key(key_type, key_params)\n conf.add_md([name])\n conf.install()\n assert TestEnv.apache_restart() == 0\n assert TestEnv.a2md([\"list\", name])['jout']['output'][0]['state'] == TestEnv.MD_S_INCOMPLETE\n # setup: drive it\n r = TestEnv.a2md([\"-vv\", \"drive\", name])\n assert r['rv'] == 0, \"drive for MDPrivateKeys {} {}: {}\".format(key_type, key_params, r['stderr'])\n assert TestEnv.a2md([\"list\", name])['jout']['output'][0]['state'] == TestEnv.MD_S_COMPLETE\n # check cert key length\n cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n assert cert.get_key_length() == exp_key_length\n\n # test_502_203 removed, as ToS agreement is not really checked in ACMEv2\n\n # --------- non-critical state change -> keep data ---------\n\n def test_502_300(self):\n # test case: remove one domain name from existing valid md\n # setup: create md in store\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name, \"test.\" + domain, \"xxx.\" + domain])\n assert TestEnv.apache_start() == 0\n # setup: drive it\n r = TestEnv.a2md([\"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n old_cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n # setup: remove one domain\n assert TestEnv.a2md([\"update\", name, \"domains\"] + [name, \"test.\" + domain])['rv'] == 0\n # drive\n assert TestEnv.a2md([\"-vv\", \"drive\", name])['rv'] == 0\n # compare cert serial\n new_cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n assert old_cert.same_serial_as(new_cert)\n\n def test_502_301(self):\n # test case: change contact info on existing valid md\n # setup: create md in store\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name])\n assert TestEnv.apache_start() == 0\n # setup: drive it\n r = TestEnv.a2md([\"drive\", name])\n assert r['rv'] == 0, \"a2md drive failed: {0}\".format(r['stderr'])\n old_cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n # setup: add second domain\n assert TestEnv.a2md([\"update\", name, \"contacts\", \"test@\" + domain])['rv'] == 0\n # drive\n assert TestEnv.a2md([\"drive\", name])['rv'] == 0\n # compare cert serial\n new_cert = CertUtil(TestEnv.store_domain_file(name, 'pubcert.pem'))\n assert old_cert.same_serial_as(new_cert)\n\n # --------- network problems ---------\n\n def test_502_400(self):\n # test case: server not reachable\n domain = self.test_domain\n name = \"www.\" + domain\n self._prepare_md([name])\n assert TestEnv.a2md(\n [\"update\", name, \"ca\", \"http://localhost:4711/directory\"]\n )['rv'] == 0\n # drive\n run = TestEnv.a2md([\"drive\", name])\n assert run['rv'] == 1\n assert run['jout']['status'] != 0\n assert run['jout']['description'] == 'Connection refused'\n\n # --------- _utils_ ---------\n\n def _prepare_md(self, domains):\n assert TestEnv.a2md([\"add\"] + domains)['rv'] == 0\n assert TestEnv.a2md(\n [\"update\", domains[0], \"contacts\", \"admin@\" + domains[0]]\n )['rv'] == 0\n assert TestEnv.a2md( \n [\"update\", domains[0], \"agreement\", TestEnv.ACME_TOS]\n )['rv'] == 0\n\n def _write_res_file(self, doc_root, name, content):\n if not os.path.exists(doc_root):\n os.makedirs(doc_root)\n open(os.path.join(doc_root, name), \"w\").write(content)\n\n RE_MSG_OPENSSL_BAD_DECRYPT = re.compile('.*\\'bad decrypt\\'.*')\n\n def _check_account_key(self, name):\n # read encryption key\n md_store = json.loads(open(TestEnv.path_store_json(), 'r').read())\n encrypt_key = base64.urlsafe_b64decode(str(md_store['key']))\n # check: key file is encrypted PEM\n md = TestEnv.a2md([\"list\", name])['jout']['output'][0]\n acc = md['ca']['account']\n CertUtil.validate_privkey(TestEnv.path_account_key(acc), lambda *args: encrypt_key)\n","sub_path":"test/test_0502_acmev2_drive.py","file_name":"test_0502_acmev2_drive.py","file_ext":"py","file_size_in_byte":24146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"505173339","text":"#! /usr/bin/env python3\n\nimport collections\nimport operator\nimport errno\nimport glob\nimport os\nimport itertools\n\nimport numpy as np\nimport torch\nimport yaml\nfrom easy_module_attribute_getter import utils as emag_utils\nimport logging\nimport inspect\nimport pytorch_metric_learning.utils.common_functions as pml_cf\nimport datetime\nimport sqlite3\nimport tqdm\nimport tarfile, zipfile\nfrom . import constants as const\n\n\ndef load_model_for_eval(model_factory, model_args, model_name, factory_kwargs, model_folder=None, device=None):\n untrained_trunk = model_name in const.UNTRAINED_TRUNK_ALIASES\n untrained_trunk_and_embedder = model_name in const.UNTRAINED_TRUNK_AND_EMBEDDER_ALIASES\n trunk_model = model_factory.create(named_specs=model_args, subset=\"trunk\", **factory_kwargs)\n if untrained_trunk:\n embedder_model = pml_cf.Identity()\n else:\n embedder_model = model_factory.create(named_specs=model_args, subset=\"embedder\", **factory_kwargs)\n if not untrained_trunk_and_embedder: \n if model_name in const.TRAINED_ALIASES:\n _, model_name = pml_cf.latest_version(model_folder, best=True)\n pml_cf.load_dict_of_models(\n {\"trunk\": trunk_model, \"embedder\": embedder_model},\n model_name,\n model_folder,\n device,\n log_if_successful = True,\n assert_success = True\n )\n return torch.nn.DataParallel(trunk_model), torch.nn.DataParallel(embedder_model)\n\n\ndef move_optimizer_to_gpu(optimizer, device):\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = v.to(device)\n\n\ndef makedir_if_not_there(dir_name):\n try:\n os.makedirs(dir_name)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n\ndef load_yaml(fname):\n with open(fname, 'r') as f:\n loaded_yaml = yaml.safe_load(f)\n return loaded_yaml\n\n\ndef write_yaml(fname, input_dict, open_as):\n with open(fname, open_as) as outfile:\n yaml.dump(input_dict, outfile, default_flow_style=False, sort_keys=False)\n\n\ndef latest_sub_experiment_epochs(sub_experiment_dir_dict):\n latest_epochs = {}\n for sub_experiment_name, folders in sub_experiment_dir_dict.items():\n model_folder = folders[\"models\"]\n latest_epochs[sub_experiment_name], _ = pml_cf.latest_version(model_folder)\n return latest_epochs\n\n\ndef get_sorted_config_diff_folders(config_folder):\n full_base_path = os.path.join(config_folder, const.CONFIG_DIFF_BASE_FOLDER_NAME)\n config_diff_folder_names = glob.glob(\"%s*\"%full_base_path) \n latest_epochs = []\n if len(config_diff_folder_names) > 0:\n for c in config_diff_folder_names:\n latest_epochs.append([c]+[int(x) for x in c.replace(full_base_path,\"\").split('_')])\n num_training_sets = len(latest_epochs[0])-1\n latest_epochs = sorted(latest_epochs, key=operator.itemgetter(*list(range(1, num_training_sets+1))))\n return [x[0] for x in latest_epochs], [x[1:] for x in latest_epochs]\n return [], []\n\ndef get_all_resume_training_config_diffs(config_folder, split_manager):\n config_diffs, latest_epochs = get_sorted_config_diff_folders(config_folder)\n if len(config_diffs) == 0:\n return {}\n split_scheme_names = [split_manager.get_split_scheme_name(i) for i in range(len(latest_epochs[0]))]\n resume_training_dict = {}\n for i, k in enumerate(config_diffs):\n resume_training_dict[k] = {split_scheme:epoch for (split_scheme,epoch) in zip(split_scheme_names, latest_epochs[i])}\n return resume_training_dict\n\n\ndef save_config_files(config_folder, dict_of_yamls, resume_training, latest_epochs):\n makedir_if_not_there(config_folder)\n new_dir = None\n existing_config_diff_folders, _ = get_sorted_config_diff_folders(config_folder)\n\n for config_name, config_dict in dict_of_yamls.items():\n fname = os.path.join(config_folder, '%s.yaml'%config_name)\n if not resume_training:\n write_yaml(fname, config_dict, 'w')\n else:\n curr_yaml = load_yaml(fname)\n for config_diff_folder in existing_config_diff_folders:\n config_diff = os.path.join(config_diff_folder, '%s.yaml'%config_name)\n if os.path.isfile(config_diff):\n curr_yaml = emag_utils.merge_two_dicts(curr_yaml, load_yaml(config_diff), max_merge_depth=float('inf'))\n\n yaml_diff = {}\n for k, v in config_dict.items():\n if (k not in curr_yaml) or (v != curr_yaml[k]):\n yaml_diff[k] = v\n\n if yaml_diff != {}:\n new_dir = os.path.join(config_folder, const.CONFIG_DIFF_BASE_FOLDER_NAME + '_'.join([str(epoch) for epoch in latest_epochs]))\n makedir_if_not_there(new_dir)\n fname = os.path.join(new_dir, '%s.yaml' %config_name)\n write_yaml(fname, yaml_diff, 'a')\n\n\ndef get_last_linear(input_model, return_name=False):\n for name in [\"fc\", \"last_linear\"]:\n last_layer = getattr(input_model, name, None)\n if last_layer:\n if return_name:\n return last_layer, name\n return last_layer\n\ndef set_last_linear(input_model, set_to):\n setattr(input_model, get_last_linear(input_model, return_name=True)[1], set_to)\n\n\ndef check_init_arguments(input_obj, str_to_check):\n obj_stack = [input_obj]\n while len(obj_stack) > 0:\n curr_obj = obj_stack.pop()\n obj_stack += list(curr_obj.__bases__)\n if str_to_check in str(inspect.signature(curr_obj.__init__)):\n return True\n return False\n\n\ndef try_getting_db_count(record_keeper, table_name):\n try:\n len_of_existing_record = record_keeper.query(\"SELECT count(*) FROM %s\"%table_name, use_global_db=False)[0][\"count(*)\"] \n except sqlite3.OperationalError:\n len_of_existing_record = 0\n return len_of_existing_record\n\n\ndef get_datetime():\n return datetime.datetime.now()\n\n\ndef extract_progress(compressed_obj):\n logging.info(\"Extracting dataset\")\n if isinstance(compressed_obj, tarfile.TarFile):\n iterable = compressed_obj\n length = len(compressed_obj.getmembers())\n elif isinstance(compressed_obj, zipfile.ZipFile):\n iterable = compressed_obj.namelist()\n length = len(iterable)\n for member in tqdm.tqdm(iterable, total=length):\n yield member\n\n\ndef if_str_convert_to_singleton_list(input):\n if isinstance(input, str):\n return [input]\n return input\n\ndef first_key_of_dict(input):\n return list(input.keys())[0]\n\ndef first_val_of_dict(input):\n return input[first_key_of_dict(input)]\n\n\ndef get_attr_and_try_as_function(input_object, input_attr):\n attr = getattr(input_object, input_attr)\n try:\n return attr()\n except TypeError:\n return attr\n\n\ndef get_eval_record_name_dict(hooks, tester, split_names=None):\n prefix = hooks.record_group_name_prefix \n hooks.record_group_name_prefix = \"\" #temporary\n if split_names is None:\n non_meta = {\"base_record_group_name\": hooks.base_record_group_name(tester)}\n else:\n non_meta = {k:hooks.record_group_name(tester, k) for k in split_names}\n hooks.record_group_name_prefix = prefix\n return non_meta","sub_path":"src/powerful_benchmarker/utils/common_functions.py","file_name":"common_functions.py","file_ext":"py","file_size_in_byte":7328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"527951200","text":"#!/usr/bin/python\nimport sys\n\ndef fReturnExpression(vOne, vTwo, vExpression):\n \n vExpression = vExpression.replace('\\r','')\n\n if vExpression == \"sum\":\n vReturn = vOne + vTwo\n elif vExpression == \"diff\":\n vReturn = vOne - vTwo\n else:\n print(\"Expression \", vExpression, \"doesn't exist!\")\n vReturn=None\n return vReturn\n\n\nprint(\"Choice your command (sum/diff):\")\n\n\n# necessary if I need to make a code that works for pyton 2 and 3 version\n#\n#if sys.hexversion >= 0x3000000:\n# vCommand = input()\n#else:\n# vCommand = raw_input()\n\nvCommand = input()\n\nprint(\"First number: \")\nvFirstNumber = int(input())\nprint(\"Second number: \")\nvSecondNumber = int(input())\n\nprint(vFirstNumber, \" \", vCommand, \" \", vSecondNumber, \" equal \", fReturnExpression(vFirstNumber, vSecondNumber, vCommand))\n","sub_path":"Genericos/teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"653504864","text":"import argparse\r\nimport os\r\n\r\nif __name__ == '__main__':\r\n CURRENT_DIR = os.path.dirname(__file__)\r\n ROOT_DIR = os.path.dirname(os.path.dirname(CURRENT_DIR))\r\n ANNO_GT_DIR = os.path.join(ROOT_DIR, 'data_set', 'face_detection', 'wider_face_split')\r\n #print(ANNO_GT_DIR)\r\n file = open(ANNO_GT_DIR + '/wider_face_train_bbx_gt.txt')\r\n wfile = open(ANNO_GT_DIR + '/wider_face_train_mtcnn_bbx.txt', 'w')\r\n \r\n while True:\r\n item = ''\r\n line = file.readline()\r\n if not line:\r\n break\r\n line = line.strip()\r\n item += line + ' '\r\n\r\n index = file.readline()\r\n index = index.strip()\r\n num = int(index)\r\n\r\n if num == 0:\r\n tmp = file.readline()\r\n continue\r\n\r\n for i in range(0, num):\r\n bbox = file.readline()\r\n bbox = bbox.strip()\r\n bbox = bbox.split(' ')\r\n bbox = list(map(float, bbox[:]))\r\n item += str(bbox[0]) + ' ' + str(bbox[1]) + ' ' + str(bbox[0] + bbox[2]) + ' ' + str(bbox[1] + bbox[3]) + ' '\r\n\r\n wfile.write(item + '\\n')\r\n\r\n file.close()\r\n wfile.close()","sub_path":"P03_FaceRecognition/FaceDetect_MTCNN/mtcnn/data_preprocess/gen_Pnet_label_list.py","file_name":"gen_Pnet_label_list.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"516261268","text":"import modules.runas\nimport modules.ssh\nimport modules.legate_dask\nimport modules.openmpi\nimport modules.gasnet\nimport modules.nsys\n\ndef emit(writer, **kwargs):\n if \"cudaVersionFull\" not in kwargs:\n raise Exception(\"'cudaVersionFull' is mandatory!\")\n if \"rapidsVersion\" not in kwargs:\n raise Exception(\"'rapidsVersion' is mandatory!\")\n # everything is already installed, just add runas and ssh\n modules.runas.emit(writer)\n modules.ssh.emit(writer)\n modules.legate_dask.emit(writer, **kwargs)\n modules.openmpi.emit(writer, devBuild=False, ompiVersion=\"4.0.2\")\n modules.gasnet.emit(writer, conduit=\"mpi\")\n modules.nsys.emit(writer, version=\"2020.2.1\")\n writer.emit(\"\"\"\n ENV OPT_DIR=/opt\n ENV LEGATE_DIR=/home/scratch.mjoux_gpu/dev/legate.core/install\n ENV LIBRARY_PATH=\"$${LEGATE_DIR}/lib:$${LIBRARY_PATH}\"\n ENV LD_LIBRARY_PATH=\"$${LEGATE_DIR}/lib:$${LD_LIBRARY_PATH}\"\n \"\"\")\n\ndef images():\n return {\n \"legate-dask:10.0\": {\n \"base\": \"rapidsai/rapidsai-dev:0.12-cuda10.0-devel-ubuntu16.04-py3.7\",\n \"rapidsVersion\": \"0.12\",\n \"cudaVersionFull\": \"10.0.130\",\n \"needsContext\": True,\n },\n \"legate-dask-0.14:10.0\": {\n \"base\": \"rapidsai/rapidsai-dev-nightly:0.14-cuda10.0-devel-ubuntu16.04-py3.7\",\n \"rapidsVersion\": \"0.14\",\n \"cudaVersionFull\": \"10.0.130\",\n \"needsContext\": True,\n },\n \"legate-dask-0.15:10.2\": {\n \"base\": \"rapidsai/rapidsai-dev-nightly:0.15-cuda10.2-devel-ubuntu16.04-py3.7\",\n \"rapidsVersion\": \"0.15\",\n \"cudaVersionFull\": \"10.2.89\",\n \"needsContext\": True,\n },\n \"legate-dask-0.18:11.0\": {\n \"base\": \"rapidsai/rapidsai-core-dev-nightly:0.18-cuda11.0-devel-ubuntu18.04-py3.7\",\n \"rapidsVersion\": \"0.18\",\n \"cudaVersionFull\": \"11.0.1\",\n \"needsContext\": True,\n },\n \"legate-dask-debug:10.0\": {\n \"base\": \"rapidsai/rapidsai-dev:0.12-cuda10.0-devel-ubuntu16.04-py3.7\",\n \"rapidsVersion\": \"0.12\",\n \"cudaVersionFull\": \"10.0.130\",\n \"needsContext\": True,\n \"debug\": True,\n }\n }\n","sub_path":"images/legate_dask.py","file_name":"legate_dask.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"129821373","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n-------------------------------------\nCreated on 2020/4/24 16:41\n@author: Teyying\n@site: https://github.com/teyying\n@email: 165227316@qq.com\n-------------------------------------\n@file: collectPane.py\n@description:\n@problem:\n-------------------------------------\n\n\"\"\"\n\n\nfrom functools import partial\n\nfrom PyQt5.QtCore import Qt, QRectF, QSize, QEvent\nfrom PyQt5.QtGui import QBitmap, QPainter, QBrush, QCursor\nfrom PyQt5.QtWidgets import QDialog, QPushButton, QWidget, QLabel, QHBoxLayout, QScrollArea, QFrame\n\nfrom main.resource.collectUi import Ui_Card\n\n\nclass Ui_Card_Logic(QDialog, Ui_Card):\n def __init__(self, parent=None):\n super(Ui_Card_Logic, self).__init__()\n self.setupUi(self)\n self.setWindowFlags(Qt.FramelessWindowHint) # 隐藏标题栏\n self.setAttribute(Qt.WA_DeleteOnClose)\n self.flagMove = False\n self.widTitle.installEventFilter(self)\n\n # 用遮罩的方法给窗体设置圆角\n self.whiteMask = QBitmap(self.size()) # 创建位图,窗体大小\n self.whiteMask.fill(Qt.white) # 填充位图全白,相当于把窗口擦掉了,后面再用画刷显示出来。\n p = QPainter(self.whiteMask)\n brush = QBrush(Qt.black) # 创建画刷并设置成黑色,这样黑色区域内的窗口就显示出来了。\n p.setBrush(brush) # 设置画刷\n rectF = QRectF(0.0, 0.0, 884, 680) # 画一个矩形\n p.drawRoundedRect(rectF, 8.0, 8.0) # 给矩形添加圆角\n self.setMask(self.whiteMask) # 设置遮罩\n\n # self.uiCardFullScreen = Ui_CardFullScreen_Logic()\n # self.widFullScreen.installEventFilter(self)\n\n self.setBtns()\n\n def setBtns(self):\n # 速度:77字 / 分,正确率:95 %,级别: 七级\n # 19\n try:\n num = 100\n if num > 1052:\n num = 1052\n self.labTitle.setText(str(num))\n row = 0\n column = 0\n for i in range(num):\n btn = QPushButton()\n btn.setFixedSize(210, 300)\n btn.setCursor(QCursor(Qt.PointingHandCursor))\n self.gridLayout.addWidget(btn, row, column)\n column += 1\n if column == 4:\n row += 1\n column = 0\n\n self.btns = self.scrollAreaWid.children()[1:] # 列表第一个是QGrdLayout\n self.numBtns = len(self.btns) # 图片文件共有1052张图,如果超过就会崩溃。暂不解决这个问题。\n self.index = 0\n self.timer = self.startTimer(10)\n\n except Exception as e:\n print(e)\n\n def slot_btns(self, styleStr):\n self.uiCardFullScreen = Ui_CardFullScreen(styleStr)\n self.uiCardFullScreen.exec()\n\n def timerEvent(self, e):\n \"\"\"每10毫秒添加一张图片,这样图片多了之后启动窗口就不会出现无响应状态\"\"\"\n try:\n self.btns[self.index].setStyleSheet(f\"border-images: url('UiMain/images/card/{self.index}.png')\")\n self.btns[self.index].clicked.connect(partial(self.slot_btns, self.btns[self.index].styleSheet()))\n\n if self.index == self.numBtns - 1:\n self.killTimer(self.timer)\n self.index += 1\n except Exception as e:\n print(e)\n\n def eventFilter(self, obj, e):\n \"\"\"只有self.widTitle注册了遍历器,所以没有用obj对象\"\"\"\n if e.type() == e.MouseButtonPress and e.button() == Qt.LeftButton:\n self.flagMove = True\n self.posMove = e.globalPos() - self.pos() # 获取鼠标相对窗口的位置\n e.accept()\n if e.type() == e.MouseMove and self.flagMove:\n self.move(e.globalPos() - self.posMove) # 更改窗口位置\n e.accept()\n if e.type() == e.MouseButtonRelease:\n self.flagMove = False\n return False # 必须有\n\n\nclass Ui_CardFullScreen(QDialog):\n def __init__(self, styleStr):\n super(Ui_CardFullScreen, self).__init__()\n self.setAttribute(Qt.WA_DeleteOnClose)\n self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) # 隐藏标题栏,并让窗体一直在顶层\n self.setAttribute(Qt.WA_TranslucentBackground) # 窗体透明\n self.setWindowOpacity(1) # 设置为1,控件不透明\n\n hbox = QHBoxLayout(self)\n hbox.setContentsMargins(0, 0, 0, 0) # 调整边距\n self.scrollArea = QScrollArea(self)\n self.scrollArea.setStyleSheet('background:rgba(0,0,0,120)')\n self.scrollArea.setFrameShape(QFrame.NoFrame) # 去掉边框\n self.scrollArea.setWidgetResizable(True) # 这一句很重要。意思应该是让内部的widget随它的尺寸\n self.widPix = QWidget()\n self.widPix.setMouseTracking(True) # 设置鼠标跟踪后会实时跟踪,不然只有在点击的时候才跟踪。\n self.widPix.installEventFilter(self)\n hbox2 = QHBoxLayout(self.widPix)\n hbox2.setContentsMargins(0, 0, 0, 0)\n self.labPix = QLabel(self.widPix)\n self.labPix.setStyleSheet(styleStr + ';background:transparent;')\n self.labPix.setFixedSize(210, 300)\n hbox2.addWidget(self.labPix)\n self.scrollArea.setWidget(self.widPix)\n hbox.addWidget(self.scrollArea)\n self.labClose = QLabel('×', self.widPix) # 为了让字体靠右靠上,只能把btn改成lab,\n self.labClose.setFixedSize(60, 60) # 不然只能qss设置水平方向text-align:right;找不到垂直靠上的方法。\n self.labClose.setAlignment(Qt.AlignRight | Qt.AlignTop)\n self.labClose.setCursor(QCursor(Qt.PointingHandCursor))\n self.labClose.setStyleSheet(\n 'QLabel {font-size:50px;color:white;border-bottom-left-radius:60px 60px;}:hover{background:red;}')\n self.labClose.hide()\n self.labPercent = QLabel(\"100%\", self.widPix)\n self.labPercent.installEventFilter(self)\n self.labPercent.setStyleSheet('background:rgba(255,255,255,120);font-size:30px;border-radius:5px;')\n self.labPercent.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n self.labPercent.setFixedSize(80, 40)\n self.labPercent.hide()\n\n def showEvent(self, e): # 这也可以写进事件遍历器里面\n self.showFullScreen()\n self.scrollArea.setFixedSize(self.size()) # 这个尺寸只有在显示满屏后才能得到此Ui的尺寸\n self.labClose.move(self.width() - self.labClose.width(), 0) # 固定在右上角\n self.labPercent.move(self.width() / 2 - self.labPercent.width() / 2,\n self.height() / 2 - self.labPercent.height() / 2)\n\n def eventFilter(self, obj, e):\n if obj == self.widPix:\n if e.type() == e.MouseMove: # 设置鼠标在屏幕四周60px内显示关闭按钮,离开60px范围藏关闭按钮\n if self.labClose.isHidden():\n if e.globalX() == 0 or e.globalY() == 0 or e.globalX() >= self.width() - 1 or e.globalY() >= self.height() - 1:\n self.labClose.show()\n elif self.labClose.isVisible():\n if self.width() - 60 > e.globalX() >= 60 and self.height() - 60 > e.globalY() >= 60:\n self.labClose.hide()\n elif e.type() == e.MouseButtonPress and e.button() == Qt.LeftButton: # self.labClose不用childAt,设置鼠标跟踪应该也行\n if self.childAt(e.globalPos()) == self.widPix or self.childAt(e.globalPos()) == self.labClose:\n self.close()\n elif e.type() == e.MouseButtonDblClick and e.button() == Qt.LeftButton:\n if self.childAt(e.globalPos()) == self.labPix: # 判断双击位置是否是self.labPix\n self.labPix.setFixedSize(210, 300)\n self.num = 100\n self.labPercent.setText('100%')\n elif e.type() == e.Wheel: # e.angleDelta().y()大于0说明向上滚动,反之\n self.labPercent.show()\n num = int(self.labPercent.text()[:-1])\n if e.angleDelta().y() > 0 and num != 500: # 上滚是QPoint(0, 120),下滚是QPoint(0, -120)\n symbol = '+'\n elif e.angleDelta().y() < 0 and num != 0:\n symbol = '-'\n else:\n return False\n self.labPix.setFixedSize(eval(f\"self.labPix.width(){symbol}21\"),\n eval(f\"self.labPix.height(){symbol}30\"))\n self.labPercent.setText(eval(f\"str(num{symbol}10)+'%'\"))\n return False\n if obj == self.labPercent:\n if e.type() == e.Show:\n self.timerId = self.labPercent.startTimer(1000, Qt.VeryCoarseTimer)\n elif e.type() == e.Timer:\n self.labPercent.killTimer(self.timerId)\n self.labPercent.hide()\n return False\n\n else:\n return False\n\n\nif __name__ == '__main__':\n app = QApplication(argv)\n window = MainPane()\n window.show()\n exit(app.exec_())","sub_path":"main/collectPane.py","file_name":"collectPane.py","file_ext":"py","file_size_in_byte":9189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"232739596","text":"# https://www.urionlinejudge.com.br/judge/pt/problems/view/1248\n\n# -*- coding: utf-8 -*-\n\nN = int(input())\n\nfor caso_teste in range(N):\n dieta = str(input())\n cafe = str(input())\n almoco = str(input())\n\n if dieta == \"\" and cafe == \"\" and almoco == \"\":\n print()\n elif (len(cafe) + len(almoco)) > len(dieta):\n print(\"CHEATER\")\n else:\n refeicao = cafe + almoco\n\n dieta = list(dieta)\n\n for alimento in refeicao:\n if alimento not in dieta:\n print(\"CHEATER\")\n break\n else:\n dieta.pop(dieta.index(alimento))\n\n else:\n if len(dieta) > 0:\n dieta = \"\".join(list(sorted(dieta)))\n print(dieta)\n else:\n print()","sub_path":"Python3/Strings/1248 - Plano de Dieta.py","file_name":"1248 - Plano de Dieta.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"145192924","text":"from prettytable import PrettyTable\nimport pandas as pd\n\nt = PrettyTable(['Dispatcher','Load', 'Response Time (sec)'])\nt._set_align('r')\n\ndef print_res(file):\n\n try:\n with open(file, 'r') as file_obj:\n\n header = file_obj.readline()\n header = header.strip().split(',')\n\n table = PrettyTable(header)\n\n for line in file_obj:\n row = line.strip().split(',')\n if len(row) == len(header):\n table.add_row(row)\n else:\n print('Warning: One or more Null values')\n\n print(table)\n \n\n except FileNotFoundError:\n print('File not found')\n quit()\n\n\nfilename = input(\"Enter file name: \")\nprint_res(filename)\n\nprint(pd.read_csv(filename))\n ","sub_path":"prettyprint-results.py","file_name":"prettyprint-results.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"411171321","text":"#!/usr/bin/env python3\nfrom candles.sync_candles import get_sync_candles_class\nfrom loguru import logger\nimport click\nimport os\n\nCOMMANDS = [\"candles\"]\nlogger.level = os.getenv(\"LOG_LEVEL\", \"WARNING\")\n\n\n@click.command()\n@click.argument(\"command\", type=click.Choice(COMMANDS))\n@click.option(\"--exchange\", type=str, default=\"Bitfinex\", help=\"Bitfinex, ...\")\n@click.option(\n \"--symbol\", type=str, default=\"fUSD\", help=\"fUSD for Bitfinex funding data, or tETHUSD for ETH\",\n)\n@click.option(\"--interval\", type=str, default=\"1m\", help=\"1m for 1m candle data\")\n@click.option(\"--start\", type=str, default=None, help=\"any string python-arrow supports\")\n@click.option(\"--end\", type=str, default=None, help=\"any string python-arrow supports\")\ndef run(*args, **options): # pragma: no cover\n if options[\"command\"] == \"candles\":\n exchange = options[\"exchange\"].lower()\n client = get_sync_candles_class(\n exchange=exchange,\n symbol=options[\"symbol\"],\n interval=options[\"interval\"],\n start=options[\"start\"],\n end=options[\"end\"],\n )\n client.pull_data()\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"477508595","text":"import capabilities\n##@brief this class is used by the data-gather\n#\nclass MeasurementMaster:\n class Callback:\n def __init__(self,buffer_handler) :\n self.__buffer = weakref.ref(buffer_handler)\n #@brief callback from buffer_handler\n def new_data_ready(self,data) :\n pass\n\n ##@brief Initialized the measurement master\n #\n #@param nb_point == Nb data points should be retrieved from slaves\n #@param synchronised could be True/False if False it will act as a monitor\n def __init__(self,\n nb_point = None, # \n synchronised = True, # \n acq_time = None,\n divider = None,\n acq_dead_band = 1\n ) :\n self.__nb_point = nb_point\n self.__synchronised = synchronised\n self.__acq_time = acq_time\n self.__divider = False\n self.__acq_dead_band = acq_dead_band\n self.__slaves = []\n self.__masters = []\n self.__callbacks = []\n #@brief add a detector to get data from\n #\n #\n def addSlave(self,slave):\n buffer_handler = slave.get_capabilities(capabilities.BUFFER_CTRL)\n buffer_cbk = Callback(buffer_handler)\n buffer_handler.registerCallback(buffer_cbk)\n\n self.__slaves.append(buffer_handler)\n self.__callbacks.append(buffer_cbk)\n\n def addMaster(self,master) :\n self.__masters.append(master)\n\n\nclass MeasurementChain:\n def __init__(self) :\n self.__masters = []\n\n def addMaster(self,master) :\n self.__masters.append(master)\n","sub_path":"helper/measurement/chain.py","file_name":"chain.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"561378753","text":"\"\"\"Unit test for node harvest\n\"\"\"\n\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nimport mock\n\nfrom treadmill import postmortem\nfrom treadmill import subproc\n\n\nclass postmortemTest(unittest.TestCase):\n \"\"\"Tests for teadmill.fs.\"\"\"\n\n # Pylint complains about long names for test functions.\n # pylint: disable=C0103\n\n def setUp(self):\n self.tmroot = tempfile.mkdtemp()\n self.archive_root = tempfile.mkdtemp()\n self.tmp_dir = '/tmp/postmortem-%d' % os.getpid()\n\n os.makedirs('%s/init/server_init/log' % self.tmroot)\n os.mknod('%s/init/server_init/log/current' % self.tmroot)\n\n os.makedirs('%s/running/foo/sys/bar/log' % self.tmroot)\n os.mknod('%s/running/foo/sys/bar/log/current' % self.tmroot)\n\n os.makedirs('%s/localdisk_svc' % self.tmroot)\n os.makedirs('%s/network_svc' % self.tmroot)\n os.makedirs('%s/cgroup_svc' % self.tmroot)\n\n def tearDown(self):\n if self.tmroot and os.path.isdir(self.tmroot):\n shutil.rmtree(self.tmroot)\n\n if self.archive_root and os.path.isdir(self.archive_root):\n shutil.rmtree(self.archive_root)\n\n if self.tmp_dir and os.path.isdir(self.tmp_dir):\n shutil.rmtree(self.tmp_dir)\n\n @mock.patch('shutil.copyfile', mock.Mock())\n @mock.patch('shutil.copytree', mock.Mock())\n @mock.patch('tempfile.mkdtemp',\n mock.Mock(return_value='/tmp/postmortem-%d' % os.getpid()))\n @mock.patch('treadmill.subproc.check_output',\n mock.Mock(return_value='foo'))\n def test_collect_init_services(self):\n \"\"\"test node information collection.\n \"\"\"\n # XXX(boysson): Should be all os.path.join below\n archive_file = '%s/archive.tar' % self.archive_root\n real_file = postmortem.collect(self.tmroot, archive_file)\n self.assertEqual(real_file, '%s/archive.tar.gz' % self.archive_root)\n\n shutil.copyfile.assert_any_call(\n '%s/init/server_init/log/current' % self.tmroot,\n '%s%s/init/server_init/log/current' % (self.tmp_dir,\n self.tmroot)\n )\n shutil.copyfile.assert_any_call(\n '%s/running/foo/sys/bar/log/current' % self.tmroot,\n '%s%s/running/foo/sys/bar/log/current' % (self.tmp_dir,\n self.tmroot)\n )\n\n subproc.check_output.assert_any_call(['sysctl', '-a'])\n subproc.check_output.assert_any_call(['tail', '-n', '100',\n '/var/log/messages'])\n subproc.check_output.assert_any_call(['dmesg'])\n subproc.check_output.assert_any_call(['ifconfig'])\n\n shutil.copytree.assert_any_call(\n '%s/network_svc' % self.tmroot,\n '%s%s/network_svc' % (self.tmp_dir, self.tmroot)\n )\n shutil.copytree.assert_any_call(\n '%s/cgroup_svc' % self.tmroot,\n '%s%s/cgroup_svc' % (self.tmp_dir, self.tmroot)\n )\n shutil.copytree.assert_any_call(\n '%s/localdisk_svc' % self.tmroot,\n '%s%s/localdisk_svc' % (self.tmp_dir, self.tmroot)\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/postmortem_test.py","file_name":"postmortem_test.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"573064746","text":"#!/usr/bin/env python\n\n##### imports #####\nimport os\nimport sys\nfrom testlib.base.base_utils import get_args\nfrom testlib.scripts.android.fastboot import fastboot_utils\n\n##### initialization #####\nglobals().update(vars(get_args(sys.argv)))\nargs = {}\nfor entry in script_args:\n\tkey, val = entry.split(\"=\")\n\targs[key] = val\nflash_files = args[\"flash_files\"]\n\n##### test start #####\nos.system(\"mkdir -p ./temp/files/flash\")\nfastboot_utils.download_flash_scripts()\n\nfastboot_utils.flash_bxt(zip_file=flash_files, serial=serial)\nos.system(\"sudo rm -rf ./temp\")\n##### test end #####","sub_path":"ACS_v.18.20.4_1/ACS/testlib/scripts/android/fastboot/tests_bxt-p/flash_ioc_linuxhost.py","file_name":"flash_ioc_linuxhost.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"56481326","text":"\"\"\"\n677. Map Sum Pairs\n\nImplement the MapSum class:\n\nMapSum() Initializes the MapSum object.\nvoid insert(String key, int val) Inserts the key-val pair into the map.\nIf the key already existed, the original key-value pair will be overridden to the new one.\nint sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.\n\n\nExample 1:\n\nInput\n[\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\"]\n[[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"]]\nOutput\n[null, null, 3, null, 5]\n\nExplanation\nMapSum mapSum = new MapSum();\nmapSum.insert(\"apple\", 3);\nmapSum.sum(\"ap\"); // return 3 (apple = 3)\nmapSum.insert(\"app\", 2);\nmapSum.sum(\"ap\"); // return 5 (apple + app = 3 + 2 = 5)\n\n\nConstraints:\n\n1 <= key.length, prefix.length <= 50\nkey and prefix consist of only lowercase English letters.\n1 <= val <= 1000\nAt most 50 calls will be made to insert and sum.\n\"\"\"\n\n\"\"\"\nApproach #3: Trie [Accepted]\nIntuition and Algorithm\n\nSince we are dealing with prefixes, a Trie (prefix tree) is a natural data structure to approach this problem. \nFor every node of the trie corresponding to some prefix, we will remember the desired answer (score) and store it at this node. \nAs in Approach #2, this involves modifying each node by delta = val - map[key].\n\n\nComplexity Analysis\n\nTime Complexity: Every insert operation is O(K)O(K), where KK is the length of the key. Every sum operation is O(K)O(K).\n\nSpace Complexity: The space used is linear in the size of the total input.\n\"\"\"\n\n\nclass MapSum:\n\n class TrieNode(object):\n __slots__ = 'children', 'score'\n\n def __init__(self):\n self.score = 0\n self.children = {}\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.map = {}\n self._roottrie = MapSum.TrieNode()\n\n def insert(self, key: str, val: int) -> None:\n\n delta = val - self.map.get(key, 0)\n self.map[key] = val\n node = self._roottrie\n node.score += delta\n for c in key:\n node = node.children.setdefault(c, MapSum.TrieNode())\n node.score += delta\n\n def sum(self, prefix: str) -> int:\n node = self._roottrie\n for c in prefix:\n if c not in node.children:\n return 0\n node = node.children[c]\n return node.score\n\n","sub_path":"PythonLeetcode/leetcodeM/677_MapSumPairs.py","file_name":"677_MapSumPairs.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"320871589","text":"import os\nimport requests\nimport sys\nimport json\nfrom flask import Flask, request, render_template, url_for, flash, session, redirect, jsonify\nfrom timeit import default_timer as timer\nfrom werkzeug.contrib.fixers import ProxyFix\n\napp=Flask(__name__)\napp.secret_key = \"secret_key\"\napp.wsgi_app = ProxyFix(app.wsgi_app)\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n # return \"?This is the post\"\n # elif request.method == 'GET':\n\n\n@app.route(\"/dnsshow\", methods=['GET', 'POST'])\ndef dnsshow():\n domain_suffix = request.form['domain']\n if request.method == 'POST':\n # IF Domain is empty\n if not domain_suffix:\n flash(\"PLease enter a domain\")\n return redirect(url_for('index'))\n try:\n start = timer()\n # EMPTY LISTS\n all_a_records=[]\n all_aaaa_records=[]\n all_mx_records=[]\n all_cn_records=[]\n all_soa_records=[]\n all_txt_records=[]\n all_ns_records=[]\n # DOMAIN PREFIXES\n a_domain_prefix='http://dns-api.org/A/'\n aaaa_domain_prefix='http://dns-api.org/AAAA/'\n mx_domain_prefix='http://dns-api.org/MX/'\n cn_domain_prefix='http://dns-api.org/CNAME/'\n soa_domain_prefix='http://dns-api.org/SOA/'\n txt_domain_prefix='http://dns-api.org/TXT/'\n ns_domain_prefix='http://dns-api.org/NS/'\n # @ RECORD LOOKUP\n domain_to_lookup = a_domain_prefix+domain_suffix\n response = requests.get(domain_to_lookup)\n for a in response.json():\n all_a_records.append(a)\n print('finished first lookup')\n # AAAA RECORD LOOKUP\n domain_to_lookup = aaaa_domain_prefix+domain_suffix\n response = requests.get(domain_to_lookup)\n for aaaa in response.json():\n all_aaaa_records.append(aaaa)\n print('finished second lookup')\n # MX RECORD LOOKUP\n domain_to_lookup=mx_domain_prefix+domain_suffix\n response=requests.get(domain_to_lookup)\n print(\"finished the 3rd lookup\")\n for mx in response.json():\n all_mx_records.append(mx)\n # =================================\n # CNAME RECORD LOOKUP\n domain_to_lookup=cn_domain_prefix+domain_suffix\n response=requests.get(domain_to_lookup)\n print(\"finished the 4th lookup\")\n for cn in response.json():\n all_cn_records.append(cn)\n # =================================\n # SOA RECORD LOOKUP\n domain_to_lookup=soa_domain_prefix+domain_suffix\n response=requests.get(domain_to_lookup)\n print(\"finished the 5th lookup\")\n for soa in response.json():\n all_soa_records.append(soa)\n # =================================\n # TXT RECORD LOOKUP\n domain_to_lookup=txt_domain_prefix+domain_suffix\n response=requests.get(domain_to_lookup)\n print(\"finished the sixth lookup\")\n for txt in response.json():\n all_txt_records.append(txt)\n # =================================\n # NAMESERVER RECORD LOOKUP\n domain_to_lookup=ns_domain_prefix+domain_suffix\n response=requests.get(domain_to_lookup)\n print(\"finished the 7th lookup\")\n for ns in response.json():\n all_ns_records.append(ns)\n end=timer()\n print(str(end)+\" - \"+str(start)+\" = \" +str(end-start))\n return render_template('index.html',\n domain = domain_suffix.upper(),\n all_a_records = all_a_records,\n all_aaaa_records = all_aaaa_records,\n all_mx_records = all_mx_records,\n all_cn_records = all_cn_records,\n all_soa_records = all_soa_records,\n all_txt_records = all_txt_records,\n all_ns_records = all_ns_records)\n except:\n e = sys.exc_info()[0]\n print(str(e))\n return redirect(url_for(index))\n\n@app.route('/myip')\ndef myip():\n visitorip = request.remote_addr\n visitoripjson = jsonify({'ip': request.remote_addr}), 200\n # return visitorip\n return render_template('myip.html',\n visitorip = visitorip)\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 8000))\n app.run(host='0.0.0.0', port=port, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"595999805","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 12 15:12:54 2016\n\n@author: matt\n\"\"\"\nimport shelve\nimport requests\nfrom lxml import html\n\n\ndef getTab(url):\n page = requests.get(url)\n tree= html.fromstring(page.content)\n myxpath = '//*[@id=\"cont\"]/pre[2]/text()'\n tab = tree.xpath(myxpath)\n return tab\n\nband = 'radiohead'\npage = '1'\n\ndef getTree(band, page):\n if type(page) == int:\n page = str(page)\n bandURL = 'https://www.ultimate-guitar.com/search.php?band_name=' + band + \\\n '&type%5B1%5D=200&type2%5B0%5D=40000&rating%5B4%5D=5&tuning%5Bstandard%5D=standard&page=' \\\n + page + '&view_state=advanced&tab_type_group=text&app_name=ugt&order=myweight'\n pageBand = requests.get(bandURL)\n return html.fromstring(pageBand.content)\n#urlBand = 'https://www.ultimate-guitar.com/search.php?search_type=title&order=&value=metallica+'\n\n#pageBand = requests.get(getURL(band, page))\n#tree1 = html.fromstring(pageBand.content)\n\ntree1 = getTree(band, page)\npages = tree1.find_class('paging')\nmaxPage = len(list(pages[0].iter('a')))\nprint('Max Page: '+ str(maxPage))\n\nsongs = tree1.find_class('song result-link')\nsongLinks = []\nfor i in songs:\n songLinks.append(i.get('href')) \n\nfor i in range(maxPage -1):\n looppage = i + 2\n looptree = getTree(band, str(looppage))\n loopsongs = looptree.find_class('song result-link')\n for song in loopsongs:\n songLinks.append(song.get('href'))\n \n\nprint('No of tabs: ' + str(len(songLinks)))\nmyTabs = []\nj = 0\nfor i in songLinks:\n myTabs.append(getTab(i))\n j = j + 1\n\nfilename='shelve.out'\nmy_shelf = shelve.open(filename,'n') \n\nfor key in dir():\n try:\n my_shelf[key] = globals()[key]\n except TypeError:\n #\n # __builtins__, my_shelf, and imported modules can not be shelved.\n #\n print('ERROR shelving: {0}'.format(key))\n \nmy_shelf.close()","sub_path":"getTabs.py","file_name":"getTabs.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"102762297","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2020/4/21 10:37 PM\n---------\n@summary: 简单的爬虫示例(基于内存队列,因此不支持分布式)\n---------\n@author: Boris\n@email: boris@bzkj.tech\n\"\"\"\n\nimport spider\nimport json\n\n\nclass TestSingleSpider(spider.SingleSpider):\n def start_requests(self, *args, **kws):\n yield spider.Request(\"http://www.bj.chinanews.com/focus/1.html\")\n\n def parser(self, request, response):\n for link in response.xpath('//ul[@class=\"branch_list_ul paging\"]//a'):\n title = link.xpath(\"./text()\").extract_first()\n url = link.xpath(\"./@href\").extract_first()\n\n print(\"采集到列表 {} {}\".format(title, url))\n\n yield spider.Request(url, title=title, callback=self.parser_detail)\n\n def parser_detail(self, request, response):\n if response.status_code != 200:\n raise Exception(response) # 封堵重试\n\n response.code = \"gbk\"\n\n title = request.title\n url = request.url\n\n content = response.xpath(\n 'string(//div[@class=\" branch_con_text\"])'\n ).extract_first()\n\n item = {\"title\": title, \"url\": url, \"content\": content}\n\n print(\"采集到正文 {}\".format(json.dumps(item, indent=4, ensure_ascii=False)))\n\n\nif __name__ == \"__main__\":\n test_single_spider = TestSingleSpider(parser_count=100)\n test_single_spider.start()\n","sub_path":"tests/test_single_spider.py","file_name":"test_single_spider.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"577815824","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 16 15:46:24 2021\r\n\r\n@author: PRIYANKA REDDY\r\n\"\"\"\r\n\r\n# Importing of Libraries\r\nimport boto3\r\nimport csv\r\n\r\n# Creation of Client\r\nclient = boto3.client('rekognition',\r\n aws_access_key_id = \"AKIAWIHVMFXLBSLBFDNL\",\r\n aws_secret_access_key = \"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\",\r\n region_name = 'us-east-1'\r\n )\r\n\r\n# Defining function to list the faces\r\ndef list_faces_in_collection(collection_id):\r\n\r\n maxResults=2\r\n faces_count=0\r\n tokens=True\r\n #using built in function of rekognition\r\n response=client.list_faces(CollectionId=collection_id,\r\n MaxResults=maxResults)\r\n\r\n print('Faces in collection : ' + collection_id)\r\n\r\n while tokens:\r\n faces=response['Faces']\r\n #to print details of each face in the collection\r\n for face in faces:\r\n print(\"Face Id : \" + face[\"FaceId\"]) #The id by which Rekognition knows this face\r\n print(\"External Id : \" + face[\"ExternalImageId\"]) #The name by which we know the face.\r\n faces_count+=1\r\n\r\n if 'NextToken' in response:\r\n nextToken=response['NextToken']\r\n response=client.list_faces(CollectionId=collection_id,\r\n NextToken=nextToken,MaxResults=maxResults)\r\n else:\r\n tokens=False\r\n return faces_count #returns the total number of faces found in collection\r\n\r\ndef main():\r\n bucket = 'aiattendance' # Replace with your bucket name\r\n collection_id='students123' # Replace with your collection id\r\n\r\n faces_count=list_faces_in_collection(collection_id)\r\n print(\"faces count: \" + str(faces_count))\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"codes/3.listing faces.py","file_name":"3.listing faces.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"191286502","text":"# MIT License\n#\n# Copyright (c) 2019 DARPA\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# This file is a part of the CIRN Interaction Language.\n\nimport pytest\n\nimport geopandas as gpd\nfrom shapely.geometry import box\n\nfrom validation.score import in_voxel_error\nfrom validation.score import out_of_voxel_error\n\n\nclass TestInVoxelError(object):\n def test_empty_reports_and_empty_transmissions(self):\n tx_gdf = gpd.GeoDataFrame(geometry=[])\n report_in_gdf = gpd.GeoDataFrame(geometry=[])\n\n normalized_in_voxel_error, a_tx_inside = in_voxel_error(tx_gdf_list=[tx_gdf], report_in_gdf=report_in_gdf)\n\n assert normalized_in_voxel_error == 0\n assert a_tx_inside == 0\n\n def test_empty_reports_and_nonempty_transmissions(self):\n b = box(minx=0.0, miny=0.0, maxx=1.0, maxy=1.0)\n\n tx_gdf = gpd.GeoDataFrame(geometry=[b])\n report_in_gdf = gpd.GeoDataFrame(geometry=[])\n\n normalized_in_voxel_error, a_tx_inside = in_voxel_error(tx_gdf_list=[tx_gdf], report_in_gdf=report_in_gdf)\n\n assert normalized_in_voxel_error == 0\n assert a_tx_inside == 0\n\n def test_nonempty_reports_and_empty_transmissions(self):\n b = box(minx=0.0, miny=0.0, maxx=1.0, maxy=1.0)\n\n tx_gdf = gpd.GeoDataFrame(geometry=[])\n report_in_gdf = gpd.GeoDataFrame(geometry=[b])\n report_in_gdf[\"report_on\"] = 1.0\n\n normalized_in_voxel_error, a_tx_inside = in_voxel_error(tx_gdf_list=[tx_gdf], report_in_gdf=report_in_gdf)\n\n assert normalized_in_voxel_error == 1\n assert a_tx_inside == 0\n\n\nclass TestOutOfVoxelError(object):\n def test_empty_transmissions(self):\n tx_gdf = gpd.GeoDataFrame(geometry=[])\n report_in_gdf = gpd.GeoDataFrame(geometry=[])\n\n normalized_out_of_voxel_error = out_of_voxel_error(tx_gdf_list=[tx_gdf], report_in_gdf=report_in_gdf)\n\n assert normalized_out_of_voxel_error == 0\n\n def test_nonempty_transmissions_and_zero_tx_inside(self):\n b = box(minx=0.0, miny=0.0, maxx=1.0, maxy=1.0)\n\n tx_gdf = gpd.GeoDataFrame(geometry=[b])\n report_in_gdf = gpd.GeoDataFrame(geometry=[])\n\n normalized_out_of_voxel_error = out_of_voxel_error(tx_gdf_list=[tx_gdf], report_in_gdf=report_in_gdf)\n\n assert normalized_out_of_voxel_error == 1\n\n def test_nonempty_transmissions_and_perfect_overlap(self):\n b = box(minx=0.0, miny=0.0, maxx=1.0, maxy=1.0)\n\n tx_gdf = gpd.GeoDataFrame(geometry=[b])\n report_in_gdf = gpd.GeoDataFrame(geometry=[b])\n report_in_gdf[\"report_on\"] = 1.0\n\n normalized_out_of_voxel_error = out_of_voxel_error(tx_gdf_list=[tx_gdf], report_in_gdf=report_in_gdf)\n\n assert normalized_out_of_voxel_error == 0.0\n \n def test_negative_out_of_voxel_error(self):\n b1 = box(minx=0.0, miny=0.0, maxx=2.0, maxy=1.0)\n b2 = box(minx=0.0, miny=0.0, maxx=1.0, maxy=1.0)\n b3 = box(minx=0.0, miny=0.0, maxx=0.5, maxy=1.0)\n \n tx_gdf_low = gpd.GeoDataFrame(geometry=[b1])\n tx_gdf_mid = gpd.GeoDataFrame(geometry=[b2])\n tx_gdf_high = gpd.GeoDataFrame(geometry=[b3])\n \n report_in_gdf = gpd.GeoDataFrame(geometry=[b2])\n report_in_gdf[\"report_on\"] = 1.0\n\n normalized_in_voxel_error, a_tx_inside = in_voxel_error(tx_gdf_list=[tx_gdf_low, tx_gdf_mid, tx_gdf_high], report_in_gdf=report_in_gdf)\n\n assert normalized_in_voxel_error == 0.0\n assert a_tx_inside == 1.0\n \n normalized_out_of_voxel_error = out_of_voxel_error(tx_gdf_list=[tx_gdf_low, tx_gdf_mid, tx_gdf_high], report_in_gdf=report_in_gdf)\n\n assert normalized_out_of_voxel_error == 0.0\n\n","sub_path":"tools/spectrumvalidation/tests/validation/test_in_voxel_error.py","file_name":"test_in_voxel_error.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"454672013","text":"class GenericTree:\n\n class Node:\n\n def __init__(self, data):\n self.data = data\n self.children = []\n\n @property\n def get_data(self):\n return self.data\n\n @property\n def get_children(self):\n return self.children\n\n def __init__(self):\n self.root = None\n\n def insert(self, data, parent=None):\n node = GenericTree.Node(data)\n\n if not self.root:\n self.root = node\n elif parent:\n parent.children.append(node)\n else:\n raise ValueError(\"Need to specify parent of new node\")\n\n return node\n\n\nclass BinarySearchTree:\n\n class Node:\n\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n @property\n def get_data(self):\n return self.data\n\n @property\n def get_children(self):\n if not self.left and not self.right:\n return None\n else:\n return [self.left, self.right]\n\n def __init__(self):\n self.root = None\n\n def insert(self, data):\n node = BinarySearchTree.Node(data)\n\n if not self.root:\n self.root = node\n else:\n self.__insert(data, self.root)\n\n def __insert(self, data, node):\n if data < node.data:\n if not node.left:\n node.left = BinarySearchTree.Node(data)\n else:\n self.__insert(data, node.left)\n else:\n if not node.right:\n node.right = BinarySearchTree.Node(data)\n else:\n self.__insert(data, node.right)","sub_path":"Trees.py","file_name":"Trees.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"366332251","text":"INDENT = ' '\n\n\nclass Entry():\n \"\"\"\n Representation of an Entry in an EGG file.\n NOTE: If performance becomes an issue for large scene, consider using __slots__ to save space and speed up Entry\n management.\n \"\"\"\n def __init__(self, entry_type, name=None, content=[]):\n self.type = entry_type\n if isinstance(content, list):\n self._contents = content\n else:\n self._contents = [content]\n self.name = name\n\n def count(self):\n return len(self._contents)\n\n def append(self, entry):\n self._contents.append(entry)\n\n def format_output(self):\n output_lines = []\n output_lines.append('<{}>{} {{'.format(self.type, '' if not self.name else ' {}'.format(self.name)))\n if self.count() > 1:\n for content in self._contents:\n if isinstance(content, Entry):\n output_lines.extend([INDENT + line for line in content.format_output()])\n elif isinstance(content, tuple):\n output_lines.append(INDENT + ' '.join(str(x) for x in content))\n else:\n output_lines.append(INDENT + content)\n output_lines.append('}')\n elif self.count() == 1:\n content = self._contents[0]\n if isinstance(content, Entry):\n output_lines.extend([INDENT + line for line in content.format_output()])\n output_lines.append('}')\n elif isinstance(content, tuple):\n output_lines[-1] += ' {} }}'.format(' '.join(str(x) for x in content))\n else:\n output_lines[-1] += ' {} }}'.format(content)\n else:\n output_lines[-1] += '}'\n\n return output_lines\n\n def __len__(self):\n return self.count()\n\n def __str__(self):\n return '\\n'.join(self.format_output())\n\n def __repr__(self):\n return '{} \"{}\" object at {}'.format(self.type, self.name, hex(id(self)))\n","sub_path":"egg.py","file_name":"egg.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"126518387","text":"import functools\n\nimport colander\n\nfrom cliquet import authorization\nfrom cliquet.schema import PermissionsSchema\n\n\nclass ViewSet(object):\n \"\"\"The default ViewSet object.\n\n A viewset contains all the information needed to register\n any resource in the Cornice registry.\n\n It provides the same features as ``cornice.resource()``, except\n that it is much more flexible and extensible.\n \"\"\"\n service_name = \"{resource_name}-{endpoint_type}\"\n collection_path = \"/{resource_name}s\"\n record_path = \"/{resource_name}s/{{id}}\"\n\n collection_methods = ('GET', 'POST', 'DELETE')\n record_methods = ('GET', 'PUT', 'PATCH', 'DELETE')\n validate_schema_for = ('POST', 'PUT', 'PATCH')\n\n readonly_methods = ('GET',)\n\n service_arguments = {\n 'description': 'Collection of {resource_name}',\n }\n\n default_arguments = {\n 'permission': authorization.PRIVATE\n }\n\n default_collection_arguments = {}\n collection_get_arguments = {\n 'cors_headers': ('Next-Page', 'Total-Records', 'Last-Modified', 'ETag',\n 'Cache-Control', 'Expires', 'Pragma')\n }\n\n default_record_arguments = {}\n record_get_arguments = {\n 'cors_headers': ('Last-Modified', 'ETag',\n 'Cache-Control', 'Expires', 'Pragma')\n }\n\n def __init__(self, **kwargs):\n self.update(**kwargs)\n self.record_arguments = functools.partial(self.get_view_arguments,\n 'record')\n self.collection_arguments = functools.partial(self.get_view_arguments,\n 'collection')\n\n def update(self, **kwargs):\n \"\"\"Update viewset attributes with provided values.\"\"\"\n self.__dict__.update(**kwargs)\n\n def get_view_arguments(self, endpoint_type, resource, method):\n \"\"\"Return the Pyramid/Cornice view arguments for the given endpoint\n type and method.\n\n :param str endpoint_type: either \"collection\" or \"record\".\n :param resource: the resource object.\n :param str method: the HTTP method.\n \"\"\"\n args = self.default_arguments.copy()\n default_arguments = getattr(self,\n 'default_%s_arguments' % endpoint_type)\n args.update(**default_arguments)\n\n by_method = '%s_%s_arguments' % (endpoint_type, method.lower())\n method_args = getattr(self, by_method, {})\n args.update(**method_args)\n\n args['schema'] = self.get_record_schema(resource, method)\n\n return args\n\n def get_record_schema(self, resource, method):\n \"\"\"Return the Cornice schema for the given method.\n \"\"\"\n simple_mapping = colander.MappingSchema(unknown='preserve')\n\n if method.lower() not in map(str.lower, self.validate_schema_for):\n # Simply validate that posted body is a mapping.\n return simple_mapping\n\n if method.lower() == 'patch':\n record_mapping = simple_mapping\n else:\n record_mapping = resource.mapping\n\n try:\n record_mapping.deserialize({})\n # Empty data accepted.\n record_mapping.missing = colander.drop\n record_mapping.default = {}\n except colander.Invalid:\n pass\n\n class PayloadSchema(colander.MappingSchema):\n data = record_mapping\n\n def schema_type(self, **kw):\n return colander.Mapping(unknown='raise')\n\n return PayloadSchema()\n\n def get_view(self, endpoint_type, method):\n \"\"\"Return the view method name located on the resource object, for the\n given type and method.\n\n * For collections, this will be \"collection_{method|lower}\n * For records, this will be \"{method|lower}.\n \"\"\"\n if endpoint_type == 'record':\n return method.lower()\n return '%s_%s' % (endpoint_type, method.lower())\n\n def get_name(self, resource):\n \"\"\"Returns the name of the resource.\n \"\"\"\n if 'name' in self.__dict__:\n name = self.__dict__['name']\n elif hasattr(resource, 'name') and not callable(resource.name):\n name = resource.name\n else:\n name = resource.__name__.lower()\n\n return name\n\n def get_service_name(self, endpoint_type, resource):\n \"\"\"Returns the name of the service, depending a given type and\n resource.\n \"\"\"\n return self.service_name.format(\n resource_name=self.get_name(resource),\n endpoint_type=endpoint_type)\n\n def get_service_arguments(self):\n return self.service_arguments.copy()\n\n def is_endpoint_enabled(self, endpoint_type, resource_name, method,\n settings):\n \"\"\"Returns if the given endpoint is enabled or not.\n\n Uses the settings to tell so.\n \"\"\"\n setting_enabled = '%s_%s_%s_enabled' % (\n endpoint_type, resource_name, method.lower())\n return settings.get(setting_enabled, True)\n\n\nclass ProtectedViewSet(ViewSet):\n def get_record_schema(self, resource, method):\n schema = super(ProtectedViewSet, self).get_record_schema(resource,\n method)\n\n if method.lower() not in map(str.lower, self.validate_schema_for):\n return schema\n\n if method.lower() == 'patch':\n # Data is optional when patching permissions.\n schema.children[-1].missing = colander.drop\n\n permissions_node = PermissionsSchema(missing=colander.drop,\n permissions=resource.permissions,\n name='permissions')\n schema.add(permissions_node)\n return schema\n\n def get_view_arguments(self, endpoint_type, resource, method):\n args = super(ProtectedViewSet, self).get_view_arguments(endpoint_type,\n resource,\n method)\n args['permission'] = authorization.DYNAMIC\n return args\n\n def get_service_arguments(self):\n args = super(ProtectedViewSet, self).get_service_arguments()\n args['factory'] = authorization.RouteFactory\n return args\n","sub_path":"cliquet/viewset.py","file_name":"viewset.py","file_ext":"py","file_size_in_byte":6398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"640602737","text":"import os \nimport platform\nimport sys\nimport random\n\ndef start():\n\n\tprint(\"\"\"\n\t\t\tWELCOME FROM MY GAME\n\t\t\tHAVE FUN!\n\t\t\"\"\")\t\n\tprint(\"\"\"\n\t\t\tCHOOSE ONE ROOM TO PLAY\n\t\t\t=======================\n\t\t\t1.Room One\n\t\t\t2.Room Two\n\t\t\t3.Room Three\n\t\t\"\"\")\n\n\trooms = {\n\t\"1\" : room_one,\n\t\"2\" : room_two,\n\t\"3\" : room_three,\n\t}\n\n\tchoice = input(\"> \")\n\n\taction = rooms.get(choice,None)\n\n\tif not action:\n\t\tprint(\"Invalid room choice\")\n\n\telse: \n\t\taction()\n\ndef clear_screen():\n\n\tos_type = platform.system()\n\n\tif os_type == 'Linux':\n\t\tos.system('clear')\n\tif os_type == 'Windows':\n\t\tos.system('cls')\n\ndef room_one():\n\n\tclear_screen()\n\tprint(\"\"\"\n\t\t\tWELCOME FROM ROOM ONE\n\t\t\t=====================\n\t\t\"\"\")\n\n\tprint(\"This room is full of gold. How much do you take?\")\n\n\tchoice = input(\"> \")\n\tgold_amount = 0 \n\n\tif \"0\" in choice or \"1\" in choice:\n\t\tgold_amount = int(choice)\n\telse: \n\t\tloser(\"You should enter a valid number\")\n\n\tif gold_amount < 20 : \n\t\twinner(\"You are not greedy. You win the game!\")\n\telse: \n\t\tloser(\"You are greedy. You lose the game!\")\n\n\n\ndef room_two():\n\tclear_screen()\n\tprint(\"\"\"\n\t\t\tWELCOME FROM ROOM TWO\n\t\t\t=====================\n\t\t\"\"\")\n\tprint(\"\"\"\n\t\t\tRules\n\t\t\t-------------------------------\n\t\t\tIn this room, you must a number.\n\t\t\tThe game generate a number randomly between 2 and 21.\n\t\t\tAnd the number is divided by 2.\n\t\t\tWhen your input number is equal to the quotient , you win the game!\n\t\t\"\"\")\t\n\n\tinput_num = int(input(\"> \"))\n\n\trandom_num = random.randint(2,21)\n\tthe_ans = int(random_num / 2)\n\t\n\tif input_num == the_ans: \n\t\twinner(\"You win the game.\")\n\telse: \n\t\tloser(\"You lose the game\")\n\ndef room_three():\n\tclear_screen()\n\tprint(\"\"\"\n\t\t\tWELCOME FROM ROOM THREE\n\t\t\t=======================\n\t\t\"\"\")\n\n\tprint(\"\"\"\n\t\t\tRules\n\t\t\t---------------------------------------------------------\n\t\t\tIn the room three, player must roll a die for three times.\n\t\t\tWhen your value is greater than 3 after rolling the die for three times, you win the game.\n\t\t\"\"\")\n\tinput(\"Press enter to start! \")\n\n\ti = 1\n\ttotal = 0 \n\twhile i <= 3: \n\t\tprint(f\"Roll the die for {i} time\")\n\t\tinput(\"> \")\n\t\tvalue = random.randint(1,6)\n\t\tprint(f\"The value for the {i} time is {value}\")\n\n\t\ttotal += value \n\t\ti += 1\n\n\tresult = int(total/3)\n\n\tif result < 3: \n\t\tloser(\"Your value is less than 3\")\n\telse: \n\t\twinner(\"You win the game.\")\n\ndef loser(message=''):\n\n\tif message != '':\n\t\tprint(message)\n\n\tprint(\"Game terminated!\")\n\tsys.exit(0)\n\ndef winner(message=''):\n\n\tif message != '':\n\t\tprint(message)\n\tprint(\"\"\"\n\t\t\tCongratulation! You are the winner.\n\t\t\tThank you for playing my game.\n\t\t\"\"\")\n\tsys.exit(0)\n\nif __name__ == '__main__':\n\n\tstart()\n\n\n\n","sub_path":"ex36.py","file_name":"ex36.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"312916740","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\ndef pytest_addoption(parser):\n parser.addoption('--language', action='store', default='ru',\n help=\"Choose language: ru, en, es, fr\")\n\n\n@pytest.fixture(scope=\"function\")\ndef browser(request):\n language = request.config.getoption(\"language\")\n if language == \"ru\":\n print(\"\\nStart ru languages for test..\")\n options = Options()\n options.add_experimental_option('prefs', {'intl.accept_languages': 'ru'})\n browser = webdriver.Chrome(options=options)\n\n if language == \"en\":\n print(\"\\nStart en languages for test..\")\n options = Options()\n options.add_experimental_option('prefs', {'intl.accept_languages': 'en'})\n browser = webdriver.Chrome(options=options)\n\n elif language == \"es\":\n print(\"\\nStart es languages for test..\")\n options = Options()\n options.add_experimental_option('prefs', {'intl.accept_languages': 'es'})\n browser = webdriver.Chrome(options=options)\n\n elif language == \"fr\":\n print(\"\\nStart fr languages for test..\")\n options = Options()\n options.add_experimental_option('prefs', {'intl.accept_languages': 'fr'})\n browser = webdriver.Chrome(options=options)\n else:\n print(f'Язык {language} не поддерживается. Выберите ru, en, es, fr.')\n yield browser\n print(\"\\nQuit browser..\")\n browser.quit()","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"18532432","text":"from global_imports import *\n\nimport app_utilities , \\\n debug_utilities , \\\n element_utilities , \\\n general_utilities , \\\n home_utilities , \\\n iframe_utilities , \\\n network_utilities , \\\n reporting_utilities , \\\n statusbar_utilities , \\\n test_utilities\n \n\nclass UTILS(app_utilities.main ,\n debug_utilities.main ,\n element_utilities.main ,\n general_utilities.main ,\n home_utilities.main ,\n iframe_utilities.main ,\n network_utilities.main ,\n reporting_utilities.main ,\n statusbar_utilities.main ,\n test_utilities.main):\n #\n # When you create your instance of this class, include the\n # \"self\" object so we can access the calling class' objects.\n #\n def __init__(self, p_parent):\n self.parent = p_parent\n self.device = p_parent.device\n self.data_layer = p_parent.data_layer\n self.apps = p_parent.apps\n self.marionette = p_parent.marionette\n self.actions = Actions(self.marionette)\n\n self._resultArray = []\n self._commentArray = []\n self.errNum = 0\n self.passed = 0\n self.failed = 0\n self.start_time = time.time()\n\n self.testNum = self.get_os_variable(\"TEST_NAME\")\n self.testDesc = self.get_os_variable(\"TEST_DESC\")\n self.det_fnam = self.get_os_variable(\"DET_FILE\")\n self.sum_fnam = self.get_os_variable(\"SUM_FILE\")\n \n #\n # Default device to 'silent + vibrate'.\n #\n self.data_layer.set_setting(\"vibration.enabled\", True)\n self.data_layer.set_setting(\"audio.volume.notification\", 0)\n \n #\n # Default timeout for element searches.\n #\n self.marionette.set_search_timeout(20)\n \n #\n # Set the current time to 'now'.\n #\n self.setTimeToNow()\n \n #\n # Unlock (if necessary).\n #\n self.parent.lockscreen.unlock()","sub_path":"OWDTestToolkit/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"353721524","text":"import sys\nsys.path.append(r\"D:\\课题\\GCL4SVD\\Baselines\\rnn\") # 绝对路径\nimport tensorflow as tf\nimport numpy as np\nimport os\nfrom utils import read_raw_dataset_from_csv\nfrom RNN_new import RNN\nfrom utils import batch_iter_test,batch_iter\nfrom utils import hd_load_data_and_labels\nfrom sklearn.metrics import *\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ntf.flags.DEFINE_string(\n \"datas\", \"../data/FFmpeg+qemu_train.csv\", \"Path of data\")\ntf.flags.DEFINE_string(\n \"datas_test\", \"../data/FFmpeg+qemu_test.csv\", \"Path of positive data\")\ntf.flags.DEFINE_string(\n \"datas_val\", \"../data/FFmpeg+qemu_valid.csv\", \"Path of positive data\")\ntf.flags.DEFINE_string('save_file', 'FFmpeg+qemu-RNN.txt', 'file String.')\n\ntf.flags.DEFINE_integer(\"max_sentence_length\", 100,\n \"Max sentence length in test/test data (Default: 100)\") # 最大序列长度!!!\n# Model Hyperparameters\ntf.flags.DEFINE_string(\n \"cell_type\", \"lstm\", \"Type of rnn cell. Choose 'vanilla' or 'lstm' or 'gru' (Default: vanilla)\")\ntf.flags.DEFINE_string(\n \"word2vec\", None, \"Word2vec file with pre-trained embeddings\")\ntf.flags.DEFINE_integer(\"embedding_dim\", 300,\n \"Dimensionality of character embedding (Default: 300)\")\ntf.flags.DEFINE_integer(\n \"hidden_size\", 128, \"Dimensionality of character embedding (Default: 128)\")\ntf.flags.DEFINE_float(\"dropout_keep_prob\", 0.5,\n \"Dropout keep probability (Default: 0.5)\")\ntf.flags.DEFINE_float(\"l2_reg_lambda\",0.2,\n \"L2 regularization lambda (Default: 3.0)\")\ntf.flags.DEFINE_integer(\"evaluate_every\", 100,\n \"Evaluate model on dev set after this many steps\")\ntf.flags.DEFINE_float(\"dev_sample_percentage\", .1,\n \"train.split\") # 用于划分验证集的\n# Training parameters\ntf.flags.DEFINE_integer(\"batch_size\",128, \"Batch Size (Default: 64)\")\ntf.flags.DEFINE_integer(\n \"num_epochs\", 300, \"Number of training epochs (Default: 100)\")\n# tf.flags.DEFINE_integer(\"num_checkpoints\", 1, \"Number of checkpoints to store\")\ntf.flags.DEFINE_float(\"learning_rate\", 1e-4,\n \"Which learning rate to start with. (Default: 1e-3)\")\n\n\nFLAGS = tf.flags.FLAGS\n\nf = open(FLAGS.save_file,'w+',encoding='utf-8')\n\ndef train():\n # 这里再加上直接输入的验证集\n datas = read_raw_dataset_from_csv(FLAGS.datas) # 训练集的数据\n datas_test = read_raw_dataset_from_csv(FLAGS.datas_test) # 测试集的数据\n datas_val = read_raw_dataset_from_csv(FLAGS.datas_val)\n # x_text,y_train =hd_load_data_and_labels_train(datas)\n print(\"开始加载数据!!!!!!!!!!\")\n x_text, y_train = hd_load_data_and_labels(datas)\n x_test,y_test = hd_load_data_and_labels(datas_test)\n x_val, y_val = hd_load_data_and_labels(datas_val)\n\n # 创建词汇表\n max_sentence_length = min(FLAGS.max_sentence_length, max([len(x.split()) for x in x_text]))\n text_vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(\n max_document_length=max_sentence_length)\n x_train = np.array(list(text_vocab_processor.fit_transform(x_text)))\n print(\"Text Vocabulary Size: {:d}\".format(\n len(text_vocab_processor.vocabulary_)))\n print(\"x = {0}\".format(x_train.shape)) # 文本矩阵大小\n print(\"y = {0}\".format(y_train.shape)) # 标签矩阵大小\n\n shuffle_indices = np.random.permutation(np.arange(len(x_train)))\n x_train = x_train[shuffle_indices]\n y_train = y_train[shuffle_indices]\n\n max_f1 = 0\n min_loss = 10000000000000000\n\n\n with tf.Graph().as_default():\n # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.1)\n session_conf = tf.ConfigProto()\n session_conf.gpu_options.allow_growth = True\n sess = tf.Session(config=session_conf)\n\n with sess.as_default():\n rnn = RNN(\n sequence_length=x_train.shape[1], # 词长度 根据设置的最大词长度 100\n num_classes=y_train.shape[1], # 2\n vocab_size=len(text_vocab_processor.vocabulary_),\n embedding_size=FLAGS.embedding_dim,\n cell_type=FLAGS.cell_type,\n hidden_size=FLAGS.hidden_size,\n l2_reg_lambda=FLAGS.l2_reg_lambda,\n )\n\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n train_op = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(\n rnn.loss, global_step=global_step)\n \n\n # test部分\n x_test1 = np.array(list(text_vocab_processor.fit_transform(x_test)))\n y_test_idx = np.argmax(y_test, axis=1) # axis =1 表示行\n\n # val部分\n x_val1 = np.array(list(text_vocab_processor.fit_transform(x_val)))\n y_val_idx = np.argmax(y_val, axis=1) # axis =1 表示行\n\n\n # 初始化变量\n sess.run(tf.global_variables_initializer())\n\n f1 = 0\n batches = batch_iter_test(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n # Train\n feed_dict = {\n rnn.input_text: x_batch,\n rnn.input_y: y_batch,\n rnn.dropout_keep_prob: FLAGS.dropout_keep_prob\n }\n _, step, train_loss, train_accuracy, logits, y = sess.run(\n [train_op, global_step, rnn.loss,\n rnn.accuracy, rnn.logits, rnn.input_y], feed_dict)\n\n\n if step % FLAGS.evaluate_every == 0:\n feed_dict_val = {\n rnn.input_text: x_val1,\n rnn.input_y: y_val,\n rnn.dropout_keep_prob: 1.0\n }\n val_loss, val_accuracy, val_logits, val_predictions = sess.run(\n [rnn.loss, rnn.accuracy, rnn.logits, rnn.predictions], feed_dict_val)\n val_pre = precision_score(y_val_idx, val_predictions, average='binary', pos_label=1)\n val_recall = recall_score(y_val_idx, val_predictions, average='binary', pos_label=1)\n val_f1_measure = f1_score(y_val_idx, val_predictions, average='binary', pos_label=1)\n\n # if val_loss <= min_loss:\n if val_f1_measure >= max_f1:\n # min_loss = val_loss\n max_f1 = val_f1_measure\n\n feed_dict_dev = {\n rnn.input_text: x_test1,\n rnn.input_y: y_test,\n rnn.dropout_keep_prob: 1.0\n }\n test_loss, test_accuracy, logits, test_predictions = sess.run(\n [rnn.loss, rnn.accuracy, rnn.logits, rnn.predictions], feed_dict_dev)\n test_pre = precision_score(y_test_idx, test_predictions, average='binary', pos_label=1)\n test_recall = recall_score(y_test_idx, test_predictions, average='binary', pos_label=1)\n f1_measure = f1_score(y_test_idx, test_predictions, average='binary', pos_label=1)\n # auc = roc_auc_score(y_test_idx, test_predictions)\n test_mcc = matthews_corrcoef(y_test_idx,test_predictions)\n\n\n if f1_measure >= float(f1):\n f1 = f1_measure\n\n print(\"train_loss=\", \"{:.5f}\".format(train_loss),\n \"val_loss=\", \"{:.5f}\".format(val_loss), \"val_f1=\", \"{:.3f}\".format(val_f1_measure), \"test_loss=\", \"{:.5f}\".format(test_loss),\n \"test_accuracy=\", \"{:.3f}\".format(test_accuracy),\n \"test_pre=\", \"{:.3f}\".format(test_pre), \"test_recall=\",\n \"{:.3f}\".format(test_recall), \"test_f1=\", \"{:.3f}\".format(f1_measure),\n \"best_f1=\", \"{:.3f}\".format(f1),\"test_mcc=\", \"{:.3f}\".format(test_mcc))\n\n result = \" train_loss=\" + \"{:.5f} \".format(\n train_loss) + \" val_loss=\" + \"{:.5f}\".format(val_loss) + \" val_f1=\" + \"{:.3f}\".format(\n val_f1_measure) + \"test_loss=\" + \"{:.5f}\".format(test_loss)+ \"test_accuracy=\" + \"{:.3f}\".format(test_accuracy) + \" test_pre=\" + \"{:.3f} \".format(\n test_pre) + \" test_recall=\" + \"{:.3f} \".format(\n test_recall) + \" test_f1=\" + \"{:.3f} \".format(\n f1_measure) + \" best_f1=\" + \"{:.3f} \".format(\n f1)+\"test_mcc=\" + \"{:.3f}\".format(test_mcc)\n f.write(result)\n f.write('\\n')\n f.write('end')\n\n\n\n\n\ndef main(_):\n train()\n\nif __name__ == \"__main__\":\n tf.app.run()","sub_path":"Baselines/LSTM/src/train_new.py","file_name":"train_new.py","file_ext":"py","file_size_in_byte":9020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"567210025","text":"import paho.mqtt.client as mqtt\nfrom datetime import datetime\nimport json\nimport sys\nimport getopt\nimport os\nimport time\nimport ast\n\ndef mqttConnected(client, userdata, flags, rc):\n print(\"SUCCESS: MQTT broker connected\")\n\ndef mqttSubscribe(client, userdata, mid, granted_qos):\n print(\"SUCCESS: MQTT topic subcribed\")\n\ndef mqttUnsubscribe(client, userdata, mid):\n print(\"SUCCESS: MQTT topic unsubcribed\")\n\ndef mqttMessage(client, userdata, msg):\n global mqttMessRx\n # Parse string to dictionary\n mqttMessRx = ast.literal_eval(str(msg.payload.decode('utf-8')))\n print('__Packet get: ' + str(mqttMessRx))\n\n\ndef mqttGetEspId(client, userdata, msg):\n global ESP_ID\n ESP_ID = msg.payload.decode('utf-8')\n print(ESP_ID)\n\ndef main(argv):\n \"\"\"Test system performance and stability\"\"\"\n # All variable\n global ESP_ID #Get ESP in topicTest to create esp topic\n global mqttMessRx\n global mqttMessTx\n global mode\n global num_send_frame\n global num_get_success\n global num_get_fail\n global start_time\n num_send_frame = 0\n num_get_success = 0\n num_get_fail = 0\n ESP_ID = None\n mqttMessTx = {}\n mqttMessRx = {}\n mode = 'default'\n # Get argument\n try:\n opts, args = getopt.getopt(argv, \"dh\", [\"default\", \"help\"])\n except getopt.GetoptError:\n sys.exit(2)\n # Parse argument\n for opt, agr in opts:\n if opt in ('-h','--help'):\n print('This is help')\n sys.exit()\n elif opt in ('-d','--default'):\n mode = 'default'\n # Set mode\n if mode == 'default':\n mqttBroker = 'iot.eclipse.org'\n mqttTestTopic = 'topicTest'\n # Create log file\n log_file_name = 'log ' + str(datetime.now()) + '.txt'\n print(log_file_name)\n log_file = open(log_file_name, 'w')\n # Connect to MQTT broker and get esp id\n client = mqtt.Client();\n client.on_connect = mqttConnected\n client.on_subscribe = mqttSubscribe\n print(\"Try to connect to \"+mqttBroker)\n client.connect(mqttBroker, port=1883, keepalive=60)\n print(\"Try to subscribe to \"+mqttTestTopic)\n client.subscribe(mqttTestTopic)\n client.on_message = mqttGetEspId\n # While to get ESP_ID\n while ESP_ID == None:\n client.loop()\n # Write to log\n print('Get ' + ESP_ID + '\\n')\n log_file.write('Get ' + ESP_ID + '\\n')\n # Unsubscribe topicTest\n client.on_unsubscribe = mqttUnsubscribe\n client.unsubscribe(mqttTestTopic)\n # Create new topic\n mqttMasterTopic = ESP_ID + \"/master\"\n mqttSlaveTopic = ESP_ID + \"/slave\"\n print('Create new topic ' + mqttMasterTopic + '\\n')\n print('Create new topic ' + mqttSlaveTopic + '\\n')\n log_file.write('Create new topic ' + mqttMasterTopic + '\\n')\n log_file.write('Create new topic ' + mqttSlaveTopic + '\\n')\n # Subscribe to new topic\n client.subscribe(mqttSlaveTopic)\n client.on_subscribe = mqttSubscribe\n client.on_message = mqttMessage\n # Create loop message\n start_time = datetime.now()\n while True:\n try:\n # Reset mqttMessRx\n mqttMessRx['ID'] = ''\n mqttMessRx['FUNC'] = ''\n mqttMessRx['ADDR'] = ''\n mqttMessRx['DATA'] = ''\n # Send cmd to turn device ON\n mqttMessTx['ID'] = ESP_ID\n mqttMessTx['FUNC'] = 'Ctrl'\n mqttMessTx['ADDR'] = '1'\n mqttMessTx['DATA'] = 'On'\n print('__Packet send: ', str(mqttMessTx))\n client.publish(topic=mqttMasterTopic, payload=json.dumps(mqttMessTx))\n # Wait for respond\n timeout = 0\n num_send_frame = num_send_frame + 1\n while mqttMessRx['ID'] == '':\n timeout = timeout + 1\n client.loop()\n if timeout > 100000:\n num_get_fail = num_get_fail + 1\n print('__Packet error: TIMEOUT')\n break\n print('======================================')\n # Clear mqttMessRx\n mqttMessRx['ID'] = ''\n time.sleep(3)\n # Send cmd to turn device OFF\n mqttMessTx['ID'] = ESP_ID\n mqttMessTx['FUNC'] = 'Ctrl'\n mqttMessTx['ADDR'] = '1'\n mqttMessTx['DATA'] = 'Off'\n print('__Packet send: ', str(mqttMessTx))\n client.publish(topic=mqttMasterTopic, payload=json.dumps(mqttMessTx))\n # Wait for respond\n timeout = 0\n num_send_frame = num_send_frame + 1\n while mqttMessRx['ID'] == '':\n timeout = timeout + 1\n client.loop()\n if timeout > 100000:\n num_get_fail = num_get_fail + 1\n print('__Packet error: TIMEOUT')\n break\n print('======================================')\n # Clear mqttMessRx\n mqttMessRx['ID'] = ''\n time.sleep(3)\n # Send cmd to turn device OFF\n mqttMessTx['ID'] = ESP_ID\n mqttMessTx['FUNC'] = 'Data'\n mqttMessTx['ADDR'] = '1'\n mqttMessTx['DATA'] = ''\n print('__Packet send: ', str(mqttMessTx))\n client.publish(topic=mqttMasterTopic, payload=json.dumps(mqttMessTx))\n # Wait for respond\n timeout = 0\n num_send_frame = num_send_frame + 1\n while mqttMessRx['ID'] == '':\n timeout = timeout + 1\n client.loop()\n if timeout > 100000:\n num_get_fail = num_get_fail + 1\n print('__Packet error: TIMEOUT')\n break\n print('======================================')\n # Clear mqttMessRx\n mqttMessRx['ID'] = ''\n time.sleep(3)\n except KeyboardInterrupt:\n print('\\n== TEST END ==')\n log_file.write('\\nTOTAL RUNTIME: ' + str(datetime.now() - start_time))\n print('\\nTOTAL RUNTIME: ' + str(datetime.now() - start_time))\n log_file.write('\\nTOTAL FRAME SENT: ' + str(num_send_frame))\n print('\\nTOTAL FRAME SENT: ' + str(num_send_frame))\n log_file.write('\\nTOTAL FRAME SUCCESS: ' + str(num_send_frame - num_get_fail))\n print('\\nTOTAL FRAME SUCCESS: ' + str(num_send_frame - num_get_fail))\n log_file.write('\\nTOTAL FRAME FAILURE: ' + str(num_get_fail))\n print('\\nTOTAL FRAME FAILURE: ' + str(num_get_fail))\n log_file.write('\\nSUCCESS RATE: ' + str(100 - num_get_fail*100/num_send_frame))\n print('\\nSUCCESS RATE: ' + str(100 - num_get_fail*100/num_send_frame))\n if((num_get_fail*100/num_send_frame) < 3):\n log_file.write('\\nTEST RESULT: OK')\n print('\\nTEST RESULT: OK')\n else:\n log_file.write('\\nTEST RESULT: FAIL')\n print('\\nTEST RESULT: FAIL')\n print('\\nLOG FILE: ' + log_file.name)\n sys.exit()\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"2_Workspace/test_case/performance_test.py","file_name":"performance_test.py","file_ext":"py","file_size_in_byte":7036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"581477811","text":"from __future__ import division, print_function, unicode_literals\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers import LSTM\r\nfrom keras.layers import Dropout\r\nfrom keras.layers.embeddings import Embedding\r\nfrom keras.callbacks import Callback, ModelCheckpoint\r\nfrom keras.optimizers import Adam\r\nimport keras.backend as K\r\nfrom sacred import Experiment\r\nfrom sacred.observers import MongoObserver\r\nfrom sacred.utils import apply_backspaces_and_linefeeds\r\n\r\n\r\n\r\nex = Experiment('LSTM_Classification', ingredients=['Echo_hotel'])\r\nex.observers.append(MongoObserver.create())\r\nex.captured_out_filter = apply_backspaces_and_linefeeds\r\n\r\n\r\n@ex.capture\r\ndef log_performance(_run, logs):\r\n _run.add_artifact(\"weights.hdf5\")\r\n _run.log_scalar(\"loss\", float(logs.get('loss')))\r\n _run.log_scalar(\"binary_accuracy\", float(logs.get('binary_accuracy')))\r\n _run.log_scalar(\"c_score\", float(logs.get('c_score')))\r\n _run.log_scalar(\"val_loss\", float(logs.get('val_loss')))\r\n _run.log_scalar(\"val_binary_accuracy\", float(logs.get('val_binary_accuracy')))\r\n _run.log_scalar(\"val_c_score\", float(logs.get('val_c_score')))\r\n _run.result = float(logs.get('val_c_score'))\r\n\r\n\r\nclass LogPerformance(Callback):\r\n def on_epoch_end(self, batch, logs={}):\r\n log_performance(logs=logs)\r\n\r\n\r\ndef c_score(y_true, y_pred):\r\n y_pred = K.round(y_pred)\r\n positive_points = K.sum(y_true*y_pred)\r\n negative_guesses = K.sum(K.clip(y_pred-y_true, 0.0, 1.0))\r\n return (positive_points-negative_guesses)/K.sum(y_true)\r\n\r\n\r\n@ex.config\r\ndef my_config():\r\n embedding_vector_dimensionality = 128\r\n embedding_dropout_factor = 0.4\r\n recurrent_dropout_factor = 0.2\r\n LSTM_dropout_factor = 0.2\r\n layer_dropout_factor = 0.2\r\n LSTM_layer_sizes = [200]\r\n lr = 0.001\r\n lr_decay = 0.0\r\n batch_size = 256\r\n epoch_no = 15000\r\n max_train_size = None # whole dataset\r\n max_test_size = None # whole dataset\r\n\r\n\r\n@ex.automain\r\ndef train_network(embedding_vector_dimensionality, embedding_dropout_factor, recurrent_dropout_factor,\r\n LSTM_dropout_factor, layer_dropout_factor, LSTM_layer_sizes, lr, lr_decay,\r\n batch_size, epoch_no, max_train_size, max_test_size):\r\n X_train, y_train, X_test, y_test = load_data()\r\n if max_train_size and type(max_train_size) == int:\r\n X_train = X_train[:max_train_size]\r\n y_train = y_train[:max_train_size]\r\n if max_test_size and type(max_test_size) == int:\r\n X_test = X_test[:max_test_size]\r\n y_test = y_test[:max_test_size]\r\n print(\"Shape of the training input: (%d, %d)\" % X_train.shape)\r\n print(\"Shape of the training output: (%d, %d)\" % y_train.shape)\r\n model = Sequential()\r\n model.add(Embedding(get_word_count(), embedding_vector_dimensionality, input_length=X_train.shape[1]))\r\n model.add(Dropout(embedding_dropout_factor))\r\n for size in LSTM_layer_sizes[:-1]:\r\n model.add(LSTM(units=size, return_sequences=True,\r\n recurrent_dropout=recurrent_dropout_factor,\r\n dropout=LSTM_dropout_factor))\r\n model.add(Dropout(layer_dropout_factor))\r\n model.add(LSTM(units=LSTM_layer_sizes[-1], recurrent_dropout=recurrent_dropout_factor, dropout=LSTM_dropout_factor))\r\n model.add(Dropout(layer_dropout_factor))\r\n model.add(Dense(y_train.shape[1], activation='sigmoid'))\r\n optimizer = Adam(lr=lr, decay=lr_decay)\r\n model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['binary_accuracy', c_score])\r\n print(model.summary())\r\n model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epoch_no, batch_size=batch_size,\r\n callbacks=[ModelCheckpoint(\"weights.hdf5\", monitor='val_loss',\r\n save_best_only=True, mode='auto', period=1),\r\n LogPerformance()])\r\n\r\n scores = model.evaluate(X_test, y_test, verbose=0)\r\n print(\"Accuracy: %.2f%%\" % (scores[1]*100))","sub_path":"DL-Assignment 3/soruce/LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"432360440","text":"import lldb\n\nINTEL_ARGS_REGISTERS = [\n \"rdx\", \"rcx\", \"r8\", \"r9\",\n]\n\n\ndef class_from_reciever(reciever):\n return reciever.split()[0].strip(\"<:\")\n\n\ndef selector_from_register(register):\n return register.split()[-1].strip('\"')\n\n\ndef output_for_command(debugger, command):\n interpreter = debugger.GetCommandInterpreter()\n result = lldb.SBCommandReturnObject()\n interpreter.HandleCommand(command, result)\n\n if result.GetStatus() == 2:\n return result.GetOutput()\n else:\n return \"\"\n\n\ndef blue(string):\n return \"\\x1b[34m\" + string + \"\\x1b[39m\"\n\n\ndef red(string):\n return \"\\x1b[31m\" + string + \"\\x1b[39m\"\n\n\ndef objc_context(debugger, command, result, internal_dict):\n reciever = output_for_command(debugger, \"po $rdi\").strip()\n selector = selector_from_register(output_for_command(debugger, \"x/s $rsi\"))\n number_of_arguments = selector.count(\":\")\n labels = selector.split(\":\")\n body = \"Reciever: {} Selector: {}\\nArgs:\\n\".format(blue(reciever),\n red(selector))\n for i in range(number_of_arguments):\n register = INTEL_ARGS_REGISTERS[i]\n arg = output_for_command(debugger, \"po $%s\" % register).strip()\n body += \"\\n{}: {}\\n\".format(red(labels[i]), arg)\n\n disassembly = output_for_command(debugger, \"disassemble -c 5\")\n\n try:\n import pygments.lexers\n import pygments.formatters\n disassembly = pygments.highlight(\n disassembly, pygments.lexers.NasmLexer(),\n pygments.formatters.TerminalFormatter())\n except ImportError:\n pass\n\n print(body + \"\\n\" + disassembly)\n\n\ndef __lldb_init_module(debugger, internal_dict):\n handle = debugger.HandleCommand\n handle('command script add -f context.objc_context objc_context')\n","sub_path":"lldbhelpers/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"159389381","text":"from pyfiles.cardclasses.NonAttackCard import NonAttackCard\n\nclass Terra(NonAttackCard):\n def __init__(self):\n super().__init__() # Inherits the methods NOT VARIABLES!\n self.__name = \"\"\n self.__file_path = \"\"\n self.__cost = None\n self.__rarity = \"\"\n self.__is_exhausted = False\n self.__template = \"\"\n self.__image = \"\"\n self.__label = \"\"\n self.__unit = \"\"\n self.__color = \"\"\n self.__effects = []\n self.__activated_effects = []\n self.__description = \"\"\n\n","sub_path":"bin/pyfiles/cardclasses/Terra.py","file_name":"Terra.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"399441595","text":"import re\nimport itertools as it\nimport collections as coll\nimport warnings\nimport logging\n\nimport numpy as np\n\nfrom pdbx.reader.PdbxParser import PdbxReader as Reader\n\nfrom fr3d.data import Atom\nfrom fr3d.data import Component\nfrom fr3d.data import Structure\nfrom fr3d.unit_ids import encode\n\n\n\"\"\" The set of symbols that mark an operator expression as complex \"\"\"\nCOMPLEX_SYMBOLS = set('()-')\n\n\nclass MissingBlockException(Exception):\n \"\"\"This class is raised when trying to get a missing block of data.\n \"\"\"\n pass\n\n\nclass MissingColumn(Exception):\n \"\"\"This is raised when trying to get a missing column from a table.\n \"\"\"\n pass\n\n\nclass ComplexOperatorException(Exception):\n \"\"\"This is raised when we come across complex operators that we cannot\n easily deal with. These tend to show up in viral structures and not things\n we deal with currently.\n \"\"\"\n pass\n\n\nclass UnusableUnobservedTable(Exception):\n pass\n\n\nclass MissingSymmetry(Exception):\n \"\"\"This is raised when we cannot determine a symmetry operator for an atom.\n \"\"\"\n pass\n\n\nclass Cif(object):\n \"\"\"Top level container for all Cif related data. This assumes that each\n mmCIF file contains a single datablock. This doesn't have to be true but\n makes things easier.\n \"\"\"\n\n def __init__(self, handle=None, data=None):\n if data is None:\n reader = Reader(handle)\n self.data = []\n reader.read(self.data)\n self.data = self.data[0]\n else:\n self.data = data\n\n if handle is None and data is None:\n raise ValueError(\"Must give either handle or data\")\n\n self.pdb = self.data.getName()\n self._operators = self.__load_operators__()\n self._assemblies = self.__load_assemblies__()\n self._entities = self.__load_entities__()\n self._chem = self.__load_chem_comp__()\n self.logger = logging.getLogger('fr3d.cif.reader.Cif')\n\n def __load_operators__(self):\n operators = {}\n for op in self.pdbx_struct_oper_list:\n op['matrix'] = [[None] * 3, [None] * 3, [None] * 3]\n op['vector'] = [None] * 3\n\n for row in range(3):\n op['vector'][row] = float(op['vector[%s]' % str(row + 1)])\n\n for column in range(3):\n key = 'matrix[%s][%s]' % (str(row + 1), str(column + 1))\n op['matrix'][row][column] = float(op[key])\n\n transform = np.zeros((4, 4))\n transform[0:3, 0:3] = op['matrix']\n transform[0:3, 3] = op['vector']\n transform[3, 3] = 1.0\n\n op['matrix'] = np.array(op['matrix'])\n op['vector'] = np.array(op['vector'])\n op['transform'] = np.array(transform)\n\n operators[op['id']] = op\n\n identity = self.__identity_operator__()\n operators[identity['id']] = identity\n\n return operators\n\n def __identity_operator__(self):\n mat = np.identity(3)\n vector = np.array([1, 1, 1])\n trans = np.zeros((4, 4))\n trans[0:3, 0:3] = mat\n trans[0:3, 3] = vector\n trans[3, 3] = 1.0\n return {\n 'id': 'I',\n 'name': 'I',\n 'vector': vector,\n 'matrix': mat,\n 'transform': trans\n }\n\n def __load_assemblies__(self):\n assemblies = coll.defaultdict(list)\n for assembly in self.pdbx_struct_assembly_gen:\n oper_expression = assembly['oper_expression']\n\n # TODO: Implement computation of complex operators\n if COMPLEX_SYMBOLS & set(oper_expression):\n warnings.warn('Cannot compute symmetries from complex '\n 'expressions. Will use a simple identity '\n 'transformation if no others possible')\n operators = []\n else:\n operators = oper_expression.split(',')\n\n for asym_id in assembly['asym_id_list'].split(','):\n for operator in operators:\n op = self._operators[operator]\n assemblies[asym_id].append(op)\n\n for asym_id, ops in assemblies.items():\n if not ops:\n self.logger.info(\"Adding default identity operator for %s\",\n asym_id)\n assemblies[asym_id].append(self._operators['I'])\n\n return assemblies\n\n def __load_entities__(self):\n entities = {}\n for entity in self.entity:\n entities[entity['id']] = entity\n return entities\n\n def __load_chem_comp__(self):\n chem = {}\n for obj in self.chem_comp:\n chem[obj['id']] = obj\n return chem\n\n def structure(self):\n \"\"\"Get the structure from the Cif file.\n\n :returns: The first structure in the cif file.\n \"\"\"\n\n pdb = self.data.getName()\n residues = self.__residues__(pdb)\n return Structure(list(residues), pdb=pdb)\n\n def experimental_sequence(self, chain):\n \"\"\"Get the experimental sequence for a given chain.\n\n :chain: The chain name to use, should be the pdb_strand_id in the cif\n file.\n :returns: A list of the sequence. The entries in the list may be 1, 2\n or 3 character entries if the chain is RNA, DNA or amino acids\n respectively.\n \"\"\"\n\n sequence = []\n for row in self.pdbx_poly_seq_scheme:\n if chain != row['pdb_strand_id']:\n continue\n sequence.append(row['mon_id'])\n return sequence\n\n def experimental_sequence_mapping(self, chain):\n \"\"\"Create a mapping between the observed sequences and the experimental\n sequences. This allows the determination of what residues are\n unobserved and which are observed as well as where the gaps in the\n structure are. This will prevent duplicate mappings from being created.\n In some cases, like 4X4N, there are duplicate entries for a single unit\n id like position.\n\n :chain: Name of the chain to use.\n :returns: An iterable that produces the sequence, the sequence unit id,\n the unit id.\n \"\"\"\n\n pdb = self.data.getName()\n mapping = coll.defaultdict(list)\n for residue in self.__residues__(pdb):\n if residue.chain == chain:\n key = (residue.number, residue.insertion_code)\n mapping[key].append(residue.unit_id())\n mapping = dict(mapping)\n\n entries = self.pdbx_poly_seq_scheme\n filtered = it.ifilter(lambda r: r['pdb_strand_id'] == chain, entries)\n # model = self.atom_site[0]['pdbx_PDB_model_num']\n\n seen = set()\n prev_number = None\n for index, row in enumerate(filtered):\n insertion_code = row['pdb_ins_code']\n if insertion_code == '.':\n insertion_code = None\n\n number = row['pdb_seq_num']\n if number == '?' or row['auth_seq_num'] == '?':\n unit_ids = [None]\n else:\n if prev_number == number:\n self.logger.warning(\"Duplicate pdbx_poly_seq_scheme \"\n \"entry at %s\", number)\n continue\n\n prev_number = number\n key = (int(number), insertion_code)\n\n if key not in mapping:\n raise ValueError(\"Could not find unit for %s\", key)\n\n unit_ids = mapping[key]\n\n seq_data = (pdb, chain, row['mon_id'], row['seq_id'])\n seq_id = '%s|Sequence|%s|%s|%s' % seq_data\n\n if seq_id in seen:\n raise ValueError(\"Can't map one sequence residue twice\")\n\n seen.add(seq_id)\n for unit_id in unit_ids:\n seen.add(unit_id)\n yield (row['mon_id'], seq_id, unit_id)\n\n def __breaks__(self):\n pass\n\n def __residues__(self, pdb):\n mapping = it.groupby(sorted(self.__atoms__(pdb),\n key=lambda a: a.component_unit_id()),\n lambda a: a.component_unit_id())\n\n for comp_id, atoms in mapping:\n atoms = list(atoms)\n first = atoms[0]\n type = self._chem.get(first.component_id, {})\n type = type.get('type', None)\n alt_id = first.alt_id\n if alt_id == '.':\n alt_id = None\n yield Component(atoms,\n pdb=first.pdb,\n model=first.model,\n type=type,\n alt_id=alt_id,\n chain=first.chain,\n symmetry=first.symmetry,\n sequence=first.component_id,\n number=first.component_number,\n index=first.component_index,\n insertion_code=first.insertion_code,\n polymeric=first.polymeric)\n\n def __atoms__(self, pdb):\n max_operators = max(len(op) for op in self._assemblies.values())\n\n if not max_operators:\n raise ValueError(\"Could not find any operators\")\n\n def operator(entry):\n pdb, atom, number = entry\n operators = self.operators(atom['label_asym_id'])\n if number < len(operators):\n return pdb, atom, operators[number]\n return None\n\n atoms = []\n for index in xrange(max_operators):\n indexes = it.repeat(index, len(self.atom_site))\n pdbs = it.repeat(pdb, len(self.atom_site))\n zipped = it.izip(pdbs, self.atom_site, indexes)\n with_operators = it.imap(operator, zipped)\n filtered = it.ifilter(None, with_operators)\n atoms.append(it.imap(lambda a: self.__atom__(*a), filtered))\n\n return it.chain.from_iterable(atoms)\n\n def __atom__(self, pdb, atom, symmetry):\n x, y, z = self.__apply_symmetry__(atom, symmetry)\n\n index = atom['label_seq_id']\n if index != '.':\n index = int(index)\n\n symmetry_name = self.__symmetry_name__(symmetry)\n\n ins_code = atom['pdbx_PDB_ins_code']\n if ins_code == '?':\n ins_code = None\n\n alt_id = atom['label_alt_id']\n if alt_id == '.':\n alt_id = None\n\n return Atom(pdb=pdb,\n model=int(atom['pdbx_PDB_model_num']),\n chain=atom['auth_asym_id'],\n component_id=atom['label_comp_id'],\n component_number=int(atom['auth_seq_id']),\n component_index=index,\n insertion_code=ins_code,\n alt_id=alt_id,\n x=x, y=y, z=z,\n group=atom['group_PDB'],\n type=atom['type_symbol'],\n name=atom['label_atom_id'],\n symmetry=symmetry_name,\n polymeric=self.is_polymeric_atom(atom))\n\n def __apply_symmetry__(self, atom, symmetry):\n coords = [float(atom['Cartn_x']),\n float(atom['Cartn_y']),\n float(atom['Cartn_z']),\n 1.0]\n result = np.dot(symmetry['transform'], np.array(coords))\n return result[0:3].T\n\n def __symmetry_name__(self, symmetry):\n symmetry_name = symmetry.get('name')\n if not symmetry_name or symmetry_name == '?':\n symmetry_name = 'P_%s' % symmetry['id']\n return symmetry_name\n\n def table(self, name):\n return Table(self, self.__block__(name))\n\n def operators(self, asym_id):\n matching = []\n seen = set()\n assemblies = self._assemblies[asym_id]\n for assembly in assemblies:\n if assembly['id'] not in seen:\n seen.add(assembly['id'])\n matching.append(assembly)\n return matching\n\n def is_water(self, entity_id):\n return self._entities[entity_id]['type'] == 'water'\n\n def is_polymeric(self, entity_id):\n return self._entities[entity_id]['type'] == 'polymer'\n\n def is_polymeric_atom(self, atom):\n return self.is_polymeric(atom['label_entity_id'])\n\n def __block__(self, name):\n block_name = re.sub('^_', '', name)\n block = self.data.getObj(block_name)\n if not block:\n raise MissingBlockException(\"Unknown block \" + name)\n return block\n\n def __getattr__(self, name):\n try:\n return self.table(name)\n except MissingBlockException:\n raise AttributeError(\"Unknown block \" + name)\n\n\nclass Table(object):\n\n \"\"\"Container for a single table in the data block. This provides some\n useful methods for accessing the data.\n \"\"\"\n\n def __init__(self, cif, block, rows=None):\n self._cif = cif\n self.block = block\n self.rows = rows\n\n self.columns = self.block.getItemNameList()\n self.columns = [re.sub('_.+\\.', '', name) for name in self.columns]\n\n if self.rows is None:\n length = self.block.getRowCount()\n self.rows = [self.__row__(index) for index in xrange(length)]\n\n def column(self, name):\n \"\"\"Get a column by name\"\"\"\n if name not in self.columns:\n raise MissingColumn(\"Unknown column\")\n\n values = []\n for row in self.rows:\n values.append(row[name])\n return values\n\n def size(self):\n \"\"\"Get a tuple of (rowCount, columnCount).\n \"\"\"\n return (len(self), len(self.columns))\n\n def __row__(self, number):\n \"\"\"Get a row by index. Note that this may or may not be in the same\n order as they appear in the cif file, since cif files are not required\n to be ordered. The row will be a dict of the form { attribute: value }.\n Each attribute will have the name of the block stripped.\n \"\"\"\n return dict(zip(self.columns, self.block.getRow(number)))\n\n def __getattr__(self, name):\n \"\"\"Get the column with the given name.\n \"\"\"\n try:\n return self.column(name)\n except MissingColumn:\n raise AttributeError(\"Unknown column: %s\" % name)\n\n def __getitem__(self, index):\n if isinstance(index, str):\n try:\n return self.column(index)\n except MissingColumn:\n raise KeyError(\"Unknown column: %s\" % index)\n\n if isinstance(index, int):\n return self.rows[index]\n\n if isinstance(index, slice):\n return Table(self._cif, self.block, rows=self.rows[index])\n\n raise TypeError(\"Unknown key type, should be str, int or slice\")\n\n def __len__(self):\n \"\"\"Get the number of rows.\n \"\"\"\n return len(self.rows)\n","sub_path":"corr_server/fr3d/cif/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":14874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"97264538","text":"# coding:UTF-8\n# \u001B$B= 5:\n print('1 分钟内发送次数超过 5 次, 请等待 1 分钟')\n return False\n print(content, end='\\t')\n print('sms send successful')\n client.hincrby('sended_sms', telephone_number, 1)\n return True\n else:\n sendsms(telephone_number, content[:70], key=key)\n sendsms(telephone_number, content[70:], key=key)\n\n\nif __name__ == '__main__':\n client = redis.Redis(host='localhost', password='fakepassword')\n telephone_numbers = (12345654321, 18899966651, 18899966653)\n client.hmset('sended_sms', {str(t_num): 0 for t_num in telephone_numbers})\n \n sendsms(12345654321, content='hello')\n sendsms(12345654321, content='hi')\n sendsms(12345654321, content='idiot')\n sendsms(12345654321, content='Are you Trump Donald')\n sendsms(12345654321, content='I am Biden, thank you brother')\n sendsms(12345654321, content='今天天气很好,万里无云,蓝蓝的天空上飘着洁白的云彩')\n sendsms(18899966651, content='How are you?')\n sendsms(18899966651, content=''.join([str(i) for i in range(203)]))\n sendsms(18899966653, content='1'*140)\n sendsms(18899966653, content='1'*139)\n\n","sub_path":"week05/week0502_no_wrapper.py","file_name":"week0502_no_wrapper.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"27833699","text":"\"\"\"\nHandles \"clients\" in IPtables for captive portal.\n\"\"\"\n\nimport ipaddress\nfrom uuid import uuid4\nfrom datetime import datetime\n\nimport iptc\n\nimport errors\n\n\nclass Client(object):\n\n def __init__(self, **kw):\n # Required parameters\n self.storage = kw.pop('storage')\n self._chain = kw.pop('chain')\n\n # First try to get an existing client by ID\n self.client_id = kw.pop('client_id', None)\n if self.client_id:\n client_data = self.storage.get_client_by_id(self.client_id)\n\n # If ID is specified then we raise exception if client isn't\n # found.\n if client_data is None:\n raise StorageNotFound('Client not found')\n\n # Next try to get an existing client by IP and protocol\n self.ip_address = kw.pop('ip_address')\n self.protocol = kw.pop('protocol')\n\n if self.ip_address and self.protocol:\n client_data = self.storage.get_client(\n self._ip_address,\n self.protocol\n )\n\n if client_data:\n self.load_client(client_data)\n else:\n self.client_id = str(uuid4())\n self.created = datetime.now()\n self.enabled = False\n self.last_packets = 0\n self.last_activity = None\n\n # Init iptables\n self.table = iptc.Table(iptc.Table.MANGLE)\n self.chain = iptc.Chain(self.table, self._chain)\n\n\n def load_client(self, data):\n self.client_id = data.get('client_id')\n self.created = data.get('created')\n self.ip_address = data.get('ip_address')\n self.protocol = data.get('protocol')\n self.enabled = data.get('enabled')\n self.last_packets = data.get('last_packets')\n self.last_activity = data.get('last_activity')\n\n\n def commit(self):\n self.commit_client()\n\n if self.enabled:\n self.commit_rule()\n else:\n self.remove_rule()\n\n\n def commit_client(self):\n self.storage.write_client(\n self\n )\n\n\n def delete(self):\n self.remove_rule()\n self.storage.remove_client(self)\n\n\n def remove_rule(self):\n rule = self.find_rule(self._ip_address, self.protocol)\n if rule:\n self.chain.delete_rule(rule)\n\n\n def find_rule(self, ip_address, protocol):\n \"\"\"\n Takes an ipaddress.IPv4Interface object as ip_address argument.\n \"\"\"\n\n if not isinstance(ip_address, ipaddress.IPv4Interface):\n raise ValueError('Invalid argument type')\n\n for rule in self.chain.rules:\n src_ip = rule.src\n\n try:\n _ip = str(ip_address.ip)\n except:\n # If we can't understand the argument just return None\n return None\n\n if src_ip.startswith(_ip) and rule.protocol == protocol:\n return rule\n else:\n return None\n\n\n def commit_rule(self):\n rule = self.find_rule(self._ip_address, self.protocol)\n if not rule:\n rule = iptc.Rule()\n rule.src = self.ip_address\n rule.protocol = self.protocol\n rule.target = iptc.Target(rule, 'RETURN')\n self.chain.insert_rule(rule)\n\n\n @property\n def ip_address(self):\n return str(self._ip_address.ip)\n\n @ip_address.setter\n def ip_address(self, value):\n if isinstance(value, str):\n self._ip_address = ipaddress.IPv4Interface(value)\n elif isinstance(value, ipaddress.IPv4Interface):\n self._ip_address = value\n else:\n raise ValueError('Cannot set invalid value')\n\n\n","sub_path":"tools/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"246957085","text":"from keras.models import Sequential, Model\nfrom keras.layers import Reshape, Activation, Conv2D, Input, MaxPooling2D, BatchNormalization, Flatten, Dense, Lambda\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.merge import concatenate\nimport matplotlib.pyplot as plt\nimport keras.backend as K\nimport tensorflow as tf\nimport time\nimport numpy as np\nimport os, cv2\nfrom tqdm import tqdm\nfrom utils import WeightReader, decode_netout, draw_boxes, normalize\n\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\n# def get_session(gpu_fraction=0.8):\n# '''Assume that you have 6GB of GPU memory and want to allocate ~2GB'''\n#\n# num_threads = os.environ.get('OMP_NUM_THREADS')\n# gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)\n#\n# if num_threads:\n# return tf.Session(config=tf.ConfigProto(\n# gpu_options=gpu_options, intra_op_parallelism_threads=num_threads))\n# else:\n# return tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n#\n# K.set_session(get_session())\n\nLABELS = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']\n\nIMAGE_H, IMAGE_W = 416, 416\nGRID_H, GRID_W = 13 , 13\nBOX = 5\nCLASS = len(LABELS)\nCLASS_WEIGHTS = np.ones(CLASS, dtype='float32')\nOBJ_THRESHOLD = 0.3#0.5\nNMS_THRESHOLD = 0.3#0.45\nANCHORS = [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828]\n\nTRUE_BOX_BUFFER = 50\n\nwt_path = '/home/pass/git/data/yolo.weights'\ntrain_image_folder = '/home/pass/git/data/train2014/'\ntrain_annot_folder = '/home/pass/git/data/train2014pascal/'\nvalid_image_folder = '/home/pass/git/data/val2014/'\nvalid_annot_folder = '/home/pass/git/data/val2014pascal/'\n\n\n\n\n# the function to implement the orgnization layer (thanks to github.com/allanzelener/YAD2K)\ndef space_to_depth_x2(x):\n return tf.space_to_depth(x, block_size=2)\n\ninput_image = Input(shape=(IMAGE_H, IMAGE_W, 3))\ntrue_boxes = Input(shape=(1, 1, 1, TRUE_BOX_BUFFER , 4))\n\n# Layer 1\nx = Conv2D(32, (3,3), strides=(1,1), padding='same', name='conv_1', use_bias=False)(input_image)\nx = BatchNormalization(name='norm_1')(x)\nx = LeakyReLU(alpha=0.1)(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\n\n# Layer 2\nx = Conv2D(64, (3,3), strides=(1,1), padding='same', name='conv_2', use_bias=False)(x)\nx = BatchNormalization(name='norm_2')(x)\nx = LeakyReLU(alpha=0.1)(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\n\n# Layer 3\nx = Conv2D(128, (3,3), strides=(1,1), padding='same', name='conv_3', use_bias=False)(x)\nx = BatchNormalization(name='norm_3')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 4\nx = Conv2D(64, (1,1), strides=(1,1), padding='same', name='conv_4', use_bias=False)(x)\nx = BatchNormalization(name='norm_4')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 5\nx = Conv2D(128, (3,3), strides=(1,1), padding='same', name='conv_5', use_bias=False)(x)\nx = BatchNormalization(name='norm_5')(x)\nx = LeakyReLU(alpha=0.1)(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\n\n# Layer 6\nx = Conv2D(256, (3,3), strides=(1,1), padding='same', name='conv_6', use_bias=False)(x)\nx = BatchNormalization(name='norm_6')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 7\nx = Conv2D(128, (1,1), strides=(1,1), padding='same', name='conv_7', use_bias=False)(x)\nx = BatchNormalization(name='norm_7')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 8\nx = Conv2D(256, (3,3), strides=(1,1), padding='same', name='conv_8', use_bias=False)(x)\nx = BatchNormalization(name='norm_8')(x)\nx = LeakyReLU(alpha=0.1)(x)\nx = MaxPooling2D(pool_size=(2, 2))(x)\n\n# Layer 9\nx = Conv2D(512, (3,3), strides=(1,1), padding='same', name='conv_9', use_bias=False)(x)\nx = BatchNormalization(name='norm_9')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 10\nx = Conv2D(256, (1,1), strides=(1,1), padding='same', name='conv_10', use_bias=False)(x)\nx = BatchNormalization(name='norm_10')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 11\nx = Conv2D(512, (3,3), strides=(1,1), padding='same', name='conv_11', use_bias=False)(x)\nx = BatchNormalization(name='norm_11')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 12\nx = Conv2D(256, (1,1), strides=(1,1), padding='same', name='conv_12', use_bias=False)(x)\nx = BatchNormalization(name='norm_12')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 13\nx = Conv2D(512, (3,3), strides=(1,1), padding='same', name='conv_13', use_bias=False)(x)\nx = BatchNormalization(name='norm_13')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\nskip_connection = x\n\nx = MaxPooling2D(pool_size=(2, 2))(x)\n\n# Layer 14\nx = Conv2D(1024, (3,3), strides=(1,1), padding='same', name='conv_14', use_bias=False)(x)\nx = BatchNormalization(name='norm_14')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 15\nx = Conv2D(512, (1,1), strides=(1,1), padding='same', name='conv_15', use_bias=False)(x)\nx = BatchNormalization(name='norm_15')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 16\nx = Conv2D(1024, (3,3), strides=(1,1), padding='same', name='conv_16', use_bias=False)(x)\nx = BatchNormalization(name='norm_16')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 17\nx = Conv2D(512, (1,1), strides=(1,1), padding='same', name='conv_17', use_bias=False)(x)\nx = BatchNormalization(name='norm_17')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 18\nx = Conv2D(1024, (3,3), strides=(1,1), padding='same', name='conv_18', use_bias=False)(x)\nx = BatchNormalization(name='norm_18')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 19\nx = Conv2D(1024, (3,3), strides=(1,1), padding='same', name='conv_19', use_bias=False)(x)\nx = BatchNormalization(name='norm_19')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 20\nx = Conv2D(1024, (3,3), strides=(1,1), padding='same', name='conv_20', use_bias=False)(x)\nx = BatchNormalization(name='norm_20')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 21\nskip_connection = Conv2D(64, (1,1), strides=(1,1), padding='same', name='conv_21', use_bias=False)(skip_connection)\nskip_connection = BatchNormalization(name='norm_21')(skip_connection)\nskip_connection = LeakyReLU(alpha=0.1)(skip_connection)\nskip_connection = Lambda(space_to_depth_x2)(skip_connection)\n\nx = concatenate([skip_connection, x])\n\n# Layer 22\nx = Conv2D(1024, (3,3), strides=(1,1), padding='same', name='conv_22', use_bias=False)(x)\nx = BatchNormalization(name='norm_22')(x)\nx = LeakyReLU(alpha=0.1)(x)\n\n# Layer 23\nx = Conv2D(BOX * (4 + 1 + CLASS), (1,1), strides=(1,1), padding='same', name='conv_23')(x)\noutput = Reshape((GRID_H, GRID_W, BOX, 4 + 1 + CLASS))(x)\n\n# small hack to allow true_boxes to be registered when Keras build the model\n# for more information: https://github.com/fchollet/keras/issues/2790\noutput = Lambda(lambda args: args[0])([output, true_boxes])\n\nmodel = Model([input_image, true_boxes], output)\n\n# Print construct of model\nmodel.summary()\n\n\n\nmodel.load_weights(\"weights_coco.h5\")\n\ndummy_array = np.zeros((1,1,1,1,TRUE_BOX_BUFFER,4))\n#\ndef test_img(link_img):\n start = time.time()\n image = cv2.imread(link_img)\n\n # plt.figure(figsize=(10, 10))\n\n input_image = cv2.resize(image, (416, 416))\n input_image = input_image / 255.\n input_image = input_image[:, :, ::-1]\n input_image = np.expand_dims(input_image, 0)\n\n netout = model.predict([input_image, dummy_array])\n print (netout[0].shape)\n boxes = decode_netout(netout[0],\n obj_threshold=OBJ_THRESHOLD,\n nms_threshold=NMS_THRESHOLD,\n anchors=ANCHORS,\n nb_class=CLASS)\n image = draw_boxes(image, boxes, labels=LABELS)\n print(\"{} s\".format(time.time() - start))\n plt.imshow(image[:, :, ::-1]);\n plt.show()\n\nk = 'lol'\nwhile 1:\n k = input(\"Nhap link anh('q' de thoat)\")\n if k == 'q' or k == 'Q':\n break\n try:\n test_img(k)\n except:\n pass\n\n\n\n# Detect in video\n# video_inp = '../basic-yolo-keras/images/test.mp4'\n# video_out = '../basic-yolo-keras/images/test_bbox.mp4'\n#\n# video_reader = cv2.VideoCapture(video_inp)\n#\n# nb_frames = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))\n# frame_h = int(video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT))\n# frame_w = int(video_reader.get(cv2.CAP_PROP_FRAME_WIDTH))\n#\n# video_writer = cv2.VideoWriter(video_out,\n# cv2.VideoWriter_fourcc(*'XVID'),\n# 50.0,\n# (frame_w, frame_h))\n#\n# for i in tqdm(range(nb_frames)):\n# ret, image = video_reader.read()\n#\n# input_image = cv2.resize(image, (416, 416))\n# input_image = input_image / 255.\n# input_image = input_image[:, :, ::-1]\n# input_image = np.expand_dims(input_image, 0)\n#\n# netout = model.predict([input_image, dummy_array])\n#\n# boxes = decode_netout(netout[0],\n# obj_threshold=0.3,\n# nms_threshold=NMS_THRESHOLD,\n# anchors=ANCHORS,\n# nb_class=CLASS)\n# image = draw_boxes(image, boxes, labels=LABELS)\n#\n# video_writer.write(np.uint8(image))\n#\n# video_reader.release()\n# video_writer.release()","sub_path":"test_img.py","file_name":"test_img.py","file_ext":"py","file_size_in_byte":9716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"165130834","text":"import psycopg2\nfrom psycopg2._psycopg import DatabaseError\n\nconn1 = psycopg2.connect(dbname=\"Fly Booking\", user=\"postgres\", host=\"localhost\")\nconn2 = psycopg2.connect(dbname=\"Hotel Booking\", user=\"postgres\", host=\"localhost\")\nconn3 = psycopg2.connect(dbname=\"Account\", user=\"postgres\", host=\"localhost\")\n\nconn1.tpc_begin(conn1.xid(42, 'flighthotel', 'conn1'))\nconn2.tpc_begin(conn2.xid(42, 'flighthotel', 'conn2'))\nconn3.tpc_begin(conn2.xid(42, 'flighthotel', 'conn3'))\n\ncur1 = conn1.cursor()\ncur2 = conn2.cursor()\ncur3 = conn3.cursor()\n\ncur1.execute(\"INSERT INTO flights VALUES ('42', 'Tanya', 'CAT 2017', 'AMS', 'JFK', '01/01/2018');\")\ncur2.execute(\"INSERT INTO hotels VALUES ('42', 'Tanya', 'Hilton', '01/01/2017', '10/01/2018');\")\ncur3.execute('UPDATE accounts SET \"Ammount\" = \"Ammount\" - 200 WHERE \"Account ID\"=\\'42\\'');\n\ntry:\n conn1.tpc_prepare()\n conn2.tpc_prepare()\n conn3.tpc_prepare()\nexcept DatabaseError as e:\n print(e)\n conn1.tpc_rollback()\n conn2.tpc_rollback()\n conn3.tpc_rollback()\nelse:\n conn1.tpc_commit()\n conn2.tpc_commit()\n conn3.tpc_commit()\n\ncur1.close()\nconn1.close()\ncur2.close()\nconn2.close()\n","sub_path":"2PC_task.py","file_name":"2PC_task.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"206756957","text":"import re,os,datetime,time\ndef pick_date():\n allowable_letters = ['d','m','y']\n input_parse_regex = re.compile(r\"(\\d+)([a-z])\")\n \"\"\"Function that returns a date object based on input from user\"\"\"\n x = input(\"Subtract days, months or years from current date\\n\" +\n \"By entering digit(s) followed by d, m, y.\\nOr simply \" +\n \"press 'enter' to manually enter a date:\\n\").lower()\n mo_x = re.findall(input_parse_regex,x)\n try:\n num = int(mo_x[0][0])\n letter = mo_x[0][1]\n if any(letter == char for char in allowable_letters):\n if letter == 'd':\n d = datetime.date.today() - datetime.timedelta(days=num)\n elif letter == 'm':\n month = 30 #Month is approximately 30 days\n d = datetime.date.today() - datetime.timedelta(days=month*num)\n elif letter == 'y':\n year = 365 #Year is approximately 365 days\n d = datetime.date.today() - datetime.timedelta(days=year*num)\n else:\n yyyy = int(input(\"YEAR: \"))\n mm = int(input(\"MONTH: \"))\n dd = int(input(\"DAY: \"))\n d = datetime.date(yyyy,mm,dd)\n except IndexError:\n yyyy = int(input(\"YEAR: \"))\n mm = int(input(\"MONTH: \"))\n dd = int(input(\"DAY: \"))\n d = datetime.date(yyyy,mm,dd)\n return d\n\ndef pull_edi(needle_string, date0, date1,dir_to_search = r'C:\\Brampton EDI\\4B_processed_data\\headoffice_edi',start_name = 'DCXVT', end_name = '.text'):\n files = []\n newest_date = datetime.date(1000,1,1)\n count = 0\n file_content_list = []\n for entry in os.scandir(dir_to_search):\n if entry.name.startswith(start_name) and entry.name.endswith(end_name):\n #Extract creation time from file\n t = time.ctime(os.path.getctime(entry.path))\n #Extract a date from the creation time\n a_date = datetime.datetime.strptime(t, \"%a %b %d %H:%M:%S %Y\").date()\n #Make sure this date is within the given time frame\n if a_date >= date0 and a_date <= date1: # If creation date within time frame\n files.append(entry.path)\n with open(entry.path, 'r') as f:\n temp = f.read()\n if needle_string in temp: # If needle in file then append content\n if a_date > newest_date:\n newest_date = a_date\n temp = temp.split('\\n')\n count = count + 1\n file_content_list.extend(temp)\n\n print(\"The newest {0} with string '{1}' in it is from: {2}\".format(start_name, needle_string, newest_date))\n print(str(count) + ' Files Read')\n return file_content_list\n\ndef unique( seq ):\n \"\"\"List -> Set with initial order\"\"\"\n seen = set()\n for item in seq:\n if item not in seen:\n seen.add( item )\n yield item\n\n","sub_path":"usefulscripts.py","file_name":"usefulscripts.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"81339930","text":"a,b = map(int,input().split())\n\ndef fast_pow(x,y):\n\tans = 1\n\twhile y:\n\t\tif (y & 1): ans = ans*x\n\t\tx = x*x\n\t\ty >>= 1\n\treturn ans\n\nans = 0\nlo = 1\nhi = fast_pow(10,18)\nwhile lo <= hi:\n\tmid = (lo + hi) >> 1\n\ttmp1 = fast_pow(a,mid)\n\ttmp2 = fast_pow(mid,b)\n\tif tmp1 == tmp2:\n\t\tans = mid\n\t\tbreak\n\telif tmp1 > tmp2:\n\t\thi = mid - 1\n\telse:\n\t\tlo = mid + 1\nprint(ans)","sub_path":"codeforces/ICPC_Central_Russia_Regional_CRC19/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"217714093","text":"#!/usr/bin/env python3\n\n__author__ = \"cloudstrife9999\"\n\nfrom sys import version_info\nfrom json import load\n\nfrom icu_environment.icu_environment import ICUEnvironment\n\n\ndef check_preconditions() -> bool:\n minimum_major: int = 3\n minimum_minor: int = 6\n minimum_version: str = \"{}.{}\".format(minimum_major, minimum_minor)\n\n if version_info.major < minimum_major or version_info.minor < minimum_minor:\n print(\"The minimum required version of Python is {}, while {}.{} was found.\".format(minimum_version, version_info.major, version_info.minor))\n return False\n\n return True\n\n\ndef main() -> None:\n if not check_preconditions():\n return\n\n with open(\"config.json\", \"r\") as i_f:\n config: dict = load(fp=i_f)\n\n ICUEnvironment(config=config)\n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"389668240","text":"import sys\r\nfrom collections import deque\r\n\r\n##all_trips = {}\r\n##\r\n##for i in range(10+1):\r\n## for j in range(i,min(i+3,10+1)):\r\n## for k in range(i,min(i+3,10+1)):\r\n## trip = [i,j,k]\r\n## trip.sort()\r\n## trip = tuple(trip)\r\n## isSurp = 0\r\n## if max(trip)-min(trip) > 2:\r\n## sys.stderr.write( \"Err in trip.\")\r\n## break\r\n## if max(trip)-min(trip) == 2:\r\n## isSurp = 1\r\n## points = sum(trip)\r\n## try:\r\n## all_trips[points].add( (max(trip),isSurp,trip) )\r\n## except KeyError:\r\n## all_trips[points] = set()\r\n## all_trips[points].add( (max(trip),isSurp,trip) )\r\n##\r\n##for x in all_trips:\r\n## all_trips[x] = list(all_trips[x])\r\n## all_trips[x].sort()\r\n## print x, (x+2)/3, (x+2)%3, all_trips[x]\r\n\r\nif __name__ == \"__main__\":\r\n\r\n f = open( \"B-large.in.txt\" )\r\n g = open( \"output_large.txt\", \"w\" )\r\n\r\n f.readline()\r\n line = f.readline()\r\n caseI = 1\r\n while line != \"\":\r\n line = [ int(x) for x in line.split() ]\r\n N = line[0]\r\n surprise = line[1]\r\n p = line[2]\r\n points = line[3:]\r\n points.sort()\r\n points.reverse()\r\n\r\n maxp = 0\r\n either = 0\r\n make_surprise = 0\r\n for x in points:\r\n this_p = (x+2)/3\r\n if x in [0,1,29,30]:\r\n if this_p >= p:\r\n maxp += 1\r\n elif this_p >= p:\r\n either += 1\r\n maxp += 1\r\n elif this_p == p-1 and (x+2)%3 > 0:\r\n make_surprise += 1\r\n else:\r\n either += 1\r\n\r\n if make_surprise >= surprise:\r\n make_surprise -= surprise\r\n maxp += surprise\r\n make_surprise = 0\r\n else:\r\n maxp += make_surprise\r\n\r\n g.write( \"Case #%s: %s\\n\"%(caseI,maxp) )\r\n\r\n line = f.readline()\r\n caseI += 1\r\n\r\n f.close()\r\n g.close()\r\n \r\n","sub_path":"solutions_python/Problem_96/847.py","file_name":"847.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"27737959","text":"import os.path\nimport re\n\n\n# 遍历指定目录,显示目录下的所有文件名\ndef eachFile(filepath):\n count = 0\n pathDir = os.listdir(filepath)\n for allDir in pathDir:\n child = os.path.join('%s/%s' % (filepath, allDir))\n if os.path.isfile(child):\n count += readFile(child)\n continue\n else:\n eachFile(child)\n\n# 遍历出结果 返回文件的名字\ndef readFile(filenames):\n fopen = open(filenames, 'r') # r 代表read\n fileread = fopen.read()\n t = re.search(r'buy\\.repayfundpackage\\.rabbitmq\\.queue', fileread)\n fopen.close()\n if t:\n arr.append(filenames)\n return 1\n return 0\n\n'''\nbuy\\.insurance\\.rabbitmq\\.queue 2\nbuy\\.repayfundpackage\\.rabbitmq\\.queue 2\nfcVerify\\.rabbitmq\\.queueName\ndeposit\\.frozen\\.rabbitmq\\.queueName\ngjb\\.fund\\.consumer\\.rabbitmq\\.queueName\nbillimport\\.rabbitmq\\.consumer\\.queue\ninvite\\.crowd\\.login\\.rabbitmq\\.queue\ninvite\\.friends\\.rabbitmq\\.queue\ninvite\\.register\\.rabbitmq\\.queue\ninvitation\\.wxshare\\.rabbitmq\\.queue\nlyq\\.loan\\.rabbitmq\\.queueName\nocelot\\.import\\.bill\\.rabbitmq\\.queueName\nopsevent\\.consumer\\.rabbitmq\\.queueName\nrabbit\\.order\\.queue\\.name\nperiodbill\\.rabbitmq\\.consumer\\.queue\nrepay\\.rabbitmq\\.queueName\nreturnloan\\.rpd\\.lyq\\.rabbitmq\\.queueName\ndecentral\\.deposit\\.rabbitmq\\.queueName\nrpplan\\.deposit\\.rabbitmq\\.queueName\nrpb\\.openaccount\\.rabbitmq\\.consumer\\.queue\nrpb\\.userrecharge\\.rabbitmq\\.queueName\nrpd\\.certification\\.rabbitmq\\.queueName\nuser\\.login\\.event\\.queue\nusercenter\\.rabbitmq\\.queueName\\.userCreated\nuser\\.daily\\.sign\\.rabbitmq\\.consumer\\.queue\nutilities\\.repay\\.rabbitmq\\.queueName\nwelfare\\.redpacket\\.rabbitmq\\.queueName\nwelfare\\.coupon\\.rabbitmq\\.queueName\nwelfare\\.loanCoupon\\.rabbitmq\\.queueName\nwelfare\\.repay\\.rabbitmq\\.queueName\nLMK_applySubmitSuccess\ngold_coin_pay_success\nVcard_SuccBuyOrQuitFinancial\nLMK_CardStatusChanged\nLMK_TransferAccountSuccess\np2pmarket_purchase_notify\nbonus_pay_success_notify\n'''\n\n\n #reg = r'.*?(welfare\\.redpacket\\.rabbitmq\\.queueName).*?'\n #key = re.compile(reg,re.S)\n #keylist = key.findall(fileread)\n #if keylist is not None:\n #return len(keylist)\n\nif __name__ == \"__main__\":\n count = 0\n filenames = '/Users/lichuang.lc/Documents/git/ops-activity/mainVenue/server/src/main/java' # refer root dir\n arr = []\n count = eachFile(filenames)\n print(count)\n print(len(arr))","sub_path":"文本处理/代码扫描/scanCode.py","file_name":"scanCode.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"577000700","text":"import random\nimport time\n\ndef game():\n print(\"Welcome in my dice game!\")\n \n roll1 = random.randint(1, 6)\n roll2 = random.randint(1, 6)\n \n #print(\"Your turn\")\n \n input(\"Press ENTER to roll the dice!: \")\n print(\"You rolled \"+str(roll1))\n time.sleep(1)\n print(\"Ai rolled \"+ str(roll2))\n time.sleep(1)\n\n \n \n \n \n \n if roll1 > roll2:\n print(\"You won!\")\n elif roll1 == roll2:\n print(\"Draw!\")\n else:\n print(\"AI won!\")\n\n \n\n dec = input(\"Do you want to try again? (y/n): \")\n if dec == \"y\":\n game()\n else:\n print(\"Goodbye!\")\n \n\n\ngame()\n","sub_path":"Practice Python/roll the dice game.py","file_name":"roll the dice game.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"626013065","text":"lista = []\r\nwhile True:\r\n v = int(input(\"Digite um valor: \"))\r\n if v in lista:\r\n print(\"Valor duplicado não adicionado!\")\r\n else:\r\n lista.append(v)\r\n print(\"Valor adicionado com sucesso...\")\r\n op = str(input(\"Deseja continuar? [S/N]\")).strip().upper()[0]\r\n if op == 'N':\r\n break\r\nprint(sorted(lista))","sub_path":"PythonBasicoMundo03/Desafio79.py","file_name":"Desafio79.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"145415314","text":"# -*- coding: utf-8 -*-\n# @Author: Theo Lemaire\n# @Email: theo.lemaire@epfl.ch\n# @Date: 2020-04-21 11:32:49\n# @Last Modified by: Theo Lemaire\n# @Last Modified time: 2020-06-08 20:21:15\n\nimport abc\n\nfrom ..utils import isIterable, si_format\n\n\nclass StimObject(metaclass=abc.ABCMeta):\n ''' Generic interface to a simulation object. '''\n fcode_replace_pairs = [\n ('/', '_per_'),\n (',', '_'),\n ('(', ''),\n (')', ''),\n (' ', '')\n ]\n\n @abc.abstractmethod\n def copy(self):\n ''' String representation. '''\n raise NotImplementedError\n\n @staticmethod\n @abc.abstractmethod\n def inputs():\n raise NotImplementedError\n\n def xformat(self, x, factor, precision, minfigs, strict_nfigs=False):\n if isIterable(x):\n l = [self.xformat(xx, factor, precision, minfigs, strict_nfigs=strict_nfigs)\n for xx in x]\n return f'({\", \".join(l)})'\n if isinstance(x, str):\n return x\n xf = si_format(x * factor, precision=precision, space='')\n if strict_nfigs:\n if minfigs is not None:\n nfigs = len(xf.split('.')[0])\n if nfigs < minfigs:\n xf = '0' * (minfigs - nfigs) + xf\n return xf\n\n def paramStr(self, k, **kwargs):\n val = getattr(self, k)\n if val is None:\n return None\n xf = self.xformat(\n val,\n self.inputs()[k].get('factor', 1.),\n self.inputs()[k].get('precision', 0),\n self.inputs()[k].get('minfigs', None),\n **kwargs)\n return f\"{xf}{self.inputs()[k].get('unit', '')}\"\n\n def pdict(self, sf='{key}={value}', **kwargs):\n d = {k: self.paramStr(k, **kwargs) for k in self.inputs().keys()}\n return {k: sf.format(key=k, value=v) for k, v in d.items() if v is not None}\n\n @property\n def meta(self):\n return {k: getattr(self, k) for k in self.inputs().keys()}\n\n def __eq__(self, other):\n if not isinstance(other, self.__class__):\n return False\n for k in self.inputs().keys():\n if getattr(self, k) != getattr(other, k):\n return False\n return True\n\n def __repr__(self):\n return f'{self.__class__.__name__}({\", \".join(self.pdict().values())})'\n\n @property\n def desc(self):\n return ', '.join(self.pdict(sf='{key} = {value}').values())\n\n def slugify(self, s):\n for pair in self.fcode_replace_pairs:\n s = s.replace(*pair)\n return s\n\n @property\n def filecodes(self):\n d = self.pdict(sf='{key}_{value}', strict_nfigs=True)\n return {k: self.slugify(v) for k, v in d.items()}\n\n def checkInt(self, key, value):\n if not isinstance(value, int):\n raise TypeError(f'Invalid {self.inputs()[key][\"desc\"]} (must be an integer)')\n return value\n\n def checkFloat(self, key, value):\n if isinstance(value, int):\n value = float(value)\n if not isinstance(value, float):\n raise TypeError(f'Invalid {self.inputs()[key][\"desc\"]} (must be float typed)')\n return value\n\n def checkStrictlyPositive(self, key, value):\n if value <= 0:\n raise ValueError(f'Invalid {key} (must be strictly positive)')\n\n def checkPositiveOrNull(self, key, value):\n if value < 0:\n raise ValueError(f'Invalid {key} (must be positive or null)')\n\n def checkStrictlyNegative(self, key, value):\n if value >= 0:\n raise ValueError(f'Invalid {key} (must be strictly negative)')\n\n def checkNegativeOrNull(self, key, value):\n if value > 0:\n d = self.inputs()[key]\n raise ValueError(f'Invalid {key} {d[\"unit\"]} (must be negative or null)')\n\n def checkBounded(self, key, value, bounds):\n if value < bounds[0] or value > bounds[1]:\n d = self.inputs()[key]\n f, u = d.get(\"factor\", 1), d[\"unit\"]\n bounds_str = f'[{bounds[0] * f}; {bounds[1] * f}] {u}'\n raise ValueError(f'Invalid {d[\"desc\"]}: {value * f} {u} (must be within {bounds_str})')\n","sub_path":"PySONIC/core/stimobj.py","file_name":"stimobj.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"539237065","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import fields, models, api\nfrom datetime import datetime\n\n\nclass InstalledPart(models.Model):\n _name = 'installed.part'\n _description = 'Installed Part'\n _rec_name = 'machine_center_id'\n _inherit = ['mail.thread', 'mail.activity.mixin']\n\n partner_id = fields.Many2one('res.partner', string='Sawmill (Customer)', tracking=True) \n machine_center_id = fields.Many2one('machine.center', string='Machine Center', tracking=True)\n machine_center_oem_id = fields.Many2one('machine.center.oem',string='Machine Center OEM')\n knife_provider_id = fields.Many2one('knife.provider',string='Knife Provider', tracking=True)\n knives_per_segment_id = fields.Many2one('knives.per.segment',string='Knives Per Segment')\n pockets_id = fields.Many2one('knives.per.segment',string='# of Pockets')\n length_of_knives_id = fields.Many2one('length.of.knives',string='Length Of Knives')\n length_of_knife_id = fields.Many2one('length.of.knives',string='Length Of knife')\n length_of_short_knife_id = fields.Many2one('length.of.knives',string='Length of Short Knife')\n length_of_long_knife_id = fields.Many2one('length.of.knives',string='Length of Long Knife')\n short_knives_per_ea_head_id = fields.Many2one('knives.per.segment', string='Short Knives per ea Heads')\n spline = fields.Boolean(string='Spline')\n long_knives_ea_head_id = fields.Many2one('numbers',string='Long Knives ea Head')\n knives_per_pocket_id = fields.Many2one('numbers',string='Knives per Pocket')\n segment_per_head= fields.Selection([('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),('9','9'),('10','10')],string='# of Segments per Head')\n of_head = fields.Selection([('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),('9','9'),('10','10')],string='# Of Heads')\n length_of_pockets = fields.Char(string='Length of Pocket')\n installed_part_detail_id = fields.One2many('installed.part.detail','install_part_id',string='Install Part Detail', required=True)\n is_drumhead = fields.Boolean(string='Drumhead',default='False')\n is_conicals = fields.Boolean(string='Conical',default='False')\n is_chipper = fields.Boolean(string='Chipper',default='False')\n description = fields.Char(string='Description')\n date = fields.Date(string='Date')\n\n @api.onchange('date')\n def onchange_date(self):\n if self.installed_part_detail_id:\n self.installed_part_detail_id.update({'date': self.date})\n self.installed_part_detail_id._onchange_date()\n\n @api.onchange('machine_center_id')\n def onchange_machine_center_id(self):\n if self.machine_center_id:\n if self.machine_center_id.id == self.env.ref('cortex_products.machine_center_drumhead').id:\n self.is_drumhead = True\n self.is_conicals = False\n self.is_chipper = False\n elif self.machine_center_id.id == self.env.ref('cortex_products.machine_center_conical').id:\n self.is_conicals = True\n self.is_chipper = False\n self.is_drumhead = False\n elif self.machine_center_id.id == self.env.ref('cortex_products.machine_center_chipper').id:\n self.is_chipper = True\n self.is_conicals = False\n self.is_drumhead = False\n else:\n self.is_drumhead = True\n self.is_chipper = False\n self.is_conicals = False\n else:\n self.is_chipper = False\n self.is_conicals = False\n self.is_drumhead = False\n\n def name_get(self):\n result = []\n for record in self:\n for line in record:\n if line.description:\n result.append((line.installed_part_detail_id.install_part_id.id, '[%s] %s' % (line.machine_center_id.name, line.description)))\n else:\n result.append((line.installed_part_detail_id.install_part_id.id, '[%s]' % (line.machine_center_id.name)))\n return result\n\n\nclass InstalledPartDetail(models.Model):\n _name = 'installed.part.detail'\n _rec_name = 'product_id'\n\n install_part_id = fields.Many2one('installed.part',string='Installed Part', ondelete='cascade')\n product_id = fields.Many2one('product.product', string='# Part')\n installed_knife = fields.Float(string='# of Installed (Operating) Parts', digits=(16,0))\n estimated_monthly_consumption = fields.Integer(string='Estimated Monthly Consumption (annual consumption for parts)')\n head_location_id = fields.Many2one('drumhead.location',string='Head Location')\n date = fields.Date(string='Date')\n installed = fields.Boolean(string='Active', readonly=True , default=True)\n categ_id = fields.Many2one('product.category', related='product_id.categ_id', string='Product Category', store=True)\n partner_id = fields.Many2one(related=\"install_part_id.partner_id\", string='Customer', store=True)\n knife_lenth = fields.Float(related=\"product_id.length\", string='Lenth of Knife', store=True)\n monthly_consumption_calculate = fields.Integer(string='Estimated Monthly Consumption', compute=\"compute_knife_inches\", store=\"True\")\n estimated_annual_consumption = fields.Integer(string='Est. Annual Consumption', compute=\"compute_knife_inches\", store=\"True\")\n estimated_monthly_knife_inches = fields.Integer(string='Est Monthly Knife Inches')\n estimated_annual_knife_inches = fields.Integer(string='Est Annual Knife Inches ')\n frequency = fields.Selection([('monthly', 'Monthly'), ('yearly', 'Yearly'), ('2_year', '2 Year')], string='Frequency', default='monthly')\n \n\n @api.depends('estimated_monthly_consumption','frequency')\n def compute_knife_inches(self):\n for rec in self:\n product_length = rec.product_id.length\n if rec.frequency == 'yearly':\n rec.estimated_annual_consumption = rec.estimated_monthly_consumption\n rec.monthly_consumption_calculate = rec.estimated_monthly_consumption/12\n rec.estimated_monthly_knife_inches = (rec.estimated_monthly_consumption/12) * product_length\n rec.estimated_annual_knife_inches = rec.estimated_monthly_consumption * product_length\n elif rec.frequency == '2_year':\n rec.estimated_annual_consumption = rec.estimated_monthly_consumption/2\n rec.monthly_consumption_calculate = rec.estimated_monthly_consumption/24\n rec.estimated_monthly_knife_inches = (rec.estimated_monthly_consumption/24) * product_length\n rec.estimated_annual_knife_inches = (rec.estimated_monthly_consumption/2) * product_length\n else:\n rec.estimated_annual_consumption = rec.estimated_monthly_consumption * 12 \n rec.monthly_consumption_calculate = rec.estimated_monthly_consumption \n rec.estimated_monthly_knife_inches = rec.estimated_monthly_consumption * product_length\n rec.estimated_annual_knife_inches = rec.estimated_monthly_consumption * product_length * 12\n\n @api.onchange('date')\n def _onchange_date(self):\n for line in self:\n if line.date:\n if line.date > datetime.now().date():\n line.installed = False\n else:\n line.installed = True\n\n # Update installed part which have passed date and still not actived\n def update_installed_part_active(self):\n installed_part_obj = self.search([('date', '<=', datetime.now().date()), ('installed', '=', False)])\n if installed_part_obj:\n installed_part_obj.write({'installed': True})\n return True\n","sub_path":"cortex_products/models/installed_part.py","file_name":"installed_part.py","file_ext":"py","file_size_in_byte":7740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"327033233","text":"# _*_ coding:utf-8 _*_\n\"\"\"\n Create on 2017/9/18 下午5:02\n @author: han\n\"\"\"\n\n\nclass DescSquare(object):\n def __init__(self, start):\n self.value = start\n\n def __get__(self, instance, owner):\n return self.value ** 2\n\n def __set__(self, instance, value):\n self.value = value\n\n\"\"\"\n 描述符实例必须是**客户类**上的一个类属性而不是**客户类实例**上的属性,\n 实际上我们必须像这样把描述符赋给一个类属性----如果赋给一个self实例属性,\n 它将无法工作。\n\"\"\"\n\n\nclass Client1:\n x = DescSquare(3)\n\n\nclass Client2:\n x = DescSquare(32)\n\n\ndef main():\n c1 = Client1()\n c2 = Client2()\n\n print(c1.x)\n c1.X = 4\n print(c1.x)\n print(c2.x)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"metadata_programing/property/descriptor/dynamic_calculate.py","file_name":"dynamic_calculate.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"601440101","text":"import functools, weakref, io, pickle, hashlib, copyreg, inspect\nimport warnings\nfrom types import FunctionType, CodeType\nfrom ._version import version as __version__\n\n__doc__ = \"\"\"Persistent memoization\n\nExample usage:\n\nfrom persistentmemo import PersistentMemo, PersistentMemoStoreRedis, fdeps\n\nmemo = PersistentMemo()\nmemoize = memo.memoize\n\nPI = 3.14\n\n@fdeps(PI)\ndef foo(x, y):\n return x * (y - PI)\n\n@memoize()\n@fdeps(foo)\ndef bar(z):\n return foo(z, z+1) + 2\n\n# mandatory fibonacci example\n@memoize()\ndef fibs(n):\n if n==0 or n==1: return n\n return fibs(n-1) + fibs(n-2)\n\ndef init_persistentmemo():\n import redis\n redis_pool = redis.ConnectionPool(host='127.0.0.1',port=6379)\n redis_obj = redis.StrictRedis(connection_pool=redis_pool)\n memo.store = PersistentMemoStoreRedis(redis_obj)\n\ndef main():\n init_persistentmemo()\n # or you could just do \"memo.store = {}\"\n print(bar(4), bar(4))\n print(fibs(300))\n\"\"\"\n__all__ = ['PersistentMemo', 'fdeps',\n 'PersistentMemoStoreRedis']\n\nclass _RefBox(object):\n #__slots__ = ['value','__weakref__']\n __slots__ = ['value']\n def __init__(self, value):\n self.value = value\n def __hash__(self):\n return id(self.value)\n def __eq__(self, x):\n self_value_id = id(self.value)\n return ((type(x) == type(self) and self_value_id == id(x.value))\n or self_value_id == id(x))\n def __repr__(self):\n return repr(self.value)\n\nclass _Pickle_Hash(object):\n \"\"\"This is only used to mark already-hashed objects in hash_serialize\"\"\"\nclass _Pickle_Function(object):\n \"\"\"This is only used to mark functions in hash_serialize\"\"\"\nclass _Pickle_Code(object):\n \"\"\"This is only used to mark code objects in hash_serialize\"\"\"\nclass _Pickle_FDeps(object):\n \"\"\"This is only used to mark FDeps objects in hash_serialize\"\"\"\n\nclass _HashIO(object):\n def __init__(self, h):\n self.h = h\n def write(self, s):\n self.h.update(s)\n\ndef fdeps(*deps, use_eval=False, set_readonly=True):\n deps = tuple(deps)\n def wrapper(func):\n class FDeps(object):\n __call__ = staticmethod(func)\n __persistentmemo_readonly__ = set_readonly\n def __init__(self):\n self.deps = deps\n self.do_eval = use_eval\n functools.update_wrapper(self, self.__call__)\n @property\n def __memo_extra_dep__(self):\n if self.do_eval:\n mod_dict = inspect.getmodule(self.__wrapped__).__dict__\n self.deps = tuple(eval(x, mod_dict) if type(x) is str else x\n for x in self.deps)\n self.do_eval = False\n return self.deps\n def __reduce__(self):\n return (_Pickle_FDeps,\n (self.__call__, self.__memo_extra_dep__))\n return FDeps()\n return wrapper\n\nclass PersistentMemoStoreRedis(object):\n def __init__(self, redis, *,\n prefix1=b\"persistentmemo:md5:\",\n prefix2=b\":\"):\n self._prefix = prefix1 + prefix2\n self._redis = redis\n def __getitem__(self, key):\n v = self._redis.get(self._prefix+key)\n if v is None: raise KeyError\n return v\n def __setitem__(self, key, value):\n self._redis.set(self._prefix+key, value)\n\nclass HashPickler(pickle._Pickler):\n def __init__(self, persistentmemo, *args, **kwargs):\n self.pm = persistentmemo\n self.dispatch = self.dispatch.copy()\n dispatch_table = copyreg.dispatch_table.copy()\n dispatch_table[dict] = self.reduce_dict\n dispatch_table[set] = self.reduce_set\n dispatch_table[frozenset] = self.reduce_set\n dispatch_table[CodeType] = self.reduce_code\n dispatch_table[FunctionType] = self.reduce_function\n for k in dispatch_table:\n self.dispatch.pop(k, None)\n self.dispatch_table = dispatch_table\n super().__init__(*args, **kwargs)\n @staticmethod\n def reduce_dict(obj):\n return (type(obj), (), None, None,\n sorted(obj.items()))\n @staticmethod\n def reduce_set(obj):\n return (type(obj), (), None,\n sorted(obj))\n @staticmethod\n def reduce_function(obj):\n return (_Pickle_Function,\n (obj.__code__,\n getattr(obj,'__wrapped__', None)))\n @staticmethod\n def reduce_code(obj):\n return (_Pickle_Code,\n ([getattr(obj,k) for k in\n ('co_argcount','co_cellvars','co_code','co_consts',\n 'co_flags','co_freevars','co_kwonlyargcount',\n 'co_name','co_names','co_nlocals','co_stacksize',\n 'co_varnames')],))\n def persistent_id(self, obj):\n obj_refbox = _RefBox(obj)\n try:\n cached_hash = self.pm._cached_hash[obj_refbox]\n except KeyError:\n if getattr(obj, '__persistentmemo_readonly__', False):\n self.pm.set_readonly(obj)\n cached_hash = self.pm._cached_hash[obj_refbox]\n else:\n cached_hash = None\n if cached_hash is None:\n return None\n else:\n return (_Pickle_Hash, cached_hash)\n\nclass PersistentMemo(object):\n \"\"\"persistent memoization\nself.store must implement __getitem__ and __setitem__\"\"\"\n _redis = None\n store = None\n hashpickler_class = HashPickler\n def __init__(self):\n #self._cached_hash = weakref.WeakKeyDictionary()\n self._cached_hash = {}\n def hash_serialize(self, obj, file):\n p = self.hashpickler_class(file=file, persistentmemo=self)\n p.dump(obj)\n def hash(self, obj):\n try:\n return self._cached_hash[_RefBox(obj)]\n except KeyError:\n pass\n h = hashlib.md5()\n self.hash_serialize(obj, file=_HashIO(h))\n return h.digest()\n def serialize(self, obj):\n \"\"\"this is used for function results; you may override this\"\"\"\n return pickle.dumps(obj, protocol=3)\n def deserialize(self, buf):\n \"\"\"this is used for function results; you may override this\"\"\"\n return pickle.loads(buf)\n def set_readonly(self, obj, readonly=True, hash_value=None):\n if readonly:\n self._cached_hash[_RefBox(obj)] = None\n h = self.hash(obj) if hash_value is None else hash_value\n self._cached_hash[_RefBox(obj)] = h\n else:\n self._cached_hash.pop(_RefBox(obj), None)\n return obj\n def memoize(self):\n def wrapper(func):\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n S = self.store\n if S is None:\n warnings.warn(\"you must set self.store to something that implements __getitem__ and __setitem__; without it there will be no caching\")\n return func(*args, **kwargs)\n call_data = [func, args, kwargs]\n key = self.hash(call_data)\n try:\n value = S[key]\n except KeyError:\n pass\n else:\n return self.deserialize(value)\n result = func(*args, **kwargs)\n S[key] = self.serialize(result)\n return result\n return wrapped\n return wrapper\n","sub_path":"persistentmemo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"331772385","text":"\"\"\"\n'''\n Assignment-1 Create Social Network\n'''\n\n\n#def create_social_network(data):\n '''\n The data argument passed to the function is a string\n It represents simple social network data\n In this social network data there are people following other people\n\n Here is an example social network data string:\n John follows Bryant,Debra,Walter\n Bryant follows Olive,Ollie,Freda,Mercedes\n Mercedes follows Walter,Robin,Bryant\n Olive follows John,Ollie\n\n The string has multiple lines and each line represents one person\n The first word of each line is the name of the person\n The second word is follows that separates the person from the followers\n After the second word is a list of people separated by ,\n\n create_social_network function should split the string on lines\n then extract the person and the followers by splitting each line\n finally add the person and the followers to a dictionary and\n return the dictionary\n\n Caution: watch out for trailing spaces while splitting the string.\n It may cause your test cases to fail although your output may be right\n\n Error handling case:\n Return a empty dictionary if the string format of the data is invalid\n Empty dictionary is not None, it is a dictionary with no keys\n '''\n\n # remove the pass below and start writing your code\n# return data\"\"\"\n\ndef main():\n '''\n handling testcase input and printing output\n '''\n input_lines = input()\n adict = {}\n for _ in range(int(input_lines)):\n data = input()\n if 'follows' in data:\n list_value = data.split(\" follows \")\n if list_value[0] not in adict:\n adict[list_value[0]] = list_value[1].split(',')\n else:\n # adict[list_value[0]] = list_value[1].append(list_value[1].split(','))\n adict[list_value[0]].extend(list_value[1].split(','))\n # print(create_social_network(adict))\n else:\n break\n print(adict)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"m12/p1/create_social_network.py","file_name":"create_social_network.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"82064125","text":"__author__ = 'ma0722'\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n # @param head, a ListNode\n # @return a boolean\n def hasCycle(self, head):\n if not head:\n return False\n p = q = head\n while p:\n p = p.next\n if q and q.next:\n q = q.next.next\n else:\n return False\n if p == q:\n return True\n return False\n\nif __name__ == '__main__':\n s = Solution()\n node1 = ListNode(1)\n node1.next = node1\n print(s.hasCycle(node1))","sub_path":"ok_p_141.py","file_name":"ok_p_141.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"77091824","text":"\"\"\"\nGiven a mxn grid filled with non-negative numbers, find a path from top left to bottom right, whcih minumizes the sum all all numbers along its path.\nNote: you can only move either down or right at any point in time.\n# at any point, I only consider down and right until I reach the final\nConstraints:\n- m == grid.length\n- n == grid[i].length\n- 1 <= m, n <= 200\n- 0 <= grid[i][j] <= 100\n\"\"\"\n\n\ndef minPathSum(grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n MAX_ROWS = len(grid)\n MAX_COLS = len(grid[0])\n # create a db table\n db = [[0 for _ in range(MAX_COLS)] for _ in range(MAX_ROWS)]\n\n # fill the db table: min(top, left, current_cell)\n for i in range(0, MAX_ROWS):\n for j in range(0, MAX_COLS):\n if i - 1 >= 0:\n top = db[i - 1][j]\n else:\n top = 2 ** 31\n\n if j - 1 >= 0:\n left = db[i][j - 1]\n else:\n left = 2 ** 31\n\n if i - 1 == -1 and j - 1 == -1:\n top = 0\n left = 0\n\n db[i][j] = grid[i][j] + min(left, top)\n\n return db[MAX_ROWS - 1][MAX_COLS - 1]\n\n\nprint(minPathSum([[1, 2]]))","sub_path":"practice_for_amazon/min_path_sum/min_path_sum.py","file_name":"min_path_sum.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"272048520","text":"import dynet as dy\n\n\nclass FeedForwardNeuralNet(object):\n\n def __init__(self, model, args):\n self.pc = model.add_subcollection()\n self.args = args\n self.num_input = int(args[0])\n self.num_output = int(args[2])\n self.hidden_list = args[1]\n self.act = args[3]\n self.model = model\n self.number_of_layers = len(self.hidden_list)\n num_hidden_1 = self.hidden_list[0]\n\n # Add first layer\n self.W1 = self.pc.add_parameters((num_hidden_1, self.num_input))\n self.b1 = self.pc.add_parameters((num_hidden_1))\n\n # Add remaining layers\n self.weight_matrix_array = []\n self.biases_array = []\n self.weight_matrix_array.append(self.W1)\n self.biases_array.append(self.b1)\n for k in range(1, self.number_of_layers):\n self.weight_matrix_array.append(self.model.add_parameters(\n (self.hidden_list[k], self.hidden_list[k - 1])))\n self.biases_array.append(self.model.add_parameters((self.hidden_list[k])))\n self.weight_matrix_array.append(self.model.add_parameters(\n (self.num_output, self.hidden_list[-1])))\n self.biases_array.append(self.model.add_parameters((self.num_output)))\n self.spec = (self.num_input, self.hidden_list, self.num_output, self.act)\n\n def basic_affine(self, exp):\n W1 = dy.parameter(self.W1)\n b1 = dy.parameter(self.b1)\n return dy.tanh(dy.affine_transform([b1, W1, exp]))\n\n def calculate_loss(self, input, output):\n # dy.renew_cg()\n weight_matrix_array = []\n biases_array = []\n for (W, b) in zip(self.weight_matrix_array, self.biases_array):\n weight_matrix_array.append(dy.parameter(W))\n biases_array.append(dy.parameter(b))\n acts = self.act\n w = weight_matrix_array[0]\n b = biases_array[0]\n act = acts[0]\n intermediate = act(dy.affine_transform([b, w, input]))\n activations = [intermediate]\n for (W, b, g) in zip(weight_matrix_array[1:], biases_array[1:], acts[1:]):\n pred = g(dy.affine_transform([b, W, activations[-1]]))\n activations.append(pred)\n losses = output - pred\n return dy.l2_norm(losses)\n\n def calculate_loss_classification(self, input, output):\n # dy.renew_cg()\n weight_matrix_array = []\n biases_array = []\n for (W, b) in zip(self.weight_matrix_array, self.biases_array):\n weight_matrix_array.append(dy.parameter(W))\n biases_array.append(dy.parameter(b))\n acts = self.act\n w = weight_matrix_array[0]\n b = biases_array[0]\n act = acts[0]\n intermediate = act(dy.affine_transform([b, w, input]))\n activations = [intermediate]\n for (W, b, g) in zip(weight_matrix_array[1:], biases_array[1:], acts[1:]):\n pred = g(dy.affine_transform([b, W, activations[-1]]))\n activations.append(pred)\n losses = dy.pickneglogsoftmax(pred, output)\n return losses\n\n def predict(self, input):\n weight_matrix_array = []\n biases_array = []\n acts = []\n for (W, b, act) in zip(self.weight_matrix_array, self.biases_array, self.act):\n weight_matrix_array.append(dy.parameter(W))\n biases_array.append(dy.parameter(b))\n acts.append(act)\n g = acts[0]\n w = weight_matrix_array[0]\n b = biases_array[0]\n intermediate = g(w * input + b)\n activations = [intermediate]\n for (W, b, act) in zip(weight_matrix_array[1:], biases_array[1:], acts):\n pred = act(W * activations[-1] + b)\n activations.append(pred)\n return pred\n","sub_path":"sub_challenges/self_assessed_affect/clean_scripts/DeepNetworks/FeedForwardNeuralNet.py","file_name":"FeedForwardNeuralNet.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"587600601","text":"from crawlers.base import BaseCrawler\nfrom crawlers.models import *\n\n\nclass BlogTruyen(BaseCrawler):\n def setup(self):\n self._selectors.update({\n 'manga_list': 'div.list p span a',\n 'chapter_list': '#list-chapters span.title a',\n 'chapter_list_updated': '#list-chapters span.title + span',\n })\n\n self._selectors['manga_detail'].update({\n 'cover': 'div.thumbnail img',\n 'description': 'div.content',\n 'genre_list': 'div.description span.category a',\n 'title': '#breadcrumbs span:contains(\">\")',\n 'alternative': 'p:contains(\"Tên khác\") span.color-red',\n 'author': 'p:contains(\"Tác giả\") a.color-green',\n 'last_updated': 'div:contains(\"Update\") > span.color-green',\n 'status': 'p:contains(\"Trạng thái\") span.color-red',\n })\n\n self._selectors['chapter_detail'].update({\n 'title': 'div.breadcrumbs + h1',\n 'page_list': 'article#content img',\n })\n\n self._urls.update({\n 'base_url': 'http://blogtruyen.com',\n 'manga_list': 'http://blogtruyen.com/ajax/Search/AjaxLoadListManga?key=tatca&orderBy=5&p={page}',\n 'manga_detail': 'http://blogtruyen.com/{manga_id}',\n 'chapter_detail': 'http://blogtruyen.com/{chapter_id}',\n })\n\n self._configs.update({\n 'datetime_pattern': '%d/%m/%Y %H:%M',\n })\n\n def _get_id_from_url(self, url):\n if url.endswith('/'):\n url = url[:len(url) - 1]\n if '/' in url:\n url = '/'.join(url.split('/')[-2::])\n return url\n\n def _get_manga_detail_from_html_document(self, manga, document):\n super(BlogTruyen, self)._get_manga_detail_from_html_document(manga, document)\n manga.title = self._extract_manga_title(document)\n\n def _extract_manga_title(self, document):\n title = super(BlogTruyen, self)._extract_manga_title(document)\n return title.split('>')[-1].strip()\n\n def _extract_chapter_title(self, document):\n title = super(BlogTruyen, self)._extract_chapter_title(document)\n return title.split('>')[-1].strip()\n\n def _extract_manga_alternative(self, document):\n alternative = super(BlogTruyen, self)._extract_manga_alternative(document)\n return ', '.join([title.strip() for title in alternative.split(';') if title.strip()])\n\n\nif __name__ == '__main__':\n crawler = BlogTruyen()\n\n # manga_list = crawler.get_manga_list()\n # [print(manga) for manga in manga_list]\n\n # manga = manga_list[0]\n # manga = Manga('http://blogtruyen.com/14926/giac-mo-ty-phu')\n # crawler.get_manga_detail(manga)\n # print(manga)\n\n # chapter = manga.chapter_list[-1]\n chapter = Chapter('http://blogtruyen.com/c3896/bleach-chap-35')\n crawler.get_chapter_detail(chapter)\n print(chapter)\n","sub_path":"crawlers/blogtruyen.py","file_name":"blogtruyen.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"63388522","text":"from Useful import *\n\nclass Network:\n\n\tdef __init__(self, config):\n\t\t'''\n\t\t:param config: array of length L, specifying the number of nodes in each layer\n\t\tassuming an edge between every pair of nodes in adjacent layers\n\n\t\t>>> config = [1,1]\n\t\t>>> n = Network(config)\n\t\t>>> print(n.w)\n\t\t[[[0]]]\n\n\n\t\t'''\n\t\tself.numLayers = len(config)\n\t\tself.nodes = [[0 for i in range(config[k])] for k in range(self.numLayers)]\n\t\tself.initialize_weights(self.numLayers, config)\n\n\n\tdef initialize_weights(self, numLayers, config):\n\t\t'''\n\t\t:return w: a weight matrix whose entries are arrays detailing the transitions between layers\n\t\tw[i] represents the transitions between the ith layer and i+1th layer\n\t\tw[i][j] represents the connection between layer a[i] and node j in layer a[i+1]\n\t\tw[i][j][k] is the weight of the kth node in layer a[i] and the jth node in layer a[i+1]\n\n\t\t'''\n\t\t# might to reference field itself and not return since its a matrix and not a primitive\n\t\tself.w = []\n\t\tfor i in range(numLayers-1):\n\t\t\t# create a matrix with dimensions config[k] by config[j]\n\t\t\trow = [0 for k in range(config[i])]\n\t\t\tm = [row for j in range(config[i+1])]\n\t\t\tself.w.append(m)\n\n# class Node:\n# \tdef __init__(self):\n# \t\tself.activation = 0","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"46538497","text":"from flask import Flask, render_template, flash,redirect,request,g\r\nfrom flask_bootstrap import Bootstrap\r\nfrom flask_wtf import Form, RecaptchaField\r\nfrom wtforms import SelectField\r\nimport flask_sijax\r\nimport re\r\nfrom flask_wtf.file import FileField\r\nfrom wtforms import TextField, HiddenField, ValidationError, RadioField,\\\r\n BooleanField, SubmitField, IntegerField, FormField, validators,StringField,DecimalField,SelectMultipleField\r\nfrom wtforms.validators import Required\r\nimport bokeh.plotting as plt\r\nfrom bokeh.models import Plot,Tool,HoverTool,Select,TextInput,Button,Slider\r\nfrom bokeh.resources import CDN\r\nfrom bokeh.embed import file_html\r\nimport scipy.constants\r\nimport itur\r\nimport numpy as np\r\nfrom flask_table import Table, Col\r\n\r\nimport tinydb\r\nimport os,sys\r\nimport webbrowser\r\nimport pickle\r\nimport requests\r\n\r\n\r\n\r\n\r\nclass MakeGraph():\r\n #<--- Variables --->\r\n el = float()\r\n URL = \"https://nominatim.openstreetmap.org/search\"\r\n #rr = float(rp.rre.data)\r\n geoloc = (float(),float())\r\n rr = float()\r\n graphs = dict()\r\n tau = float()\r\n #rr = float(rp.rre.data)\r\n p0 = float\r\n xpic = str()\r\n equip = str()\r\n freq = float()\r\n card = str()\r\n bw = float\r\n ref_mod = str()\r\n g1a=float()\r\n g1b=float()\r\n am = str()\r\n #<--- Constants --->\r\n pi = float()\r\n wl = float()\r\n rainp = bool()\r\n modp = bool()\r\n availp=bool()\r\n modulation_level = dict()\r\n html = ''\r\n d = np.arange(0.01, 20, 0.01)\r\n truc = Slider()\r\n graphs = dict()\r\n table = str()\r\n db = ''\r\n def __init__(self,d1a,d1b,el,geoloc,rr,tau,p0,xpic,equip,freq,card,bw,ref_mod,am,rainp,modp,availp):\r\n self.g1a = d1a\r\n self.g1b = d1b\r\n self.el = el\r\n self.geoloc = geoloc\r\n self.rr = rr\r\n self.tau = tau\r\n self.p0 = p0\r\n self.xpic = xpic\r\n self.equip = equip\r\n self.freq = freq\r\n self.card=card\r\n self.bw = bw\r\n self.ref_mod = ref_mod\r\n self.am = am\r\n self.rainp=rainp\r\n self.modp = modp\r\n self.availp=availp\r\n self.pi = scipy.constants.pi\r\n self.wl = float(scipy.constants.speed_of_light / (freq * (10 ** 9)))\r\n self.graphs['rain'] = None\r\n self.graphs['mod'] = None\r\n self.graphs['avail'] = None\r\n self.db = tinydb.TinyDB('db_huawei_XPIC.json') if xpic == '1' else tinydb.TinyDB('db_huawei.json')\r\n\r\n\r\n\r\n def update(self,d1a,d1b,el,geoloc,rr,tau,p0,xpic,equip,freq,card,bw,ref_mod,am):\r\n self.g1a = d1a\r\n self.g1b = d1b\r\n self.el = el\r\n self.geoloc = geoloc\r\n self.rr = rr\r\n self.tau = tau\r\n self.p0 = p0\r\n self.xpic = xpic\r\n self.equip = equip\r\n self.freq = freq\r\n self.card = card\r\n self.bw = bw\r\n self.ref_mod = ref_mod\r\n self.am = am\r\n self.modulation_level.clear()\r\n self.db = tinydb.TinyDB('db_huawei_XPIC.json') if xpic == '1' else tinydb.TinyDB('db_huawei.json')\r\n\r\n\r\n def getTx(self,mod):\r\n user = tinydb.Query()\r\n table = self.db.table(self.equip)\r\n row = table.search((user.MODEL.search('(' + self.card + ')')) & (user.BAND_DESIGNATOR == float(self.freq)) & (\r\n user.BANDWIDTH == float(self.bw)) & (user.MODULATION_TYPE == str(mod)))\r\n return row[0]['MAX_TX_POWER']\r\n\r\n def getCapa(self,mod):\r\n user = tinydb.Query()\r\n table = self.db.table(self.equip)\r\n row = table.search((user.MODEL.search('(' + self.card + ')')) & (user.BAND_DESIGNATOR == float(self.freq)) & (\r\n user.BANDWIDTH == float(self.bw)) & (user.MODULATION_TYPE == str(mod)))\r\n return row[0]['CAPACITY']\r\n\r\n def getRxThr(self,mod=''):\r\n user = tinydb.Query()\r\n # manu='Ericsson',boolAM,equip,fre,modem,bw,mod\r\n # cb1 = equip , fe = freq, carde = card_modem, cpe = bandwidth , ref_mode = modulation\r\n\r\n if mod == '':\r\n mod = self.ref_mod\r\n table = self.db.table(self.equip)\r\n row = table.search((user.MODEL.search('(' + self.card + ')')) & (user.BAND_DESIGNATOR == float(self.freq)) & (\r\n user.BANDWIDTH == float(self.bw)) & (user.MODULATION_TYPE == str(mod)))\r\n if (self.am == '1'):\r\n return row[0]['TYP_RX_THRESHOLD3'] + row[0]['ACM_DROP_OFFSET']\r\n else:\r\n return row[0]['TYP_RX_THRESHOLD3']\r\n\r\n\r\n\r\n def bandwCh(self,xpic, equi, freq, carde, bandw):\r\n table = self.db.table(str(equi))\r\n modulations = list()\r\n match_str = str(carde)\r\n i = 0\r\n choix = list()\r\n\r\n def sortMod(mod):\r\n if (re.match('BPSK', str(mod))):\r\n mod = '2QAM'\r\n if (re.match('QPSK', str(mod))):\r\n mod = '4QAM'\r\n if (re.match('8PSK', str(mod))):\r\n mod = '8QAM'\r\n return int(str(mod).split('QAM')[0])\r\n\r\n for row in table:\r\n modulation = row['MODULATION_TYPE']\r\n freq0 = str(row['BAND_DESIGNATOR'])\r\n bandwidth = str(row['BANDWIDTH'])\r\n if (re.search('(' + match_str + ')', str(row['MODEL'])) != None) and str(freq0) == str(freq) and str(\r\n bandwidth) == str(bandw) and modulation not in modulations:\r\n modulations.append(modulation)\r\n modulations.sort(key=sortMod)\r\n return modulations\r\n\r\n def getThrList(self):\r\n modulations = self.bandwCh(self.xpic,self.equip,self.freq,self.card,self.bw)\r\n table = self.db.table(self.equip)\r\n for mod in modulations:\r\n self.modulation_level[mod] = self.getRxThr(mod)\r\n def plotRain(self,g1a,g1b,el,geoloc,rr,tau,p0,xpic,equip,freq,card,bw,ref_mod,am,d):\r\n p1 = np.arange(0.001,1,0.001)\r\n self.update(g1a,g1b,el,geoloc,rr,tau,p0,xpic,equip,freq,card,bw,ref_mod,am)\r\n self.getThrList()\r\n\r\n rx = (g1a + g1b - 20 * np.log10(\r\n (4 * self.pi * d * 1000) / self.wl) - itur.models.itu530.rain_attenuation(0, 0, d, freq, el, p1, tau, rr).value)\r\n\r\n mod_d = list()\r\n levels = list(self.modulation_level.values())\r\n mods_lab = list(self.modulation_level.keys())\r\n tx_mod = dict()\r\n capa_mod = dict()\r\n for lab in mods_lab:\r\n tx_mod[lab] = self.getTx(lab)\r\n capa_mod[lab] = self.getCapa(lab)\r\n capaline = list()\r\n\r\n for val in rx:\r\n max_mod = -100\r\n match = False\r\n capa = None\r\n for lab, mod in self.modulation_level.items():\r\n if val + tx_mod[lab] > mod:\r\n max_mod = mod\r\n capa = capa_mod[lab]\r\n match = True\r\n capaline.append(float(capa)) if match else capaline.append(0)\r\n\r\n source1 = dict(x=100-p1,y=capaline)\r\n return source1\r\n def plotMod(self,g1a,g1b,el,geoloc,rr,tau,p0,xpic,equip,freq,card,bw,ref_mod,am):\r\n d = np.arange(0.01, 20, 0.01)\r\n self.update(g1a, g1b, el, geoloc, rr, tau, p0, xpic, equip, freq, card, bw, ref_mod, am)\r\n #infosl = dict(gainA=np.full(1999,g1a),gainB=np.full(1999,g1b),rain=np.full(1999,np.round(rr,1)),polar=np.full(1999,tau),avail=np.full(1999,np.round(100-p0,5)))\r\n #infose = {'xpic':np.full(1999,xpic),'equip':np.full(1999,equip),'freq':np.full(1999,freq),'card':np.full(1999,card),'bw':np.full(1999,bw),'ref_mod':np.full(1999,ref_mod),'am':np.full(1999,am)}\r\n\r\n p=plt.figure(title='Capacity according to the distance',x_axis_label = 'Distance (km)',y_axis_label = 'Capacity (Mbps)')\r\n\r\n self.getThrList()\r\n\r\n # print(str(pi)+' -- '+str(tx1)+' -- '+str(g1a)+' -- '+str(g1b)+' -- '+str(20*np.log10((4*pi*9.94*1000)/wl)))\r\n rain_att = list()\r\n rain_att =(g1a + g1b - 20 * np.log10(\r\n (4 * self.pi * d * 1000) / self.wl) - itur.models.itu530.rain_attenuation(geoloc[0], geoloc[1], d, freq, el, p0,\r\n tau, rr).value)\r\n mod_d = list()\r\n levels = list(self.modulation_level.values())\r\n mods_lab = list(self.modulation_level.keys())\r\n tx_mod = dict()\r\n capa_mod = dict()\r\n for lab in mods_lab:\r\n tx_mod[lab]=self.getTx(lab)\r\n capa_mod[lab]=self.getCapa(lab)\r\n capaline = list()\r\n\r\n\r\n for val in rain_att:\r\n max_mod = -100\r\n match = False\r\n capa = None\r\n for lab,mod in self.modulation_level.items():\r\n if val+tx_mod[lab]> mod:\r\n max_mod = mod\r\n capa = capa_mod[lab]\r\n match=True\r\n capaline.append(float(capa)) if match else capaline.append(0)\r\n dico = dict(x=d,y=capaline)\r\n # dico = dict(list(dico.items()) + list(infosl.items()) + list(infose.items()))\r\n return dico #infl=np.full(1999,infosl.__str__()),infe=np.full(1999,infose.__str__()))\r\n\r\n def plotAvail(self,g1a,g1b,el,geoloc,rr,tau,p0,xpic,equip,freq,card,bw,ref_mod,am):\r\n d = np.arange(0.01, 20, 0.01)\r\n self.update(g1a, g1b, el, geoloc, rr, tau, p0, xpic, equip, freq, card, bw, ref_mod, am)\r\n rx_thr = self.getRxThr(ref_mod)\r\n tx1 = self.getTx(ref_mod)\r\n res = list()\r\n p=plt.figure(title='Availability according to the distance',x_axis_label = 'Distance (km)',y_axis_label = 'Availability')\r\n for dcrt in d:\r\n\r\n #d_t = itur.models.itu530.inverse_rain_attenuation(geoloc[0], geoloc[1], str(dcrt)+'_test', freq, el, 0, tau,rr).value\r\n #print('d = '+str(dcrt)+'; d_t = '+str(d_t))\r\n att_max = tx1 + g1a + g1b - float(rx_thr) - 20 * np.log10((4 * self.pi * dcrt * 1000) / self.wl)\r\n val = float()\r\n val = itur.models.itu530.inverse_rain_attenuation(geoloc[0], geoloc[1], dcrt, freq, el, att_max, tau,rr).value\r\n val = 100 - round(val, 9)\r\n res.append(val)\r\n return dict(x=d,y=res,freq=np.full(1999,freq))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n # def addline(self,d1a,d1b,el,geoloc,rr,tau,p0,xpic,equip,freq,card,bw,ref_mod,rainp,modp,availp):\r\n # d = self.d\r\n # self.update(d1a, d1b, el, geoloc, rr, tau, p0, xpic, equip, freq, card, bw, ref_mod)\r\n # html = ''\r\n # if (rainp):\r\n # p = self.graphs['rain']\r\n # p.line(d, itur.models.itu530.rain_attenuation(0, 0, d, freq, el, 0.01, tau, rr), line_width=2)\r\n # p.add_tools(HoverTool())\r\n # self.graphs['rain'] = p\r\n # html = html + file_html(p, CDN, \"my plot\")\r\n #\r\n # if (self.modp):\r\n # p = self.graphs['mod']\r\n # self.getThrList()\r\n # # print(str(pi)+' -- '+str(tx1)+' -- '+str(g1a)+' -- '+str(g1b)+' -- '+str(20*np.log10((4*pi*9.94*1000)/wl)))\r\n # rain_att = list()\r\n # rain_att = (d1a + d1b - 20 * np.log10(\r\n # (4 * self.pi * d * 1000) / self.wl) - itur.models.itu530.rain_attenuation(geoloc[0], geoloc[1], d, freq,\r\n # el, p0,\r\n # tau, rr).value)\r\n # mod_d = list()\r\n # levels = list(self.modulation_level.values())\r\n # mods_lab = list(self.modulation_level.keys())\r\n # tx_mod = dict()\r\n # capa_mod = dict()\r\n # for lab in mods_lab:\r\n # tx_mod[lab] = self.getTx(lab)\r\n # capa_mod[lab] = self.getCapa(lab)\r\n # capaline = list()\r\n #\r\n # for val in rain_att:\r\n # max_mod = -100\r\n # match = False\r\n # for lab, mod in self.modulation_level.items():\r\n # capa = None\r\n # if val + tx_mod[lab] > mod:\r\n # max_mod = mod\r\n # capa = capa_mod[lab]\r\n # match = True\r\n # capaline.append(float(capa)) if match else capaline.append(0)\r\n # p.line(d, capaline)\r\n # p.add_tools(HoverTool())\r\n # html = html + file_html(p, CDN, \"my plot\")\r\n # self.graphs['mod'] = p\r\n # # plt.hlines(-100,0,20,label='Rx Sensitivity',linestyles='dotted',colors=cmap(random.randint(1,20)))\r\n # # plt.plot(tx2+g2a+g2b-itur.models.itu530.rain_attenuation(geoloc[0],geoloc[1], d, f2, el, 0.01,tau,rr).value-20*np.log((4*pi*d)/wl),label=str(f2)+'GHz')\r\n # if (self.availp):\r\n # rx_thr = self.getRxThr(ref_mod)\r\n # tx1 = self.getTx(ref_mod)\r\n # res = list()\r\n # p = self.graphs['avail']\r\n # for dcrt in d:\r\n # att_max = tx1 + d1a + d1b - float(rx_thr) - 20 * np.log10((4 * self.pi * dcrt * 1000) / self.wl)\r\n # val = float()\r\n #\r\n # val = np.nan_to_num(\r\n # itur.models.itu530.inverse_rain_attenuation(geoloc[0], geoloc[1], dcrt, freq, el, att_max, tau,\r\n # rr).value)\r\n # val = 100 - round(val, 5)\r\n # res.append(val)\r\n # # z = np.polyfit(d,res,10)\r\n # # f = np.poly1d(z)\r\n # # print(f(d))\r\n # p.line(d, res)\r\n # self.graphs['avail'] = p\r\n # html = html + file_html(p, CDN, \"my plot\")\r\n # self.graphs['html'] = html\r\n # return self.graphs\r\n\r\n def getGraphs(self):\r\n return self.graphs\r\n\r\n","sub_path":"make_graph.py","file_name":"make_graph.py","file_ext":"py","file_size_in_byte":13639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"571344806","text":"# Copyright 2015-2016 F5 Networks Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom pprint import pprint as pp\n\nTESTDESCRIPTION = \"TESTDESCRIPTION\"\n\n\ndef delete_resource(resources):\n for resource in resources.get_collection():\n resource.delete()\n\n\ndef setup_virtual_test(request, bigip, partition, name):\n def teardown():\n delete_resource(vc1)\n request.addfinalizer(teardown)\n vc1 = bigip.ltm.virtuals\n pp('****')\n virtual1 = vc1.virtual\n virtual1.create(name=name, partition=partition)\n return virtual1, vc1\n\n\nclass TestVirtual(object):\n def test_virtual_create_refresh_update_delete_load(self, request, bigip):\n virtual1, vc1 = setup_virtual_test(request, bigip, 'Common', 'vstest1')\n assert virtual1.name == 'vstest1'\n virtual1.description = TESTDESCRIPTION\n virtual1.update()\n assert virtual1.description == TESTDESCRIPTION\n virtual1.description = ''\n virtual1.refresh()\n assert virtual1.description == TESTDESCRIPTION\n virtual2 = vc1.virtual\n virtual2.load(partition='Common', name='vstest1')\n assert virtual2.selfLink == virtual1.selfLink\n\n\ndef test_profiles_CE(bigip, opt_release):\n v1 = bigip.ltm.virtuals.virtual\n v1.create(name=\"tv1\", partition=\"Common\")\n p1 = v1.profiles_s.profiles\n p1.create(name=\"http\")\n pp(p1.raw)\n test_profiles_s = v1.profiles_s\n pp(test_profiles_s.raw)\n test_profiles_s.context = 'all'\n pp(test_profiles_s.raw)\n assert p1.selfLink ==\\\n u\"https://localhost/mgmt/tm/ltm/virtual/\"\\\n \"~Common~tv1/profiles/http?ver=\"+opt_release\n\n p2 = v1.profiles_s.profiles\n assert p2.exists(name='http')\n\n v1.delete()\n","sub_path":"test/functional/tm/ltm/test_virtual.py","file_name":"test_virtual.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"450948384","text":"from rectpack import newPacker\r\n\r\nrectangles = [(100, 30), (40, 60), (30, 30),(70, 70), (100, 50), (30, 30)]\r\nbins = [(300, 450), (80, 40), (200, 150)]\r\n\r\npacker = newPacker()\r\n\r\n# Add the rectangles to packing queue\r\nfor r in rectangles:\r\n packer.add_rect(*r)\r\n\r\n# Add the bins where the rectangles will be placed\r\nfor b in bins:\r\n packer.add_bin(*b)\r\n\r\n# Start packing\r\npacker.pack()\r\n","sub_path":"rectpack/rectpact.py","file_name":"rectpact.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"353745955","text":"from cv2 import aruco\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\n# size = aruco.DICT_4X4_250\n# size = aruco.DICT_5X5_250\nsize = aruco.DICT_6X6_250\n\naruco_dict = aruco.Dictionary_get(size)\n\nfig = plt.figure()\nnx = 4\nny = 3\nfor i in range(1, nx*ny+1):\n ax = fig.add_subplot(ny,nx, i)\n img = aruco.drawMarker(aruco_dict,i, 700)\n plt.imshow(img, cmap = mpl.cm.gray, interpolation = \"nearest\")\n ax.axis(\"off\")\n\nplt.savefig(\"markers5x5.png\")\nplt.show()\n","sub_path":"Aruco/Aruco_generator.py","file_name":"Aruco_generator.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"446837764","text":"\"\"\"Module describes IStream3 data channel\"\"\"\nimport os\nimport json\nimport struct\n\n\nclass Channel:\n \"\"\"IStream3 channel\"\"\"\n @staticmethod\n def search_in_meta(metadata, searched_key):\n \"\"\"recursive search in json by key\"\"\"\n result = ''\n if isinstance(metadata, type({})):\n for key in metadata:\n if key == searched_key:\n return metadata[key]\n result = Channel.search_in_meta(metadata[key], searched_key)\n if len(result):\n return result\n return result\n\n def __init__(self, path, stream_id=0):\n if os.path.exists(path) is False:\n raise IOError(path)\n\n self.chunks = []\n self.metadata = None\n for name in os.listdir(path):\n if name.endswith('.data.idx'):\n self.chunks.append(os.path.join(path, name))\n elif name.startswith('stream.'+str(stream_id)+'.'):\n with open(os.path.join(path, name)) as stream_file:\n self.metadata = json.load(stream_file)\n self.chunks.sort()\n\n def search(self, key):\n \"\"\"search in IStream3 channel json metadata by key\"\"\"\n return Channel.search_in_meta(self.metadata, key)\n\n\nclass Block:\n \"\"\"IStream3 index entry\"\"\"\n def __init__(self, fd) -> None:\n self._block = fd.read(77)\n if len(self._block) != 77:\n raise EOFError()\n self.entry_size,\\\n self.block_type,\\\n self.stream_type,\\\n self.stream_id,\\\n self.flags,\\\n self.duration,\\\n self.timestamp,\\\n self.ts_rel,\\\n self.dts_rel,\\\n self.block_size,\\\n self.offset,\\\n self.index,\\\n self.block_id,\\\n self.mark = struct.unpack('=BBBQQQQIIQQQQH', self._block)\n if self.mark != 0xbabe:\n raise EOFError\n\n def __repr__(self):\n return f'{self.__class__.__name__}(block_type={self.block_type})'\n\n def __str__(self):\n return f'{self.index}\\t{self.block_id}\\t{self.block_type}\\t{self.stream_id}\\t{self.stream_type}\\t' \\\n f'{self.duration}\\t{self.flags}\\t{self.block_size}\\t{self.timestamp}\\t{self.ts_rel}'\n\n @property\n def relative_timestamp(self):\n \"\"\"returns block relative timestamp in data file\"\"\"\n return self.ts_rel\n\n def __len__(self):\n return self.block_size\n\n\nclass IndexIterator:\n \"\"\"IStream3 index file iterator\"\"\"\n _file = None\n _end = 0\n\n def __next__(self):\n try:\n if self._file is not None:\n block = Block(self._file)\n if not self._end or block.timestamp <= self._end:\n return block\n raise StopIteration\n except EOFError:\n raise StopIteration from None\n\n def filename(self, name):\n \"\"\"Sets IStream3 index filename\"\"\"\n self._file = open(name, 'rb')\n\n filename = property(None, filename)\n\n def end(self, stop):\n \"\"\"Sets IStream3 index timestamp to dump till\"\"\"\n self._end = stop\n\n end = property(None, end)\n\n\nclass Index:\n \"\"\"IStream3 index file\"\"\"\n def __init__(self, path, last_timestamp):\n self._path = path\n self._last_timestamp = last_timestamp\n\n @property\n def path(self):\n \"\"\"returns IStream3 index file path\"\"\"\n return self._path\n\n def __iter__(self):\n index_iterator = IndexIterator()\n index_iterator.filename = self._path\n index_iterator.end = self._last_timestamp\n return index_iterator\n\n\nclass Data:\n \"\"\"IStream3 data file\"\"\"\n def __init__(self, path):\n self._size = os.path.getsize(path)\n self._file_desc = open(path, 'rb')\n\n def __len__(self):\n return self._size\n\n def frame(self, block) -> bytes:\n \"\"\"Returns data frame by index block offset and index block size\"\"\"\n self._file_desc.seek(block.offset-len(block), 0)\n return self._file_desc.read(len(block))\n","sub_path":"src/is3dump/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"89168676","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 09 16:08:45 2017\r\n\r\nclass for reading dcimg files\r\n\r\n@author: kner\r\n\"\"\"\r\n\r\nimport dcimg_defs as defs\r\nimport numpy as np\r\nct = defs.ct\r\n\r\ndcimgapi = ct.cdll.LoadLibrary('dcimgapi.dll')\r\n\r\nclass dcimg_reader(object):\r\n \r\n def __init__(self, filename):\r\n iparams = defs.INIT()\r\n temp = defs.GUID()\r\n temp.Data4 = ct.c_char_p(b'00000000')\r\n iparams.guid = ct.pointer(temp)\r\n iparams.size = ct.sizeof(iparams)\r\n \r\n h = dcimgapi.dcimg_init(ct.pointer(iparams))\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n self.iparams = iparams\r\n \r\n iopen = defs.OPEN()\r\n iopen.size = ct.sizeof(iopen)\r\n iopen.path = defs.LPCSTR(filename.encode())\r\n \r\n h = dcimgapi.dcimg_openA(ct.pointer(iopen))\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n self.hdcimg = iopen.hdcimg\r\n # for matlab declare other member data\r\n self.width = None\r\n self.height = None\r\n self.rowbytes = None\r\n self.pixelsize = None\r\n self.totalsessions = None\r\n self.totalframes = None\r\n self.data = None\r\n self.dataset = None\r\n \r\n def __del__(self):\r\n h = dcimgapi.dcimg_close(self.hdcimg)\r\n if (h==1):\r\n print('file closed')\r\n else:\r\n print('problems')\r\n print(hex(np.uint32(h)))\r\n \r\n def getinfo(self):\r\n nwidth = ct.c_int32(0)\r\n h = dcimgapi.dcimg_getparaml( self.hdcimg, defs.DCIMG_IDPARAML_IMAGE_WIDTH, ct.byref(nwidth) )\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n self.width = nwidth.value\r\n nheight = ct.c_int32(0)\r\n h = dcimgapi.dcimg_getparaml( self.hdcimg, defs.DCIMG_IDPARAML_IMAGE_HEIGHT, ct.byref(nheight) )\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n self.height = nheight.value\r\n nrowbytes = ct.c_int32(0)\r\n h = dcimgapi.dcimg_getparaml( self.hdcimg, defs.DCIMG_IDPARAML_IMAGE_ROWBYTES, ct.byref(nrowbytes) )\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n self.rowbytes = nrowbytes.value\r\n npixelsize = ct.c_int32(0) \r\n h = dcimgapi.dcimg_getparaml( self.hdcimg, defs.DCIMG_IDPARAML_IMAGE_PIXELTYPE, ct.byref(npixelsize) )\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n if not (npixelsize.value == defs.DCIMG_PIXELTYPE_MONO16):\r\n print('pixel size not 16 bit.')\r\n self.pixelsize = npixelsize.value\r\n nsessions = ct.c_int32(0)\r\n h = dcimgapi.dcimg_getparaml( self.hdcimg, defs.DCIMG_IDPARAML_NUMBEROF_SESSION, ct.byref(nsessions))\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n self.totalsessions = nsessions.value\r\n # get number of frames\r\n nframes = ct.c_int32(0)\r\n h = dcimgapi.dcimg_getparaml( self.hdcimg, defs.DCIMG_IDPARAML_NUMBEROF_TOTALFRAME, ct.byref(nframes))\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n self.totalframes = nframes.value\r\n\r\n def getFrame(self,frameno,sessionno=0):\r\n h = dcimgapi.dcimg_setsessionindex( self.hdcimg, ct.c_int32(sessionno) )\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n \r\n iframe = defs.FRAME()\r\n iframe.size = ct.c_int32(ct.sizeof(iframe))\r\n iframe.iFrame = ct.c_int32(frameno)\r\n #data = np.zeros((2048,2048), dtype=np.uint16)\r\n h = dcimgapi.dcimg_lockframe( self.hdcimg, ct.byref(iframe) )\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n datasize = self.width*self.height\r\n data = np.fromiter(iframe.buf, dtype=np.uint16, count=datasize)\r\n self.data = data.reshape(self.width,self.height)\r\n return True\r\n \r\n def getFrames(self,frame_beg,frame_end,sessionno=0):\r\n if (frame_beg>frame_end) or (frame_beg<0):\r\n print('Invalid frame values!')\r\n return False\r\n if frame_end>self.totalframes:\r\n print('last frame is greater than total number of frames!')\r\n return False\r\n \r\n h = dcimgapi.dcimg_setsessionindex( self.hdcimg, ct.c_int32(sessionno) )\r\n if (h!=1):\r\n print(hex(np.uint32(h)))\r\n \r\n Nf = frame_end - frame_beg\r\n self.dataset = np.zeros((Nf,self.width,self.height), dtype=np.uint16)\r\n for m in range(Nf):\r\n self.getFrame(frame_beg+m,sessionno)\r\n self.dataset[m] = self.data.copy()\r\n del self.data\r\n return True","sub_path":"bfmatlab551/dcimg_reader.py","file_name":"dcimg_reader.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"537581292","text":"from PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom math import sin,cos,pi,acos\n\nTwoPi = pi*2\nclass Edge(QGraphicsItem):\n\tdef __init__(self,sourceNode, destNode):\n\t\tsuper(Edge,self).__init__()\n\t\tself.sourcePoint=None\n\t\tself.destPoint=None\t\n\t\tself.arrowSize=10\n\t\tself.setAcceptedMouseButtons(Qt.NoButton)\n\t\tself.source=sourceNode\n\t\tself.dest=destNode\n\t\tself.source.addEdge(self)\n\t\tself.dest.addEdge(self)\n\n\t\tself.adjust()\n\tdef sourceNode(self):\n\t\treturn self.source\n\tdef setSourceNode(self,node):\n\t\tself.source=node\n\t\tadjust()\n\tdef destNode(self):\n\t\treturn self.dest\n\tdef setDestNode(self,node):\n\t\tself.dest=node\n\t\tadjust()\n\tdef adjust(self):\n\t\tif not self.source or not self.dest:\n\t\t\treturn\n\t\tline=QLineF(self.mapFromItem(self.source,0,0), self.mapFromItem(self.dest,0,0))\n\t\tlength = line.length()\n\n\t\tself.prepareGeometryChange()\n\n\t\tif length > 20.0:\n\t\t\tedgeOffset=QPointF((line.dx()*10)/length,(line.dy()*10)/length)\n\t\t\tself.sourcePoint = line.p1() + edgeOffset\n\t\t\tself.destPoint = line.p2() - edgeOffset\n\t\telse:\n\t\t\tself.sourcePoint = self.destPoint = line.p1()\n\n\tdef boundingRect(self):\n\t\tif not self.source or not self.dest:\n\t\t\treturn QRectF()\n\t\tpenWidth=1\n\t\textra = (penWidth + self.arrowSize) / 2.0;\n\t\treturn QRectF(self.sourcePoint, QSizeF(self.destPoint.x() - self.sourcePoint.x(),self.destPoint.y() - self.sourcePoint.y())).normalized().adjusted(-extra,-extra,extra,extra)\n\n\tdef paint(self,painter, option=None, widget=None):\n\t\tif not self.source or not self.dest:\n\t\t\treturn\n\t\tline=QLineF(self.sourcePoint,self.destPoint)\n\t\tif line.length() == 0.0:\n\t\t\treturn\n\t\t#draw the line itself\n\t\tpainter.setPen(QPen(Qt.black,1,Qt.SolidLine,Qt.RoundCap,Qt.RoundJoin))\n\t\tpainter.drawLine(line)\n\n\t\t#draw the arrows\n\t\tangle = acos(line.dx()/line.length())\n\t\tif line.dy() >= 0:\n\t\t\tangle = TwoPi - angle\n\t\tsourceArrowP1= self.sourcePoint + QPointF(sin(angle + pi / 3 ) * self.arrowSize, \\\n\t\t\t\t\t\t\t\t\t\t cos(angle + pi / 3 ) * self.arrowSize)\n\t\tsourceArrowP2= self.sourcePoint + QPointF(sin(angle + pi - pi / 3 ) * self.arrowSize, \\\n\t\t\t\t cos(angle + pi - pi / 3 ) * self.arrowSize)\n\n\t\tdestArrowP1= self.destPoint + QPointF(sin(angle - pi / 3 ) * self.arrowSize, \\\n\t\t\t\t cos(angle - pi / 3 ) * self.arrowSize)\n\t\tdestArrowP2= self.destPoint + QPointF(sin(angle - pi + pi / 3 ) * self.arrowSize, \\\n\t\t\t\t cos(angle - pi + pi / 3 ) * self.arrowSize)\n\n\t\tpainter.setBrush(Qt.black)\n\t\tpoints1=[line.p1(),sourceArrowP1,sourceArrowP2]\n\t\tpoints2=[line.p2(),destArrowP1,destArrowP2]\n\t\tpainter.drawPolygon(QPolygonF(points1))\n\t\tpainter.drawPolygon(QPolygonF(points2))\n","sub_path":"utils/nodes-py/edge.py","file_name":"edge.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"278573176","text":"import json\ndef is_json(value):\n try :\n json.dumps(value)\n return True\n except:\n return False\n\ndef fileSearch(fileToSearch, filesObject):\n thisJson = json.loads(filesObject)\n print(thisJson)\n print('-----')\n pathFound = []\n for key in thisJson:\n if key == '_files':\n if thisJson[key].count(fileToSearch) != 0:\n pathFound.append('/' + fileToSearch)\n else:\n if is_json(thisJson[key]):\n newPathFound = fileSearch(fileToSearch, json.dumps(thisJson[key]))\n for i in range(len(newPathFound)):\n newPathFound[i] = '/' + key + newPathFound[i]\n pathFound.extend(newPathFound)\n return pathFound\n\"\"\"\n#jsonObject = ''' {\n \"FolderA\": {\n \"_files\": [ \"file1\", \"file2\" ] ,\n \"SubfolderC\": {\n \"_files\": [ \"file1\" ]\n } ,\n \"SubfolderB\": {\n \"_files\" : [ \"file1\" ]\n }\n }\n } \n '''\nprint(fileSearch('file1', jsonObject))\n\"\"\"\n\n\"\"\"\njsonObject = ''' {\n \"I\" : {\n \"_files\" : [\"her\"] ,\n \"hate\" : {\n \"_files\" : [\"me\", \"you\"] ,\n \"hater\" : {\n \"_files\" : [\"gonna hate hate hate hate hate\"]\n } \n } ,\n \"love\" : {\n \"_files\" : [\"you\", \"adfafdfa\", \"xx\", \"xy\"]\n }, \n \"hate that\" :{\n \"_files\" : [\"weekly cp problems\"],\n \"I love\" : {\n \n \"_files\" : [\"you\", \"me\", \"teemo\"]\n }\n },\n \"Don't want to\" : {\n \"_files\" : [\"DIEEEE\", \"Sometime I wish I never been born at all\"],\n \", but I can put\" : {\n \"_files\" : [\"on clothes\"],\n \"nobody else\" : {\n \"_files\" : [\"love me\", \"like you do\"],\n \"aboves\" : {\n \"_files\" : [\"you\", \"me\", \"pizza\"]\n }\n\n }\n }\n }\n\n }\n\n}\n'''\nprint(fileSearch(\"you\", jsonObject))\n\"\"\"","sub_path":"Prob#2_File_Search/file_serch.py","file_name":"file_serch.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"213169874","text":"import matplotlib.pyplot as plt\nplt.rcParams.update({'font.size': 22})\n\nfile = open(\"Opgave7.1m16.txt\", \"r\")\n\nlines = file.readlines()\n\nxs = []\nys = []\ns = 0\ni = 0\nfor line in lines:\n if i < 100:\n elements = line.split(', ')\n xs.append(int(elements[0]))\n ys.append(int(elements[1][:-1]))\n else:\n elements = line.split(' = ')\n if elements[0] == 'S':\n s = int(elements[1][:-1])\n i += 1\n\nsxs = [0, 100]\nsys = [s, s]\n\nplt.scatter(xs, ys, label=\"Coun-Sketch results\")\nplt.plot(sxs, sys, label=\"S\", c='red')\nplt.title('Cout-Sketch compared to real value wiht m = 16')\nplt.xlabel('test results arranged ascendinly')\nplt.ylabel('Actual sum')\nplt.legend()\nplt.show()\n","sub_path":"Project/pythonPlotting/Plots7.1m16.py","file_name":"Plots7.1m16.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"556143156","text":"import argparse\nimport os.path\nimport zipfile\n\n\nIGNORE_DIR = (\n 'site-packages',\n 'curses',\n 'dbm',\n 'distutils',\n 'idlelib',\n 'lib2to3',\n 'msilib',\n 'pydoc_data',\n 'tkinter',\n 'turtledemo',\n 'venv',\n 'ensurepip',\n\n# 2.7 specific\n 'bsddb',\n 'lib-tk'\n)\n\nIGNORE_FILE = (\n 'site.py',\n 'sysconfig.py',\n 'doctest.py',\n 'turtle.py',\n 'tabnanny.py',\n 'this.py',\n '__phello__.foo.py',\n '_osx_support.py',\n 'asyncio/test_utils.py',\n\n# 2.7 specific\n 'anydbm.py',\n 'user.py',\n 'whichdb.py',\n)\n\n\ndef dir_in_interest(arch_path):\n for exclusion in IGNORE_DIR:\n if arch_path == exclusion:\n return False\n return True\n\n\ndef file_in_interest(fs_path, arch_path):\n if arch_path in IGNORE_FILE:\n return False\n return True\n\n\ndef in_interest(fs_path, arch_path, is_dir, pathbits):\n name = pathbits[-1]\n if is_dir:\n if (name == '__pycache__' or name == 'test' or name == 'tests'):\n return False\n if arch_path.startswith('plat-'):\n return False\n else:\n if not arch_path.endswith('.py'):\n return False\n if is_dir:\n return dir_in_interest(arch_path)\n else:\n return file_in_interest(fs_path, arch_path)\n\n\ndef enum_content(seed, catalog, pathbits = None):\n if pathbits is None:\n fs_path = seed\n is_dir = True\n else:\n fs_path = os.path.join(seed, *pathbits)\n is_dir = os.path.isdir(fs_path)\n if pathbits is not None:\n arc_path = '/'.join(pathbits)\n if not in_interest(fs_path, arc_path, is_dir, pathbits):\n return\n if not is_dir:\n catalog.append((fs_path, arc_path))\n else:\n pathbits = []\n if is_dir:\n files = []\n dirs = []\n for name in os.listdir(fs_path):\n p = os.path.join(fs_path, name)\n if os.path.isdir(p):\n dirs.append(name)\n else:\n files.append(name)\n for name in sorted(dirs):\n pathbits.append(name)\n enum_content(seed, catalog, pathbits)\n del pathbits[-1]\n for name in sorted(files):\n pathbits.append(name)\n enum_content(seed, catalog, pathbits)\n del pathbits[-1]\n\n\ndef build_stdlib():\n parser = argparse.ArgumentParser()\n parser.add_argument('--pysrc-root', required=True)\n parser.add_argument('--output-zip', required=True)\n parser.add_argument('--py2', action='store_true')\n args = parser.parse_args()\n\n dirhere = os.path.normpath(os.path.abspath(os.path.dirname(__file__)))\n stdlib_srcdir = os.path.normpath(os.path.abspath(os.path.join(args.pysrc_root, 'Lib')))\n zipfilename = os.path.normpath(os.path.abspath(args.output_zip))\n display_zipname = os.path.basename(zipfilename)\n\n catalog = []\n enum_content(stdlib_srcdir, catalog)\n catalog += [\n (os.path.join(dirhere, 'site.py'), 'site.py'),\n (os.path.join(dirhere, 'sysconfig.py'), 'sysconfig.py'),\n (os.path.join(dirhere, '_sysconfigdata.py'), '_sysconfigdata.py'),\n ]\n if args.py2:\n catalog += [(os.path.join(dirhere, '_sitebuiltins.py'), '_sitebuiltins.py')]\n\n print(\"::: compiling python-stdlib zip package '{0}' ...\".format(zipfilename))\n with zipfile.ZipFile(zipfilename, \"w\", zipfile.ZIP_DEFLATED) as fzip:\n for entry in catalog:\n fname, arcname = entry[0], entry[1]\n fzip.write(fname, arcname)\n print(\"::: {0} >>> {1}/{2}\".format(fname, display_zipname, arcname))\n\n\nif __name__ == '__main__':\n build_stdlib()\n","sub_path":"build/tools/build-target-python/build_stdlib.py","file_name":"build_stdlib.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"230310237","text":"import os\nimport csv\nfrom itertools import islice\nimport glob\nfrom pathlib import Path\nimport pdb\n\nCSV_ROOT = Path(Path.home(), 'king-county-assessor')\n\nyears = glob.glob(str(CSV_ROOT / '*'))\n\ndata_files = {}\n\n\ndef calculate_stats(rows, key):\n values = sorted([\n int(row[key])\n for row in rows\n ])\n\n count = len(values)\n median = values[int(count / 2)]\n total = sum(values)\n\n return {\n 'total': total,\n 'median': median,\n 'count': count,\n 'average': total / count,\n }\n\n\ndef calculate_stats_for_complex(rows, unit_count_key, average_unit_size_key):\n unit_count_and_size = sorted([\n (\n int(row[unit_count_key]),\n int(row[average_unit_size_key])\n )\n for row in rows\n ])\n\n total_livable_square_footage = sum(\n unit_count * unit_size\n for unit_count, unit_size in unit_count_and_size\n )\n\n total_unit_count = sum(\n unit_count\n for unit_count, unit_size in unit_count_and_size\n )\n\n average_livable_square_footage = total_livable_square_footage / total_unit_count\n\n return {\n 'total': total_livable_square_footage,\n 'median': 'N/A',\n 'count': total_unit_count,\n 'average': average_livable_square_footage,\n }\n\n\n# note that year is really the yyyy-mm-dd when it was fetched\nfor year in years:\n yyyy_mm_dd = os.path.basename(year)\n data_files[yyyy_mm_dd] = {}\n\n for filename, stats_function, args in (\n ('EXTR_ResBldg.csv', calculate_stats, ('SqFtTotLiving',)),\n ('EXTR_CondoUnit2.csv', calculate_stats, ('Footage',)),\n ('EXTR_AptComplex.csv', calculate_stats_for_complex, ('NbrUnits', 'AvgUnitSize')),\n ('EXTR_CondoComplex.csv', calculate_stats_for_complex, ('NbrUnits', 'AvgUnitSize')),\n ):\n path = str(CSV_ROOT / year / filename)\n data_files[yyyy_mm_dd][filename] = {}\n\n with open(path) as f:\n all_rows = csv.DictReader(f)\n # all_rows = list(islice(csv.DictReader(f), 100)) # uncomment to quickly test on a small subset of the data\n\n data_files[yyyy_mm_dd][filename]['livable_square_footage'] = stats_function(all_rows, * args)\n\nprint(data_files)\n\npdb.set_trace()\n\n# It's not well documented, but 'SqFtTotLiving' appears to be the main key.\n# There doesn't appear to be a \"total square footage\" key.\n# SqFtTotBasement appears to include SqFtFinBasement (Total basement square feet > finished basement square feet)\n# * it's unclear if SqFtTotLiving includes SqFtFinBasement\n# all of the keys other than 'SqFtTotLiving' are frequently 0\n\nsq_ft_keys = ('SqFt1stFloor', 'SqFtHalfFloor', 'SqFt2ndFloor', 'SqFtUpperFloor', 'SqFtUnfinFull', 'SqFtUnfinHalf', 'SqFtTotLiving', 'SqFtTotBasement', 'SqFtFinBasement', 'SqFtGarageBasement', 'SqFtGarageAttached', 'SqFtOpenPorch', 'SqFtEnclosedPorch', 'SqFtDeck')\n\n","sub_path":"lib/median_square_footage.py","file_name":"median_square_footage.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"326647714","text":"import sys\nimport time\nimport gen_bench as gb\n\nfrom msg_scheduler import model as mmodel\nfrom msg_scheduler import constrains, analyzer\nfrom scheduler import model as tmodel\n#from scheduler import solver_z3 as tsolver\n#from scheduler import solver_gurobi_new as tsolver\nfrom scheduler import solver_gekko as tsolver\nfrom scheduler import edfsim\n\ndef record_test_model(file, task_dict):\n # print param for each node\n file.writelines(\"######## TEST MODLE START ########\\n\")\n for node in task_dict:\n file.writelines(\"######## Node {} ########\\n\".format(node.name))\n tasks = task_dict[node]\n real_util = 0\n for i in range(12):\n task = tasks[i]\n real_util += task.wcet / task.peroid\n #print(\"per {}\".format(task.peroid))\n file.writelines('task id: {}, task type: {}'.format(i, type(task)))\n _phi0 = int(task.offset0)\n _d0 = int(task.deadline0)\n _wcet0 = int(task.wcet)\n file.writelines('\\toffset0: {}, wcet: {}, deadline0: {}, peroid: {}'.format(\n _phi0, _wcet0, _d0, task.peroid))\n if isinstance(task, tmodel.CommTask):\n file.writelines(', delta: {}\\n'.format(task.delta))\n else:\n file.writelines('\\n')\n file.writelines('check util: %f\\n' % real_util)\n\n file.writelines(\"######## TEST MODLE END ########\\n\")\n\ndef do_test(peroids, util, gran, net_type, times):\n #return times\n split_time = 0\n task_sche_time = 0\n msg_sche_time = 0\n # call gen_model\n network, task_dict, commu_pair = gb.gen_test_model(peroids, util, gran, net_type, times)\n # draw the network\n # network.draw()\n # check param\n with open(\"./output/bench_test.txt\", 'w') as f:\n record_test_model(f, task_dict)\n f.close()\n\n free_utils = dict()\n for node in task_dict:\n free_utils[node] = util*0.75\n\n # test solver\n solver = tsolver.Solver(network, task_dict, free_utils, commu_pair)\n solver_result_dict, split_time = solver.solve(\"./output/gurobi_result.txt\")\n\n if not solver_result_dict:\n print(\"\\x1b[31m#### Can't solve spliting\\x1b[0m\")\n time.sleep(3)\n return -1, -1, -1\n \n # 测试密度\n print(\"-- 密度测试 --\")\n for node in task_dict:\n tasks = task_dict[node]\n s = 0\n for task in tasks:\n if isinstance(task, tmodel.FreeTask):\n s += task.wcet / task.deadline0\n else:\n s += task.wcet / solver_result_dict[\"{}_deadline\".format(task.name)]\n print(\"{}: s={}\".format(node.name, s))\n print(\"-- 任务调度 --\")\n _temp_sum = 0\n _count = 0\n for node in task_dict:\n tasks = task_dict[node]\n print(node.name)\n # re-setup phi and deadline\n tasks4edf = []\n for task in tasks:\n _tid = int(task.name.split('_')[2]) + 1\n #print(_tid)\n if isinstance(task, tmodel.FreeTask):\n _C = int(task.wcet)\n _T = int(task.peroid)\n _offset = int(task.offset0)\n _D = int(task.deadline0)\n _task: edfsim.Task = edfsim.Task(C=_C, D=_D, T=_T, offset=_offset, tid=_tid)\n else:\n # re-setup\n _C = int(task.wcet)\n _T = int(task.peroid)\n _offset = solver_result_dict['{}_phi'.format(task.name)]\n _D = solver_result_dict['{}_deadline'.format(task.name)]\n _task: edfsim.Task = edfsim.Task(C=_C, D=_D, T=_T, offset=_offset, tid=_tid)\n tasks4edf.append(_task)\n # do edf sim\n # dump taskset\n #for task in tasks4edf:\n # print('Task(tid={}, T={}, C={}, D={}, offset={})'.format(task.tid, task.T, task.C, task.D, task.offset))\n _t0 = time.time()\n edfsim.testEDFSim(tasks4edf,[])\n _t1 = time.time()\n _count += 1\n _temp_sum += _t1 - _t0\n \n task_sche_time = _temp_sum / _count\n print(\"-- 通信调度 --\")\n gb.setup_frame_constraints(task_dict, solver_result_dict)\n \n sc = mmodel.Scheduler(network)\n for node in task_dict:\n sc.add_apps(task_dict[node])\n\n \n hook = constrains.Z3Hook()\n _t0 = time.time()\n print(\"- 生成约束 -\")\n sc.add_constrains(hook)\n print(\"- 求解 -\")\n df = hook.to_dataframe()\n _t1 = time.time()\n msg_sche_time = _t1 - _t0\n if df.empty:\n return -2, -2, -2\n #an = analyzer.Analyzer(df, network, sc.app_lcm)\n #an.print_by_time()\n #an.animate()\n #print(\"Message Passing Solved in {} s!\".format(_t1-_t0))\n return split_time, task_sche_time, msg_sche_time\n\nif __name__ == '__main__':\n\n print(\"\")\n\n # setup param\n peroids = [50000, 75000] #us\n util = 0.5\n gran = 1 # us\n net_type = 0\n\n for net_type in range(2, 3):\n for times in range(0,100):\n print(\"\\x1b[32m####Starting {} time test\\x1b[0m\".format(times))\n t1, t2, t3 = do_test(peroids, util, gran, net_type, times)\n with open(\"./output/normal/calu_time_size_{}.txt\".format(net_type), \"a\") as f:\n f.writelines('%.2f\\t%.2f\\t%.2f\\n'%(t1, t2, t3))\n f.close()\n \n print(\"#### Test Done! ####\")\n\n while True:\n pass","sub_path":"bench_test.py","file_name":"bench_test.py","file_ext":"py","file_size_in_byte":5307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"643836813","text":"import heapq\r\nimport sys\r\ninput = sys.stdin.readline\r\nINF = int(1e9)\r\nn,m = map(int,input().split())\r\nstart = int(input())\r\ngraph = [[] for i in range(n+1)]\r\ndistance = [INF] * (n+1)\r\n\r\nfor _ in range(m):\r\n x,y,w = map(int, input().split())\r\n graph[x].append((y,w))\r\n\r\ndef dijkstra(start):\r\n q = []\r\n heapq.heappush(q,(start,0))\r\n distance[start] = 0\r\n while q:\r\n now, dist = heapq.heappop(q)\r\n if distance[now] < dist:\r\n continue\r\n for i in graph[now]:\r\n cost = dist + i[1]\r\n if cost < distance[i[0]]:\r\n distance[i[0]] = cost\r\n heapq.heappush(q,(i[0],cost))\r\ndijkstra(start)\r\nfor i in range(1,n+1):\r\n if distance[i] == INF:\r\n print(\"INF\")\r\n else:\r\n print(distance[i])\r\n\r\n'''\r\n6 11\r\n1\r\n1 2 2\r\n1 3 5\r\n1 4 1\r\n2 3 3\r\n2 4 2\r\n3 2 3\r\n3 6 5\r\n4 3 3\r\n4 5 1\r\n5 3 1\r\n5 6 2\r\n'''","sub_path":"Python/Code2011/201117_DijkstraShortestPath.py","file_name":"201117_DijkstraShortestPath.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"616736554","text":"import sys\nimport semver\nimport logging\n\nimport utils.gql as gql\nimport utils.threaded as threaded\nimport utils.promtool as promtool\nimport reconcile.openshift_resources_base as orb\nimport reconcile.queries as queries\n\nQONTRACT_INTEGRATION = 'prometheus_rules_validator'\nQONTRACT_INTEGRATION_VERSION = semver.format_version(0, 1, 0)\n\n\ndef check_rule(rule):\n rule['check_result'] = promtool.check_rule(rule['spec'])\n return rule\n\n\ndef run(dry_run, thread_pool_size=10, cluster_name=None):\n orb.QONTRACT_INTEGRATION = QONTRACT_INTEGRATION\n orb.QONTRACT_INTEGRATION_VERSION = QONTRACT_INTEGRATION_VERSION\n\n gqlapi = gql.get_api()\n rules_paths = queries.get_prometheus_rules_paths()\n\n rules = []\n for n in gqlapi.query(orb.NAMESPACES_QUERY)['namespaces']:\n if cluster_name and n['cluster']['name'] != cluster_name:\n continue\n\n if not n['managedResourceTypes'] or \\\n 'PrometheusRule' not in n['managedResourceTypes']:\n continue\n\n openshift_resources = n.get('openshiftResources')\n if not openshift_resources:\n logging.warning(\"No openshiftResources defined for namespace\"\n f\"{n['name']} in cluster {n['cluster']['name']}\")\n continue\n\n for r in openshift_resources:\n if r['path'] not in rules_paths:\n continue\n\n openshift_resource = orb.fetch_openshift_resource(r, n)\n rules.append({'path': r['path'],\n 'spec': openshift_resource.body['spec'],\n 'namespace': n['name'],\n 'cluster': n['cluster']['name']})\n\n failed = [r for r in threaded.run(check_rule, rules, thread_pool_size)\n if not r['check_result']]\n\n if failed:\n for f in failed:\n logging.warning(f\"Error in rule {f['path']} from namespace \"\n f\"{f['namespace']} in cluster {f['cluster']}: \"\n f\"{f['check_result']}\")\n\n sys.exit(1)\n","sub_path":"reconcile/prometheus_rules_validator.py","file_name":"prometheus_rules_validator.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"644692095","text":"import pytest\nfrom pymap3d.vincenty import vreckon, vdist\nfrom numpy.testing import assert_allclose\nimport pymap3d as pm\ntry: # for validation\n import pyproj\nexcept ImportError:\n pyproj = None\n\naz = 38\nsr = 3e3\nlla0 = (42, -82, 200)\n\n\ndef test_vincenty():\n\n lat2, lon2, a21 = vreckon(10, 20, sr, az)\n assert_allclose((lat2, lon2, a21),\n (10.02137267, 20.016847, 218.0029286))\n\n assert_allclose(vdist(10, 20, lat2, lon2), (sr, az, a21))\n\n\n@pytest.mark.skipif(pyproj is None, reason=\"PyProj not installed\")\ndef test_compare_vicenty():\n lat2, lon2, a21 = vreckon(10, 20, sr, az)\n\n p4lon, p4lat, p4a21 = pyproj.Geod(ellps='WGS84').fwd(lon2, lat2, az, sr)\n assert_allclose((p4lon, p4lat, p4a21 % 360.), (lon2, lat2, a21), rtol=0.0025)\n\n p4az, p4a21, p4sr = pyproj.Geod(ellps='WGS84').inv(20, 10, lon2, lat2)\n assert_allclose((p4az, p4a21 % 360., p4sr), (az, a21, sr))\n\n\n@pytest.mark.skipif(pyproj is None, reason=\"PyProj not installed\")\ndef test_compare_geodetic():\n xyz = pm.geodetic2ecef(*lla0)\n\n ecef = pyproj.Proj(proj='geocent', ellps='WGS84', datum='WGS84')\n lla = pyproj.Proj(proj='latlong', ellps='WGS84', datum='WGS84')\n\n assert_allclose(pyproj.transform(lla, ecef, lla0[1], lla0[0], lla0[2]), xyz)\n assert_allclose(pyproj.transform(ecef, lla, *xyz),\n (lla0[1], lla0[0], lla0[2]))\n\n\nif __name__ == '__main__':\n pytest.main()\n","sub_path":"tests/test_pyproj_compare.py","file_name":"test_pyproj_compare.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"128461352","text":"from core.models import Product\n\nfrom .city import sample_city\nfrom .country import sample_country\n\n\ndef sample_product_data(**params):\n defaults = {\n \"category\": \"personal-training\",\n \"title\": \"test\",\n \"description\": \"test\",\n \"is_virtual\": False,\n \"price\": 20.00,\n \"countries\": [\n sample_country()\n ],\n \"cities\": [\n sample_city()\n ]\n }\n\n defaults.update(params)\n return defaults\n\n\ndef sample_product(user, **params):\n defaults = sample_product_data(**params)\n defaults[\"user\"] = user\n return Product.objects.create_product(**defaults)\n","sub_path":"src/tests/utils/core/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"507632753","text":"# pylint: disable=print-call\nimport base64\nimport os\nimport subprocess\nimport time\nfrom contextlib import contextmanager\n\nimport kubernetes\nimport pytest\nimport six\nimport yaml\nfrom dagster_k8s.utils import wait_for_pod\nfrom dagster_test.test_project import test_project_docker_image\n\nfrom dagster import check\nfrom dagster.utils import git_repository_root\n\nfrom .integration_utils import IS_BUILDKITE, check_output, get_test_namespace, image_pull_policy\n\nTEST_CONFIGMAP_NAME = 'test-env-configmap'\nTEST_SECRET_NAME = 'test-env-secret'\n\n\n@pytest.fixture(scope='session')\ndef helm_namespace(\n cluster_provider, request\n): # pylint: disable=unused-argument, redefined-outer-name\n '''If an existing Helm chart namespace is specified via pytest CLI with the argument\n --existing-helm-namespace, we will use that chart.\n\n Otherwise, provision a test namespace and install Helm chart into that namespace.\n\n Yields the Helm chart namespace.\n '''\n\n existing_helm_namespace = request.config.getoption('--existing-helm-namespace')\n\n if existing_helm_namespace:\n yield existing_helm_namespace\n\n else:\n # Never bother cleaning up on Buildkite\n if IS_BUILDKITE:\n should_cleanup = False\n # Otherwise, always clean up unless --no-cleanup specified\n else:\n should_cleanup = not request.config.getoption('--no-cleanup')\n\n with test_namespace(should_cleanup) as namespace:\n with helm_test_resources(namespace, should_cleanup):\n docker_image = test_project_docker_image()\n with helm_chart(namespace, docker_image, should_cleanup):\n print('Helm chart successfully installed in namespace %s' % namespace)\n yield namespace\n\n\n@contextmanager\ndef test_namespace(should_cleanup=True):\n # Will be something like dagster-test-3fcd70 to avoid ns collisions in shared test environment\n namespace = get_test_namespace()\n\n print('--- \\033[32m:k8s: Creating test namespace %s\\033[0m' % namespace)\n kube_api = kubernetes.client.CoreV1Api()\n\n try:\n print('Creating namespace %s' % namespace)\n kube_namespace = kubernetes.client.V1Namespace(\n metadata=kubernetes.client.V1ObjectMeta(name=namespace)\n )\n kube_api.create_namespace(kube_namespace)\n yield namespace\n\n finally:\n # Can skip this step as a time saver when we're going to destroy the cluster anyway, e.g.\n # w/ a kind cluster\n if should_cleanup:\n print('Deleting namespace %s' % namespace)\n kube_api.delete_namespace(name=namespace)\n\n\n@contextmanager\ndef helm_test_resources(namespace, should_cleanup=True):\n '''Create a couple of resources to test Helm interaction w/ pre-existing resources.\n '''\n check.str_param(namespace, 'namespace')\n check.bool_param(should_cleanup, 'should_cleanup')\n\n try:\n print(\n 'Creating k8s test objects ConfigMap %s and Secret %s'\n % (TEST_CONFIGMAP_NAME, TEST_SECRET_NAME)\n )\n kube_api = kubernetes.client.CoreV1Api()\n\n configmap = kubernetes.client.V1ConfigMap(\n api_version='v1',\n kind='ConfigMap',\n data={'TEST_ENV_VAR': 'foobar'},\n metadata=kubernetes.client.V1ObjectMeta(name=TEST_CONFIGMAP_NAME),\n )\n kube_api.create_namespaced_config_map(namespace=namespace, body=configmap)\n\n # Secret values are expected to be base64 encoded\n secret_val = six.ensure_str(base64.b64encode(six.ensure_binary('foobar')))\n secret = kubernetes.client.V1Secret(\n api_version='v1',\n kind='Secret',\n data={'TEST_SECRET_ENV_VAR': secret_val},\n metadata=kubernetes.client.V1ObjectMeta(name=TEST_SECRET_NAME),\n )\n kube_api.create_namespaced_secret(namespace=namespace, body=secret)\n\n yield\n\n finally:\n # Can skip this step as a time saver when we're going to destroy the cluster anyway, e.g.\n # w/ a kind cluster\n if should_cleanup:\n kube_api.delete_namespaced_config_map(name=TEST_CONFIGMAP_NAME, namespace=namespace)\n kube_api.delete_namespaced_secret(name=TEST_SECRET_NAME, namespace=namespace)\n\n\n@contextmanager\ndef helm_chart(namespace, docker_image, should_cleanup=True):\n '''Install dagster-k8s helm chart.\n '''\n check.str_param(namespace, 'namespace')\n check.str_param(docker_image, 'docker_image')\n check.bool_param(should_cleanup, 'should_cleanup')\n\n print('--- \\033[32m:helm: Installing Helm chart\\033[0m')\n\n try:\n repository, tag = docker_image.split(':')\n pull_policy = image_pull_policy()\n\n helm_config = {\n 'dagit': {\n 'image': {'repository': repository, 'tag': tag, 'pullPolicy': pull_policy},\n 'env': {'TEST_SET_ENV_VAR': 'test_dagit_env_var'},\n 'env_config_maps': [TEST_CONFIGMAP_NAME],\n 'env_secrets': [TEST_SECRET_NAME],\n 'livenessProbe': {\n 'tcpSocket': {'port': 'http'},\n 'periodSeconds': 20,\n 'failureThreshold': 3,\n },\n 'startupProbe': {\n 'tcpSocket': {'port': 'http'},\n 'failureThreshold': 6,\n 'periodSeconds': 10,\n },\n },\n 'flower': {\n 'livenessProbe': {\n 'tcpSocket': {'port': 'flower'},\n 'periodSeconds': 20,\n 'failureThreshold': 3,\n },\n 'startupProbe': {\n 'tcpSocket': {'port': 'flower'},\n 'failureThreshold': 6,\n 'periodSeconds': 10,\n },\n },\n 'celery': {\n 'image': {'repository': repository, 'tag': tag, 'pullPolicy': pull_policy},\n # https://github.com/dagster-io/dagster/issues/2671\n # 'extraWorkerQueues': [{'name': 'extra-queue-1', 'replicaCount': 1},],\n 'livenessProbe': {\n 'exec': {\n 'command': [\n '/bin/sh',\n '-c',\n 'celery status -A dagster_celery_k8s.app -b {broker_url} | grep \"{HOSTNAME}:.*OK\"'.format(\n broker_url='some_broker_url', HOSTNAME='some_hostname',\n ),\n ]\n },\n 'initialDelaySeconds': 15,\n 'periodSeconds': 10,\n 'timeoutSeconds': 10,\n 'successThreshold': 1,\n 'failureThreshold': 3,\n },\n },\n 'pipeline_run': {\n 'image': {'repository': repository, 'tag': tag, 'pullPolicy': pull_policy},\n 'env': {'TEST_SET_ENV_VAR': 'test_pipeline_run_env_var'},\n 'env_config_maps': [TEST_CONFIGMAP_NAME],\n 'env_secrets': [TEST_SECRET_NAME],\n },\n 'scheduler': {'k8sEnabled': 'true', 'schedulerNamespace': namespace},\n 'serviceAccount': {'name': 'dagit-admin'},\n 'postgresqlPassword': 'test',\n 'postgresqlDatabase': 'test',\n 'postgresqlUser': 'test',\n }\n helm_config_yaml = yaml.dump(helm_config, default_flow_style=False)\n\n dagster_k8s_path = os.path.join(\n git_repository_root(), 'python_modules', 'libraries', 'dagster-k8s'\n )\n\n helm_cmd = [\n 'helm',\n 'install',\n '--namespace',\n namespace,\n '-f',\n '-',\n 'dagster',\n os.path.join(dagster_k8s_path, 'helm', 'dagster'),\n ]\n\n print('Running Helm Install: \\n', ' '.join(helm_cmd), '\\nWith config:\\n', helm_config_yaml)\n\n p = subprocess.Popen(\n helm_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n stdout, stderr = p.communicate(six.ensure_binary(helm_config_yaml))\n print('Helm install completed with stdout: ', stdout)\n print('Helm install completed with stderr: ', stderr)\n assert p.returncode == 0\n\n # Wait for Dagit pod to be ready (won't actually stay up w/out js rebuild)\n kube_api = kubernetes.client.CoreV1Api()\n\n print('Waiting for Dagit pod to be ready...')\n dagit_pod = None\n while dagit_pod is None:\n pods = kube_api.list_namespaced_pod(namespace=namespace)\n pod_names = [p.metadata.name for p in pods.items if 'dagit' in p.metadata.name]\n if pod_names:\n dagit_pod = pod_names[0]\n time.sleep(1)\n\n # Wait for Celery worker queues to become ready\n print('Waiting for celery workers')\n pods = kubernetes.client.CoreV1Api().list_namespaced_pod(namespace=namespace)\n pod_names = [p.metadata.name for p in pods.items if 'celery-workers' in p.metadata.name]\n for pod_name in pod_names:\n print('Waiting for Celery worker pod %s' % pod_name)\n wait_for_pod(pod_name, namespace=namespace)\n\n yield\n\n finally:\n # Can skip this step as a time saver when we're going to destroy the cluster anyway, e.g.\n # w/ a kind cluster\n if should_cleanup:\n print('Uninstalling helm chart')\n check_output(\n ['helm', 'uninstall', 'dagster', '--namespace', namespace], cwd=dagster_k8s_path,\n )\n","sub_path":"integration_tests/python_modules/dagster-k8s-test-infra/dagster_k8s_test_infra/helm.py","file_name":"helm.py","file_ext":"py","file_size_in_byte":9635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"119150315","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"accounts/login/\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register_view, name=\"register\"),\n path(\"menu\", views.showform, name=\"menu\"),\n path(\"cart\", views.order_view),\n]\n","sub_path":"project3/orders/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"484268603","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport os, re\nfrom sentence import Sentence\nimport logging\nimport re\nfrom data_prep import *\nfrom file_io import *\n\n\nlogging.basicConfig(filename='glm_parser.log',\n level=logging.DEBUG,\n format='%(asctime)s %(levelname)s: %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p')\n\ndef getClassFromModule(attr_name, module_path, module_name,\n silent=False):\n \"\"\"\n This procedure is used by argument processing. It returns a class object\n given a module path and attribute name.\n\n Basically what it does is to find the module using module path, and then\n iterate through all objects inside that module's namespace (including those\n introduced by import statements). For each object in the name space, this\n function would then check existence of attr_name, i.e. the desired interface\n name (could be any attribute fetch-able by getattr() built-in). If and only if\n one such desired interface exists then the object containing that interface\n would be returned, which is mostly a class, but could theoretically be anything\n object instance with a specified attribute.\n\n If import error happens (i.e. module could not be found/imported), or there is/are\n no/more than one interface(s) existing, then exception will be raised.\n\n :param attr_name: The name of the desired interface\n :type attr_name: str\n :param module_path: The path of the module. Relative to src/\n :type module_path: str\n :param module_name: Name of the module e.g. file name\n :type module_name: str\n :param silent: Whether to report existences of interface objects\n :return: class object\n \"\"\"\n # Load module by import statement (mimic using __import__)\n # We first load the module (i.e. directory) and then fetch its attribute (i.e. py file)\n module_obj = getattr(__import__(module_path + '.' + module_name,\n globals(), # Current global\n locals(), # Current local\n [], # I don't know what is this\n -1), module_name)\n intf_class_count = 0\n intf_class_name = None\n for obj_name in dir(module_obj):\n if hasattr(getattr(module_obj, obj_name), attr_name):\n intf_class_count += 1\n intf_class_name = obj_name\n if silent is False:\n print(\"Interface object %s detected\\n\\t with interface %s\" %\n (obj_name, attr_name))\n if intf_class_count < 1:\n raise ImportError(\"Interface object with attribute %s not found\" % (attr_name, ))\n elif intf_class_count > 1:\n raise ImportError(\"Could not resolve arbitrary on attribute %s\" % (attr_name, ))\n else:\n class_obj = getattr(module_obj, intf_class_name)\n return class_obj\n\nclass DataPool():\n \"\"\"\n Data object that holds all sentences (dependency trees) and provides\n interface for loading data from the disk and retrieving them using an\n index.\n\n Data are classified into sections when stored in the disk, but we\n do not preserve such structural information, and all sentences\n will be loaded and \"flattened\" to be held in a single list.\n\n The instance maintains a current_index variable, which is used to\n locate the last sentence object we have read. Calling get_next()\n method will increase this by 1, and calling has_next() will test\n this index against the total number. The value of the index is\n persistent during get_next() and has_next() calls, and will only\n be reset to initial value -1 when reset() is called (manually or\n during init).\n \"\"\"\n def __init__( self,\n section_regex = '',\n data_path = \"./penn-wsj-deps/\",\n fgen = None,\n format_path = None,\n textString = None,\n format_list = None,\n comment_sign = '',\n prep_path = 'data/prep/',\n shardNum = 1,\n sc = None,\n hadoop = False):\n\n \"\"\"\n Initialize the Data set\n\n :param section_regex: the sections to be used.\n A regular expression that indicates which sections to be used e.g.\n (0[0-9])|(1[0-9])|(2[0-1])/.*tab\n :type section_regex: str\n\n :param data_path: the relative or absolute path to the 'penn-wsj-deps' folder\n (including \"penn-wsj-deps\")\n :type data_path: str\n\n :param format_path: the file that describes the file format for the type of data\n :type format_path: str\n \"\"\"\n if isinstance(fgen, basestring):\n self.fgen = getClassFromModule('get_local_vector', 'feature', fgen)\n else:\n self.fgen = fgen\n self.hadoop = hadoop\n self.sc = sc\n self.shardNum = shardNum\n self.reset_all()\n\n if textString is not None:\n self.load_stringtext(textString,format_list,comment_sign)\n else:\n self.data_path = data_path\n self.section_regex = section_regex\n self.prep_path = prep_path\n self.dataPrep = DataPrep(dataPath = self.data_path,\n dataRegex = self.section_regex,\n shardNum = self.shardNum,\n targetPath = self.prep_path,\n sparkContext = sc)\n self.load(format_path, sc)\n return\n\n def loadedPath(self):\n if self.dataPrep:\n if self.hadoop == True:\n return self.dataPrep.hadoopPath()\n else:\n return self.dataPrep.localPath()\n else:\n raise RuntimeError(\"DATAPOOL [ERROR]: Data has not been loaded by DataPrep, cannot retrieve data path.\")\n return\n\n def load_stringtext(self, textString, format_list, comment_sign):\n lines = textString.splitlines()\n column_list = {}\n for field in format_list:\n if not(field.isdigit()):\n column_list[field] = []\n\n length = len(format_list)\n\n for line in lines:\n entity = line.split()\n if len(entity) == length and entity[0] != comment_sign:\n for i in range(length):\n if not(format_list[i].isdigit()):\n column_list[format_list[i]].append(str(entity[i].encode('utf-8')))\n else:\n if not(format_list[0].isdigit()) and column_list[format_list[0]] != []:\n sent = Sentence(column_list, format_list, self.fgen)\n self.data_list.append(sent)\n\n column_list = {}\n\n for field in format_list:\n if not (field.isdigit()):\n column_list[field] = []\n\n def reset_all(self):\n \"\"\"\n Reset the index variables and the data list.\n\n Restores the instance to a state when no sentence has been read\n \"\"\"\n self.reset_index()\n self.data_list = []\n\n return\n\n def reset_index(self):\n \"\"\"\n Reset the index variable to the very beginning of\n sentence list\n \"\"\"\n self.current_index = -1\n\n def has_next_data(self):\n \"\"\"\n Returns True if there is still sentence not read. This call\n does not advence data pointer. Call to get_next_data() will\n do the job.\n\n :return: False if we have reaches the end of data_list\n True otherwise\n \"\"\"\n i = self.current_index + 1\n if i >= 0 and i < len(self.data_list):\n return True\n else:\n return False\n\n def get_next_data(self):\n \"\"\"\n Return the next sentence object, which is previously read\n from disk files.\n\n This method does not perform index checking, so please make sure\n the internal index is valid by calling has_next_data(), or an exception\n will be raise (which would be definitely not what you want)\n \"\"\"\n if(self.has_next_data()):\n self.current_index += 1\n # Logging how many entries we have supplied\n if self.current_index % 1000 == 0:\n logging.debug(\"Data finishing %.2f%% ...\" %\n (100 * self.current_index/len(self.data_list), ))\n\n return self.data_list[self.current_index]\n raise IndexError(\"Run out of data while calling get_next_data()\")\n\n def get_format_list(self):\n if self.field_name_list == []:\n raise RuntimeError(\"DATAPOOL [ERROR]: format_list empty\")\n return self.field_name_list\n\n def get_comment_sign(self):\n return self.comment_sign\n\n def load(self, formatPath, sparkContext=None):\n \"\"\"\n For each section in the initializer, iterate through all files\n under that section directory, and load the content of each\n individual file into the class instance.\n\n This method should be called after section regex has been initalized\n and before any get_data method is called.\n \"\"\"\n logging.debug(\"Loading data...\")\n print(\"Loading data...\")\n\n # Load format file\n print(\"Loading dataFormat from: \" + formatPath)\n if self.hadoop == True:\n fformat = fileRead(formatPath, sparkContext=sparkContext)\n else:\n fformat = open(formatPath)\n\n self.field_name_list = []\n self.comment_sign = ''\n\n remaining_field_names = 0\n for line in fformat:\n format_line = line.strip().split()\n\n if remaining_field_names > 0:\n self.field_name_list.append(line.strip())\n remaining_field_names -= 1\n\n if format_line[0] == \"field_names:\":\n remaining_field_names = int(format_line[1])\n\n if format_line[0] == \"comment_sign:\":\n self.comment_sign = format_line[1]\n\n if self.field_name_list == []:\n raise RuntimeError(\"DATAPOOL [ERROR]: format file read failure\")\n\n if self.hadoop == False:\n fformat.close()\n\n # Load data\n if self.hadoop == True:\n self.dataPrep.loadHadoop()\n else:\n self.dataPrep.loadLocal()\n\n # Add data to data_list\n # If using yarn mode, local data will not be loaded\n if self.hadoop == False:\n for dirName, subdirList, fileList in os.walk(self.dataPrep.localPath()):\n for file_name in fileList:\n file_path = \"%s/%s\" % ( str(dirName), str(file_name) )\n self.data_list += self.get_data_list(file_path)\n else:\n aRdd = sparkContext.textFile(self.dataPrep.hadoopPath()).cache()\n tmp = aRdd.collect()\n tmpStr = ''.join(str(e)+\"\\n\" for e in tmp)\n self.load_stringtext(textString = tmpStr,\n format_list = self.field_name_list,\n comment_sign = self.comment_sign)\n return\n\n\n def get_data_list(self, file_path):\n \"\"\"\n Form the DependencyTree list from the specified file.\n\n :param file_path: the path to the data file\n :type file_path: str\n\n :return: a list of DependencyTree in the specified file\n :rtype: list(Sentence)\n \"\"\"\n\n f = open(file_path)\n data_list = []\n\n column_list = {}\n\n for field in self.field_name_list:\n if not(field.isdigit()):\n column_list[field] = []\n\n length = len(self.field_name_list)\n\n for entity in f:\n entity = entity[:-1].split()\n if len(entity) == length and entity[0] != self.comment_sign:\n for i in range(length):\n if not(self.field_name_list[i].isdigit()):\n column_list[self.field_name_list[i]].append(entity[i])\n\n else:\n # Prevent any non-mature (i.e. trivial) sentence structure\n if not(self.field_name_list[0].isdigit()) and column_list[self.field_name_list[0]] != []:\n\n # Add \"ROOT\" for word and pos here\n sent = Sentence(column_list, self.field_name_list, self.fgen)\n data_list.append(sent)\n\n column_list = {}\n\n for field in self.field_name_list:\n if not (field.isdigit()):\n column_list[field] = []\n\n f.close()\n\n return data_list\n\n def get_sent_num(self):\n return len(self.data_list)\n","sub_path":"src/data/data_pool.py","file_name":"data_pool.py","file_ext":"py","file_size_in_byte":12898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"105794685","text":"# This adapts sys.path to include all relevant packages\nimport context\n\n# our own packages\nfrom base import TestSystemCalcBase\n\n# Monkey patching for unit tests\nimport patches\n\nclass TestHubSystem(TestSystemCalcBase):\n\tdef __init__(self, methodName='runTest'):\n\t\tTestSystemCalcBase.__init__(self, methodName)\n\n\tdef setUp(self):\n\t\tTestSystemCalcBase.setUp(self)\n\t\tself._add_device('com.victronenergy.battery.ttyO1',\n\t\t\tproduct_name='battery',\n\t\t\tvalues={\n\t\t\t\t'/Dc/0/Voltage': 12.15,\n\t\t\t\t'/Dc/0/Current': 5.3,\n\t\t\t\t'/Dc/0/Power': 65,\n\t\t\t\t'/Dc/0/Temperature': 25,\n\t\t\t\t'/Soc': 15.3,\n\t\t\t\t'/DeviceInstance': 0})\n\t\tself._add_device('com.victronenergy.battery.ttyO2',\n\t\t\tproduct_name='battery',\n\t\t\tvalues={\n\t\t\t\t'/Dc/0/Voltage': 12.15,\n\t\t\t\t'/Dc/0/Current': 5.3,\n\t\t\t\t'/Dc/0/Power': 65,\n\t\t\t\t'/Dc/0/Temperature': 25,\n\t\t\t\t'/Soc': 15.3,\n\t\t\t\t'/DeviceInstance': 1,\n\t\t\t\t'/CustomName': 'Sled battery'})\n\n\tdef test_batteries_path(self):\n\t\tself._update_values(5000)\n\t\tdata = self._service._dbusobjects['/Batteries']\n\t\tself.assertTrue(len(data) == 2)\n\n\t\t# Check battery service selection\n\t\tdi = {b['instance']: b['active_battery_service'] for b in data}\n\t\tself.assertEqual(di, {0: True, 1: False})\n\n\t\t# Check customname\n\t\tdi = {b['instance']: b['name'] for b in data}\n\t\tself.assertEqual(di, {0: \"battery\", 1: \"Sled battery\"})\n\n\t\tfor b in data:\n\t\t\tfor f in (\"id\", \"voltage\", \"current\", \"name\"):\n\t\t\t\tassert f in b\n","sub_path":"tests/batterydata_test.py","file_name":"batterydata_test.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"169269243","text":"# Alexandros Gidarakos - https://www.linkedin.com/in/alexandrosgidarakos\n# My solution to MITx 6.00.1x Lecture 5 Problem 9\n\ndef semordnilap(str1, str2):\n '''\n str1: a string\n str2: a string\n\n returns: True if str1 and str2 are semordnilap;\n False otherwise.\n '''\n\n len1 = len(str1)\n len2 = len(str2)\n\n if len1 != len2:\n return False\n\n if len1 == 2:\n return str1[0] == str2[1] and str1[1] == str2[0]\n elif str1[0] == str2[-1] and str1[-1] == str2[0]:\n return semordnilap(str1[1:], str2[:-1])\n else:\n return False\n","sub_path":"lecture-5/lecture-5-problem-9.py","file_name":"lecture-5-problem-9.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"39387064","text":"import tensorflow as tf\nimport gym\n\nfrom baselines.common.mpi_running_mean_std import RunningMeanStd\nimport baselines.common.tf_util as tf_util\nfrom baselines.common.distributions import make_proba_dist_type\n\n\nclass BasePolicy(object):\n def __init__(self, placeholders=None):\n \"\"\"\n A base policy object for PPO1\n\n :param placeholders: (dict) To feed existing placeholders if needed\n \"\"\"\n super(BasePolicy, self).__init__()\n self.sess = None\n self.pdtype = None\n self._act = None\n self.scope = None\n self.obs_ph = None\n self.stochastic_ph = None\n\n if placeholders is not None:\n self.obs_ph = placeholders.get(\"obs\", None)\n self.stochastic_ph = placeholders.get(\"stochastic\", None)\n\n def get_obs_and_pdtype(self, ob_space, ac_space):\n \"\"\"\n Initialize probability distribution and get observation placeholder.\n\n :param ob_space: (Gym Spaces) the observation space\n :param ac_space: (Gym Spaces) the action space\n \"\"\"\n assert isinstance(ob_space, gym.spaces.Box)\n\n self.pdtype = pdtype = make_proba_dist_type(ac_space)\n sequence_length = None\n\n if self.obs_ph is None:\n self.obs_ph = tf.placeholder(dtype=tf.float32, shape=[sequence_length] + list(ob_space.shape), name=\"ob\")\n\n return self.obs_ph, pdtype\n\n def act(self, stochastic, obs):\n \"\"\"\n Get the action from the policy, using the observation\n\n :param stochastic: (bool) whether or not to use a stochastic or deterministic policy\n :param obs: (TensorFlow Tensor or numpy Number) the observation\n :return: (numpy Number, numpy Number) the action and value function\n \"\"\"\n ac1, vpred1 = self._act(stochastic, obs[None], sess=self.sess)\n return ac1[0], vpred1[0]\n\n def get_variables(self):\n \"\"\"\n Get all the policy's variables\n\n :return: ([TensorFlow Tensor]) the variables of the network\n \"\"\"\n return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, self.scope)\n\n def get_trainable_variables(self):\n \"\"\"\n Get the policy's trainable variables\n\n :return: ([TensorFlow Tensor]) the trainable variables of the network\n \"\"\"\n return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope)\n\n @classmethod\n def get_initial_state(cls):\n \"\"\"\n Get the initial state\n\n :return: ([numpy Number]) the initial state\n \"\"\"\n return []\n\n\nclass MlpPolicy(BasePolicy):\n recurrent = False\n\n def __init__(self, name, *args, sess=None, reuse=False, placeholders=None, **kwargs):\n \"\"\"\n A MLP policy object for PPO1\n\n :param name: (str) type of the policy (lin, logits, value)\n :param ob_space: (Gym Space) The observation space of the environment\n :param ac_space: (Gym Space) The action space of the environment\n :param hid_size: (int) the size of the hidden layers\n :param num_hid_layers: (int) the number of hidden layers\n :param sess: (TensorFlow session) The current TensorFlow session containing the variables.\n :param reuse: (bool) If the policy is reusable or not\n :param placeholders: (dict) To feed existing placeholders if needed\n :param gaussian_fixed_var: (bool) enable gaussian sampling with fixed variance, when using continuous actions\n \"\"\"\n super(MlpPolicy, self).__init__(placeholders=placeholders)\n self.reuse = reuse\n self.name = name\n self._init(*args, **kwargs)\n self.scope = tf.get_variable_scope().name\n self.sess = sess\n\n def _init(self, ob_space, ac_space, hid_size, num_hid_layers, gaussian_fixed_var=True):\n \"\"\"\n\n :param ob_space: (Gym Space) The observation space of the environment\n :param ac_space: (Gym Space) The action space of the environment\n :param hid_size: (int) the size of the hidden layers\n :param num_hid_layers: (int) the number of hidden layers\n :param gaussian_fixed_var: (bool) enable gaussian sampling with fixed variance, when using continuous actions\n \"\"\"\n obs, pdtype = self.get_obs_and_pdtype(ob_space, ac_space)\n\n with tf.variable_scope(self.name + \"/obfilter\", reuse=self.reuse):\n self.ob_rms = RunningMeanStd(shape=ob_space.shape)\n\n with tf.variable_scope(self.name + '/vf', reuse=self.reuse):\n obz = tf.clip_by_value((obs - self.ob_rms.mean) / self.ob_rms.std, -5.0, 5.0)\n last_out = obz\n for i in range(num_hid_layers):\n last_out = tf.nn.tanh(tf.layers.dense(last_out, hid_size, name=\"fc%i\" % (i + 1),\n kernel_initializer=tf_util.normc_initializer(1.0)))\n self.vpred = tf.layers.dense(last_out, 1, name='final',\n kernel_initializer=tf_util.normc_initializer(1.0))[:, 0]\n\n with tf.variable_scope(self.name + '/pol', reuse=self.reuse):\n last_out = obz\n for i in range(num_hid_layers):\n last_out = tf.nn.tanh(tf.layers.dense(last_out, hid_size, name='fc%i' % (i + 1),\n kernel_initializer=tf_util.normc_initializer(1.0)))\n if gaussian_fixed_var and isinstance(ac_space, gym.spaces.Box):\n mean = tf.layers.dense(last_out, pdtype.param_shape()[0] // 2, name='final',\n kernel_initializer=tf_util.normc_initializer(0.01))\n logstd = tf.get_variable(name=\"logstd\", shape=[1, pdtype.param_shape()[0] // 2],\n initializer=tf.zeros_initializer())\n pdparam = tf.concat([mean, mean * 0.0 + logstd], axis=1)\n else:\n pdparam = tf.layers.dense(last_out, pdtype.param_shape()[0], name='final',\n kernel_initializer=tf_util.normc_initializer(0.01))\n\n self.proba_distribution = pdtype.proba_distribution_from_flat(pdparam)\n\n self.state_in = []\n self.state_out = []\n\n if self.stochastic_ph is None:\n self.stochastic_ph = tf.placeholder(dtype=tf.bool, shape=())\n action = tf_util.switch(self.stochastic_ph, self.proba_distribution.sample(), self.proba_distribution.mode())\n self._act = tf_util.function([self.stochastic_ph, obs], [action, self.vpred])\n","sub_path":"baselines/ppo1/mlp_policy.py","file_name":"mlp_policy.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"445601620","text":"\nimport numpy as np\n\nfrom scipy import sparse\n\nclass LabelVectorizer(object):\n\n def __init__(self, labels, dim=100):\n self.labels = labels\n self.dim = dim\n\n def vectorize(self, word_list):\n rows = []\n cols = []\n data = []\n\n if len(word_list) is not 0:\n norm = 1 / len(word_list)\n for w_id in word_list:\n label = self.labels[w_id]\n rows.append(0)\n cols.append(label)\n data.append(norm)\n\n v = sparse.coo_matrix((data, (rows, cols)), shape=(1, self.dim))\n v.sum_duplicates()\n\n return v.tocsr()\n\n\n #def vectorize(self, word_list):\n # res = np.zeros(self.dim)\n\n # num = len(word_list)\n\n # if num == 0:\n # return res\n\n # for w_id in word_list:\n # res[self.labels[w_id]] += 1\n\n # res /= num\n\n # return res\n","sub_path":"sentiment2/label_vectorizer.py","file_name":"label_vectorizer.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"556025983","text":"import pygame, sys\nx = 0\ny = 0\nred = (255, 0, 0)\nblue = (0, 0, 255)\nblack = (0,0,0)\nxdir = 1\nydir = 1\nwidth = 1000\nheight = 800\npygame.init()\nscreen = pygame.display.set_mode((width, height))\n\nwhile 1:\n event = pygame.event.poll()\n if event.type == pygame.QUIT:\n sys.exit()\n screen.fill(black)\n pygame.draw.line(screen, red, (0, y), (width-1, y))\n pygame.draw.line(screen, blue, (x, 0), (x, height-1))\n x += xdir\n y += ydir\n if x == 0 or x == width-1: \n xdir *= -1\n if y == 0 or y == height-1: \n ydir *= -1\n \n pygame.display.flip()\n","sub_path":"practice/practice7.py","file_name":"practice7.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"626539639","text":"#!/usr/bin/env python3\n# Copyright © 2012-13 Qtrac Ltd. All rights reserved.\n# This program or module is free software: you can redistribute it\n# and/or modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version. It is provided for\n# educational purposes and is distributed in the hope that it will be\n# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n\nfrom Qtrac import coroutine\n\n\ndef main():\n form = Form()\n test_user_interaction_with(form)\n\n\nclass Form:\n\n def __init__(self):\n self.create_widgets()\n self.create_mediator()\n\n\n def create_widgets(self):\n self.nameText = Text()\n self.emailText = Text()\n self.okButton = Button(\"OK\")\n self.cancelButton = Button(\"Cancel\")\n\n\n def create_mediator(self):\n self.mediator = self._update_ui_mediator(self._clicked_mediator())\n for widget in (self.nameText, self.emailText, self.okButton,\n self.cancelButton):\n widget.mediator = self.mediator\n self.mediator.send(None)\n\n\n @coroutine\n def _update_ui_mediator(self, successor=None):\n while True:\n widget = (yield)\n self.okButton.enabled = (bool(self.nameText.text) and\n bool(self.emailText.text))\n if successor is not None:\n successor.send(widget)\n\n\n @coroutine\n def _clicked_mediator(self, successor=None):\n while True:\n widget = (yield)\n if widget == self.okButton:\n print(\"OK\")\n elif widget == self.cancelButton:\n print(\"Cancel\")\n elif successor is not None:\n successor.send(widget)\n\ndef mediated(Class):\n setattr(Class, \"mediator\", None)\n def on_change(self):\n if self.mediator is not None:\n self.mediator.send(self)\n setattr(Class, \"on_change\", on_change)\n return Class\n\n\n@mediated\nclass Button:\n\n def __init__(self, text=\"\"):\n super().__init__()\n self.enabled = True\n self.text = text\n \n\n def click(self):\n if self.enabled:\n self.on_change()\n\n\n def __str__(self):\n return \"Button({!r}) {}\".format(self.text,\n \"enabled\" if self.enabled else \"disabled\")\n\n\n@mediated\nclass Text:\n\n def __init__(self, text=\"\"):\n super().__init__()\n self.__text = text\n \n\n @property\n def text(self):\n return self.__text\n\n\n @text.setter\n def text(self, text):\n if self.text != text:\n self.__text = text\n self.on_change()\n\n\n def __str__(self):\n return \"Text({!r})\".format(self.text)\n\n\ndef test_user_interaction_with(form):\n form.okButton.click() # Ignored because it is disabled\n print(form.okButton.enabled) # False\n form.nameText.text = \"Fred\"\n print(form.okButton.enabled) # False\n form.emailText.text = \"fred@bloggers.com\"\n print(form.okButton.enabled) # True\n form.okButton.click() # OK\n form.emailText.text = \"\"\n print(form.okButton.enabled) # False\n form.cancelButton.click() # Cancel\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Gse/examples/mediator2d.py","file_name":"mediator2d.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"277227990","text":"import os\nimport MeCab\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom sklearn.datasets import load_digits\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import accuracy_score\n\nimport numpy as np\n\n\n\ndef tokenize(text):\n \"\"\" MeCab で分かち書きした結果をトークンとして返す \"\"\"\n wakati = MeCab.Tagger(\"-O wakati\")\n return wakati.parse(text)\n\ntoken_dict = []\n# ひとつひとつファイルを読み込んで\n# ファイル名に対して語彙群のディクショナリを生成する\ntoken_dict.append('あらゆる現実をすべて自分の方へねじ曲げたのだ')\ntoken_dict.append('一週間ばかり、ニューヨークを取材した。')\ntoken_dict.append('テレビゲームやパソコンで、ねじ曲げたのだ')\ntoken_dict.append('ロンドンを取材したい')\ntoken_dict.append('ねじ曲げたいのであった')\n\nlabel = ['true','false','true','false']\n\n\n# scikit-learn の TF-IDF ベクタライザーを使う\ntfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english')\ntfs = tfidf.fit_transform(token_dict)\n\nprint(token_dict)\nprint(tfs.toarray())\n\nrow,col = tfs.shape\npre = tfs[row-1]\ntfs = tfs[:row-1]\n\nC = 1.\nkernel = 'rbf'\ngamma = 0.01\n\nclassifier = SVC(C=C, kernel=kernel, gamma=gamma)\nclassifier.fit(tfs, label)\npred_y = classifier.predict(pre)\nprint(pred_y);","sub_path":"nlclassifier.py","file_name":"nlclassifier.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"473523617","text":"# coding=utf-8\n\nimport lxml.html as html\n\n\nclass CalendarHolidays(object):\n site_url = 'http://www.calend.ru/'\n\n def __init__(self):\n self.holidays = list()\n self._parse_site(self.site_url)\n\n def get_holidays_today(self):\n return self.holidays\n\n def _parse_site(self, url):\n page = html.parse(url).getroot()\n block = page.cssselect('div.famous-date')\n divs = block[0].cssselect('div')\n del divs[0]\n for div in divs:\n a = div.cssselect('a')\n images = div.cssselect('img')\n if a and images:\n item = dict()\n item['name'] = a[0].get('title')\n item['categories'] = list()\n for img in images:\n if img.get('title'):\n item['categories'].append(img.get('title'))\n self.holidays.append(item)","sub_path":"speaker-microservice/calendar_holidays.py","file_name":"calendar_holidays.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"473868239","text":"__author__ = 'Jason'\n\nHistMonth = 6 # Number of months we get historical open, high, low, close data to analyze\nBinA = 18.52 # 1 = 1%\nBinB = 7.31\nBinC = 1.44\nVolDays = 15 # Number of days we look back for determining the volume*price average\nAggPct = 25 # For low div yield stocks, only buy if the price hits a target that it hits AggPct % of the time\nMidPct = 50\nConsPct = 75 # For high div yield stocks, only buy if the price hits a target that it hits ConsPct % of the time\nMinAvgVolClose = 1000000 # Minimum acceptable value of average(vol*close) for a stock\n\nBinA /= 100 # BinA = BinA/100\nBinB /= 100 # BinB = BinB/100\nBinC /= 100 # BinC = BinC/100\n\nimport dropbox\nimport datetime\nimport numpy\nimport json\nimport urllib.request\nimport ystockquote\nimport csv\n\n# Determine the date to grab ex-dividend data from. We want to find the day that is two stock market open days in the\n# future from today.\n# This is done by starting with tomorrow and querying the kimono website for the stocks going ex-div that day. If the\n# stock market is open that day (tomorrow), the ex_date in the data retrieved and my date that I used to query Kimono\n# will match. If the market isn't open that day, they won't match. So I keep incrementing days until the dates match\n# twice (which means today is the Ex-date minus 2 for that day), and continue with those stocks.\nExDateMinus = 0 # number of times the dates match\nBuyDate = 0 # Ex date minus 1 (date to buy the stock on)\ntestdate = datetime.date.today()\nwhile ExDateMinus < 2: # increment until dates match twice\n results = [] # clear results variable (if I didn't do this, it would just append every new query for some reason)\n testdate = testdate + datetime.timedelta(1) # increment the day\n datestr = testdate.strftime('%d%b%Y') # put the date in the correct format for calling kimono\n\n # retrieve stock list from Kimono for the datestr day\n results = json.loads(\n urllib.request.urlopen(\n \"https://www.kimonolabs.com/api/91l4rt90?apikey=EFZQ2bXmUUTQ0mjCq0Nf4YHxJfy2LLPO&kimmodify=1&date=\"\n + datestr).read().decode(\"utf-8\"))\n\n results = results[\"dividends\"]\n\n # Check if the dates match\n if testdate.strftime('%m/%d/%Y') == results[1][\"ex_date\"]:\n ExDateMinus += 1\n if ExDateMinus == 1 and BuyDate == 0:\n BuyDate = testdate.strftime('%m/%d/%Y')\n\nHistDate = testdate - datetime.timedelta(HistMonth*365/12) # Determine the date that we want to look back until for\n # our historical data\nBadWiki = [] # Used to keep track of stock tickers that didn't have info on Yahoo finance\nfor i in results:\n try:\n # Retrieve historical quotes from Yahoo - must convert dates into strings of the correct format, A class and\n # B class stocks must be represented as XXX-A instead of XXX/A\n # This tries to grab data up until the ex-date, but since we are two days out, will grab data up until the\n # most recent day possible\n HistData = ystockquote.get_historical_prices(i[\"symbol\"].replace('/', '-'), HistDate.strftime(\"%Y-%m-%d\"),\n testdate.strftime('%Y-%m-%d'))\n except:\n # If there is no data on yahoo finance for the symbol, we will get an error. Record that error by adding the\n # ticker to the error array and assigning values of -1 to everything we would otherwise calculate.\n BadWiki = numpy.append(BadWiki, i[\"symbol\"])\n i[\"divyield\"] = -1\n i[\"avgvolclose\"] = -1\n i[\"discount\"] = -1\n else:\n # The problem with dictionaries is that they are random, so the dates will not be in order. That means I must\n # sort the dates manually. To do this, I create a list of the dates, taken directly from HistData, and sort\n # them. Once they are sorted, I scroll through that list and grab the corresponding Open, Low, Close, and Volume\n # data and put them into their own lists, so now they are in order from oldest to most recent.\n SortedDates = sorted(HistData.keys())\n OpenData = []\n LowData = []\n CloseData = []\n VolData = []\n for j in SortedDates:\n OpenData = numpy.append(OpenData, float(HistData[j]['Open']))\n LowData = numpy.append(LowData, float(HistData[j]['Low']))\n CloseData = numpy.append(CloseData, float(HistData[j]['Close']))\n VolData = numpy.append(VolData, float(HistData[j]['Volume']))\n NumDays = CloseData.size\n\n # Calculate dividend yield based on ex-day minus 2 (the day this code is run)\n i[\"divyield\"] = i[\"dividend\"] / CloseData[NumDays-1]\n\n # Calculate average vol*(close price) for 'VolDays' prior to the ex-date minus 2\n i[\"avgvolclose\"] = numpy.average(VolData[NumDays-VolDays:] * CloseData[NumDays-VolDays:])\n\n # Calculate buy percentiles (aka discount prices)\n MaxDecrease = (LowData - OpenData) / OpenData\n if i[\"divyield\"] >= BinA: # Least Aggressive\n i[\"discount\"] = numpy.percentile(MaxDecrease, ConsPct)*-1\n elif i[\"divyield\"] >= BinB:\n i[\"discount\"] = numpy.percentile(MaxDecrease, MidPct)*-1\n elif i[\"divyield\"] >= BinC: # Most Aggressive\n i[\"discount\"] = numpy.percentile(MaxDecrease, AggPct)*-1\n else:\n i[\"discount\"] = -1\n\nprint(\"Stocks for which historical data couldn't be retrieved:\")\nprint(BadWiki)\nBadWikiString = \";\".join(BadWiki)\n\n# Make list containing index number of stocks that either didn't show up in Yahoo, had a dividend yield less than\n# specified by BinC, or had an average vol*price of less than MinAvgVolClose\ncounter = 0\nDeleteRows = []\nfor i in results:\n if i[\"discount\"] == -1 or i[\"avgvolclose\"] < MinAvgVolClose:\n DeleteRows = numpy.append(DeleteRows, counter)\n counter += 1\n\n# Delete all stocks that the DeleteRows list specifies (that didn't meet our criteria)\nresults = numpy.delete(results, DeleteRows, axis=0)\n\n# Make a list of all rows that aren't in the top ten dividend yields and delete them to leave us with no more than ten\n# stocks to buy\nDeleteRows = []\ncounter = 0\nfor i in results:\n rank = 1\n for j in results:\n if i[\"divyield\"] < j[\"divyield\"]:\n rank += 1\n if rank > 10:\n DeleteRows = numpy.append(DeleteRows, counter)\n counter += 1\nresults = numpy.delete(results, DeleteRows, axis=0)\n\n# Output the buyable stocks to the .csv file\n\n# create array to paste into csv file\noutputarray = [[0, 0, 0]]\nfor i in results:\n outputarray = numpy.append(outputarray, [[BuyDate, i[\"symbol\"].replace('/', '_'), i[\"discount\"]]], axis=0)\noutputarray = numpy.delete(outputarray, 0, axis=0)\n\nprint(\"Top stocks to buy:\")\nprint(outputarray)\n# print(results)\n\n\n#THIS ERRORS OUT BUT I HAVE NO CLUE WHY\n#with open('C:\\\\Users\\\\Jason\\\\Desktop\\\\daily_buys-1.csv', 'w') as f:\n# reader = csv.reader(f)\n# DailyBuys = list(reader)\n# print(DailyBuys)\n\n\n\n# Useful code bits?\n# Dropbox Access token: hRrnzPLZC6AAAAAAAAAAUDuJoL0chCmHZfrOvvrahagMOxFztgA5BvlfcWFkJ0vf\n# data = data[np.logical_not(np.logical_and(data[:,0] > 20, data[:,0] < 25))]\n\n#Notes:\n# I ran the code at 7:26 pm and it did not show the historical data for that day (only up to the day prior)","sub_path":"GetStockHistoricalData.py","file_name":"GetStockHistoricalData.py","file_ext":"py","file_size_in_byte":7316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"245720654","text":"import ROOT\n\ndef printCanvas(canvas, name, formats, directory):\n for format in formats : \n outFile=directory+\"/\"+name+\".\"+format\n canvas.Print(outFile)\n\ndef drawTGraph(graphs, name, xlabel, ylabel, legend, leftText, rightText, formats, directory, range=None, log_range=None):\n canvas=ROOT.TCanvas(name,name, 550, 400)\n canvas.SetGridx()\n canvas.SetGridy()\n Tleft=ROOT.TLatex(0.125,0.92,leftText)\n Tleft.SetNDC(ROOT.kTRUE) \n Tleft.SetTextSize(0.048)\n #font = Tleft.GetTextFont() \n #TPaveText* Tright=new TPaveText(0.8,0.85,0.945,0.90,\"NDC\") \n #Tright.SetTextFont(font) \n #Tright.AddText(rightText) \n #Tright.SetFillColor(0)\n\n mg = ROOT.TMultiGraph()\n colors = [ ROOT.kRed, ROOT.kMagenta, ROOT.kBlue, ROOT.kCyan+1, ROOT.kGreen+2, ROOT.kOrange+1 ]\n markers = [20, 21, 22, 23, 29, 33, 34]\n for i,graph in enumerate(graphs):\n graph.SetMarkerColor(colors[i])\n graph.SetLineColor(colors[i])\n graph.SetLineWidth(2)\n graph.SetMarkerStyle(markers[i])\n mg.Add(graph)\n mg.Draw(\"AL\")\n mg.GetXaxis().SetTitle(xlabel)\n #mg.GetXaxis().SetTitleFont(font)\n if range:\n mg.GetXaxis().SetRangeUser(range[0][0], range[0][1])\n mg.GetYaxis().SetRangeUser(range[1][0], range[1][1])\n mg.GetYaxis().SetTitle(ylabel)\n #mg.GetYaxis().SetTitleFont(font)\n mg.SetTitle(\"\")\n #legend.SetTextFont(font) \n legend.SetFillColor(10)\n legend.SetFillStyle(0)\n legend.SetLineColor(0)\n legend.SetTextSize(0.035)\n legend.Draw() \n Tleft.Draw() \n #Tright.Draw() \n #canvas.Write() \n printCanvas(canvas, name, formats, directory) \n if log_range:\n mg.GetXaxis().SetRangeUser(log_range[0][0], log_range[0][1])\n mg.GetYaxis().SetRangeUser(log_range[1][0], log_range[1][1])\n\n canvas.SetLogx()\n printCanvas(canvas, name+\"_logX\", formats, directory) \n\n\ndef gStyle():\n #ROOT.gROOT.SetStyle(\"Plain\")\n ROOT.gStyle.SetOptStat(0)\n ROOT.gStyle.SetOptTitle(0)\n # Fonts\n ROOT.gStyle.SetTextFont(42)\n ROOT.gStyle.SetTextSize(0.06)\n #ROOT.gStyle.SetLegendTextSize(0.05)\n ROOT.gStyle.SetLabelFont(42,\"xyz\")\n ROOT.gStyle.SetLabelSize(0.035,\"xyx\")\n ROOT.gStyle.SetTitleOffset(1.4,\"xyz\")\n ROOT.gStyle.SetTitleSize(0.035,\"xyz\")\n ROOT.gStyle.SetHistLineWidth(2)\n ROOT.gStyle.SetHistLineColor(1)\n\n ROOT.gStyle.SetPadBorderMode(0)\n ROOT.gStyle.SetPadColor(0)\n\n ROOT.gStyle.SetPaperSize(20,26)\n ROOT.gStyle.SetPadTopMargin(0.10) #055)\n ROOT.gStyle.SetPadRightMargin(0.055)\n ROOT.gStyle.SetPadBottomMargin(0.15)\n ROOT.gStyle.SetPadLeftMargin(0.125)\n\n ROOT.gStyle.SetFrameBorderMode(0) \n\n ROOT.TGaxis.SetExponentOffset(-0.06, 0., \"y\")\n\n #ROOT.gStyle.SetPadTickX(1) # To get tick marks on the opposite side of the frame\n #ROOT.gStyle.SetPadTickY(1) \n\n","sub_path":"toolBox/drawCanvas.py","file_name":"drawCanvas.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"7940238","text":"class Solution:\n def jump(self, nums: List[int]) -> int:\n \"\"\"\n Goal: minimum number of jumps\n Constraints:\n - Use minimum ladders\n - always reach end\n Idea:\n - select maximum reachability of a ladder\n 2 3 1 1 4\n 0 1 1 \n \n mj(i) = minimum jumps to reach index i\n mj(0) = 0\n usedMax = 2\n maxPossible = 2 4\n \n count = 1\n Each time usedMax is exhausted and we use new maxPossible, we increase count\n [2,3,1,1,4]\n 2 \n \"\"\"\n N = len(nums)\n if N == 1: return 0\n \n count = 1\n usedMax, maxPossible = nums[0], nums[0]\n \n for i in range(1, N):\n if usedMax < i:\n count += 1\n usedMax = maxPossible\n \n maxPossible = max(maxPossible, i+nums[i])\n return count \n \n","sub_path":"Algorithms/Greedy/maxJump.py","file_name":"maxJump.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"324024115","text":"'''test for Quadcopter.py'''\nimport pytest\nfrom vtol import setup_vehicle\n\nCONFIGS = {\n 'vehicle_simulated': True,\n 'vehicle_type': 'Quadcopter',\n 'vehicle_id': 1,\n 'coms_simulated': True,\n 'altitude': 5,\n 'comm_sim_file': 'comm_sim_example.json'\n}\n\nwith open('configs.json', 'r') as data:\n VEHICLE = setup_vehicle(CONFIGS)\n print(\"HERE\")\n\n\ndef test_takeoff():\n '''quadcopter dronekit-sitl takeoff'''\n global VEHICLE # pylint: disable=global-statement\n VEHICLE.takeoff()\n alt = VEHICLE.location.global_relative_frame.alt\n assert 4 < alt < 6, \"vehicle did not reach target alt\"\n\n\ndef test_land():\n '''quadcopter dronekit-sitl land'''\n global VEHICLE # pylint: disable=global-statement\n VEHICLE.land()\n alt = VEHICLE.location.global_relative_frame.alt\n assert -1 < alt < 1, \"vehicle did not land\"\n\ndef test_change_status():\n '''set status sets the vehicles status correctly and throws with invalid status'''\n global VEHICLE # pylint: disable=global-statement\n VEHICLE.change_status('paused')\n assert VEHICLE.status == 'paused'\n\n with pytest.raises(Exception):\n VEHICLE.change_status('invalid')\n","sub_path":"src/tests/test_vtol.py","file_name":"test_vtol.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"193902496","text":"from flask_restful import Resource\nfrom flask import jsonify, make_response, request\nimport datetime\nimport random\n\nfrom data import db_session\nfrom models.anecdotes import Anecdote\nfrom models.categories import Category\nfrom .auth import auth\n\nDELTAS = {\n \"day\": datetime.timedelta(days=1),\n \"week\": datetime.timedelta(days=7),\n \"month\": datetime.timedelta(days=30),\n \"year\": datetime.timedelta(days=365)\n}\n\n\nclass AnecdotesResource(Resource):\n def get(self):\n db_sess = db_session.create_session()\n\n ids = db_sess.query(Anecdote.id).filter(Anecdote.is_published == 1).all()\n if not ids:\n return make_response(jsonify({\"error\": \"anecdote not found\"}), 404)\n\n rand_id = random.choice(ids)\n anecdote = db_sess.query(Anecdote).get(rand_id)\n return make_response(jsonify({\"anecdote\": {\"text\": anecdote.text,\n \"id\": rand_id,\n \"rating\": anecdote.rating,\n \"name\": anecdote.name,\n \"category\": anecdote.category.title,\n \"created_date\": anecdote.created_date,\n \"user_name\": anecdote.user.name}}), 200)\n\n @auth.login_required\n def post(self):\n if auth.current_user().is_banned:\n return make_response(jsonify({\"error\": \"permission denied\"}), 403)\n data = request.json\n\n if not data:\n return make_response(jsonify({\"error\": \"parameters are required\"}), 400)\n\n keys = [\"name\", \"text\", \"category\"]\n if any(i not in keys for i in data.keys()):\n return make_response(jsonify({\"error\": \"unexpected parameters\"}), 400)\n\n db_sess = db_session.create_session()\n\n try:\n category = db_sess.query(Category) \\\n .filter(Category.title == data[\"category\"]).first()\n\n if not category:\n return make_response(jsonify({\"error\": \"category not found\"}), 404)\n\n anecdote = Anecdote(name=data[\"name\"],\n text=data[\"text\"],\n user_id=auth.current_user().id,\n created_date=datetime.datetime.now(),\n category_id=category.id)\n db_sess.add(anecdote)\n db_sess.commit()\n except Exception:\n return make_response(jsonify({\"error\": \"bad request\"}), 400)\n\n return make_response(jsonify({\"id\": anecdote.id}), 201)\n\n\nclass AnecdotesListResource(Resource):\n def get(self):\n db_sess = db_session.create_session()\n\n if not request.json.get(\"page\", None):\n anecdotes = db_sess.query(Anecdote).limit(20).all()\n return make_response(jsonify({\"anecdotes\": anecdotes}), 200)\n\n try:\n page = request.json[\"page\"]\n anecdotes = db_sess.query(Anecdote).offset((page - 1) * 20).limit(20).all()\n return make_response(jsonify({\"anecdotes\": anecdotes}), 200)\n except Exception:\n return make_response(jsonify({\"error\": \"validation error\"}), 400)\n\n @auth.login_required\n def post(self):\n if auth.current_user().is_banned:\n return make_response(jsonify({\"error\": \"permission denied\"}), 403)\n\n if not request.json:\n return make_response(jsonify({\"error\": \"parameters are required\"}), 400)\n elif not request.json.get(\"data\", None):\n return make_response(jsonify({\"error\": \"parameters are required\"}), 400)\n\n keys = [\"name\", \"text\", \"category\"]\n json_data = request.json[\"data\"]\n invalid = []\n valid = []\n\n db_sess = db_session.create_session()\n for data in json_data:\n if any(i not in keys for i in data.keys()):\n invalid.append({**data})\n continue\n\n try:\n category = db_sess.query(Category) \\\n .filter(Category.title == data[\"category\"]).first()\n\n if not category:\n invalid.append({**data})\n continue\n\n anecdote = Anecdote(name=data[\"name\"],\n text=data[\"text\"],\n user_id=auth.current_user().id,\n created_date=datetime.datetime.now(),\n category_id=category.id)\n db_sess.add(anecdote)\n valid.append({\"name\": anecdote.name})\n except Exception:\n invalid.append({**data})\n\n if invalid:\n return make_response(jsonify({\n \"validation_error\": {\n \"bad_params\": invalid\n }\n }), 400)\n\n db_sess.commit()\n return make_response(jsonify({\"anecdotes\": valid}), 201)\n\n\nclass AnecdotesTopResource(Resource):\n def get(self):\n db_sess = db_session.create_session()\n\n if not request.json:\n anecdotes = db_sess.query(Anecdote). \\\n order_by(Anecdote.rating.desc()).filter(Anecdote.is_published == 1).limit(10).all()\n res = [{\"name\": i.name, \"text\": i.text, \"id\": i.id,\n \"rating\": i.rating} for i in anecdotes]\n return make_response(jsonify({\"anecdotes\": res}),\n 200)\n\n size = request.json.get(\"size\", 10)\n if not isinstance(size, int):\n return make_response(jsonify({\"error\": \"size is incorrect\"}),\n 400)\n\n period = request.json.get(\"period\", None)\n if not period:\n anecdotes = db_sess.query(Anecdote). \\\n order_by(Anecdote.rating.desc()).filter(Anecdote.is_published == 1).limit(size).all()\n res = [{\"name\": i.name, \"text\": i.text, \"id\": i.id,\n \"rating\": i.rating} for i in anecdotes]\n return make_response(jsonify({\"anecdotes\": res}),\n 200)\n\n try:\n delta = DELTAS[period]\n except Exception:\n return make_response(jsonify({\"error\": \"wrong period parameter\"}),\n 400)\n\n anecdotes = db_sess.query(Anecdote). \\\n filter(Anecdote.created_date >= datetime.datetime.now() - delta, Anecdote.is_published == 1) \\\n .order_by(Anecdote.rating.desc()).limit(size).all()\n\n res = [{\"name\": i.name, \"text\": i.text, \"id\": i.id,\n \"rating\": i.rating} for i in anecdotes]\n\n return make_response(jsonify({\"anecdotes\": res}), 200)\n\n\nclass AnecdotesModerateResource(Resource):\n @auth.login_required\n def patch(self):\n if not auth.current_user().is_admin or\\\n auth.current_user().is_banned:\n return make_response(jsonify({\"error\": \"permission denied\"}), 403)\n\n try:\n db_sess = db_session.create_session()\n anecdote = db_sess.query(Anecdote).get(request.json[\"anecdote_id\"])\n\n if not anecdote:\n return make_response(jsonify({\"error\": \"anecdote not found\"}), 404)\n\n anecdote.is_published = request.json[\"is_published\"]\n db_sess.commit()\n except Exception:\n return make_response(jsonify({\"error\": \"bad request\"}), 400)\n\n return make_response(jsonify({\"id\": anecdote.id}), 200)\n\n @auth.login_required\n def get(self):\n if not auth.current_user().is_admin or\\\n auth.current_user().is_banned:\n return make_response(jsonify({\"error\": \"permission denied\"}), 403)\n\n db_sess = db_session.create_session()\n anecdotes = db_sess.query(Anecdote).filter(Anecdote.is_published == 0)\n\n resp = []\n for anecdote in anecdotes:\n resp.append({anecdote.id, anecdote.text})\n\n return make_response(jsonify({\"anecdotes\": resp}), 200)\n","sub_path":"api/anecdotes_resource.py","file_name":"anecdotes_resource.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"610625580","text":"from django.urls import path,include\nfrom . import views\n\napp_name = 'usuario'\n\nurlpatterns = [\n\n path('perfil/', views.perfil, name='perfil'),\n path('submit_login/', views.submit_login, name='submit_login'),\n path('index/', views.index_perfil, name='index'),\n path('logout/', views.logout_user, name='logout_user'),\n path('home/', views.index_perfil, name=\"home\"),\n path('perfilProfissional/', views.PerfilProf, name=\"Profissional\"),\n path('alterarUsuario/', views.alterarUsuario, name=\"alterarUsuario\"),\n path('detalhesusuario/', views.detalhesusuario, name=\"detalhesusuario\"),\n path('sobre/', views.sobre, name=\"sobre\"),\n path('perfildoProfissional/',views.perfildoProfissional, name=\"perfildoProfissional\"),\n\n\n\n\n]","sub_path":"usuario/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"370478667","text":"#From flask import Flask, request, jsonify\nfrom os import environ\nimport json\nimport os\nimport amqp_setup\n\nmonitorBindingKey='send.email'\n\n#app = Flask(__name__)\n\n#retrieve name, email address & date\\time of appt\n#@app.route(\"/notification\", methods=['PATCH'])\ndef send_notif():\n amqp_setup.check_setup()\n \n queue_name = 'Notification'\n \n # set up a consumer and start to wait for coming messages\n amqp_setup.channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)\n amqp_setup.channel.start_consuming()\n\ndef callback(channel, method, properties, body): # required signature for the callback; no return\n print(\"\\nReceived an order log by \" + __file__)\n processInfo(json.loads(body))\n print() # print a new line feed\n\ndef processInfo(data):\n url = \"https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send\"\n #dissect the info here and put it into payload\n\n name = data['patient_name']\n email = data['email']\n appointment_time = data['appointment_time']\n\n msg = \"Dear \"+name+\", \\\\n\\\\nYour appointment with G9T6 clinic will take place tomorrow at \"+appointment_time+\". Please arrive 5 minutes before your appointment time to check in. Thank you and see you.\\\\n\\\\nBest Regards, \\\\nG9T6 Clinic\"\n\n payload = \"{\\\"personalizations\\\": [{\\\"to\\\": [{\\\"email\\\":\\\"\" + email + \"\\\"}],\\\"subject\\\": \\\"Upcoming appointment details\\\"}],\\\"from\\\": {\\\"email\\\": \\\"esd.g9t6clinic@gmail.com\\\"},\\\"content\\\": [{\\\"type\\\": \\\"text/plain\\\",\\\"value\\\":\\\"\" + msg + \"\\\"}]}\"\n headers = {\n 'content-type': \"application/json\",\n 'x-rapidapi-key': \"ba007e6714msh5ec101f1353401cp18c367jsncafd61131b64\",\n 'x-rapidapi-host': \"rapidprod-sendgrid-v1.p.rapidapi.com\"\n }\n\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n\n \n if(response):\n reply = json.dumps(\n {\n \"code\": 200,\n \"message\": \"The email is sent successfully.\"\n })\n else:\n reply = json.dumps(\n {\n \"code\": 500,\n \"message\": \"The email failed to send.\"\n })\n \n print(reply)\n\nif __name__ == \"__main__\": # execute this program only if it is run as a script (not by 'import')\n print(\"\\nThis is \" + os.path.basename(__file__), end='')\n print(\": monitoring routing key '{}' in exchange '{}' ...\".format(monitorBindingKey, amqp_setup.exchangename))\n send_notif()","sub_path":"docker-compose/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"493023628","text":"#from pyspark.sql import SparkSession\n#from datetime import datetime\nfrom pyspark import SparkContext\n\nsc = SparkContext(appName = \"job2_Spark\")\n\n#now = datetime.now()\n#current_time = now.strftime(\"%H:%M:%S\")\n#print(\"Current Time =\", current_time)\n\n#spark = ps.sql.SparkSession.builder.appName(\"Python Spark SQL basic example\").\\\n# config(\"spark.some.config.option\", \"some-value\").getOrCreate()\n\n#importiamo il dataset sulle azioni\n#df_azioni=spark.read.csv('/home/giacomo/apache-hive-3.1.2-bin/data/BIG_DATA_PROGETTO-1/historical_stock_prices.csv',\n# inferSchema=\"true\", header=\"true\")\nazioni = sc.textFile(\"/home/giacomo/apache-hive-3.1.2-bin/data/BIG_DATA_PROGETTO-1/file_grandi/historical_stock_prices_update_02.csv\")\n#importiamo il dataset sui settori\nsettori = sc.textFile(\"/home/giacomo/apache-hive-3.1.2-bin/data/BIG_DATA_PROGETTO-1/historical_stocks_update_per_hive.csv\")\n#df_settori=spark.read.csv('/home/giacomo/hadoop-3.2.1/DATI_AGGIUNTIVI/BIG_DATA_PROGETTO-1/historical_stocks.csv',\n# inferSchema=\"true\", header=\"true\",sep=\",\")\n\n#trasformiamo i dataframe df_azioni e df_settori in rdd\n#azioni = df_azioni.rdd\n#settori = df_settori.rdd\n\n#stampe di test\n#print(\"\\nazioni:\\n\")\n#azioni.foreach(lambda a: print (a))\n\n#print(\"\\nsettori:\\n\")\n#settori.foreach(lambda a: print (a))\nazioni = azioni.map(lambda a: a.split(','))\nsettori = settori.map(lambda s: s.split(';'))\n\"\"\"\nazioni_modificato è un RDD così costruito: \n -Da azioni applichiamo un filter per rimuovere le azioni più vecchie del 2008\n -Applichiamo un map per creare una coppia (K,V), in particolare:\n -K è la coppia (ticker,anno) (rispettivamente a[0] e a[7])\n -V è un dizionario in cui mettiamo \n -data_iniziale (si intende la data minima nell'anno per il ticker)\n -prezzo_iniziale (prezzo di chiusura associato alla data iniziale)\n -data_finale (si intende la data massima nell'anno per il ticker)\n -prezzo_finale (prezzo di chiusura associato alla data finale)\n -volume (somma dei volumi di tutte le azioni del ticker nell'anno)\n -var_giornaliera (somma dei prezzi chiusura di tutte le zioni del ticker nell'anno)\n \n Il dizionario costruito in questo modo è particolarmente adatto all'operazione di riduzione(reduceByKey)\n che viene fatta in seguito sulla chiave in modo da ottenere poi le informazioni per ciascuna chiave \n (ticker,anno) \n\"\"\"\nazioni_modificato = azioni.filter(lambda a: a[7] >= '2008-01-01').\\\n map(lambda a:( (a[0] , a[7].split('-')[0]) ,\n {'data_iniziale':a[7],'prezzo_iniziale':float(a[2]),\n 'data_finale':a[7],'prezzo_finale':float(a[2]),\n 'volume':float(a[6]), 'var_giornaliera':float(a[2])} ))\n\"\"\"\ncount_per_azione_anno serve per contare le occorrenze ci ciascuna azione raggruppate per chiave (ticker,anno) \nin modo tale che poi per conoscere la media del 'volume' e della 'var_giornaliera',\ndividiamo per il numero di occorrenza la la somma dei volumi e dei prezzi di chiusura.\n\"\"\"\ncount_per_azione_anno = azioni_modificato.groupByKey().map(lambda a: (a[0], len(list(a[1]))))\n\"\"\"\nriduzione(a1,a2) serve per il reduceByKey che si applica all'RDD azioni_modificato ed in particolare,\nprende in input (V,V) dove V è un valore della coppia (K,V) definita sopra:\n -calcola il minimo tra due 'data_iniziale'\n -memorizza 'prezzo_iniziale' associato alla data minima\n -calcola il massimo tra due 'data_finale'\n -memorizza 'prezzo_finale' associato alla data massima \n -somma il volume e la variazione giornaliera\nATTENZIONE questi valori sono calcolati a due a due, ovvero la funzione viene richiamata con due elementi per volta,\nquindi applica correttamente la riduzione d'interesse SOLO SE richiamata all'intero di reduceByKey\nRICORDANDO che per essere applicata questa funzione deve essere della forma (V,V) --> V\n\"\"\"\ndef riduzione(a1,a2):\n a = {}\n if(a1.get('data_iniziale')a2.get('data_finale')):\n a['data_finale'] = a1.get('data_finale')\n a['prezzo_finale'] = a1.get('prezzo_finale')\n else:\n a['data_finale'] = a2.get('data_finale')\n a['prezzo_finale'] = a2.get('prezzo_finale')\n a['volume']=a1.get('volume')+a2.get('volume')\n a['var_giornaliera']=float(a1.get('var_giornaliera')+a2.get('var_giornaliera'))\n return a\n\nazioni_modificato = azioni_modificato.reduceByKey(riduzione)\n\n\"\"\"\nqui facciamo il join tra i due RDD, azioni_modificato e count_per_azione_anno, per poter calcolare\nil volume medio e la var_giornaliera media dato che sono necessari il numero di occorrenze per ciascuna chiave\n\"\"\"\nunione = azioni_modificato.join(count_per_azione_anno)\n\n#stampa di test\n#print(\"\\nstampa unione:\\n\")\n#unione.foreach(lambda a: print(a))\n\n\"\"\"\nqui si definisce un primo risultato ovvero per ciascun ticker per ciascun anno:\n -variazione annuale \n -somma volume (somma dei volumi assocati al ticker nell'anno)\n -somma prezzi di chiusura (somma dei prezzi di chiusura associati al ticker nell'anno)\n\"\"\"\ndef rid_per_aa(a):\n a_finale=(a[0],{'var_annuale':(100*(a[1][0].get('prezzo_finale')-a[1][0].get('prezzo_iniziale'))/a[1][0].get('prezzo_iniziale')),\n 'somma_volume':a[1][0].get('volume'),\n 'somma_prezzo_close':a[1][0].get('var_giornaliera'),\n 'count':a[1][1]})\n return a_finale\n\nresult = unione.map(rid_per_aa)\n\"\"\"\nresult sarà fatto in questo modo: ( ('AHH',2010),{\n 'var_annuale': 0.34,\n 'somma_volume': 1190,\n 'somma_prezzo_close': 265.32,\n 'count': 30\n })\n\"\"\"\n#stampa di test\n#print(\"\\nresult:\")\n#result.foreach(lambda a: print(a))\n\"\"\"\nAdesso per includere le aziende e quindi i settori operiamo un map sull'RDD result così da avere come chiave\nsolo il ticker per poter fare il join con l'RDD settori_modificato. \nSuccessivamente eseguiremo un altro map che avrà come chiave (anno,settore),\ncosì da avere i risultati per ciascun settore\n\"\"\"\nresult = result.map(lambda a:(a[0][0],[ a[0][1],a[1] ]))\n\n\"\"\"\nquesta operazione è necessaria per non avere duplicati che poi fanno sballare i conti.\nES: potrebbe essere che ci siano ticker che compaiono più volte con lo stesso settore.\nApplicando una riduzione sulla chiave (ticker,settore) eliminiamo attraverso res_set_mod(v1,v2) i duplicati\n\"\"\"\ndef red_set_mod(v1,v2):\n return v1\nsettori_modificato = settori.map(lambda s:((s[0],s[3]),s[3])).reduceByKey(red_set_mod)\n\n#stampa di test\n#print(\"\\nsettori_modificato:\")\n#settori_modificato.foreach(lambda a: print(a))\n\"\"\"\ndopo aver eliminato i duplicati, impostiamo come chiave solo il ticker \nin modo da poter fare il join con result (nel join gli RDD devono avere stessa chiave)\n\"\"\"\nsettori_modificato = settori_modificato.map(lambda s:(s[0][0],s[1]))\n\n#stampa di test\n#print(\"\\nsettori_modificato:\")\n#settori_modificato.foreach(lambda a: print(a))\n\nresult_per_settore = result.join(settori_modificato)\n\n#stampa di test\n#print(\"\\nresult_per_settore:\")\n#result_per_settore.foreach(lambda a: print(a))\n\"\"\"\nIn questo map definiamo la nuova chiave che sarà (settore,anno) e come valore avremo\n -var_annuale\n -somma_volume\n -somma_prezzo_close\n -count\n\"\"\"\nresult_per_settore = result_per_settore.map(lambda az_set: ( (az_set[1][1],az_set[1][0][0]),\n az_set[1][0][1]))\n#stampa di test,\n#print(\"\\nresult per settore: \\n\")\n#result_per_settore.foreach(lambda a: print(a))\n\"\"\"\nquesto count ci servirà per eseguire il conteggio di tutte le tuple che hanno la stessa chiave,\nper poi calcolare: variazione_annuale media per ogni anno\n\"\"\"\ncount_per_settore = result_per_settore.groupByKey().map(lambda a: (a[0],len(list(a[1]))))\n\ndef red_per_settore(d1,d2):\n d = {\n 'var_annuale':d1['var_annuale']+d2['var_annuale'],\n 'somma_volume': d1['somma_volume']+d2['somma_volume'],\n 'somma_prezzo_close':d1['somma_prezzo_close'] + d2['somma_prezzo_close'],\n 'count': d1['count']+d2['count']\n }\n return d\nresult_per_settore = result_per_settore.reduceByKey(red_per_settore)\n\nresult_per_settore =result_per_settore.join(count_per_settore)\n\n#stampa di test\n#print(\"\\nresult per settore:\")\n#result_per_settore.foreach(lambda a: print(a))\n\"\"\"\n#In quest'ultima operazione viene calcolato il risultato finale, ovvero per ciascun settore:\n -variazione annuale media\n -volume medio\n -variazione giornaliera\n\"\"\"\nresult_finale = result_per_settore.map(lambda a:(a[0],{'var_annuale_media':a[1][0]['var_annuale']/a[1][1],\n 'volume_medio':a[1][0]['somma_volume']/a[1][0]['count'],\n 'var_giornaliera':a[1][0]['somma_prezzo_close']/a[1][0]['count']\n }))\n#print(\"\\nresult finale:\\n\")\n#result_finale.foreach(lambda a: print(a))\nresult_finale.saveAsTextFile('results')\nsc.stop()\n\n#now = datetime.now()\n#current_time = now.strftime(\"%H:%M:%S\")\n#print(\"Current Time =\", current_time)","sub_path":"job2/spark/job2_spark.py","file_name":"job2_spark.py","file_ext":"py","file_size_in_byte":9760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"52995305","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\n\ndf = pd.read_csv(\"./data/input/train.csv\").set_index(\"ID\")\n\n# identify constant features by looking at the standard deviation (check id std ==0.0)\ndesc = df.describe().transpose()\ncolumns_to_drop = desc.loc[desc[\"std\"] == 0].index.values\ndf.drop(columns_to_drop, axis=1, inplace=True)\n\n# check which column has been dropped\nprint(columns_to_drop)\n\n# do one hot encoding for categorical columns\ndf08 = df[[\"X{}\".format(x) for x in range(9) if x != 7]]\n\ntot_cardinality = 0\nfor c in df08.columns.values:\n cardinality = len(df08[c].unique())\n print(c, cardinality)\n tot_cardinality += cardinality\nprint(tot_cardinality)\n\ndf = pd.get_dummies(df, columns=[\"X{}\".format(x) for x in range(9) if x != 7])\n\n# drop outliers in target varaible\ndf.drop(df.loc[df[\"y\"] > 250].index, inplace=True)\n\n# PCA analysis\n# its a 2 dimensional PCA\npca2 = PCA(n_components=2)\npca2_results = pca2.fit_transform(df.drop([\"y\"], axis=1))\n\n# plot PCA chart\ncmap = sns.cubehelix_palette(as_cmap=True)\nf, ax = plt.subplots(figsize=(20, 15))\npoints = ax.scatter(pca2_results[:, 0], pca2_results[:, 1], c=df.y, s=50, cmap=cmap)\nf.colorbar(points)\nplt.show()\n","sub_path":"pcaAnalysis.py","file_name":"pcaAnalysis.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"268457588","text":"# coding=UTF-8\n# **********************************************************************\n# Copyright (c) 2013-2020 Cisco Systems, Inc. All rights reserved\n# written by zen warriors, do not modify!\n# **********************************************************************\n\n\nfrom cobra.mit.meta import ClassMeta\nfrom cobra.mit.meta import StatsClassMeta\nfrom cobra.mit.meta import CounterMeta\nfrom cobra.mit.meta import PropMeta\nfrom cobra.mit.meta import Category\nfrom cobra.mit.meta import SourceRelationMeta\nfrom cobra.mit.meta import NamedSourceRelationMeta\nfrom cobra.mit.meta import TargetRelationMeta\nfrom cobra.mit.meta import DeploymentPathMeta, DeploymentCategory\nfrom cobra.model.category import MoCategory, PropCategory, CounterCategory\nfrom cobra.mit.mo import Mo\n\n\n# ##################################################\nclass DomStatsRx(Mo):\n \"\"\"\n An object that holds the ARP domain received statistics.\n\n \"\"\"\n\n meta = ClassMeta(\"cobra.model.arp.DomStatsRx\")\n\n meta.moClassName = \"arpDomStatsRx\"\n meta.rnFormat = \"domstatsrx\"\n meta.category = MoCategory.REGULAR\n meta.label = \"DomStatsRx\"\n meta.writeAccessMask = 0x8408020040001\n meta.readAccessMask = 0x8408020040001\n meta.isDomainable = False\n meta.isReadOnly = True\n meta.isConfigurable = False\n meta.isDeletable = False\n meta.isContextRoot = False\n\n meta.parentClasses.add(\"cobra.model.arp.Dom\")\n\n meta.rnPrefixes = [\n ('domstatsrx', False),\n ]\n\n prop = PropMeta(\"str\", \"childAction\", \"childAction\", 4, PropCategory.CHILD_ACTION)\n prop.label = \"None\"\n prop.isImplicit = True\n prop.isAdmin = True\n prop._addConstant(\"deleteAll\", \"deleteall\", 16384)\n prop._addConstant(\"deleteNonPresent\", \"deletenonpresent\", 8192)\n prop._addConstant(\"ignore\", \"ignore\", 4096)\n meta.props.add(\"childAction\", prop)\n\n prop = PropMeta(\"str\", \"dn\", \"dn\", 1, PropCategory.DN)\n prop.label = \"None\"\n prop.isDn = True\n prop.isImplicit = True\n prop.isAdmin = True\n prop.isCreateOnly = True\n meta.props.add(\"dn\", prop)\n\n prop = PropMeta(\"str\", \"modTs\", \"modTs\", 7, PropCategory.REGULAR)\n prop.label = \"None\"\n prop.isImplicit = True\n prop.isAdmin = True\n prop.defaultValue = 0\n prop.defaultValueStr = \"never\"\n prop._addConstant(\"never\", \"never\", 0)\n meta.props.add(\"modTs\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvd\", \"pktRcvd\", 2383, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvd\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrp\", \"pktRcvdDrp\", 2393, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpArpIfNoMem\", \"pktRcvdDrpArpIfNoMem\", 2406, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Arp if no Mem Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpArpIfNoMem\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpArpRequestIgnore\", \"pktRcvdDrpArpRequestIgnore\", 2418, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Arp Request Ignore Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpArpRequestIgnore\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpBadCtxt\", \"pktRcvdDrpBadCtxt\", 2411, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Bad Context Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpBadCtxt\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpBadIf\", \"pktRcvdDrpBadIf\", 2395, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Bad if Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpBadIf\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpBadL2AddrLen\", \"pktRcvdDrpBadL2AddrLen\", 2398, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Bad L2Addr Len Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpBadL2AddrLen\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpBadL3AddrLen\", \"pktRcvdDrpBadL3AddrLen\", 2399, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Bad L3Addr Len Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpBadL3AddrLen\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpBadLen\", \"pktRcvdDrpBadLen\", 2396, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Bad Len Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpBadLen\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpBadProto\", \"pktRcvdDrpBadProto\", 2397, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Bad Proto Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpBadProto\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpBadSrcMac\", \"pktRcvdDrpBadSrcMac\", 2403, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Bad Src Mac Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpBadSrcMac\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpCtxtNotCreated\", \"pktRcvdDrpCtxtNotCreated\", 2412, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Context not Created Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpCtxtNotCreated\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpDirBcast\", \"pktRcvdDrpDirBcast\", 2401, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Dir Bcast Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpDirBcast\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpGratOnProxyArp\", \"pktRcvdDrpGratOnProxyArp\", 2417, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Grat on Proxy Arp Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpGratOnProxyArp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpInvalDstIp\", \"pktRcvdDrpInvalDstIp\", 2402, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Inval Dst Ip Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpInvalDstIp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpInvalSrcIp\", \"pktRcvdDrpInvalSrcIp\", 2400, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Inval Src Ip Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpInvalSrcIp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpL2FmQueryFail\", \"pktRcvdDrpL2FmQueryFail\", 2419, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop L2Fm Query Fail Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpL2FmQueryFail\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpL2LocalProxyArp\", \"pktRcvdDrpL2LocalProxyArp\", 2413, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop L2 Local Proxy Arp Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpL2LocalProxyArp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpL2PrtUntrusted\", \"pktRcvdDrpL2PrtUntrusted\", 2415, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop L2 Port Untrusted Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpL2PrtUntrusted\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpL2PureL2Pkt\", \"pktRcvdDrpL2PureL2Pkt\", 2414, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop L2 Pure L2 Pkt Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpL2PureL2Pkt\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpNotForUs\", \"pktRcvdDrpNotForUs\", 2407, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop not for us Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpNotForUs\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpNotInit\", \"pktRcvdDrpNotInit\", 2410, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop not Initialized Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpNotInit\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpOwnSrcIp\", \"pktRcvdDrpOwnSrcIp\", 2405, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop own Src Ip Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpOwnSrcIp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpOwnSrcMac\", \"pktRcvdDrpOwnSrcMac\", 2404, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop own Src Mac Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpOwnSrcMac\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpStdbyFhrpVip\", \"pktRcvdDrpStdbyFhrpVip\", 2416, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Standby Fhrp Vip Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpStdbyFhrpVip\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpSubnetMismatch\", \"pktRcvdDrpSubnetMismatch\", 2409, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Subnet Mismatch Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpSubnetMismatch\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdDrpTunnelFail\", \"pktRcvdDrpTunnelFail\", 2420, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Drop Tunnel Fail Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdDrpTunnelFail\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdFastpath\", \"pktRcvdFastpath\", 2391, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Fastpath Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdFastpath\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdLearnAndDropNotForUs\", \"pktRcvdLearnAndDropNotForUs\", 2408, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Learn and Drop not for us Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdLearnAndDropNotForUs\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdLocalProxyArp\", \"pktRcvdLocalProxyArp\", 2387, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Local Proxy Arp Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdLocalProxyArp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdMbufOp\", \"pktRcvdMbufOp\", 2394, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Mbuf Op Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdMbufOp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdProxyArp\", \"pktRcvdProxyArp\", 2386, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Proxy Arp Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdProxyArp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdReq\", \"pktRcvdReq\", 2384, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Req Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdReq\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdReqL2\", \"pktRcvdReqL2\", 2388, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Req Count L2\"\n prop.isOper = True\n meta.props.add(\"pktRcvdReqL2\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdRsp\", \"pktRcvdRsp\", 2385, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Reply Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdRsp\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdRspL2\", \"pktRcvdRspL2\", 2389, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Reply Count L2\"\n prop.isOper = True\n meta.props.add(\"pktRcvdRspL2\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdSnoop\", \"pktRcvdSnoop\", 2392, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Snoop Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdSnoop\", prop)\n\n prop = PropMeta(\"str\", \"pktRcvdTunnel\", \"pktRcvdTunnel\", 2390, PropCategory.REGULAR)\n prop.label = \"Arp Pkt Recv Tunnel Count\"\n prop.isOper = True\n meta.props.add(\"pktRcvdTunnel\", prop)\n\n prop = PropMeta(\"str\", \"rn\", \"rn\", 2, PropCategory.RN)\n prop.label = \"None\"\n prop.isRn = True\n prop.isImplicit = True\n prop.isAdmin = True\n prop.isCreateOnly = True\n meta.props.add(\"rn\", prop)\n\n prop = PropMeta(\"str\", \"status\", \"status\", 3, PropCategory.STATUS)\n prop.label = \"None\"\n prop.isImplicit = True\n prop.isAdmin = True\n prop._addConstant(\"created\", \"created\", 2)\n prop._addConstant(\"deleted\", \"deleted\", 8)\n prop._addConstant(\"modified\", \"modified\", 4)\n meta.props.add(\"status\", prop)\n\n def __init__(self, parentMoOrDn, markDirty=True, **creationProps):\n namingVals = []\n Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps)\n\n\n\n# End of package file\n# ##################################################\n","sub_path":"venv/Lib/site-packages/cobra/modelimpl/arp/domstatsrx.py","file_name":"domstatsrx.py","file_ext":"py","file_size_in_byte":11643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"70814908","text":"import matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\n\nfashion_mnist = tf.keras.datasets.fashion_mnist\n(images, targets), (_, _) = fashion_mnist.load_data()\nimages = images[:10000]\ntargets = targets[:10000]\n\ntargets_name = [\"T-shirt/top\", \"Trouser\", \"Pullover\", \"Dress\", \n\"Coat\", \"Sandal\", \"Shirt\", \"Sneaker\", \"Bag\", \"Ankle boot\"]\n\nimages = images.astype(np.float32).reshape(-1, 28*28)\n\nscaler = MinMaxScaler()\nimages = scaler.fit_transform(images)\n\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Dense(256, activation=\"relu\"))\nmodel.add(tf.keras.layers.Dense(128, activation=\"relu\"))\n# Softmax permet que la sommes du layer = 1 (Probabilité)\nmodel.add(tf.keras.layers.Dense(10, activation=\"softmax\"))\n\n# Define error\nmodel.compile(\n loss = \"sparse_categorical_crossentropy\",\n optimizer = \"sgd\",\n metrics = [\"accuracy\"]\n)\n\nhistory = model.fit(images, targets, epochs=10)\n\nmodel_output = model.predict(images[0:1])\nprint(np.max(model_output), targets[0:1])\n","sub_path":"tf_formation/fashion_mnist_sklearn.py","file_name":"fashion_mnist_sklearn.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"436737425","text":"#!/usr/bin/env python\r\n# encoding: utf-8\r\n\"\"\"\r\n@author: zhuangxu\r\n@email: zhuangxu0@gmail.com\r\n@time: 2019/3/13 11:32\r\n@desc:\r\n\"\"\"\r\nimport ast\r\n\r\n\r\nimport pika\r\nimport pika.exceptions as p_ex\r\n\r\n\r\ndef receive_message(queue, callback):\r\n RABBITMQ_VHOST = \"scms\"\r\n RABBITMQ_USER = \"scms\"\r\n RABBITMQ_PWD = \"scms\"\r\n server_ip = '192.168.1.220'\r\n\r\n try:\r\n credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PWD)\r\n PIKA_CONN = pika.BlockingConnection(pika.ConnectionParameters(\r\n host=server_ip, virtual_host=RABBITMQ_VHOST, credentials=credentials))\r\n channel = PIKA_CONN.channel()\r\n except p_ex.AMQPConnectionError as e:\r\n print(e.args)\r\n\r\n channel.queue_declare(queue=queue)\r\n channel.basic_consume(callback,\r\n queue=queue)\r\n\r\n print(' [*] Waiting for messages. From the queue: ' + queue)\r\n channel.start_consuming()\r\n\r\n\r\nchain1_resp_list = []\r\nchain1_x = []\r\n\r\n\r\ndef statistics(ch, method, properties, body):\r\n global chain1_x\r\n global chain1_resp_dict\r\n\r\n # RABBITMQ_CLIENT = Client('192.168.1.220:15672', 'scms', 'scms')\r\n #\r\n # chain1_gw_messages = RABBITMQ_CLIENT.get_messages(vhost=RABBITMQ_VHOST, qname=Chain1_QUEUE_NAME)\r\n\r\n m_dict = ast.literal_eval(body)\r\n gw_t = m_dict.get('gw_time')\r\n books_t = m_dict.get('books_time')\r\n review_t = m_dict.get('review_time')\r\n score_t = m_dict.get('score_time')\r\n print(str([gw_t, books_t - gw_t, review_t - books_t, score_t - review_t, score_t - gw_t]) + ',')\r\n ch.basic_ack(delivery_tag=method.delivery_tag)\r\n # chain1_x.append(gw_t)\r\n # chain1_resp_dict[gw_t] = [books_t - gw_t, review_t - books_t, score_t - review_t, score_t - gw_t]\r\n\r\n\r\nreceive_message('chain1_gw', statistics)\r\n\r\n\r\n\r\n\r\n","sub_path":"evaluate/statistics_response_time.py","file_name":"statistics_response_time.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"403634517","text":"import chainer\nimport chainer.functions as F\nimport chainer.links as L\n\n\nclass RedNN(chainer.Chain):\n def __init__(self):\n super(RedNN, self).__init__()\n with self.init_scope():\n self.l = L.Linear(50, 1000)\n\n def __call__(self, L):\n while(1):\n if len(L) == 1:\n return L[0]\n ret0, ret1 = L[-1], L[-2]\n L.pop()\n L.pop()\n ret = self.L(ret0, mytype(ret1), ret1)\n ret = F.tanh(ret)\n L.append(ret)\n","sub_path":"parsing/lib/divnull/RecNN.py","file_name":"RecNN.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"86038428","text":"def plan_route(input):\r\n peaks_list = [int(i) for i in input.split()]\r\n lis = [1 for i in peaks_list]\r\n prevs = [0 for i in peaks_list]\r\n n = len(peaks_list)\r\n for i in range (1, n):\r\n for j in range(0, i):\r\n if peaks_list[i] > peaks_list[j] and lis[i] < lis[j] + 1:\r\n lis[i] = lis[j] + 1\r\n prevs[i] = j \r\n maximum = 0\r\n for i in range(0, n):\r\n maximum = max(maximum, lis[i])\r\n i = lis.index(maximum)\r\n route = [str(peaks_list[i])]\r\n while len(route) != maximum:\r\n route.append(str(peaks_list[prevs[i]]))\r\n i = prevs[i]\r\n outroute = ' '.join(reversed(route))\r\n return outroute\r\nprint(plan_route('8 4 12 2 10 6 14 1 9 5 13 3 11 7 15'))","sub_path":"easyones/answers lab/route2.py","file_name":"route2.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"21758982","text":"# -*- coding: utf-8 -*-\n\n# Visigoth: A lightweight Python3 library for rendering data visualizations in SVG\n# Copyright (C) 2020 Niall McCarroll\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n# and associated documentation files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or\n# substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport os.path\nimport logging\n\nfrom visigoth.map_layers.geoplot import Geoplot,Multipoint,Multiline,Multipolygon\n\nfrom visigoth.utils.geojson import GeojsonReader\nfrom visigoth.utils.js import Js\n\nclass Geoimport(Geoplot):\n\n \"\"\"\n Import and plot a layer composed of points, lines and polygons described in a source file\n source file formats supported are geojson (.geojson)\n\n Arguments:\n path: path to the file to be imported\n\n Keyword Arguments:\n path (str): path to file to import\n point_style (dict|function): see Notes\n line_style (dict|function): see Notes\n polygon_style (dict|function): see Notes\n \n Notes:\n The point_style, line_style and polygon_style values should be dicts or functions operating on a properties dict and returning a style dict\n The returned dict describes the SVG rendering style for the element (point, line, area)\n Possible keys are \"label\", tooltip\", \"fill\", \"stroke\", \"stroke_width\", \"radius\", \"popup\" and \"marker\"\n These keys map to keyword arguments of the geoplot.Multipoint, geoplot.Multiline and geoplot.Multipolygon instances\n \"\"\"\n\n def __init__(self, path, point_style=lambda p:{}, line_style=lambda p:{}, polygon_style=lambda p:{}):\n super().__init__()\n self.path = path\n self.point_style = point_style\n self.line_style = line_style\n self.polygon_style = polygon_style\n self.objects = self.extract()\n\n def getPointStyle(self,props):\n return self.invoke(self.point_style,[props])\n\n def getLineStyle(self,props):\n return self.invoke(self.line_style,[props])\n\n def getPolygonStyle(self,props):\n return self.invoke(self.polygon_style,[props])\n\n def invoke(self,fn_or_val,args):\n if fn_or_val and fn_or_val.__class__.__name__ == \"function\":\n return fn_or_val(*args)\n else:\n return fn_or_val\n\n def extractGeojson(self):\n reader = GeojsonReader()\n return reader.extract(self.path)\n\n def extract(self):\n (points,lines,polys) = self.extractGeojson()\n\n # register the points/lines and polys without style information\n # so the boundaries are established. Re-add them during build.\n for (_, ppoints) in points:\n self.add(Multipoint(points))\n\n for (_, plines) in lines:\n self.add(Multiline(plines))\n\n for (_, ppolys) in polys:\n self.add(Multipolygon(ppolys))\n\n return (points,lines,polys)\n\n def getPolygonProperties(self):\n (opoints, olines, opolys) = self.objects\n return [props for (props, polys) in opolys]\n\n def build(self,fmt):\n super().build(fmt)\n self.clear()\n (opoints, olines, opolys) = self.objects\n\n for (props, points) in opoints:\n self.add(Multipoint(points, **self.getPointStyle(props)))\n\n for (props, lines) in olines:\n self.add(Multiline(lines, **self.getLineStyle(props)))\n\n for (props, polys) in opolys:\n self.add(Multipolygon(polys, **self.getPolygonStyle(props)))\n\n\n def draw(self,doc,cx,cy,constructJs=True):\n config = super().draw(doc,cx,cy,False)\n with open(os.path.join(os.path.split(__file__)[0],\"geoimport.js\"),\"r\") as jsfile:\n jscode = jsfile.read()\n Js.registerJs(doc,self,jscode,\"geoimport\",cx,cy,config,constructJs)\n return config","sub_path":"visigoth/map_layers/geoimport/geoimport.py","file_name":"geoimport.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"169210971","text":"# Time Complexity : Add - O(m*n)\n# Space Complexity :O(m*n)\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n'''\n1. Initially all the 0's are pushed on to the queue as they are independent\n2. The 1's replaced with -1, to make sure they are not revsiited when BFS is performed\n3. The minimum distance of any element with value 1 = level of predecessor + 1\n'''\n\nclass Solution:\n def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:\n \n \n rows = len(matrix)\n cols = len(matrix[0])\n \n\n queue = deque()\n for i in range(rows):\n for j in range(cols):\n if matrix[i][j] == 0:\n queue.append((i,j))\n else:\n matrix[i][j] *= -1\n \n # matrix[i][j] = \n \n dirs = [(0,-1),(0,1),(1,0),(-1,0)]\n \n level = -1\n while queue:\n \n level += 1\n size = len(queue)\n while size > 0:\n \n cur_x, cur_y = queue.popleft()\n\n for dir_x, dir_y in dirs:\n new_x = cur_x + dir_x\n new_y = cur_y + dir_y\n \n if new_x >=0 and new_x < rows and new_y >= 0 and new_y < cols and matrix[new_x][new_y] < 0: \n # print (new_x, new_y)\n matrix[new_x][new_y] = level + 1\n queue.append((new_x, new_y))\n \n size -= 1\n \n return (matrix)","sub_path":"01_matrix_BFS.py","file_name":"01_matrix_BFS.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"481546920","text":"import datetime\nimport os\n\n# APPLICATION\nDEBUG = True\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\n# CATEGORY SEARCH SETTING\nCATEGORIES_JSON_FILE='/jsons/categories.json'\nCATEGORIES_SEARCH_FIELD = 'name'\nCATEGORIES_CHILD_FIELD = 'children'\n\n# PSYCHOGRAPHICS SEARCH SETTING\nPSYCHOGRAPHICS_JSON_FILE='/jsons/psychographics.json'\nPSYCHOGRAPHICS_SEARCH_FIELD = 'label'\nPSYCHOGRAPHICS_CHILD_FIELD = 'values'\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"372457636","text":"#!/usr/bin/env python3\n# coding: utf8\n\nfrom colorama import init, Fore, Style\n\n\ndef display_error(error=True):\n if error:\n print(Fore.RED, \"[ error ]\", end=\" \")\n else:\n print(Fore.GREEN, \"[success]\", end=\" \")\n print(Style.RESET_ALL, end=\"\")\n\n\ndef make_test(old_function):\n def new_function(TestClass, description, expecting_error):\n happened_error = False\n function_result = \"\"\n exception = \"\"\n try:\n function_result = old_function()\n except Exception as e:\n exception = e\n happened_error = True\n finally:\n display_error(expecting_error != happened_error)\n display_error(expecting_error)\n display_error(happened_error)\n print(\"{:<32}\".format(description + \":\"), end=\"\")\n print(Fore.RED, str(exception).replace(\"\\n\", \"\"),\n end=\"\")\n print(Fore.BLUE, function_result, sep=\"\", end=\"\")\n print(Style.RESET_ALL, sep=\"\")\n\n TestClass.nb_tests += 1\n if expecting_error == happened_error:\n TestClass.nb_tests_succeed += 1\n\n return new_function\n","sub_path":"API_Extended_Document/test/test_functions.py","file_name":"test_functions.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"311673692","text":"#Leetcode problem Number 965\n#Univalued Tree\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n value = 0 \n ans = True\n def isUnivalTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n if root is None:\n return True\n self.value = root.val \n self.helperFunction(root)\n return self.ans\n def helperFunction(self,root):\n if root is None:\n return \n self.helperFunction(root.left)\n if self.value!= root.val:\n self.ans = False\n self.helperFunction(root.right)\n","sub_path":"Tree_Algorithms/UnivaluesTree.py","file_name":"UnivaluesTree.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"463755727","text":"from django.conf.urls import url\nfrom .views import index, detail, test\n\n\napp_name = 'collections'\nurlpatterns = [\n url(r'^$', index, name='index'),\n url(r'^detail/(?P[0-9]+)$', detail, name='detail'),\n url(r'^test$', test, name='test'),\n]\n","sub_path":"mycollections/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"579647300","text":"import requests\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n#1 웹 문서 가져오기\n\nhtml = urlopen(\"https://www.seoul.go.kr/seoul/autonomy.do\")\nsoup = BeautifulSoup(html, 'html.parser') #html 파싱\n\n#2 웹 문서에서 추출한 데이터를 리스트에 저장\n\n구청이름 = []\n구청주소 = []\n구청전화 = []\n구청홈페이지 = []\n\n구청이름 = soup.select('.tabcont strong')\n구청주소 = soup.select('.tabcont li:nth-of-type(1)')\n구청전화 = soup.select('.tabcont li:nth-of-type(2)')\n구청홈페이지 = soup.select('.tabcont li:nth-of-type(3)')\n\nfor i,s,f,j in zip(구청이름,구청주소,구청전화,구청홈페이지):\n print('구청이름 :',i.text)\n print('구청주소 :',s.text )\n print('구청전화 :',f.text)\n print('구청홈페이지:',j.text)\n print('='*50)\n\n#3. 리스트에 있는 내용을 아래처럼 출력\n\n'''\n [예시]\n 구청이름 : 강동구\n 구청주소 : \n 구청전화 :\n 구청홈페이지 :http~~~ \n \n'''","sub_path":"web/3_beautifulsoup_class/ex05_서울구청.py","file_name":"ex05_서울구청.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"640984438","text":"#!/usr/bin/python -tt\n# Copyright 2010 Google Inc.\n# Licensed under the Apache License, Version 2.0\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Google's Python Class\n# http://code.google.com/edu/languages/google-python-class/\n\n\"\"\"Wordcount exercise\nGoogle's Python class\n\nThe main() below is already defined and complete. It calls print_words()\nand print_top() functions which you write.\n\n1. For the --count flag, implement a print_words(filename) function that counts\nhow often each word appears in the text and prints:\nword1 count1\nword2 count2\n...\n\nPrint the above list in order sorted by word (python will sort punctuation to\ncome before letters -- that's fine). Store all the words as lowercase,\nso 'The' and 'the' count as the same word.\n\n2. For the --topcount flag, implement a print_top(filename) which is similar\nto print_words() but which prints just the top 20 most common words sorted\nso the most common word is first, then the next most common, and so on.\n\nUse str.split() (no arguments) to split on all whitespace.\n\nWorkflow: don't build the whole program at once. Get it to an intermediate\nmilestone and print your data structure and sys.exit(0).\nWhen that's working, try for the next milestone.\n\nOptional: define a helper function to avoid code duplication inside\nprint_words() and print_top().\n\n\"\"\"\n\nimport sys\n\n\n# +++your code here+++\n# Define print_words(filename) and print_top(filename) functions.\n# You could write a helper utility function that reads a file\n# and builds and returns a word/count dict for it.\n# Then print_words() and print_top() can just call the utility function.\n\n###\n\n# This basic command line argument parsing code is provided and\n# calls the print_words() and print_top() functions which you must define.\n\n\ndef read_file(filename):\n with open(filename) as texto:\n contents = texto.read()\n contents = contents.lower()\n new_words = ''\n for letter in contents:\n if letter.isalpha() or letter.isspace():\n new_words += letter\n contents = new_words.split()\n contents.sort()\n return contents\n\n\ndef print_words(filename, flag = True):\n lista_words = read_file(filename)\n contador = {}\n for word in lista_words:\n if not (word in contador):\n contador[word] = lista_words.count(word)\n if flag:\n for word in contador:\n print('%25s %03d' % (word.ljust(25), contador[word]))\n else:\n new_contador = list(contador.items())\n top_20 = sorted(new_contador, key = lambda t: t[1], reverse = True)[:20]\n for top in range(len(top_20)):\n print('%02d %6s %04d' % (top + 1, top_20[top][0].ljust(6), top_20[top][1]))\n\n\n\"\"\"\ndef print_top(filename):\n print_words(filename, flag = False)\n\"\"\"\n\n\ndef main():\n if len(sys.argv) != 3:\n print('usage: ./wordcount.py {--count | --topcount} file')\n sys.exit(1)\n\n option = sys.argv[1]\n filename = sys.argv[2]\n if option == '--count':\n print_words(filename)\n elif option == '--topcount':\n print_words(filename, flag = False)\n else:\n print('unknown option: ' + option)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"basic/wordcount.py","file_name":"wordcount.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"595281452","text":"# _*_ coding: UTF-8 _*_\r\n\r\n# author: dik\r\n# date: 2016-03-04\r\n# 变更推送\r\n\r\n\r\nfrom src.head import *\r\n\r\nclass BaiduNewsPlugin02:\r\n def __init__(self):\r\n pass\r\n\r\n def __call__(self):\r\n return\r\n\r\n def process(self, data_instance):\r\n logging.debug(\"newses ChangeItem starting....\")\r\n if data_instance.status[\"isNew\"]:\r\n change_items = self.build_record(data_instance)\r\n if len(change_items) > 0:\r\n MongoDBDAO.insert_many(\"CG\", \"changeitems\", change_items)\r\n\r\n def build_record(self, data_instance):\r\n change_items = []\r\n\r\n news_records = data_instance.dict[\"items\"]\r\n news_item = news_records[(len(news_records) - 1)]\r\n\r\n item = {\r\n \"status\":0,\r\n \"ename\":data_instance.dict[\"name\"],\r\n \"eid\":data_instance.dict[\"eid\"],\r\n \"ref_id\":data_instance.dict[\"_id\"],\r\n \"items\":[{\r\n \"field\":\"newses\",\r\n \"before\":\"\",\r\n \"after\":json.dumps(news_item,cls=CustomerJsonEncoder),\r\n \"desc\":\"新增新闻信息\"\r\n }],\r\n \"last_updated_time\":datetime.datetime.utcnow(),\r\n \"created_time\":datetime.datetime.utcnow(),\r\n \"info_type\":22,\r\n # \"date\":data_instance.dict[\"date\"],\r\n #\"date\":datetime.datetime.utcnow(),\r\n \"date\":datetime.datetime.strptime(CommonUtils.format_date(news_item[\"time\"],\"%Y-%m-%d\"), \"%Y-%m-%d\"),\r\n \"ops_flag\":0\r\n }\r\n change_items.append(item)\r\n logging.debug(change_items)\r\n\r\n return change_items\r\n","sub_path":"source/dumps_src/BaiduNews/BaiduNewsPlugin02.py","file_name":"BaiduNewsPlugin02.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"335736824","text":"'''\ncustom jwt\ncustom_jwt.py must be in the directory of django app, or the name of custom jwt file must be \"utils.py\" \n'''\n\nfrom datetime import datetime\nfrom calendar import timegm\nfrom rest_framework_jwt.settings import api_settings\n\ndef jwt_payload_handler(user):\n \"\"\" Custom payload handler\n Token encrpts the dictionary returned by this function, and can be decoded by rest_framework_jwt.utils.jwt_decode_handler\n \"\"\"\n return {\n 'user_id': user.pk,\n 'username': user.username,\n 'email': user.email,\n 'is_superuser': user.is_superuser,\n 'exp': datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA,\n 'orig_iat': timegm(datetime.utcnow().utctimetuple())\n }\n\n\ndef jwt_response_payload_handler(token, user=None, request=None):\n \"\"\" Custom response payload handler.\n This function contolls the custom payload afer login or token resfresh. this data is returned through the web API.\n \"\"\"\n return {\n 'token': token,\n 'user': {\n 'username': user.username,\n 'email': user.email,\n }\n }\n","sub_path":"apps/users/custom_jwt.py","file_name":"custom_jwt.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"246942318","text":"# list comprehension\n\ndigitos = [print(i) for i in range(10)]\nexponencial2 = [2**i for i in range(10)]\nexponencial2_2 = [2**i for i in range(1, 11)]\n\n\n# pandas\n# cd ..\n# cd \n# ls\n# columna Index\n\nimport pandas as pd\nfrom pandas import ExcelWriter as ew\n\n\nd = {'col1': [1, 2], 'col2': [3, 4]}\ndf1 = pd.DataFrame(data=d)\n\nprint(df1)\nprint(df1.head())\nprint(df1.columns)\n\ndf2 = pd.DataFrame(exponencial2_2)\n\nprint(df2)\nprint(df2.head())\nprint(df2.columns)\n\n\n\nxl = pd.ExcelFile(\"Clase4/Notorious_ordenes.xls\")\nxl.sheet_names\ndf = xl.parse(\"Orders\")\n\nprint(df)\nprint(df.head())\nprint(df.columns)\n\ndf.iloc[2, 4]\n\ndf.loc[2, 'Producto']\n\ndf['Estado interno']\ndf['Producto']\n\ndef tipos_de_estado(df):\n estados_internos = []\n for i in range(len(df)):\n if df.loc[i, 'Estado interno'] not in estados_internos:\n estados_internos.append(df.loc[i, 'Estado interno'])\n else:\n pass\n return estados_internos\n\ntipos_de_estado = tipos_de_estado(df)\n\ndf['Estado interno'].values\n\ndf2 = df[df['Estado interno'] == 'problemas']\n\n\ndef generar_DF_Excel(df, nombre_archivo):\n nombre_final = nombre_archivo + '.xlsx' \n writer = ew(nombre_final)\n df.to_excel(writer,'Orders2')\n writer.save()\n print('Ok')\n\n\ngenerar_DF_Excel(df2, 'ordenes_problemas')\n","sub_path":"Clase4/clase4.py","file_name":"clase4.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"466180431","text":"from gensim.models.coherencemodel import CoherenceModel\nimport pickle\n\nlda = pickle.load(open('../output/lda_model', 'rb'))\n\n# Compute Coherence Score using c_v\ncoherence_model_lda = CoherenceModel(model=lda['model'], texts= lda['texts'], corpus=lda['corpus'], dictionary=lda['dictionary'],\n coherence='u_mass')\nlda['coherence'] = coherence_model_lda.get_coherence()\nprint('\\nCoherence Score: ', lda['coherence'])\n","sub_path":"cftm/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"116758398","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'Golden'\n\n'''\n趋势型短线交易信号 - 下地狱\n1. 主空品种(包括多转空)的第二波空机会\n2. 调整期一般为5~8天(若是多转空,不排除1~4日短调整夸父逼阴),这里只做蓄势充分的空\n算法逻辑类同步步高:\nstep1:找出20日内最近一波空的最低收盘价日m:收近4日新低+背离5,10日线+ 收阴线;\nstep2:判断最近4~8日偏空调整,另外趋空日必定收在5日线上,用以确定下地狱信号\n\n回测小结:\n1. 下地狱必须遵循:主空或偏空品种,并且第一波空破位后承压10日线调整的第二波空;\n2. 对于整体震荡或偏多震荡品种(铁矿16年之后就是),只有多转空机会,这种往往没有规则的下地狱,更多的是逼阴\n'''\n\nimport time, datetime, sys, os.path\nimport logging\nfrom tqsdk import TqApi, TqSim, TqBacktest #, TargetPosTask\nfrom datetime import date\nimport matplotlib.pyplot as plt\nimport bases\nimport stgy4short\nimport argparse\n\nrq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))\ncurDay = time.strftime('%Y%m%d', time.localtime(time.time()))\ncurHour = time.strftime('%H', time.localtime(time.time()))\ncurDate = datetime.datetime.now().weekday()\ntradingDay = curDay\n\n#TODO: 用sdk获取当前是否交易日,是否有夜盘\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n# 第二步,创建日志文件和控制台两个handler\nlog_path = 'E://proj-futures/logs/'\nlog_name = log_path + tradingDay + '.log'\nlogfile = log_name\nfh = logging.FileHandler(logfile, mode='a+')\nfh.setLevel(logging.DEBUG) # 输出到file的log等级的开关\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG) # 输出到console的log等级的开关\n# 第三步,定义handler的输出格式\nformatter = logging.Formatter(\"%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s\")\nfh.setFormatter(formatter)\nch.setFormatter(formatter)\n# 第四步,将logger添加到handler里面\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n\n### 交易信号汇总\nk_low = 0\nlast_k_low = 0 \ntrading_date = ''\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--SYMBOL')\nargs = parser.parse_args()\n\nif args.SYMBOL != None:\n SYMBOL = args.SYMBOL\nelse:\n SYMBOL = \"DCE.i2005\"\n\n#STEP2:策略执行log\nlogger.info(\"Starting xiadiyu strategy for: %s\"%SYMBOL)\n\napi = TqApi(TqSim())\nklines = api.get_kline_serial(SYMBOL, duration_seconds=60*60*24, data_length=20) \n#ticks = api.get_tick_serial(SYMBOL)\nquote = api.get_quote(SYMBOL)\n\nwhile True:\n api.wait_update()\n\n # 跟踪log信息,日k数据会产生两个信号:一个是开盘时,另一个时收盘;如果想根据收盘k线分析前期趋势,用第二个信号\n # 这样就没有之前认为必须开盘才能分析之前所存在的趋势型机会了。\n # 实盘是只要14:59或盘后任何时间触发运行即可,一次退出;\n # 想尾盘参与策略型机会则收盘前运行回报策略��机会,次日择机参与则盘后任何时间运行即可\n if api.is_changing(klines):\n df = klines.to_dataframe()\n\n #logger.info(\"DATE: %s, close: %f\"%(bases.get_market_day(klines[-1][\"datetime\"]), klines[-1][\"close\"]))\n trading_date = bases.get_market_day(klines[-1][\"datetime\"])\n\n #STEP3-策略型机会判定\n index, k_low = stgy4short.get_index_m(quote, klines, logger)\n #logger.info(\"xiadiyu date: %s, adjust interval: %d\" %(trading_date, 20 - index - 1))\n # TODO:判定趋空日的品质\n if index == 11 or index == 12 or index == 14: #8,7,5日偏空调整\n logger.info(\"MYSTRATEGY - GOOD XIADIYU date: %s, for %s, adjust interval: %d\" %(trading_date, SYMBOL, 20 - index - 1))\n elif index == 13 or index == 15: # 6,4日调整\n logger.info(\"MYSTRATEGY - NORMAL XIADIYU date: %s, for %s, adjust interval: %d\" %(trading_date, SYMBOL, 20 - index - 1))\n\n #收盘跑一次即可\n break\n\napi.close()\nlogger.removeHandler(fh)\n","sub_path":"tqsdk/demo/example/xiadiyu.py","file_name":"xiadiyu.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"377114506","text":"\"\"\"\n\n\"\"\"\n\n# Participant_Number = 5\n# Participant_Data = []\n# registered_participants = 0\n# outputfile = open(\"ParticipantData.txt\", \"w\")\n#\n# while registered_participants <= Participant_Number:\n# TemPartData = [] # name, country, age\n# name = input(\"What is your name? : \")\n# TemPartData.append(name)\n# country = input(\"Please enter your country of origin: \")\n# TemPartData.append(country)\n# age = int(input(\"What is your age #?: \"))\n# TemPartData.append(age)\n# Participant_Data.append(TemPartData)\n# print(Participant_Data)\n#\n# registered_participants += 1\n#\n# for participant in Participant_Data:\n# for data in participant:\n# outputfile.write(str(data)) # str(25) -> \"25\"\n# outputfile.write(\" \")\n# outputfile.write(\"\\n\")\n#\n#\n# outputfile.close()\n\ninputFile = open(\"ParticipantData.txt\", \"r\")\n\ninput_list = []\n\nfor line in inputFile:\n tempParticipant = line.strip(\"\\n\").split()\n # print(tempParticipant)\n input_list.append(tempParticipant)\n # print(input_list)\n # \"Max US 21 \".strip(\"\\n\") - > \"Max US 21 \"\n # \"Max US 21 \".split() -> [\"max\", \"US\", \"21\",]\n\nAge = {}\nprint(input_list)\nfor part in input_list:\n tempAge = int(part[-1])\n if tempAge in Age:\n Age[tempAge] += 1\n else:\n Age[tempAge] = 1\n\nprint(Age)\n\nCountry = {}\n\nfor part in input_list:\n tempCountry = part[1]\n if tempCountry in Country:\n Country[tempCountry] += 1\n else:\n Country[tempCountry] = 1\nprint(\"Countries that attended:\", Country)\nOldest = 0\nYoungest = 100\nMostOccuringAge = 0\ncounter = 0\n\nfor tempAge in Age:\n if tempAge > Oldest:\n Oldest = tempAge\n if tempAge < Youngest:\n Youngest = tempAge\n if Age[tempAge] >= counter:\n counter = Age[tempAge]\n MostOccuringAge = tempAge\n\nprint(Oldest)\nprint(Youngest)\nprint(\"most occuring age is:\", MostOccuringAge, \"With\", counter, \"participants\")\ninputFile.close()\n","sub_path":"i-o/participant-data.py","file_name":"participant-data.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"207128627","text":"import cv2\nimport numpy as np\nimport pandas as pd\nimport os\nimport pathlib\nfrom var import List\n\nfeel = List.img_list\n\nfor item in feel:\n idir = 'img/ans/'\n odir = 'output/ans/'\n fname=item+\"\"\n num_photo=10\n bgr = np.zeros((num_photo,4),dtype=object)\n # print(bgr)\n\n for k in range(num_photo):\n\n img = cv2.imread(idir + fname + '' + str(k+1) + '.jpg') #1番からスタート\n print(idir + fname + '' + str(k+1) + '.jpg')\n h, w, c = img.shape #height, width, channnel\n\n #初期化\n l=0\n b_ave=0; g_ave=0; r_ave=0\n\n for i in range(h):\n for j in range(w):\n #画素値[0,0,0](Black)を除外してピクセルの和とbgrの画素値の合計を計算する\n if(img[i,j,0] != 0 or img[i,j,1] != 0 or img[i,j,2] != 0 ):\n l+=1 #対象となるピクセル数を計算する\n #対象となるピクセルの画素値の和を計算する\n b_ave=b_ave+img[i,j,0]\n g_ave=g_ave+img[i,j,1]\n r_ave=r_ave+img[i,j,2]\n\n #画素値合計をピクセル数で除することでRGBの画素値の平均値を求める\n b_ave=b_ave/l\n g_ave=g_ave/l\n r_ave=r_ave/l\n # print(b_ave)\n\n bgr[k]=np.array([idir + fname + str(k+1) + '.jpg', b_ave, g_ave, r_ave])\n # print(bgr[k])\n\n df = pd.DataFrame(bgr, columns=['path', 'blue', 'green', 'red']) #opencvの並び準BGRに合わせる\n if not os.path.isdir(odir):\n os.makedirs(odir)\n df.to_csv(odir + item + '.csv')\n\n# csv結合\ndef contcat_csv(f_path:str):\n # pathlibのitedir()で対象とするディレクトリのCSVファイル一覧をジェネレーターとして取得\n csvs = [pd.read_csv(str(path)) for path in pathlib.Path(f_path).glob('*.csv')]\n # そのファイル一覧をPandasで読み込んで、pd.concat()で連結してDataFrameとして返す\n return pd.concat(csvs, sort=False)\n\ndf = contcat_csv('output/ans/')\ndf = df.drop(df.columns[0], axis=1)\nid_ = np.arange(len(df))\ndf.insert(0, 'id', id_)\n\n# 連結されたDataFrameをCSVとして保存する\nif not os.path.isdir(\"csv/ans/\"):\n os.makedirs(\"csv/ans/\")\ndf.to_csv('csv/ans/total-concat.csv', index=False, header=None)\n","sub_path":"img_RGB_ans_csv.py","file_name":"img_RGB_ans_csv.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"105966792","text":"# new data processing -> new thread for hystersys\nimport serial\nfrom queue import Queue\nfrom threading import Thread\nimport re\n\n# for sleep\nfrom time import sleep\n\n#to run the game:\nimport os\nimport sys\n\nsys.path.append(os.path.join(os.getcwd(),\".\\\\Chrome-T-Rex-Rush-master\\\\\"))\nsys.path.append(os.path.join(os.getcwd(),\".\\\\Chrome-T-Rex-Rush-master\\\\sprite\"))\n\nimport pyGame\n\n\n\nfrom PyQt5 import uic\n\nimport matplotlib\nmatplotlib.use(\"Qt5Agg\")\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nfrom matplotlib.figure import Figure\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout\n\n################## Serial ####################\n\nSerial_Port = \"COM6\"\nBaud_Rate = 57600\n\nInput_Buf = Queue()\n\n#Data_Buf_Raw = Queue()\n\nExtracted_Data_Buf_2_Show = Queue()\nExtracted_Data_Buf = Queue()\n\n\nPacket_ID_RE = re.compile('165,90,([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}),1,')\n# Please Don't omit the last comma (',') in the RE above because it\n# asures us that the last '1' is really a '1' not a '1' from\n# the next byte! (It's so important to be asure of that because\n# the next byte is '165' in normal state so it has a '1' at the beginning!)\n\ntemp_packet_number = 2000\ntmp_cnst_1 = 40 + 7 * temp_packet_number\nprint(\"getting {} packets\".format( int(temp_packet_number/7)) )\n\nclass sril_thrd(Thread):\n def __init__( self, Serial_Port, Baud_Rate ):\n Thread.__init__( self, name=\"Serial_Thread\")\n self.Serial_Port_ = Serial_Port\n self.Baud_Rate_ = Baud_Rate\n \n \n def run( self ):\n print(\"Serial Port is: {}\".format(self.Serial_Port_))\n print(\"Serial Baud Rate is: {}\".format(self.Baud_Rate_))\n SER = serial.Serial( self.Serial_Port_, self.Baud_Rate_)\n SER.flushInput()\n \n i = 0\n #while i 0:\n# Data_Buf_Raw.put(tmp_2[0]) \n tmp_1 = '' \n# Unpacking the raw data to the processed data queue\n num = int( (tmp_2[0])[0] )*256 + int( (tmp_2[0])[1] )\n amp = int( (tmp_2[0])[2] )*256 + int( (tmp_2[0])[3] )\n \n if cntr_2 > 10:\n Extracted_Data_Buf_2_Show.put( amp )\n cntr_2 = 0\n \n \n Extracted_Data_Buf.put( ( num, amp) )\n cntr_2 += 1\n# print(Extracted_Data_Buf_2_Show.get())\n i += 1\n \n print(tmp_1)\n###########################################\n \n################## GUI ####################\n \nForms = uic.loadUiType( os.path.join( os.getcwd(), 'Ploter.ui') )\n \nclass Ploter( Forms[0], QMainWindow):\n def __init__(self):\n Forms[0].__init__(self)\n QMainWindow.__init__(self)\n self.setupUi(self)\n \n \n self.Tmp_Run_Bttn.clicked.connect(self.Tmp_Run_Bttn_Func)\n \n self.fig = Figure()\n self.ax = self.fig.add_axes([ 0.1, 0.1, 0.8, 0.8])\n \n self.ax.set_ylim([-100,1500])\n self.canvas = FigureCanvas(self.fig)\n self.navi = NavigationToolbar( self.canvas, self)\n \n self.points_x = []\n self.points_y = []\n self.line, = self.ax.plot( self.points_x, self.points_y)\n \n l = QVBoxLayout(self.Plt_Wdgt)\n l.addWidget(self.canvas)\n l.addWidget(self.navi)\n \n def Tmp_Run_Bttn_Func(self):\n \n \n print(\"Ich liebe sie!\")\n\n \n EMG_Shield_Serial_Reader.start()\n EMG_Data_Packet_Extractor.start()\n EMG_Process_Act.start()\n\n print(\"PyGame passed!!!\")\n \n time_x = 0\n while True :\n tmp_amp = Extracted_Data_Buf_2_Show.get(block=True)\n self.points_x.append(time_x)\n self.points_y.append(tmp_amp)\n self.line.set_data(self.points_x, self.points_y)\n self.ax.set_xlim([time_x-300,time_x+300])\n self.fig.canvas.draw()\n pltr_app.processEvents()\n time_x += 1\n \n###########################################\n\n\n############ Data Processing ##############\nthreshould = 480\npacket_number = 2\n\nclass dt_prcss(Thread):\n __strength__ = 0\n __current_state__ = False\n \n def __init__( self):\n Thread.__init__(self, name = \"hystersis for values Thread\")\n \n def run( self ):\n print(\"Data Process Started!\")\n while True:\n if Extracted_Data_Buf.qsize() > (packet_number):\n# print(\"processing one group\")\n amps = []\n for i in range(packet_number):\n a,b = Extracted_Data_Buf.get()\n amps.append(b)\n self.__strength__ = sum(amps) / packet_number\n #print(\"summation = {}\".format(self.__strength__))\n if self.__current_state__ == False:\n if self.__strength__ > threshould:\n self.__current_state__ = True\n print(\"got HIGH\")\n # here should emit\n pyGame.set_high()\n else:\n if self.__strength__ < threshould:\n self.__current_state__ = False\n print(\"got LOW\")\n #here should emit\n pyGame.set_low()\n else:\n sleep(0.1)\n\n########################################### \n \n############## Main Thread ################\n\nEMG_Shield_Serial_Reader = sril_thrd( Serial_Port, Baud_Rate)\nEMG_Shield_Serial_Reader.setDaemon(True)\n\n\nEMG_Data_Packet_Extractor = pckt_xtrctr_thrd()\nEMG_Data_Packet_Extractor.setDaemon(True)\n\n\nEMG_Process_Act = dt_prcss()\nEMG_Process_Act.setDaemon(True)\n\n\n\n\n\n#EMG_Shield_Serial_Reader.join()\n#EMG_Data_Packet_Extractor.join()\n\n\n#for i in range(Extracted_Data_Buf_2_Show.qsize()):\n# print(Extracted_Data_Buf_2_Show.get())\n \n\npltr_app = QApplication(sys.argv)\npltr_w = Ploter()\npltr_w.show()\n\ndef Game_Opener():\n pyGame.main()\n \nt = Thread(target = Game_Opener)\nt.setDaemon(True)\nt.start()\n\n\nsys.exit( pltr_app.exec_() )\n \n########################################### \n \n","sub_path":"Main_PC/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"433828386","text":"# -*- coding: utf-8 -*-\n'''\nInstaller support for OS X.\n\nInstaller is the native .pkg/.mpkg package manager for OS X.\n'''\n\n# Import Python libs\nfrom __future__ import absolute_import\nimport os.path\n\n# Import 3rd-party libs\nfrom salt.ext.six.moves import urllib # pylint: disable=import-error\n\n# Import salt libs\nimport salt.utils.itertools\n\n# Don't shadow built-in's.\n__func_alias__ = {\n 'list_': 'list'\n}\n\n__PKGUTIL = '/usr/sbin/pkgutil'\n\n# Define the module's virtual name\n__virtualname__ = 'darwin_pkgutil'\n\n\ndef __virtual__():\n if __grains__['os'] == 'MacOS':\n return __virtualname__\n return (False, 'The darwin_pkgutil execution module cannot be loaded: '\n 'only available on MacOS systems.')\n\n\ndef list_():\n '''\n List the installed packages.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' darwin_pkgutil.list\n '''\n cmd = [__PKGUTIL, '--pkgs']\n return __salt__['cmd.run_stdout'](cmd, python_shell=False)\n\n\ndef is_installed(package_id):\n '''\n Returns whether a given package id is installed.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' darwin_pkgutil.is_installed com.apple.pkg.gcc4.2Leo\n '''\n for line in salt.utils.itertools.split(list_(), '\\n'):\n if line == package_id:\n return True\n return False\n\n\ndef _install_from_path(path):\n if not os.path.exists(path):\n msg = 'Path \\'{0}\\' does not exist, cannot install'.format(path)\n raise ValueError(msg)\n else:\n cmd = 'installer -pkg \"{0}\" -target /'.format(path)\n return __salt__['cmd.retcode'](cmd)\n\n\ndef install(source, package_id=None):\n '''\n Install a .pkg from an URI or an absolute path.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' darwin_pkgutil.install source=/vagrant/build_essentials.pkg package_id=com.apple.pkg.gcc4.2Leo\n '''\n if package_id is not None and is_installed(package_id):\n return ''\n\n uri = urllib.parse.urlparse(source)\n if uri.scheme == \"\":\n return _install_from_path(source)\n else:\n msg = 'Unsupported scheme for source uri: \\'{0}\\''.format(uri.scheme)\n raise ValueError(msg)\n","sub_path":"salt/modules/darwin_pkgutil.py","file_name":"darwin_pkgutil.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"247663337","text":"import numpy as np\nimport torch\nimport math\n\n\ndef test_mask():\n lengths = np.random.randint(low=10, high=15, size=10)\n src = []\n for l in lengths:\n sent = np.random.randint(10000, size=l)\n pad = np.zeros(16-l).astype(np.int)\n sent = np.concatenate((sent, pad), axis=None)\n src.append(sent)\n\n src = torch.from_numpy(np.stack(src)).long()\n mask = (src != 0).unsqueeze(-2)\n ntokens = mask.sum()\n\n print(ntokens)\n print(np.sum(lengths))\n\n\ndef test_model_numel():\n from model import get\n net, _ = get()\n n = 0\n for p in net.parameters():\n n += p.numel()\n print(p.size())\n print(n)\n\n\ndef test_early_stop():\n exit()\n\n\ndef test_incremental():\n from common import config\n import model\n from utils import get_batch\n net, _ = model.get()\n net.eval()\n \n ckpt = torch.load(\"checkpoints/checkpoint_best_ppl.pth\", map_location='cpu')\n\n # reload model parameters\n s_dict = {}\n for k in ckpt[\"net\"]:\n new_k = k[7:]\n s_dict[new_k] = ckpt[\"net\"][k]\n\n net.load_state_dict(s_dict)\n \n import dataset\n train_iter, _, SRC_TEXT, TGT_TEXT = dataset.get()\n #data_iter = iter(train_iter.get_iterator(True, True))\n #raw_batch = next(data_iter)\n src = np.arange(4, 4+2000).reshape(80, 25)\n tgt = np.arange(4, 4+2400).reshape(80, 30)\n raw_batch = dataset.Batch(\n torch.from_numpy(src).long(),\n torch.from_numpy(tgt).long()\n )\n\n batch = get_batch(\n raw_batch.src, raw_batch.tgt,\n SRC_TEXT.vocab, TGT_TEXT.vocab\n )\n for k, v in batch.items():\n try:\n print(k, v.size())\n except AttributeError:\n pass\n\n with torch.no_grad():\n enc_out = net.encode(src=batch['src'], src_mask=batch['src_mask'])\n # No incremental\n logits1 = net.decode(enc_out, batch['src_mask'], batch['tgt'], batch['tgt_mask'])\n logits1 = net.generator(logits1, log_prob=True)\n\n # Incremental\n print(\"Incremental encoding finished!\")\n tlen = batch['tgt'].size(1)\n cache = {'cur_len':0}\n logits2 = []\n for i in range(tlen):\n x = batch['tgt'][:, i].unsqueeze(-1)\n\n logit = net.decode(\n enc_out, batch['src_mask'], x,\n batch['tgt_mask'][:, i, :(i+1)].unsqueeze(-2), cache\n )\n\n logit = net.generator(logit, log_prob=True)\n \n if i >= 0:\n ref = logits1[:, i, :]\n sys = logit.squeeze()\n \n ref_words = torch.topk(ref, 1)[1].squeeze()\n sys_words = torch.topk(sys, 1)[1].squeeze()\n\n print(\"Diff = {}\".format(torch.sum(ref - sys).item()))\n print(\"Logits sys size : {}, Logits sys : {}\".format(sys.size(), sys.sum().item()))\n print(\"Logits ref size : {}, Logits ref : {}\".format(ref.size(), ref.sum().item()))\n if (ref_words == sys_words).all() == False:\n print(\"Fuck!\")\n print(\"\\n\")\n \n logits2.append(logit)\n cache['cur_len'] = i + 1\n logits2 = torch.cat(logits2, dim=1).contiguous()\n\n print(\"Logits1: {}\".format(torch.sum(logits1).item()))\n print(\"Logits2: {}\".format(torch.sum(logits2).item()))\n\n\ndef test():\n #test_mask()\n #test_model_numel()\n #test_early_stop()\n test_incremental()\n\n\nif __name__ == \"__main__\":\n test()\n","sub_path":"config/base.transfer.combine/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"122837537","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\nfrom SNJKMZS.items import SnjkmzsItem\n\nclass SnjkmzsSpider(scrapy.Spider):\n name = \"snjkmzs\"\n allowed_domains = [\"zasa.sakura.ne.jp\"]\n start_urls = ['https://zasa.sakura.ne.jp/dp/run.php']\n\n def parse(self, response):\n for snj in response.css(\"tr\"):\n if snj.css(\".music\").extract_first() is None:\n continue\n article = SnjkmzsItem()\n# 例: ☆5 (5.9)\n id = snj.css(\".music\").extract_first()\n article['ID'] = id[id.find('?')+4:id.find('-')]\n article['title'] = snj.css(\".music ::text\")[-1].extract()\n# 例: ☆5 (5.9)\n dph = snj.css(\".H ::text\").extract_first()\n article['DPH'] = dph[1:dph.find('(')-1]\n article['uoDPH'] = dph[dph.find('(')+1:-1]\n if snj.css(\".A ::text\").extract_first() is None:\n article['DPA'] = '-'\n article['uoDPA'] = '-'\n else:\n dpa = snj.css(\".A ::text\").extract_first()\n article['DPA'] = dpa[1:dpa.find('(')-1]\n article['uoDPA'] = dpa[dpa.find('(')+1:-1]\n if snj.css(\".L ::text\").extract_first() is None:\n article['DPL'] = '-'\n article['uoDPL'] = '-'\n else:\n dpl = snj.css(\".L ::text\").extract_first()\n article['DPL'] = dpl[1:dpl.find('(')-1]\n article['uoDPL'] = dpl[dpl.find('(')+1:-1]\n yield article\n\n# next_page = response.css(\"div.page-link-option > a::attr('href')\")\n# if next_page:\n# url = response.urljoin(next_page[0].extract())\n# yield scrapy.Request(url, callback=self.parse)\n pass\n","sub_path":"build/lib/SNJKMZS/spiders/snjkmzs.py","file_name":"snjkmzs.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"14927147","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef from_prediction_string_to_world_coords(prediction_string):\n \"\"\"\n Args:\n prediction_string: given PredictionString\n Returns:\n car_id (batch_size, ): ID of car\n euler_angle (batch_size, 3): Euler angle (yaw, pitch, roll)\n camera_coords (batch_size, 3): (x, y, z) in camera coordinates\n \"\"\"\n camera_coords = [value for value in prediction_string.split(' ')]\n camera_coords = np.array(camera_coords).reshape(-1, 7)\n car_id = camera_coords[:, 0]\n euler_angle = camera_coords[:, 1: 4].astype(dtype=np.float32)\n camera_coords = camera_coords[:, 4:].astype(dtype=np.float32)\n\n return car_id, euler_angle, camera_coords\n\ndef from_camera_coords_to_image_coords(camera_coords, camera_matrix):\n \"\"\"\n Args:\n camera_coords (batch_size, 3):\n Returns:\n image_coords (batch_size, 3):\n \"\"\"\n image_coords = np.dot(camera_matrix, camera_coords.T).T # image_coords (batch_size, 3)\n image_coords[:, 0] = image_coords[:, 0] / image_coords[:, 2]\n image_coords[:, 1] = image_coords[:, 1] / image_coords[:, 2]\n\n return image_coords\n \ndef show_heatmap(heatmap, save_path=None):\n \"\"\"\n Args:\n heatmap (H//R, W//R)\n image (H, W)\n \n \"\"\"\n plt.figure()\n plt.imshow(heatmap)\n \n if save_path is not None:\n plt.savefig(save_path)\n \ndef show_image(image, save_path=None):\n plt.figure()\n image = ((image+1)/2*255).int()\n plt.imshow(image)\n \n if save_path is not None:\n plt.savefig(save_path)\n\ndef get_front_or_back(angle):\n \"\"\"\n Args:\n angle:\n Returns:\n is_front: if abs(angle) < math.pi / 2, returns 0\n \"\"\"\n if abs(angle) < math.pi / 2:\n is_front = 1\n else:\n is_front = 0\n return is_front\n \ndef get_keypoints(heatmap, threshold=0.6):\n \"\"\"\n Args:\n heatmap (H//R, W//R):\n \n \"\"\"\n if threshold < 0.5:\n pass\n # raise ValueError(\"Parametes threshold must be grater than 0.5.\")\n H, W = heatmap.size()\n \n mask = heatmap // threshold\n heatmap = mask * heatmap\n \n estimated_key_point = np.zeros((H, W))\n \n for p_h in range(1, H-1):\n for p_w in range(1, W-1):\n if mask[p_h, p_w] > 0.0:\n if is_higher_than_around(heatmap[p_h-1: p_h+2, p_w-1: p_w+2]):\n estimated_key_point[p_h, p_w] = 1.0\n \n return estimated_key_point\n \ndef is_higher_than_around(map_3x3):\n \"\"\"\n Args:\n map_3x3 (3, 3)\n \"\"\"\n \n for row in range(3):\n for column in range(3):\n if map_3x3[2, 2] < map_3x3[row, column]:\n return False\n \n return True\n \n \n","sub_path":"v5/src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"563273695","text":"from keras.utils import np_utils\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Conv2D, LSTM , Flatten, Dropout, MaxPooling2D,Input\nimport matplotlib.pyplot as plt\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor # 항상 분류와 회기가 존재한다 ㅎ\nfrom sklearn.model_selection import GridSearchCV,RandomizedSearchCV\n\ntrain = pd.read_csv('./data/dacon/comp1/train.csv', header=0,index_col=0)\ntest = pd.read_csv('./data/dacon/comp1/test.csv', header=0,index_col=0)\nsubmission = pd.read_csv('./data/dacon/comp1/sample_submission.csv', header=0,index_col=0)\n\nprint('train.shape : ',train.shape) # 10000,75 : x_train, x_test\nprint('test.shape : ',test.shape) # 10000,71 : x_predict\nprint('submission.shape : ',submission.shape) # 10000, 4 : y_predict\n\nprint(train.head())\n\n# print(train.isnull().sum()) \n\ntrain = train.interpolate() # ? 뭔법? -> 보간법//선형보간 # 값들 전체의 선을 그리고 그에 상응하는 값을 알아서 넣어준다? ?? 하나의 선을 긋고 ? 그럼 완전 간단한 예측 모델을 만든거네\n# print(train.isnull().sum()) \n# print(train.isnull().any()) \n# 회기 \n\n# for i in train.columns:\n# # print(i)\n# print(len(train[train[i].isnull()]))\n\n# 보간법에서 앞뒤가 nan이면 채워지는 값도 nan?\n\ntrain = train.fillna(train.mean(),axis=0)\ntest = train.fillna(test.mean(),axis=0)\n# train = train.fillna(method='bfill')\n# test = test.fillna(method='bfill')\ntrain = train.fillna(train.mean(),axis=0)\ntest = train.fillna(test.mean(),axis=0)\n# print()\n\n# for i in train.columns:\n# # print(i)\n# print(len(train[train[i].isnull()]))\n\n\n\ntrain = train.values\ntest = test.values\n\nprint(train.shape)\nprint(test.shape)\n\n# plt.figure(figsize=(71,71))\n# sns.heatmap(train)\n# plt.show()\n\n\nprint(type(train))\n\nx_data = train[:, :-4]\ny_data = train[:, -4:]\n\nprint(x_data.shape)\nprint(y_data.shape)\nx_train, x_test, y_train, y_test = train_test_split(x_data,y_data,random_state=3,shuffle=True,test_size=0.2)\n\n# mm = MinMaxScaler()\n# x_train = mm.fit_transform(x_train)\n# x_test = mm.transform(x_test)\n# test = mm.transform(test)\n\n# 2. model\ndef build_model(drop=0.4, optimizer='adam'):\n input1 = Input(shape=(71,),name='input1')\n x = Dense(256, activation='relu', name='hidden1')(input1)\n x = Dropout(drop)(x)\n x = Dense(256, name='hidden2')(x)\n x = Dropout(drop)(x)\n x = Dense(128, name='hidden3')(x)\n output = Dense(4,activation='relu',name='output')(x)\n model = Model(inputs=input1,outputs=output)\n model.compile(optimizer=optimizer,metrics=['mae'],loss='mse')\n\n return model\n\ndef create_hyperparameters():\n batchs = [32, 64, 128]\n optimizer = ['rmsprop','adam', 'adadelta']\n dropout = np.linspace(0.4, 0.8, 4)\n \n return {'batch_size' : batchs,'optimizer' : optimizer, 'drop': dropout}\n\nmodel = KerasRegressor(build_fn=build_model,verbose=1) # 사이킷런에서 쓸수 있도록 wrapping했다 \n\nparam = create_hyperparameters()\n\nsearch = RandomizedSearchCV(model,param,cv=4)\ntry :\n search.fit(x_train,y_train)\nexcept:\n print(\"Error !!\")\n\n# print(search.best_estimator_)\nprint(search.best_params_)\n# print(search.score(x_test,y_test))\n\n# 3. compile, fit\n# search.compile(optimizer='adam',loss = 'mse', metrics = ['mae'])\n\n# search.fit(x_train,y_train,epochs=30,batch_size=3,callbacks=[],verbose=2,validation_split=0.1)\n\n# loss = search.evaluate(x_test,y_test)\n\n# print(loss)\n\ny_pred = search.predict(test)\n\na = np.arange(10000,20000)\ny_pred = pd.DataFrame(y_pred,a)\ny_pred.to_csv('./data/dacon/comp1/sample_submission.csv', index = True, header=['hhb','hbo2','ca','na'],index_label='id') ","sub_path":"dacon/dacon01/dacon01_start_Ver_6.py","file_name":"dacon01_start_Ver_6.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"523716195","text":"variables = {\"rationnel\", \"complexe\", \"matrice\", \"polynôme\"}\n\ndef matrice(entree):\n\tmatrice = []\n\tlength = None\n\tentree = entree.replace(\"]\", \"\")\n\tentree = entree.replace(\"[\", \"\")\n\tsplit = entree.split(\";\")\n\tfor line in split:\n\t\ttmp = line.split(\",\")\n\t\tif not length:\n\t\t\tlength = len(tmp)\n\t\telse:\n\t\t\tif len(tmp) != length:\n\t\t\t\tprint(\"Problème de dimension dans la matrice.\")\n\t\t\t\treturn None\n\t\tmatrice.append(tmp)\n\tprint(matrice)\n\treturn matrice\n\ndef rationnel(entree):\n\treturn None\n\ndef complexe(entree):\n\treturn None\n\nfunction = {\"rationnel\": rationnel, \"complexe\": complexe}\n\ndef nombre(tokens):\n\ttyp = None\n\tfor token in tokens:\n\t\tif token['inconnu'] == 'i':\n\t\t\ttyp = 'complexe'\n\t\telif typ == None and token['inconnu'] != None:\n\t\t\ttyp = 'fonction'\n\t\telif token['inconnu'] == None:\n\t\t\ttyp = 'rationnel'\n\n\treturn None","sub_path":"type_variable.py","file_name":"type_variable.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"88993197","text":"import numpy as np\nfrom copy import deepcopy\nfrom collections import namedtuple\nfrom functools import reduce\n\n\nclass AbstractClustering(object):\n \"\"\"\n The trait and classes in this file provides utility functionality, \n which is not directly needed to understand the SubKmeans algorithm\n \"\"\"\n def __init__(self):\n self.InitClustersAndRotation = namedtuple(\"InitClustersAndRotation\", [\"rotationMatrix\", \"clusters\"])\n\n def calcPc(self, dims: int, m: int) -> np.ndarray:\n if m > 0:\n return np.vstack((np.eye(m), np.zeros(shape=(dims - m, m))))\n else:\n return np.zeros((dims, 0))\n\n def calcPn(self, dims: int, m: int) -> np.ndarray:\n if m < dims:\n return np.vstack((np.zeros((m, dims - m)), np.eye(dims - m)))\n else:\n return np.zeros((m, 0))\n\n def initRotationAndClusters(self, data: np.ndarray, k: int, m: int, clusterSampler, rand=np.random.uniform):\n nrOfDims = data.shape[1]\n randRotation = np.linalg.qr(rand(size=(nrOfDims, nrOfDims)))[0]\n mapping = np.matmul(self.calcPc(nrOfDims, m).T, randRotation.T)\n \n rotatedData = np.matmul(mapping, data.T).T # n x m\n clusterCenters = clusterSampler(rotatedData, k)\n\n # dps: data points\n dps2Clusters = {idx: ([], []) for idx in range(len(clusterCenters))}\n for dpIdx in range(len(rotatedData)):\n dpr = rotatedData[dpIdx]\n _, clusterId = min(zip(clusterCenters, range(len(clusterCenters))), key=lambda mcd: np.sum((dpr - mcd[0])**2))\n clusterDpList, idList = dps2Clusters[clusterId]\n clusterDpList.append(data[dpIdx])\n idList.append(dpIdx)\n\n clusterValues = list(dps2Clusters.values())\n if any(map(lambda value: not value[1], clusterValues)):\n return self.initRotationAndClusters(data, k, m, clusterSampler)\n else:\n return self.InitClustersAndRotation(randRotation, clusterValues)\n \n \nclass SubKmeansCluster(object):\n def __init__(self, fullDimMean: np.ndarray, scatterMatrix: np.ndarray, dataPoints: \"list of indices\"):\n self.fullDimMean = fullDimMean\n self.scatterMatrix = scatterMatrix\n self.dataPoints = list(dataPoints)\n self.nrOfDps = len(dataPoints)\n \n def copy(self, **kwargs):\n inputs = {\"fullDimMean\": self.fullDimMean,\n \"scatterMatrix\": self.scatterMatrix,\n \"dataPoints\": self.dataPoints}\n inputs.update(kwargs)\n return SubKmeansCluster(**inputs)\n\n def withNewDataPoints(self, newDps: list):\n \"\"\" Update in `dpAssignmentStep`\n \"\"\"\n return self.copy(dataPoints=newDps)\n\n def withNewMeanAndScatter(self, mean: np.ndarray, scatter: np.ndarray):\n \"\"\" Update in `updateClusterCenters`\n \"\"\"\n return self.copy(fullDimMean=mean, scatterMatrix=scatter)\n\n\nclass Config(object):\n def __init__(self, k: int, # Nr of clusters\n m: int, # nr of clustering dimensions\n clusters: list,\n fullDimNoiseMean: np.ndarray,\n scatterMatrixAllData: np.ndarray,\n transformation: np.ndarray, # each column represents one transformation vector for one dimension\n eigenvalues: np.ndarray,\n data: list):\n self.k = k\n self.m = m\n self.clusters = clusters\n self.fullDimNoiseMean = fullDimNoiseMean\n self.scatterMatrixAllData = scatterMatrixAllData\n self.transformation = transformation\n self.eigenvalues = eigenvalues\n self.data = data\n\n self.nrOfDims = data.shape[1]\n\n def copy(self, **kwargs):\n inputs = {\"k\": self.k,\n \"m\": self.m,\n \"clusters\": self.clusters,\n \"fullDimNoiseMean\": self.fullDimNoiseMean,\n \"scatterMatrixAllData\": self.scatterMatrixAllData,\n \"transformation\": self.transformation,\n \"eigenvalues\": self.eigenvalues,\n \"data\": self.data}\n inputs.update(kwargs)\n return Config(**inputs)\n\n def withNewClusters(self, newClusters):\n \"\"\" Update in `dpAssignmentStep`\n \"\"\"\n return self.copy(clusters=newClusters)\n\n\nclass Costs(object):\n def __init__(self, noiseData: float, clusterData: float):\n self.noiseData = noiseData\n self.clusterData = clusterData\n self.total = noiseData + clusterData\n\n def __str__(self):\n return f\"Costs: - noiseData: {self.noiseData} clusterData: {self.clusterData} total: {self.total}\"\n\n __repr__ = __str__\n\n\nclass Results(object):\n def __init__(self, labels: list, finalCosts: Costs, config: Config):\n self.labels = labels\n self.finalCosts = finalCosts\n self.config = config\n\n def m(self):\n return self.config.m\n\n def transformation(self):\n return self.config.transformation\n\n\nclass InitClusterCentroids(object):\n @classmethod\n def useKmpp(cls, data: np.ndarray, k: int, maxNrOfDpsToConsider=5000, rand=np.random):\n nrOfPoints = data.shape[0]\n sampleData = data[rand.randint(0, nrOfPoints, maxNrOfDpsToConsider)] if nrOfPoints > maxNrOfDpsToConsider else data\n\n initIdx = rand.randint(0, sampleData.shape[0])\n\n dataPoints = sampleData\n initCenter = [dataPoints[initIdx]]\n remainingData = list(range(dataPoints.shape[0]))\n remainingData.remove(initIdx)\n\n return cls.kppChooseNextCenter(initCenter, dataPoints, remainingData, k - 1)\n\n @classmethod\n def kppChooseNextCenter(cls, centers: list, data: np.ndarray, remainingData: list, stillToChoose: int, rand=np.random):\n # TODO: Not the fastest implementation...\n if stillToChoose == 0:\n return centers\n \n squaredDistances = np.array([reduce(min, [((c - data[dpIdx]) ** 2).sum() for c in centers], np.Inf) for dpIdx in remainingData])\n\n # Warning: Remove `val probAdjusted = if (prob.isNaN) 1e-10 else prob`\n probs = squaredDistances / squaredDistances.sum()\n\n newCenter = np.random.choice(remainingData, p=probs)\n centers.append(data[newCenter])\n remainingData.remove(newCenter)\n return cls.kppChooseNextCenter(centers, data, remainingData, stillToChoose - 1)\n","sub_path":"src/subkmeans/AbstractClustering.py","file_name":"AbstractClustering.py","file_ext":"py","file_size_in_byte":6411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187071392","text":"\"\"\"\nleetcode 64\n\"\"\"\n\n\ndef minPathSum(grid):\n if grid is None:\n return 0\n if len(grid) <= 1:\n return sum(grid[0])\n if len(grid[0]) <= 1:\n sum_result = 0\n for loc in grid:\n sum_result += sum(loc)\n return sum_result\n\n row = len(grid)\n loc = len(grid[0])\n dp = grid\n for i in range(1, row):\n dp[i][0] = dp[i - 1][0] + grid[i][0]\n for i in range(1, loc):\n dp[0][i] = dp[0][i - 1] + grid[0][i]\n for i in range(1, row):\n for j in range(1, loc):\n dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])\n return dp[i][j]\n\n\nif __name__ == '__main__':\n grid = [\n [1, 3, 1],\n [1, 5, 1],\n [4, 2, 1]\n ]\n # grid = [[0], [1]]\n min_sum = minPathSum(grid)\n print(min_sum)\n","sub_path":"medium/py/MinPathSum_64.py","file_name":"MinPathSum_64.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"273937243","text":"import numpy as np\nfrom tkinter import *\nfrom tkinter.messagebox import *\nimport cv2\nfrom PIL import Image, ImageTk\nimport PIL\nfrom math import *\nfrom copy import *\n\n##Fenêtre\nWIDTH = 400\nHEIGHT = 400\nSLIDERLENGTH = 100\n\n##Sliders Hyperparamètres\nCOLUMNS = 5\nCARACS = 20 #Nombre de paramètres ajustables\nROWS = ceil(CARACS / COLUMNS)\n#VARIABLES = np.random.rand(CARACS)\nmyFrame = Tk()\n\nVARIABLES = []\nfor _ in range(CARACS):\n a = DoubleVar()\n VARIABLES.append(a)\n\nABSOLUTE = 'D:/Documents/Prepa/TIPE'\n\npathNormal = ABSOLUTE + \"/Images/Normal/\"\npathAltered = ABSOLUTE + \"/Images/Altered/\"\npathModels = ABSOLUTE + \"/Models/\"\n\n\n\nmyFrame.title('Auto-encoder')\n\nissou = 0\n\nphoto = []\n\ndef loadNN():\n temp = np.random.randint(0, 255, (WIDTH, HEIGHT), dtype = 'i3').astype(np.uint8)\n return ImageTk.PhotoImage(image = Image.fromarray(temp))\n\ndef rechargerImage():\n global imageCanvas\n imageCanvas.delete(ALL)\n imageCanvas.create_image(0, 0, anchor = NW, image = loadNN())\n\ndef generer():\n global VARIABLES\n arguments = np.zeros(CARACS)\n for i in range(CARACS):\n arguments[i] = VARIABLES[i].get()\n print(arguments)\n\nimageCanvas = Canvas(myFrame, width = WIDTH, height = HEIGHT)\ntemp = ImageTk.PhotoImage(Image.open(pathNormal + '1.png').resize((WIDTH, HEIGHT), PIL.Image.ANTIALIAS))\n\n\nimageCanvas.create_image(0, 0, anchor = NW, image = temp)\nimageCanvas.pack(side = LEFT)\n\nslidersFrameMaster = Frame(myFrame)\n#VARIABLES = [1, 2, 3, 4]\n##Construction des sliders\nSLIDERS = []\nfor i in range(ROWS):\n sliderFrame = Frame(slidersFrameMaster)\n for j in range(COLUMNS):\n SLIDERS.append(Scale(sliderFrame, from_ = - 1, to = 1, orient = VERTICAL, length = SLIDERLENGTH, resolution = 0.1, tickinterval = 0.1, width = 20, variable = VARIABLES[i * COLUMNS + j]).pack(side = LEFT))\n sliderFrame.pack()\n\ndef lol():\n for V in VARIABLES:\n print(V.get())\n\nBouton = Button(slidersFrameMaster, text = 'lol', command = lol).pack()\nslidersFrameMaster.pack(side = RIGHT, padx = 10, pady = 10)\n\ngenerateButton = Button(slidersFrameMaster, text = 'Générer', command = generer).pack()\n\nmyFrame.mainloop()\n","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"317482737","text":"### Owner: David Huang\n### Model: Random Forest\n### City: New York City\n### Date: 2019-02-04\n\n############################################################ CHANGE LOG\n# 2019-01-21 Created file\n# 2019-01-23 Updated to run different features in one workflow\n# 2019-01-28 Added with features_3 data and excluded death-related targets\n# 2019-02-02 Added casualties, ability to change director, added new variables\n# 2019-02-04 Updated with features_5 and imputation via fillna()\n\n############################################################ LOAD & PREP\n\n# Load packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n# Set current directory (change to your own director)\npath = r\"D:\\_dhuang\\Work\\NYU Stern MSBA Work\\Capstone\\Data\\CapstoneModeling\"\nos.chdir(path)\n\n# Set options\npd.set_option('display.max_rows', 100)\npd.set_option('display.max_columns', 100)\npd.set_option('display.float_format', '{:,.5f}'.format)\n\n# Load datasets\nf1 = pd.read_csv('df_features_1.csv') # Count data\nf2 = pd.read_csv('df_features_2.csv') # Normalized by population\nf3 = pd.read_csv('df_features_3.csv') # Normalized by land\nf4 = pd.read_csv('df_features_4.csv') # Ron's new variables\nf5 = pd.read_csv('df_features_5.csv') # Features 1 and 4 combined\nf6 = pd.read_csv('df_features_6.csv') # Features 1 with normalized Casualties\n\n# Setting random state\nSEED = 1234\n\n############################################################ WORKFLOW FUNCTIONS\n\n# Load packages\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_error as MSE\n\n# Create model workflow that prep, train, and test random forest model\ndef rando(df, city, y_var, n_trees, depth, max_feat):\n \n # Split data into training and test sets\n geo = df[df['City'] == city].fillna(df.mean())\n X = geo.drop(['GEOID', 'City', 'Collisions', 'Casualties',\n 'PedeInjuries', 'PedeDeaths', 'TotalInjuries', \n 'TotalDeaths'], axis = 1)\n y = geo[y_var]\n \n # Split data into\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size = 0.3, random_state = SEED)\n \n # Model fitting\n rf = RandomForestRegressor(\n n_estimators = n_trees, \n max_depth = depth,\n max_features = max_feat,\n random_state = SEED)\n rf.fit(X_train, y_train)\n \n # Predict class probability using fitted model \n y_pred = rf.predict(X_test)\n \n # Score calculation\n train_score = rf.score(X_train, y_train)\n test_score = rf.score(X_test, y_test)\n rmse_score = np.sqrt(MSE(y_test, y_pred))\n \n # Prin results\n print(\"MODEL OUTPUT ****************************************\")\n print(\"\")\n print(\"Target City: {}\".format(geo['City'].unique()))\n print(\"Target Variable: {}\".format(y_var))\n print(\"Train Score: {:.2f}\".format(train_score))\n print(\"Test Score: {:.2f}\".format(test_score))\n print(\"Model RMSE: {:.2f}\".format(rmse_score))\n print(\"Target Mean: {:.2f}\".format(np.mean(y)))\n print(\"Target Stdev: {:.2f}\".format(np.std(y)))\n \n # Visualizing features importances\n importances = pd.Series(\n \tdata = rf.feature_importances_,\n \tindex = X_train.columns)\n importances_sorted = importances.sort_values()\n importances_sorted.plot(kind = 'barh', color = 'lightgreen', figsize = (7, 5))\n plt.title('Features Importances')\n plt.show()\n \n # Return prediction output as dataframe\n # pred_output = pd.DataFrame({'y_test' : y_test, 'y_pred' : y_pred})\n # pred_output.to_csv('pred_output.csv', index = False)\n \n # Spaceholder\n print(\"\")\n print(\"END OF OUTPUT ***************************************\")\n print(\"\")\n \n\n############################################################ NYC, OVERALL CASUALTIES\n \n# Run random forest model on NYC, Total Injuries, Feature Set 1\n# Train Score 0.45 / Test Score 0.24 / RMSE 79.26\nrando(df = f1, \n city = \"NYC\", \n y_var = \"Casualties\", \n n_trees = 500, \n depth = 5,\n max_feat = 0.50\n )\n\n# Run random forest model on NYC, Total Injuries, Feature Set 2\n# Train Score 0.40 / Test Score 0.19 / RMSE 81.82\nrando(df = f2,\n city = \"NYC\", \n y_var = \"Casualties\", \n n_trees = 500, \n depth = 5,\n max_feat = 0.50\n )\n\n# Run random forest model on NYC, Total Injuries, Feature Set 3\n# Train Score 0.41 / Test Score 0.17 / RMSE 82.87\nrando(df = f3,\n city = \"NYC\", \n y_var = \"Casualties\", \n n_trees = 500, \n depth = 5,\n max_feat = 0.5\n )\n\n# Run random forest model on NYC, Total Injuries, Feature Set 4 (Ron's new features)\n# Train Score 0.72 / Test Score 0.47 / RMSE 66.08\nrando(df = f4,\n city = \"NYC\",\n y_var = \"Casualties\",\n n_trees = 500,\n depth = 5,\n max_feat = 0.50\n )\n\n# Run random forest model on NYC, Total Injuries, Feature Set 5 (f1 and f4 combination)\n# Train Score 0.73 / Test Score 0.48 / RMSE 65.60\nrando(df = f5,\n city = \"NYC\",\n y_var = \"Casualties\",\n n_trees = 500,\n depth = 5,\n max_feat = 0.50\n )\n\n# Run random forest model on NYC, Total Injuries (Normalized), Features Set 6\n# Train Score 0.89 / Test Score 0.41 / RMSE 0.31\nrando(df = f6,\n city = \"NYC\",\n y_var = \"Casualties\",\n n_trees = 500,\n depth = 5,\n max_feat = 0.50\n )\n","sub_path":"archive/RandomForest_NY.py","file_name":"RandomForest_NY.py","file_ext":"py","file_size_in_byte":5463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"249338277","text":"#!/usr/bin/env python3\n\n'''\nInput: The static xml (say X_clang.xml)\nOutput: The function signatures extracted from it (corr. file shall be X.funcargs)\n'''\n\nimport sys\nimport os\n\nfrom xml.etree.ElementTree import Element, SubElement\nfrom xml.etree import ElementTree as ET\nfrom xml.dom import minidom\n\n# Tags for function declarations.\nFunctionTags = {'CXXConstructor', 'CXXDestructor', 'CXXMethod', 'FunctionDecl'}\n\ndef emit_funcargs(input_filename, output_filename) :\n \"\"\"\n Generates the .funcargs file.\n This just prints data already being extracted in static XML in a different format.\n \"\"\"\n header = '# FILENAME\\tFUNCNODEID\\tFUNCNAME\\tNARGS\\tARGTYPE*\\tRETTYPE'\n with open(input_filename, 'r') as xml_file, open(output_filename, 'w') as output_file :\n print(header, file=output_file)\n tu_tree = ET.parse(xml_file)\n for node in tu_tree.iter():\n if node.tag in FunctionTags:\n args = node.attrib['funcargs']\n if args != '':\n args = args.split(',')\n # added check because template definitions have empty linkage name\n # and also are useless for us (?)\n if node.attrib['linkage_name'] != '':\n print(node.attrib['file'], node.attrib['id'],\n node.attrib['linkage_name'], len(args), '\\t'.join(args),\n node.attrib['return_type'], sep='\\t', file=output_file)\n\n\nif __name__ == '__main__' :\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('static_xml', type=str, help='static files')\n parser.add_argument('output', type=str, help='output file')\n\n try:\n args = parser.parse_args()\n except Exception as e :\n parser.print_help()\n exit(1)\n\n emit_funcargs(args.static_xml, args.output)\n","sub_path":"parsers/funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"125746789","text":"from celery.decorators import task\nfrom celery.utils.log import get_task_logger\nfrom time import sleep\n\n\nlogger = get_task_logger(__name__)\n@task(name='my_first_task')\ndef my_first_task(duration):\n sleep(duration)\n return('first_task_done')\n\ndef backoff(attempts):\n return 2 ** attempts\n\n@task(bind=True, max_retries=4)\ndef data_extractor(self):\n try:\n for i in range(1, 11):\n print('Crawling HTML DOM')\n if i == 5:\n raise ValueError('Crawling index error')\n except Exception as exc:\n print('There was an exception lets retry after 5 seconds')\n raise self.retry(exc=exc, countdown=backoff(self.request.retries))\n\n\n","sub_path":"app/app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"429581741","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/edill/mc/lib/python3.5/site-packages/skxray/core/tests/test_speckle.py\n# Compiled at: 2016-03-04 05:19:32\n# Size of source mod 2**32: 4626 bytes\nfrom __future__ import absolute_import, division, print_function\nimport logging, numpy as np\nfrom numpy.testing import assert_array_almost_equal, assert_almost_equal\nfrom skimage.morphology import convex_hull_image\nfrom .. import speckle as xsvs\nfrom .. import roi\nfrom skxray.testing.decorators import skip_if\nlogger = logging.getLogger(__name__)\n\ndef test_xsvs():\n images = []\n for i in range(5):\n int_array = np.tril((i + 2) * np.ones(10))\n int_array[int_array == 0] = i + 1\n images.append(int_array)\n\n images_sets = [np.asarray(images)]\n roi_data = np.array(([4, 2, 2, 2], [0, 5, 4, 4]), dtype=np.int64)\n label_array = roi.rectangles(roi_data, shape=images[0].shape)\n prob_k_all, std = xsvs.xsvs(images_sets, label_array, timebin_num=2, number_of_img=5, max_cts=None)\n assert_array_almost_equal(prob_k_all[(0, 0)], np.array([0.0, 0.0, 0.2, 0.2, 0.4]))\n assert_array_almost_equal(prob_k_all[(0, 1)], np.array([0.0, 0.2, 0.2, 0.2, 0.4]))\n\n\ndef test_normalize_bin_edges():\n num_times = 3\n num_rois = 2\n mean_roi = np.array([2.5, 4.0])\n max_cts = 5\n bin_edges, bin_cen = xsvs.normalize_bin_edges(num_times, num_rois, mean_roi, max_cts)\n assert_array_almost_equal(bin_edges[(0, 0)], np.array([0.0, 0.4, 0.8,\n 1.2, 1.6]))\n assert_array_almost_equal(bin_edges[(2, 1)], np.array([0.0, 0.0625, 0.125,\n 0.1875, 0.25, 0.3125,\n 0.375, 0.4375, 0.5,\n 0.5625, 0.625, 0.6875,\n 0.75, 0.8125, 0.875,\n 0.9375, 1.0, 1.0625,\n 1.125, 1.1875]))\n assert_array_almost_equal(bin_cen[(0, 0)], np.array([0.2, 0.6, 1.0, 1.4]))","sub_path":"pycfiles/scikit-xray-0.0.5.post0.linux-x86_64.tar/test_speckle.cpython-35.py","file_name":"test_speckle.cpython-35.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"416914849","text":"from django.shortcuts import get_object_or_404, render, HttpResponseRedirect\nfrom userprofile.models import UserProfile\nfrom .models import TableMoney, Month, ExtraTableMoney\nfrom .forms import MonthCreateForm, WorkDayFormSet, TableMoneyPayFormSet, ExtraTableMoneyForm, ExtraTableMoneyPayFormSet\nfrom django.core.urlresolvers import reverse\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\n# Create your views here.\n\ndef table_money_list(request):\n\tmonths = Month.objects.all()\n\n\tif request.method == 'GET':\n\t\tcreat_month = request.GET.get('try_create')\n\t\tif creat_month:\n\t\t\tmessages.add_message(request, messages.INFO, 'ss')\n\t\t\treturn HttpResponseRedirect(reverse(\"holiday_list\"))\n\n\tcontext = {\n\t\t'months':months,\n\t}\n\treturn render(request, 'table_money_list.html', context)\n\n\ndef table_money_detail(request, pk):\n\tfrom holiday.models import HolidayMonth, HolidayMonthFromDocx\n\tmonths = get_object_or_404(Month, pk=pk)\n\ttable_moneys = months.tablemoney_set.all()\n\tholiday = get_object_or_404(HolidayMonthFromDocx, month=months.month, year=months.year)\n\textra_table_moneys = ExtraTableMoney.objects.filter(identify=str(months.year)+str(months.month))\n\n\n\t# if request.method == 'GET':\n\t# \tdelete_month = request.GET.get('delete')\n\t# \tif delete_month:\n\t# \t\tmonths.delete()\n\t# \t\treturn HttpResponseRedirect('/tablemoney/')\n\n\tcontext = {\n\t\t'months':months,\n\t\t'table_moneys':table_moneys,\n\t\t'holiday':holiday,\n\t\t'extra_table_moneys': extra_table_moneys\n\t}\n\n\n\n\treturn render(request, 'table_money_detail.html', context)\n\n\ndef delete(request):\n\tc = TableMoney.objects.all()\n\tprint(c)\n\tc.delete()\n\n\n\treturn HttpResponseRedirect('/tablemoney/')\n\n\n# def month_create(request):\n# \tform = MonthCreateForm()\n\n# \t# old_month = Month.objects.all()\n# \t# if old_month.count() > 10:\n# \t# \tMonth.objects.all().order_by(\"pk\")[0].delete()\n\n# \tif request.method == 'POST':\n# \t\tform = MonthCreateForm(request.POST)\n# \t\tif form.is_valid():\n# \t\t\tmonth = form.cleaned_data['month']\n# \t\t\tyear = form.cleaned_data['year']\n# \t\t\tif Month.objects.filter(month=month, year=year):\n# \t\t\t\tmessages.add_message(request, messages.INFO, '此月份表格已製作')\n# \t\t\telse:\n# \t\t\t\tnew_month = form.save()\n# \t\t\t\tnew_month.get_payer()\n\n# \t\t\treturn HttpResponseRedirect('/tablemoney/' + str(new_month.pk))\n\n# \treturn render(request, 'table_money_create.html', {'form': form})\n\n\ndef table_money_pay(request, pk):\n\tmonths = get_object_or_404(Month, pk=pk)\n\ttable_moneys = months.tablemoney_set.all()\n\tformset = TableMoneyPayFormSet(queryset=table_moneys)\n\n\tif request.method =='POST':\n\t\tformset = TableMoneyPayFormSet(request.POST)\n\n\t\tif formset.is_valid():\n\t\t\tformset.save(commit=False)\n\t\t\tfor form in formset:\n\t\t\t\tform.save()\n\t\t\tmessages.add_message(request, messages.INFO, '繳費完成')\n\t\t\treturn HttpResponseRedirect('/tablemoney/' + str(months.pk))\n\n\tcontext = {\n\t'formset': formset,\n\t'months': months\n\t}\n\treturn render(request, 'table_money_pay.html', context)\n\n\n\ndef extra_table_money_pay(request, pk):\n\tmonths = get_object_or_404(Month, pk=pk)\n\textra_table_moneys = ExtraTableMoney.objects.filter(identify=str(months.year)+str(months.month))\n\tformset = ExtraTableMoneyPayFormSet(queryset=extra_table_moneys)\n\n\tif request.method =='POST':\n\t\tformset = ExtraTableMoneyPayFormSet(request.POST)\n\n\t\tif formset.is_valid():\n\t\t\tformset.save(commit=False)\n\t\t\tfor form in formset:\n\t\t\t\tform.save()\n\t\t\tmessages.add_message(request, messages.INFO, '繳費完成')\n\t\t\treturn HttpResponseRedirect('/tablemoney/' + str(months.pk))\n\n\tcontext = {\n\t'formset': formset,\n\t'months': months\n\t}\n\treturn render(request, 'extra_table_money_pay.html', context)\n\n\ndef add_extra_table_money(request, pk):\n\tform = ExtraTableMoneyForm()\n\tmonths = get_object_or_404(Month, pk=pk)\n\n\tif request.method == 'POST':\n\t\tform = ExtraTableMoneyForm(request.POST)\n\t\tif form.is_valid():\n\t\t\textra = form.save(commit=False)\n\t\t\textra.month = months\n\t\t\textra.year = months.year\n\t\t\textra.save()\n\n\t\t\tmessages.add_message(request, messages.INFO, '項目新增完成')\n\t\t\treturn HttpResponseRedirect('/tablemoney/' + str(months.pk))\n\n\tcontext = {\n\t\t'form': form,\n\t\t'months': months,\n\t}\n\n\treturn render(request, 'add_extra_table_money.html', context)\n\ndef delete_extra_table_money_list(request, pk):\n\tmonth = get_object_or_404(Month, pk=pk)\n\textra_table_moneys = ExtraTableMoney.objects.filter(identify=str(month.year)+str(month.month))\n\n\tif request.method == 'GET':\n\t\tdelete_pk = request.GET.get('pk')\n\t\tdelete_extra_table_money = request.GET.get('delete')\n\n\t\tif delete_extra_table_money:\n\t\t\tExtraTableMoney.objects.filter(pk=delete_pk).delete()\n\t\t\tmessages.add_message(request, messages.INFO, '已刪除繳費項目')\n\t\t\treturn HttpResponseRedirect(reverse(table_money_detail, kwargs={\"pk\":pk}))\n\tcontext = {\n\t\t'month':month,\n\t\t'extra_table_moneys':extra_table_moneys,\n\t}\n\n\treturn render(request, 'delete_extra_table_money.html', context)\n","sub_path":"tablemoney/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"122785619","text":"__author__ = 'CroMarmot'\n\nimport RPi.GPIO as GPIO\nimport threading\nimport time\n \nclass PiZyPwm(threading.Thread):\n def __init__(self, frequency, gpioPin, gpioScheme):\n self.baseTime = 1.0 / frequency\n self.maxCycle = 100.0\n self.sliceTime = self.baseTime / self.maxCycle\n self.gpioPin = gpioPin\n self.terminated = False\n self.toTerminate = False\n GPIO.setmode(gpioScheme)\n\n def start(self, dutyCycle):\n self.dutyCycle = dutyCycle\n GPIO.setup(self.gpioPin, GPIO.OUT)\n self.thread = threading.Thread(None, self.run, None, (), {})\n self.thread.start()\n\n def run(self):\n while self.toTerminate == False:\n if self.dutyCycle > 0:\t\t\t\n GPIO.output(self.gpioPin, GPIO.HIGH)\n time.sleep(self.dutyCycle * self.sliceTime)\n \n if self.dutyCycle < self.maxCycle:\n GPIO.output(self.gpioPin, GPIO.LOW)\n time.sleep((self.maxCycle - self.dutyCycle) * self.sliceTime)\n\n self.terminated = True\n\n def changeDutyCycle(self, dutyCycle):\n self.dutyCycle = dutyCycle\n\n def changeFrequency(self, frequency):\n self.baseTime = 1.0 / frequency\n self.sliceTime = self.baseTime / self.maxCycle\n\n def stop(self):\n self.toTerminate = True\n while self.terminated == False:\n time.sleep(0.01)\n \n GPIO.output(self.gpioPin, GPIO.LOW)\n GPIO.setup(self.gpioPin, GPIO.IN)","sub_path":"raspberry/python/pizypwm.py","file_name":"pizypwm.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"547963501","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport os\nfrom fnmatch import fnmatch\nimport imageio\nimport numpy as np\ndef getTestFiles(root):\n data = {'images':[], 'labels': []}\n subdirs = next(os.walk(root))[1]\n if not subdirs:\n data['images'] = [os.path.join(root, name) for name in next(os.walk(root))[2] if fnmatch(name, \"*.png\")]\n return data\n for subdir in subdirs:\n # print subdir\n path = os.path.join(root, subdir)\n # print path\n subfiles = [os.path.join(path, name) for name in next(os.walk(path))[2] if fnmatch(name, \"*.png\")]\n data['images'] = data['images'] + subfiles\n data['labels'] = data['labels'] + [subdir] * len(subfiles)\n return data\n\npath = '/Users/henry/Desktop/Football_Project/test/'\nfiles = getTestFiles(path)\nimages = [imageio.imread(img) for img in files['images']]\n#images = np.asarray(images)\n","sub_path":"dataLoader.py","file_name":"dataLoader.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"81210955","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nfrom math import ceil\n\nimport CarbonSafeFunctions as csf\nfrom SideBar import ModelConstants, SelectBoxOptions\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\nclass CapitalCost:\n\tdef __init__(self, dictionary, MainOptions, TimeValueMoney, MonitorSwitchesData, InsurancePiscLtl, CaptureFacilitiesFinancials):\n\t\tself.dictionary = dictionary\n\t\tself.MainOptions = MainOptions\n\t\tself.TimeValueMoney = TimeValueMoney\n\t\tself.MonitorSwitchesData = MonitorSwitchesData\n\t\tself.InsurancePiscLtl = InsurancePiscLtl\n\t\tself.CaptureFacilitiesFinancials = CaptureFacilitiesFinancials\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t@st.cache(suppress_st_warning=True)\n\tdef TotalCAPEX_ITC(self):\n\t\tCAPEX_list = []\n\t\tITC_list = []\n\t\tfor facility, df in self.dictionary.items():\n\t\t\tCAPEX_list.append(df.iloc[0,0])\n\t\t\tITC_list.append(df.iloc[1,0])\n\n\t\tCAPEX_list = pd.DataFrame(CAPEX_list, index = self.dictionary.keys(), columns = ['CAPEX'])\n\t\tITC_list = pd.DataFrame(ITC_list, index = self.dictionary.keys(), columns = ['Investment Tax Credit'])\n\n\t\treturn {'Facilities CAPEX': CAPEX_list,\n\t\t\t\t'Facilities ITC': ITC_list}\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t@st.cache(suppress_st_warning=True)\n\tdef Insurance(self, TOTAL_facilities_CAPEX):\n\t\tdf = csf.create_zeros_array(self.MainOptions.total_life, rows = 2)\n\n\t\tpremium = self.InsurancePiscLtl.adjusted_premium * sum(TOTAL_facilities_CAPEX[TOTAL_facilities_CAPEX.columns[0]])\n\n\t\tdf[0,0] = self.InsurancePiscLtl.underwrite * sum(TOTAL_facilities_CAPEX[TOTAL_facilities_CAPEX.columns[0]])\n\t\tdf[1,1:] = [premium * self.TimeValueMoney.escalation[i] if i <= (self.MainOptions.in_operation-2) else 0 for i in range(self.MainOptions.total_life-1)]\n\n\t\tdf = pd.DataFrame(df, index = ['Underwrite Insurance Fee', 'Annual Premium'])\n\t\treturn df\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t@st.cache(suppress_st_warning=True)\n\tdef TrustFunds(self, post_closure_df, SourcePlantOperations, CaptureFacilities):\n\t\tdf_PSIC = csf.create_zeros_array(self.MainOptions.total_life, rows = 4)\n\n\t\tPISC_rate = self.InsurancePiscLtl.PISC_return\n\t\tpv = np.pv(PISC_rate, self.MainOptions.post_closer, - post_closure_df.loc['Total PISC & MVA CAPEX+OPEX'].sum() * (1 + self.InsurancePiscLtl.PISC_cont) / 1000000 / self.MainOptions.post_closer,0)\n\t\t\n\t\tpmt = np.pmt(PISC_rate, self.MainOptions.in_operation-1, 0, -pv * 1000000)\n\t\n\t\tdf_PSIC[0,1:] = [pmt * self.CaptureFacilitiesFinancials.in_ops[i] for i in range(1, self.MainOptions.total_life)]\n\t\tdf_PSIC[2,1:] = [- post_closure_df.loc['Total PISC & MVA CAPEX+OPEX', i] for i in range(1, self.MainOptions.total_life)]\n\n\t\tfor i in range(1, self.MainOptions.total_life):\n\t\t\tdf_PSIC[1,i] = df_PSIC[3,i-1] * PISC_rate\n\t\t\tdf_PSIC[3,i] = df_PSIC[0:3,i].sum() + df_PSIC[3,i-1]\n\t\tdf_PSIC = pd.DataFrame(df_PSIC, index = ['Payments to PISC Trust', 'Interest Earned', 'Less PISC Expenses', 'Cumulative Value ($MM)'])\n#---------------------------------------------------------------------------------------- #\n\n\t\tdf_LTL = csf.create_zeros_array(self.MainOptions.total_life, rows = 3)\n\n\t\tLTL_rate = self.InsurancePiscLtl.LTL_return\n\t\t\n\t\tfv_loss = -np.fv(self.InsurancePiscLtl.LTL_inflation, self.MainOptions.total_life-1, 0,self.InsurancePiscLtl.max_loss_res * (1 + self.InsurancePiscLtl.LTL_cont))\n\t\tpv_loss = -np.pv(LTL_rate, self.MainOptions.post_closer, 0, fv_loss*self.InsurancePiscLtl.chance_event)\n\t\tpmt = -np.pmt(LTL_rate, self.MainOptions.in_operation-1, 0, pv_loss)\n\t\tfee = pmt / CaptureFacilities.CO2_per_year\n\t\tpmt_trust = SourcePlantOperations.loc['CO2 Captured (tCO2/year)', 1] * fee\n\n\t\tdf_LTL[0,1:] = [pmt_trust * self.CaptureFacilitiesFinancials.in_ops[i] for i in range(1, self.MainOptions.total_life)]\n\n\t\tfor i in range(1, self.MainOptions.total_life):\n\t\t\tdf_LTL[1,i] = df_LTL[2,i-1] * LTL_rate\n\t\t\tdf_LTL[2,i] = df_LTL[0:2,i].sum() + df_LTL[2,i-1]\n\t\tdf_LTL = pd.DataFrame(df_LTL, index = ['Payments to LTL Trust', 'Interest Earned', 'Cumulative Value ($MM)'])\n\n\t\treturn {'PSIC Trust': df_PSIC,\n\t\t\t\t'LTL Trust': df_LTL} \n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t@st.cache(suppress_st_warning=True)\n\tdef calc_revenues(self, TechnoEconSummary, CO2_dfs, FuelPrices):\n\t\tCO2_Pricing_Paths = CO2_dfs['CO2 Pricing Paths']\n\t\tElecUsedByFacilities = CO2_dfs['Electricity Used by Capture Facilities']\n\t\tCO2PermitsOrEmissionCredits = CO2_dfs['CO2 Permits or Emission Credits']\n\t\tCO2TaxCredits = CO2_dfs['CO2 Tax Credits']\n\n\t\tdf = csf.create_zeros_array(self.MainOptions.total_life, rows = 9)\n\n\t\tmcf_per_tCO2 = (17.4825175 * self.MainOptions.tons_units / 2000)\n\n\t\tif self.MainOptions.realize == SelectBoxOptions.Realize_Offset_Green_Elec[0]:\n\t\t\tis_green_elec = 1\n\t\t\tis_tradable = 1\n\t\telif self.MainOptions.realize_one == SelectBoxOptions.no_What_Applies[0]:\n\t\t\tis_green_elec = 0\n\t\t\tis_tradable = 1\n\t\telse:\n\t\t\tis_green_elec = 1\n\t\t\tis_tradable = 0\n\n\t\tdf[0,1:] = [TechnoEconSummary.loc['Sold to EOR (tCO2)', i] * CO2_Pricing_Paths.loc['CO2-EOR Price ($/Mcf)', i] * mcf_per_tCO2 for i in range(1, self.MainOptions.total_life)]\n\t\tdf[1,1:] = [max(ElecUsedByFacilities.loc['Net Power Sold (Purchased)', i] * FuelPrices.elec_sold[i], 0) / 1000 for i in range(1, self.MainOptions.total_life)]\n\t\tdf[2,1:] = [CO2_Pricing_Paths.loc['EOR Carbon \"Green\" Premium ($/MWh)', i] * TechnoEconSummary.loc['Green \"EOR\" Electrons (MWhs)', i] * is_green_elec for i in range(1, self.MainOptions.total_life)]\n\t\tdf[3,1:] = [CO2_Pricing_Paths.loc['Sequestration \"Green\" Premium ($/MWh)', i] * TechnoEconSummary.loc['Green \"Storage\" Electrons (MWhs)', i] * is_green_elec for i in range(1, self.MainOptions.total_life)]\n\t\tdf[4,1:] = [TechnoEconSummary.loc['Sold to EOR (tCO2)',i] * CO2PermitsOrEmissionCredits.loc['EOR - Tradable Carbon Offset', i] * is_tradable for i in range(1, self.MainOptions.total_life)]\n\t\tdf[5,1:] = [TechnoEconSummary.loc['Saline Storage (tCO2)',i] * CO2PermitsOrEmissionCredits.loc['EOR - Tradable Carbon Offset', i] * is_tradable for i in range(1, self.MainOptions.total_life)]\n\t\tdf[6,1:] = [CO2TaxCredits.loc['Storage Value ($/tCO2)', i] * TechnoEconSummary.loc['Saline Storage (tCO2)',i] for i in range(1, self.MainOptions.total_life)]\n\t\tdf[7,1:] = [CO2TaxCredits.loc['EOR Value ($/tCO2)', i] * TechnoEconSummary.loc['Sold to EOR (tCO2)',i] for i in range(1, self.MainOptions.total_life)]\n\t\tdf[8,1:] = [df[0:6,i].sum() for i in range(1, self.MainOptions.total_life)]\n\n\t\tdf = pd.DataFrame(df, index = ['CO2 Sold to EOR', 'Excess CoGen Power Sold', 'Green \"EOR\" Electron Sales (to CA)', 'Green \"Storage\" Electron Sales (to CA)',\n\t\t\t\t\t\t\t\t\t\t'\"EOR\" Tradable Offsets', '\"Storage\" Tradable Offsets',\n\t\t\t\t\t\t\t\t\t\t'45Q Storage Credits', '45Q EOR Credits', 'Total Direct Revenues'])\n\t\treturn df\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t# @st.cache(suppress_st_warning=True) # DONT CASHE!\n\tdef project_CAPEX(self, facilities_CAPEX, Insurance, GlobalParameters, RevenueReserves, CapitalStructure):\n\t\tcap_facilities_CAPEX = sum(facilities_CAPEX[facilities_CAPEX.columns[0]])\n\n\t\tinsurance = Insurance.iloc[0, 0]\n\t\towner_cost = cap_facilities_CAPEX * GlobalParameters.owner_CAPEX + insurance\n\t\tdebt_reserve = 69\n\n\t\tDOE_grant = RevenueReserves.grant * 1000000\n\t\tDOE_share = RevenueReserves.other_share * 1000000\n\n\t\tCAPEX = cap_facilities_CAPEX + insurance + owner_cost - DOE_grant - DOE_share # + debt_reserve\n\n\t\tdf = pd.DataFrame([[insurance], [owner_cost], [debt_reserve], [DOE_grant], [DOE_share], [CAPEX]], index = ['Insurance Underwriting', \"Provision for Owner's Costs\", 'Debt Reserve & Working Capital', 'DOE Grant for Site Characterization',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'Other DOE Cost Sharing', 'Total CAPEX'], columns = [facilities_CAPEX.columns[0]])\n\t\tdf = pd.concat([facilities_CAPEX, df], axis = 0)\n\t\treturn df\n\n\t# @st.cache(suppress_st_warning=True) # DONT CASHE!\n\tdef finish_CAPEX(self, CAPEX, project_financial_df):\n\t\tCAPEX.loc['Debt Reserve & Working Capital'] = abs(project_financial_df['Debt Service & Operating Reserve Account'].loc['Ending Balance', 0])\n\t\tCAPEX.loc['Total CAPEX'] = CAPEX.loc['Total CAPEX'] + CAPEX.loc['Debt Reserve & Working Capital']\n\t\treturn CAPEX\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t@st.cache(suppress_st_warning=True)\n\tdef calc_OPCosts(self, financial_dfs, project_financial_df):\n\t\tdf = csf.create_zeros_array(self.MainOptions.total_life, rows = 27)\n\n\t\tdf[0,1:] = [financial_dfs['AmineCaptureFacility'].loc['Subtotal O&M', i] + financial_dfs['FlueGasTieIn'].loc['Subtotal O&M', i] for i in range(1, self.MainOptions.total_life)]\n\t\tdf[1,:] = financial_dfs['AmineCaptureFacility'].loc['Non-Fuel O&M', :]\n\n\t\tdf[2,:] = financial_dfs['CoGenFacility'].loc['Subtotal O&M', :]\n\t\tdf[3,:] = financial_dfs['CoGenFacility'].loc['Non-Fuel O&M', :]\n\n\t\tdf[4,:] = financial_dfs['SteamPlantOnly'].loc['Subtotal O&M', :]\n\t\tdf[5,:] = financial_dfs['SteamPlantOnly'].loc['Non-Fuel O&M', :]\n\n\t\tdf[6,:] = financial_dfs['CoolingTower'].loc['Subtotal O&M', :]\n\t\tdf[7,:] = financial_dfs['CoolingTower'].loc['Non-Fuel O&M', :]\n\n\t\tdf[8,:] = financial_dfs['WaterTreatmentDemineralization'].loc['Subtotal O&M', :]\n\t\tdf[9,:] = financial_dfs['WaterTreatmentDemineralization'].loc['Non-Fuel O&M', :]\n\n\t\tdf[10,:] = financial_dfs['CompressionDehydration'].loc['Subtotal O&M', :]\n\t\tdf[11,:] = financial_dfs['CompressionDehydration'].loc['Non-Fuel O&M', :]\n\n\t\tdf[12,1:] = [df[0,i] + df[2,i] + df[4,i] + df[6,i] + df[8,i] + df[10,i] for i in range(1, self.MainOptions.total_life)]\n\t\tdf[13,1:] = [df[1,i] + df[3,i] + df[5,i] + df[7,i] + df[9,i] + df[11,i] for i in range(1, self.MainOptions.total_life)]\n\n\n\t\tdf[14,:] = financial_dfs['StoragePipeline'].loc['Subtotal O&M', :]\n\t\tdf[15,:] = financial_dfs['StoragePipeline'].loc['Non-Fuel O&M', :]\n\n\t\tdf[16,:] = financial_dfs['EorSalesPipeline'].loc['Subtotal O&M', :]\n\t\tdf[17,:] = financial_dfs['EorSalesPipeline'].loc['Non-Fuel O&M', :]\n\n\t\tdf[18,:] = financial_dfs['CO2PipelineBoostersGaugesMeters'].loc['Subtotal O&M', :]\n\t\tdf[19,:] = financial_dfs['CO2PipelineBoostersGaugesMeters'].loc['Non-Power O&M', :]\n\n\n\t\tdf[20,:] = financial_dfs['StorageOperationMonitoring'].loc['Storage Site OPEX', :]\n\t\tdf[21,:] = financial_dfs['StorageOperationMonitoring'].loc['Non-Power O&M', :]\n\n\t\tdf[22,:] = project_financial_df['Industrial Insurance'].loc['Annual Premium', :]\n\t\tdf[23,:] = [project_financial_df['Trust Funds']['PSIC Trust'].loc['Payments to PISC Trust', i] + project_financial_df['Trust Funds']['LTL Trust'].loc['Payments to LTL Trust', i] for i in range(0, self.MainOptions.total_life)]\n\n\t\tdf[24,:] = [df[12,i] + df[14,i] + df[16,i] + df[18,i] + df[20,i] + df[22,i] + df[23,i] for i in range(0, self.MainOptions.total_life)]\n\t\tdf[25,:] = [df[13,i] + df[15,i] + df[17,i] + df[19,i] + df[21,i] + df[22,i] for i in range(0, self.MainOptions.total_life)]\n\n\t\tdf[26,1] = df[24,1] / project_financial_df['Total Project CAPEX'].iloc[-1, 0]\n\t\tdf[26,2: self.MainOptions.in_operation] = np.nan\n\n\t\tdf = pd.DataFrame(df, index = ['AmineCaptureFacility', '1 - Non-fuel or power', 'CoGenFacility', '2 - Non-fuel or power', 'SteamPlantOnly', '3 - Non-fuel or power',\n\t\t\t\t\t\t\t\t\t\t'CoolingTower', '4 - Non-fuel or power', 'WaterTreatmentDemineralization', '5 - Non-fuel or power', 'CompressionDehydration', '6 - Non-fuel or power',\n\t\t\t\t\t\t\t\t\t\t'Subtotal - Capture Facilities', '1 to 6 - Non-fuel or power', 'StoragePipeline', '7 - Non-fuel or power', 'EorSalesPipeline', '8 - Non-fuel or power',\n\t\t\t\t\t\t\t\t\t\t'CO2PipelineBoostersGaugesMeters', '9 - Non-fuel or power', 'PreInjectSite', '10 - Non-fuel or power', 'Annual Insurance Premiums', 'Trust Payments',\n\t\t\t\t\t\t\t\t\t\t'Total Operating Expenses', 'Total Non-fuel or power', 'OPEX % Share CAPEX'])\n\t\treturn df\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\t\n\t@st.cache(suppress_st_warning=True)\n\tdef debt_schdule(self, financial_dfs, project_financial_df, CapitalStructure):\n\t\tdf = csf.create_zeros_array(self.MainOptions.total_life, rows = 4)\n\t\ttenor = int(ceil(CapitalStructure.loan_length))\n\n\t\tdf[0,1:tenor+1] = 1; df[0,0] = np.nan\n\n\t\tdebt = round(project_financial_df['Total Project CAPEX'].iloc[-1, 0] * CapitalStructure.share_debt,1)\n\t\tdf[-1, 0] = debt\n\n\t\trate = CapitalStructure.cost_debt\n\t\tpmt = np.pmt(rate, tenor, debt, 0)\n\n\t\tdf[2,1:] = [pmt * df[0,i] for i in range(1, self.MainOptions.total_life)]\n\n\t\tfor i in range(1, self.MainOptions.total_life):\n\t\t\tdf[1,i] = df[-1, i-1] * rate * df[0,i]\n\t\t\tdf[3,i] = (df[1:3, i].sum() + df[3,i-1]) * df[0,i]\n\n\t\tdf = pd.DataFrame(df, index = ['Is Tenor?', 'Interest', 'Payment', 'Loan Balance'])\n\t\treturn df\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t@st.cache(suppress_st_warning=True)\n\tdef debt_service(self, financial_dfs, project_financial_df, RevenueReserves, CapitalStructure):\n\t\tdf = csf.create_zeros_array(self.MainOptions.total_life, rows = 5)\n\t\tdf_dummy = csf.create_zeros_array(self.MainOptions.total_life, rows = 5)\n\n\t\tOPEX_reserve = (project_financial_df['Operating Costs'].loc['Trust Payments'][1] + project_financial_df['Operating Costs'].loc['Total Operating Expenses'][1]) * RevenueReserves.OM_reserves\n\t\tdebt_reserve = project_financial_df['Debt Schedule'].loc['Payment'][1] * RevenueReserves.debt_reserves\n\t\tdf[-1,0] = round(OPEX_reserve + abs(debt_reserve),0)\n\n\n\t\tOP_income = [project_financial_df['Revenues'].loc['Total Direct Revenues', i] - project_financial_df['Operating Costs'].loc['Total Operating Expenses', i] for i in range(0, self.MainOptions.total_life)]\n\t\tdf_dummy[0,1:] = [OP_income[i] - project_financial_df['Trust Funds']['PSIC Trust'].loc['Payments to PISC Trust', i] - project_financial_df['Trust Funds']['LTL Trust'].loc['Payments to LTL Trust', i] for i in range(1, self.MainOptions.total_life)]\n\t\tdf_dummy[1,1:] = [abs(project_financial_df['Debt Schedule'].loc['Payment', i]) for i in range(1, self.MainOptions.total_life)]\n\t\tdf_dummy[2,1:] = [df_dummy[0,i] - df_dummy[1,i] * CapitalStructure.DSCR for i in range(1, self.MainOptions.total_life)]\n\n\t\tfor i in range(1, self.MainOptions.total_life):\n\t\t\tdf[0,i] = df[4,i-1]\n\n\t\t\tif (df_dummy[2,i] > 0) & (df[0,i] < (16*1000000)) & (i < self.MainOptions.in_operation-1):\n\t\t\t\tdf[1,i] = df_dummy[2,i] * 0.05\n\t\t\telse:\n\t\t\t\tdf[1,i] = 0\n\n\t\t\tif df_dummy[2,i] < 0:\n\t\t\t\tdf_dummy[3,i] = min(-df_dummy[2,i], df[0,i])\n\t\t\telif i == self.MainOptions.in_operation-1:\n\t\t\t\tdf_dummy[3,i] = df[0,i]\n\t\t\telse:\n\t\t\t\tdf_dummy[3,i] = 0\n\n\t\t\tdf[2,i] = -df_dummy[3,i]\n\n\t\t\tif df[0:3,i].sum() > 0:\n\t\t\t\tdf[3,i] = (df[0,i] + 0.25 * (df[1,i] + df[2,i])) * 0.03\n\t\t\telse:\n\t\t\t\tdf[3,i] = 0\n\n\t\t\tdf[4,i] = df[0:4, i].sum()\n\n\t\tdf_dummy[4,1:] = [(df_dummy[0,i] + df_dummy[3,i]) / df_dummy[1,i] if df_dummy[1,i] > 0 else 0 for i in range(1, self.MainOptions.total_life)]\n\n\t\tdf = pd.DataFrame(df, index = ['Beginning Balance', 'Deposits', 'Withdrawls', 'Interest Earnings', 'Ending Balance'])\n\t\tdf_dummy = pd.DataFrame(df_dummy, index = ['Net Cash Availble for Debt Service', 'Debt Payments', 'DSCR Excess (Shortfall)', '…Transfer from Reserves', 'DSCR'])\n\n\t\treturn [df, df_dummy]\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t@st.cache(suppress_st_warning=True)\n\tdef calc_OPIncome(self, project_financial_df, CapitalStructure):\n\t\tdf = csf.create_zeros_array(self.MainOptions.total_life, rows = 8)\n\n\t\ttenor = int(ceil(CapitalStructure.loan_length))\n\t\tdebt = round(project_financial_df['Total Project CAPEX'].iloc[-1, 0] * CapitalStructure.share_debt,1)\n\t\trate = CapitalStructure.cost_debt\n\t\tpmt = np.pmt(rate, tenor, debt, 0)\n\n\t\tdf[0,:] = [project_financial_df['Revenues'].loc['Total Direct Revenues', i] - project_financial_df['Operating Costs'].loc['Total Operating Expenses', i] for i in range(0, self.MainOptions.total_life)]\n\t\tdf[1,:] = project_financial_df['Debt Service & Operating Reserve Account'].loc['Interest Earnings']\n\t\tdf[2,:] = [project_financial_df['Debt Service & Operating Reserve Account'].loc['Beginning Balance', i] if i == self.MainOptions.in_operation-1 else 0 for i in range(0, self.MainOptions.total_life)]\n\t\tdf[3,:] = [project_financial_df['Trust Funds']['PSIC Trust'].loc['Payments to PISC Trust', i] for i in range(0, self.MainOptions.total_life)]\n\t\tdf[4,:] = [project_financial_df['Trust Funds']['LTL Trust'].loc['Payments to LTL Trust', i] for i in range(0, self.MainOptions.total_life)]\n\t\tdf[5,1:tenor+1] = abs(pmt)\n\t\tdf[6,:] = project_financial_df['Taxes'].loc['Net Taxes Payable']\n\t\tdf[7,:] = [df[0,i] + df[1,i] + df[2,i] - df[3,i] - df[4,i] - df[5,i] - df[6,i] for i in range(0, self.MainOptions.total_life)]\n\n\t\tdf = pd.DataFrame(df, index = ['Gross Profits', 'Interest Income', 'Return of Capital', 'PISC Trust Payments', 'LTL Trust Payments', 'Debt Payments', 'Taxes Payable', 'Net Income'])\n\t\treturn df\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\t@st.cache(suppress_st_warning=True)\n\tdef calc_taxes(self, financial_dfs, project_financial_df, CapitalStructure):\n\t\tdf = csf.create_zeros_array(self.MainOptions.total_life, rows = 8)\n\n\t\tMACRS = []\n\t\tfor i in range(0, self.MainOptions.total_life):\n\t\t\tdummy = []\n\n\t\t\tfor key in financial_dfs.keys():\n\t\t\t\tif key != 'CO2 Post-Injection Close Monitoring':\n\t\t\t\t\tdummy.append(financial_dfs[key].loc['Tax Depreciation', i])\n\t\t\tMACRS.append(sum(dummy))\n\n\n\t\tOP_income = [project_financial_df['Revenues'].loc['Total Direct Revenues', i] - project_financial_df['Operating Costs'].loc['Total Operating Expenses', i] for i in range(0, self.MainOptions.total_life)]\n\t\t\n\t\tdf[0,:] = project_financial_df['Debt Schedule'].loc['Interest']\n\t\tdf[1,:] = MACRS\n\t\tdf[2,:] = [OP_income[i] - df[0:2,i].sum() for i in range(0, self.MainOptions.total_life)]\n\t\tdf[3,:] = [df[2,i] * CapitalStructure.tax_rate for i in range(0, self.MainOptions.total_life)]\n\n\t\tfor i in range(1, self.MainOptions.total_life):\n\t\t\tif df[3,i] < 0:\n\t\t\t\tdf[4,i] = df[3,i] + df[4,i-1]\n\t\t\telse:\n\t\t\t\tdf[4,i] = min(0, df[3,i] + df[4,i-1])\n\n\t\tdf[5,:] = [max(df[4,i] + df[3,i], 0) for i in range(0, self.MainOptions.total_life)]\n\t\tdf[6,:] = [project_financial_df['Revenues'].loc['45Q Storage Credits', i] + project_financial_df['Revenues'].loc['45Q EOR Credits', i] for i in range(0, self.MainOptions.total_life)]\n\t\tdf[7,1] = sum(project_financial_df['Total ITC'][project_financial_df['Total ITC'].columns[0]])\n\n\t\tdf = pd.DataFrame(df, index = ['Interest Expense', 'MACRS Depreciation Expense', 'Taxable Income', 'Gross Taxes Owed (Loss to Carry)',\n\t\t\t\t\t\t\t\t\t\t'Carried Losses', 'Net Taxes Payable', '45Q/Future Act Tax Credits', 'Investment Tax Credits'])\n\t\treturn df\n# -------------------------------------------------------------------------------------------------------------------- #\n# -------------------------------------------------------------------------------------------------------------------- #\n\n\tdef equity_sizing(self, project_financial_df, TimeValueMoney):\n\t\tdf = csf.create_zeros_array(self.MainOptions.total_life, rows = 7)\n\n\t\tdf[0,0] = sum(project_financial_df['Total ITC'][project_financial_df['Total ITC'].columns[0]])\n\t\tdf[1,0] = df[0,0] / TimeValueMoney.tax_ROE[1]\n\n\t\tdf[2,:] = project_financial_df['Taxes'].loc['45Q/Future Act Tax Credits']\n\t\tdf[3,:] = [df[2,i] / TimeValueMoney.tax_ROE[i] for i in range(0, self.MainOptions.total_life)]\n\t\tdf[4,:] = project_financial_df['Operating Income'].loc['Net Income']\n\t\tdf[5,:] = [df[4,i] / TimeValueMoney.ROE[i] for i in range(0, self.MainOptions.total_life)]\n\t\tdf[6,:] = [df[4,i] / TimeValueMoney.NPV[i] for i in range(0, self.MainOptions.total_life)]\n\n\t\tdf[3,0] = df[3,1:].sum()\n\t\tdf[5,0] = df[5,1:].sum()\n\t\tdf[6,0] = df[6,1:].sum()\n\n\t\tdf = pd.DataFrame(df, index = ['Investment Tax Credit', 'PV of ITC Credit', '45Q/Future Act Tax Credits', 'PV of Unused Tax Credits',\n\t\t\t\t\t\t\t\t\t\t'Net Income - Free Cash Flow to Equity', 'PV @' + str(round(TimeValueMoney.ROE_rate*100,1)) + '% of Excess CFs',\n\t\t\t\t\t\t\t\t\t\t'PV @' + str(round(TimeValueMoney.NPV_rate*100,1)) + '% of Excess CFs'])\n\t\treturn df\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ProjectFinancials.py","file_name":"ProjectFinancials.py","file_ext":"py","file_size_in_byte":21865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"116019967","text":"import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport sys\n\nfin = open('torchnet_test_baseline.log')\nfin1 = open('torchnet_test_loss.log')\n\nar = []\nfor i in fin:\n ar.append(i[:-1])\n\nar1 = []\nfor i in fin1:\n\tar1.append(i[:-1])\n\nar = [float(x) for x in ar]\nar1 = [float(x) for x in ar1]\nar1 = ar1[0:200]\n##baseline VS last episode\n\nt = range(0, len(ar))\n\nplt.title('')\nplt.ylabel('Accuracy(%)')\nplt.xlabel('Epoch')\nplt.plot(t, ar, label='baseline')\nplt.plot(t, ar1, label='qan')\nplt.legend(loc='lower right')\n\nplt.savefig('acc.pdf')\n\n\n","sub_path":"torchnet_qan/20160815/paint.py","file_name":"paint.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"627220516","text":"from knock41 import Cabocha\ndef get_content_start_with_type(t, morphs):\n result = \"\"\n start = False\n for m in morphs:\n if m.pos == \"記号\":\n continue\n if m.pos == t:\n start = True\n if start:\n result += m.surface\n return result\ndef pair_chunk(chunks):\n result = []\n for chunk in chunks:\n dst = chunk.dst\n if dst == -1:# skip\n continue\n base_morph = get_content_start_with_type(\"名詞\",chunk.morphs)\n dst_morph = get_content_start_with_type(\"動詞\",chunks[dst].morphs)\n if len(base_morph) > 0 and len(dst_morph) > 0:# only both of them exist, record\n result.append((base_morph, dst_morph))\n return result\nif __name__ == \"__main__\":\n for s in Cabocha().get_sentence():\n pair = pair_chunk(s)\n for p in pair:\n print(p[0] + \"\\t\" + p[1])\n","sub_path":"bambi/chapter05/knock43.py","file_name":"knock43.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"289495887","text":"datas = {\n \"好评\": {\n \"开始\": [\n \"考虑买这个$之前我是有担心过的,因为我不知道$的质量和品质怎么样,但是看了评论后我就放心了。\",\n \"买这个$之前我是有看过好几家店,最后看到这家店的评价不错就决定在这家店买 \",\n \"看了好几家店,也对比了好几家店,最后发现还是这一家的$评价最好。\",\n \"看来看去最后还是选择了这家。\",\n \"之前在这家店也买过其他东西,感觉不错,这次又来啦。\"\n ],\n \"中间\": [\n \"收到货后我非常的开心,因为$的质量和品质真的非常的好!\",\n \"拆开包装后惊艳到我了,这就是我想要的$!\",\n \"快递超快!包装的很好!!很喜欢!!!\",\n \"包���的很精美!$的质量和品质非常不错!\",\n \"收到快递后迫不及待的拆了包装。$我真的是非常喜欢\"\n ],\n \"结束\": [\n \"经过了这次愉快的购物,我决定如果下次我还要买$的话,我一定会再来这家店买的。\",\n \"不错不错!\",\n \"我会推荐想买$的朋友也来这家店里买\",\n \"真是一次愉快的购物!\",\n \"大大的好评!以后买$再来你们店!( ̄▽ ̄)\"\n ]\n },\n \"差评\": {\n \"开始\": [\n \"我真是瞎了眼,竟然在这家店里面买$ \",\n \"我还可以说什么? 这家店的$简直不行 \",\n \"这是我买到的最差的$ \"\n ],\n \"中间\": [\n \"我以后都不会再来这家店里买东西了!\",\n \"再也不来了,不来了!\",\n \"$的质量真的非常的不行!\"\n ],\n \"结束\": [\n \"对这家店的$失望透顶!\",\n \"这家店给我对于$能做成这样刷新了世界观!\",\n \"真是一次糟心的购物!\"\n ]\n }\n}","sub_path":"build/lib/data/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"555929764","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 7 18:59:53 2021\n\n@author: Arjan\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport swifter\nfrom scipy import optimize\nfrom math import sqrt, exp, tan, log10, pi, acos, asin, sin, cos, tanh\nfrom observations import observation, detection, detection_prob\nfrom orbital import pos_heliocentric, theta_solve, theta_step\nimport seaborn as sns\nfrom population_models import init_asteroids_jpl, init_asteroids_granvik\nimport matplotlib.pyplot as plt\nimport time\nimport pickle\n\ndef init_asteroids():\n return init_asteroids_granvik(200, True)\n\n\ndef init_satellites(n, a, e, s):\n satellites = {i: {'a': a,\n 'e': e,\n 'i': 0,\n 'long_node': 0,\n 'arg_peri': 0,\n 'anomaly': s*i,\n 'payload': 'VIS',\n 'cadence': 2} for i in range(n)}\n return satellites\n\n\ndef asteroid_positions(day, df_asteroids):\n '''Propagate all orbital elements to certain day and reset observations'''\n df_asteroids['M'] = df_asteroids.swifter.progress_bar(False).apply(lambda row: theta_step(row['a'], row['anomaly'], day), axis=1)\n df_asteroids['theta'] = df_asteroids.swifter.progress_bar(False).apply(lambda row: theta_solve(row['e'], row['M']), axis=1)\n df_asteroids['x'], df_asteroids['y'], df_asteroids['z'] = zip(*df_asteroids.swifter.progress_bar(False).apply(lambda row: pos_heliocentric(row['a'], \n row['e'], \n row['i'], \n row['theta'], \n row['long_node'], \n row['arg_peri']),\n axis=1\n ))\n df_asteroids['detected'] = df_asteroids.swifter.progress_bar(False).apply(lambda row: 1 if row['n_obs'] > 4 and row['detected'] == 0 else row['detected'], axis=1)\n df_asteroids['n_obs'] = df_asteroids.swifter.progress_bar(False).apply(lambda row: 0 if day - row['last_obs'] > 90 else row['n_obs'], axis=1)\n return df_asteroids\n\n\ndef satellite_positions(day, satellites):\n '''Propagate satellite positions'''\n for sat in satellites.values():\n sat['M'] = theta_step(sat['a'], sat['anomaly'], day)\n sat['theta'] = theta_solve(sat['e'], sat['M'])\n sat['x'], sat['y'], sat['z'] = pos_heliocentric(sat['a'],\n sat['e'],\n sat['i'],\n sat['theta'],\n sat['long_node'],\n sat['arg_peri'])\n return satellites\n\n\ndef make_observations(sat, day, df_asteroids):\n if day % sat['cadence']:\n return 0\n df_asteroids['SNR'] = df_asteroids.swifter.progress_bar(False).apply(lambda row: observation(row['H'], \n row['albedo'], \n row['x'], \n row['y'], \n row['z'], \n sat['x'], \n sat['y'], \n sat['z'], \n sat['payload']\n ), \n axis=1\n )\n df_asteroids['step_obs'] = df_asteroids.swifter.progress_bar(False).apply(lambda row: min(row['step_obs'] + detection_prob(row['SNR']), 1),\n axis=1\n )\n return day\n\ndef do_survey(x):\n semi_major, eccentricity, spread = x[0], x[1], x[2]\n n_sats = 5\n df_asteroids = init_asteroids()\n #print(f\"Satellites: {n_sats}\")\n #print(f\"Semi-Major: {semi_major}\")\n #print(f\"Eccentricity: {eccentricity}\")\n #print(f\"Spread: {spread}\")\n df_asteroids['n_obs'] = 0\n df_asteroids['step_obs'] = 0\n df_asteroids['last_obs'] = 0\n df_asteroids['detected'] = 0\n df_asteroids['diameter'] = df_asteroids.apply(lambda row: 1329000/sqrt(row['albedo'])*10**(-1*row['H'] / 5), axis=1)\n #df_asteroids = df_asteroids.fillna(0.15)\n satellites = init_satellites(n_sats, semi_major, eccentricity, spread)\n completeness = []\n fig, axes = plt.subplots(1,1, figsize=(8,8))\n bg = plt.imread('background.png')\n \n for day in range(0, 1825, 2):\n n_detected = df_asteroids[df_asteroids['detected'] > 0]['detected'].count()\n n_undetected = df_asteroids[df_asteroids['detected'] == 0]['detected'].count()\n completeness.append(n_detected / (n_detected + n_undetected))\n df_asteroids = asteroid_positions(day, df_asteroids)\n satellites = satellite_positions(day, satellites)\n if day%satellites[0]['cadence'] == 0:\n for sat in satellites.values():\n make_observations(sat, day, df_asteroids)\n df_asteroids['n_obs'] = df_asteroids.swifter.progress_bar(False).apply(lambda row: row['n_obs'] + row['step_obs'], axis=1)\n df_asteroids['last_obs'] = df_asteroids.swifter.progress_bar(False).apply(lambda row: day if row['step_obs'] > 0 else row['last_obs'], axis=1)\n\n plt.pause(0.0001)\n if day == 0:\n #pass\n a = input(\"enter to start...\")\n axes.clear()\n axes.set_xlim((-5, 5))\n axes.set_ylim((-5, 5))\n axes.imshow(bg, extent=[-5, 5, -5, 5])\n sns.scatterplot(data=df_asteroids, x='x', y='y', hue='detected', ax=axes, marker='o', legend=False, vmin=0, vmax=3, size='diameter')\n sns.scatterplot(data=pd.DataFrame(satellites).transpose(), x='x', y='y', marker='D', color=\"red\", s=30)\n fig.canvas.draw()\n fig.suptitle(f\"Day: {day}, completeness: {completeness[-1]:.2%}, detections: {df_asteroids.loc[df_asteroids['step_obs'] > 0]['step_obs'].count()}\")\n df_asteroids['step_obs'] = 0\n #print(f\"Completeness: {completeness[-1]:.2%}\")\n #print()\n \n\n return float(1 - completeness[-1])\n \n \nif __name__ == '__main__':\n do_survey([1.0, 0.0, 2*pi/5])\n ","sub_path":"code/survey_visualisation.py","file_name":"survey_visualisation.py","file_ext":"py","file_size_in_byte":7070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"144927989","text":"from picamera import PiCamera\nfrom time import sleep\n\ncamera = PiCamera()\ncamera.rotation = 180\ncamera.resolution = (2592, 1944)\ncamera.framerate = 15\n\ndef takeVid():\n camera.capture('max.jpg')\n \n\ntry:\n camera.start_preview()\n takeVid()\n\nfinally:\n camera.stop_preview()\n","sub_path":"PATfilesV2/PiCamera/takingHighRes.py","file_name":"takingHighRes.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"230793820","text":"import numpy as np\nimport datetime\nfrom dataportal import DataBroker, DataMuxer\n\n\ndef _load_scan(scan_id, fill_events=False):\n '''Load scan from databroker by scan id'''\n\n if scan_id > 0 and scan_id in data_cache:\n df = data_cache[scan_id]\n else:\n hdr = DataBroker[scan_id]\n scan_id = hdr['start'].scan_id\n if scan_id in data_cache:\n df = data_cache[scan_id]\n else:\n data = DataBroker.fetch_events(hdr, fill=fill_events)\n dm = DataMuxer.from_events(data)\n df = dm.to_sparse_dataframe()\n data_cache[scan_id] = df\n return scan_id, df\n\ndef find_mass_center(array):\n n = np.size(array)\n tmp = 0\n sumtmp = 0\n for i in range(n):\n if array[i] > 50:\n tmp += i * array[i]\n sumtmp += array[i]\n if sumtmp > 0:\n mc = np.round(tmp/sumtmp)\n else:\n mc = np.round(n/2)\n return mc\n\n\ndef mov_to_center(scan_id, elem='Ga', channels=None, norm=None):\n if channels is None:\n channels = [1, 2, 3]\n\n scan_id, df = _load_scan(scan_id, fill_events=False)\n hdr = DataBroker[scan_id]['start']\n namex = hdr['fast_axis']\n\n x = df[namex]\n roi_data = np.sum(df['Det%d_%s' % (chan, elem)]\n for chan in channels)\n x = np.asarray(x)\n roi_data = np.asarray(roi_data)\n mc = np.int(find_mass_center(roi_data))\n mov(zpssx,x[mc])\n\n\ndef night_scan(angle_list,x_range,y_range,step_size,exposure_time):\n angle_list = np.array(angle_list)\n num_angle = np.size(angle_list)\n now=datetime.datetime.now()\n hh = open('itiff_prefixes_nightscan_'+str(now.isoformat())+'.txt','w')\n\n for i in range(num_angle):\n angle = angle_list[i]\n mov(zpsth,angle)\n hh.write(str(angle))\n hh.write('\\n')\n sleep(2)\n\n fly1d(zpssx, -2, 2, 100, 0.5)\n mov_to_center(-1,'Ga')\n sleep(1)\n\n fly2d(zpssx, -.75*y_range/2, .75*y_range/2, 30, zpssy, -y_range/2, y_range/2, 30, 0.5, return_speed=40)\n export(-1)\n hh.write(caget(\"XF:03IDC-ES{Merlin:1}TIFF1:FileName_RBV\",as_string=True))\n hh.write('\\n')\n fermat(zpssx,zpssy, x_range, y_range, step_size, 1, exposure_time)\n hh.write(caget(\"XF:03IDC-ES{Merlin:1}TIFF1:FileName_RBV\",as_string=True))\n hh.write('\\n')\n export(-1)\n scatter_plot(-1, 'zpssx', 'zpssy', 'Det2_Ga')\n\n hh.close()\n\n","sub_path":"profile_bs2015/startup/71_nightscan.py","file_name":"71_nightscan.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"572097976","text":"import RPi.GPIO as GPIO\nimport time\nimport simpleaudio as sa\n\nclass ButtonManager():\n '''\n Handles the input of a two buttons and corresponding LEDS\n '''\n def __init__(self, go_pin, reset_pin, go_ahead_light, stop_light, reset_time, go_sound, reset_sound):\n GPIO.setmode(GPIO.BCM)\n GPIO.setwarnings(False)\n print (\"Button Manager Created!\")\n self.go_pin = go_pin\n self.reset_pin = reset_pin\n self.button_reset = reset_time\n self.pressed = False\n self.stop_light = stop_light\n self.go_ahead_light = go_ahead_light\n self.time_since_trigger = time.time()\n GPIO.setup(self.reset_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(self.go_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(self.go_ahead_light, GPIO.OUT)\n GPIO.setup(self.stop_light, GPIO.OUT)\n # Create sounds\n self.go_sound = sa.WaveObject.from_wave_file(go_sound)\n self.reset_sound = sa.WaveObject.from_wave_file(reset_sound)\n\n def check(self):\n '''\n :return:\n 0 - The go pin hasn't been activated and hasn't been reset\n 1 - The go pin has just been activated\n 2 - The reset pin has just been activated\n '''\n go = GPIO.input(self.go_pin)\n reset = GPIO.input(self.reset_pin)\n if go == False:\n if self.pressed == False:\n if time.time() - self.time_since_trigger > self.button_reset:\n # print('Button Pressed')\n GPIO.output(self.go_ahead_light, GPIO.LOW)\n GPIO.output(self.stop_light, GPIO.HIGH)\n self.time_since_trigger = time.time()\n play_obj = self.go_sound.play()\n # We know the program will continue so we don't have to wait\n #play_obj.wait_done()\n self.pressed = True\n return 1\n if reset == False:\n if time.time() - self.time_since_trigger > self.button_reset:\n GPIO.output(self.go_ahead_light, GPIO.HIGH)\n GPIO.output(self.stop_light, GPIO.LOW)\n if self.pressed == True:\n # print('Button Reset')\n play_obj = self.reset_sound.play()\n\n # We know the program will continue so we don't have to wait\n\n self.pressed = False\n return 2\n return 0\n\n def flash_leds(self, pin, repeat_number, frequency):\n '''\n Flash LEDs\n '''\n state = GPIO.input(pin)\n for x in range(0, repeat_number):\n GPIO.output(pin, GPIO.HIGH)\n time.sleep(frequency)\n GPIO.output(pin, GPIO.LOW)\n time.sleep(frequency)\n \n if state:\n GPIO.output(pin, GPIO.HIGH)\n else:\n GPIO.output(pin, GPIO.LOW)\n","sub_path":"client/button_manager.py","file_name":"button_manager.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"556172475","text":"\n\nfrom xai.brain.wordbase.nouns._industrialist import _INDUSTRIALIST\n\n#calss header\nclass _INDUSTRIALISTS(_INDUSTRIALIST, ):\n\tdef __init__(self,): \n\t\t_INDUSTRIALIST.__init__(self)\n\t\tself.name = \"INDUSTRIALISTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"industrialist\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_industrialists.py","file_name":"_industrialists.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"182205262","text":"import numpy as np\n\n\nclass Interpreter:\n symb_type = {\"number\": 1, \"variable\": 2, \"operator\": 3}\n operator_list = [\"+\", \"-\", \"*\", \"/\"]\n\n def __init__(self, expr):\n self.original = expr\n self.expr = expr.replace(\" \", \"\")\n\n self.make_order0_list()\n self.make_oder1_list()\n\n def make_order0_list(self):\n constructor = []\n constructor_type = []\n\n # Classify each symbol in expr as number, operator or letter\n for symb in self.expr:\n if symb in self.operator_list:\n constructor_type.append(self.symb_type[\"operator\"])\n else:\n try:\n float(symb)\n constructor_type.append(self.symb_type[\"number\"])\n except:\n constructor_type.append(self.symb_type[\"variable\"])\n constructor.append(symb)\n\n self.constructor = constructor\n self.constructor_type = constructor_type\n\n self.reformat_expression()\n\n def reformat_expression(self):\n def merge_and_del(here):\n self.constructor[here] += self.constructor[here + 1]\n del self.constructor[here + 1]\n del self.constructor_type[here + 1]\n\n here = 0\n typ = lambda idx: self.constructor_type[here + idx]\n while True:\n try:\n value = typ(0) * typ(1)\n except IndexError:\n break\n else:\n if value == 1:\n merge_and_del(here)\n elif value == 2:\n here += 1\n self.constructor.insert(here, \"*\")\n self.constructor_type.insert(here, self.symb_type[\"operator\"])\n elif value == 3:\n here += 1\n elif value == 4:\n merge_and_del(here)\n elif value == 6:\n here += 1\n elif value == 9:\n self.check_valid_double_operator()\n\n def check_valid_double_operator(self):\n \"\"\"For symbols like **, ==, !=\"\"\"\n pass\n\n def add_variables(self):\n vars = np.asarray(self.constructor)[\n np.where(np.asarray(self.constructor_type) == 2)\n ]\n self.base._add_variables(vars)\n\n def make_oder1_list(self):\n # muldiv_list = []\n opr_type_dict = {\"+\": \"add\", \"-\": \"sub\", \"*\": \"mul\", \"/\": \"div\", \"^\": \"pow\"}\n\n # this first loop does all the powers\n\n # this second loop does all the multiplicaiton and division\n\n dummy = []\n dummy_empty = True\n # custom_remove = [False, None]\n prev_opr = None\n for i, obj in enumerate(self.constructor):\n\n if obj in [\"*\", \"/\"]:\n opr = opr_type_dict[obj]\n\n if dummy_empty:\n if prev_opr in [\"mul\", \"div\"]:\n dummy = [opr, dummy, self.constructor[i + 1]]\n else:\n dummy.append(\n [opr, self.constructor[i - 1], self.constructor[i + 1]]\n )\n dummy_empty = False\n\n else:\n if prev_opr in [\"mul\", \"div\"]:\n dummy = [opr, dummy, self.constructor[i + 1]]\n else:\n dummy.append(\n [opr, self.constructor[i - 1], self.constructor[i + 1]]\n )\n prev_opr = opr\n\n try:\n if obj in self.operator_list and obj not in [\"*\", \"/\"]:\n prev_opr = None\n except:\n pass\n self.list = dummy\n # print(dummy)\n\n # this third loop does all addidtion and subtraction\n expr_list = []\n for i, opr in enumerate(self.constructor):\n if expr_list == []:\n expr_empty = True\n # print(opr)\n if opr in [\"add\", \"sub\"]:\n\n if expr_empty:\n expr_list.append(\n [opr, self.constructor[i - 1], self.constructor[i + 1]]\n )\n expr_list = expr_list[0]\n expr_empty = False\n else:\n expr_list = [opr, expr_list, self.constructor[i + 1]]\n else:\n expr_list.append(self.constructor[i])\n\n # print(expr_list)\n self.expr_list = expr_list\n\n\nexpression = \"1*2+3*4\"\nexpression = \"211vs*3+53*lpets*ts+1\"\nI = Interpreter(expression)\nprint(I.expr_list)\n# test = Interpreter(expression)\n\n\n\"\"\"\nser ut som det er noe gale med make_order1:\n['mul', ['mul', [['mul', '211', 'vs']], '3', ['mul', '53', 'lpets']], 'ts']\n['211', '*', 'vs', '*', '3', '+', '53', '*', 'lpets', '*', 'ts', '+', '1']\n\nmake_order0 fjerner ikke *1 og +0. Tror det kan være lurt å \"evaluere\"\nhver miniliste fra make_order1; [mul, [\"mul\", \"211\", \"3\"], f] umiddelbart erstattes av [mul, 633, f]\nDette fjerner *1 og +0.\nMå bruke Variables-klasse fra LAS for å kunne evaluere variabler med None som verdi\nvet ikke hvordan vi gjør med ting som 3*f*2, ettersom den blir [mul, [mul, 3, f], 2]\n\n\"\"\"\n","sub_path":"roteboks/function/interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":5203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"9014039","text":"#!/usr/bin/env python3\n\n######################################################\n# created by : Pushtakio\n# purpose : basic tcp client\n# date :\n# version: 1.0.0\n#######################################################\n\nimport socket\n\nhost = 'localhost'\nport = 8080\ndata = ' '\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.connect((host,port))\n\nwhile data != 'EOF':\n data = input('my message: ')\n s.send(data)\n d = s.recv(2048)\n\ns.close()","sub_path":"network_exmaples/socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"229113856","text":"import threading\nfrom threading import Thread\nfrom audio import get_stream, get_wave\n\nclass Oscillator(threading.Thread):\n \"\"\"Basic oscillator that runs on its own thread\"\"\"\n\n def __init__(self, freq, wave_shape, duration=1.0):\n Thread.__init__(self)\n print(self.getName(), freq)\n self.stream = get_stream()\n self.wave = get_wave(wave_shape, freq, duration, taper=False)\n self.running = False\n\n def generate(self):\n \"\"\"A basic oscillator\"\"\"\n while True:\n yield self.wave\n \n def run(self):\n self.running = True\n while self.running:\n self.stream.write(self.wave.tobytes())\n self.stream.stop_stream()\n self.stream.close()\n\n def stop(self):\n self.running = False","sub_path":"modules/oscillator.py","file_name":"oscillator.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"453985406","text":"def _continuar():\n while True:\n opcao = pede_nome(\"Continuar [s|n]: \")\n if opcao == \"s\":\n return True\n elif opcao == \"n\":\n return False\n else:\n print(\"Erro. Opção Inválida.\")\n\ndef menu():\n print(\"╔\",end=\"\")\n print(\"═\"*23,end=\"\")\n print(\"╗\")\n print(\"║ [1] Cadastrar Cliente ║\")\n print(\"║ [2] Listar Clientes ║\")\n print(\"║ [3] Procurar Cliente ║\")\n print(\"║ [4] Depositar ║\")\n print(\"║ [5] Sacar ║\")\n print(\"║ [6] Tranferência ║\")\n print(\"║ [7] Emprestimo ║\")\n print(\"║ [0] Sair ║\")\n print(\"╚\",end=\"\")\n print(\"═\"*23,end=\"\")\n print(\"╝\")\n\n\ndef pede_valor_f(mensagem):\n while True:\n try:\n return float(input(mensagem))\n except ValueError:\n print(\"Ops, erro número inválido. Tente novamente.\") \n\ndef pede_valor_i(mensagem):\n while True:\n try:\n return int(input(mensagem))\n except ValueError:\n print(\"Ops, erro número inválido. Tente novamente.\")\n\ndef pede_nome(mensagem):\n return input(mensagem)\n\ndef cadastrar():\n continuar = True\n while continuar:\n nome = pede_nome(\"Digite o nome do Cliente: \")\n conta = pede_valor_i(\"Digite a conta ex.[11111]: \")\n saldo = pede_valor_f(\"Digite o saldo: \")\n nomes.append(nome)\n contas.append(conta)\n saldos.append(saldo)\n continuar = _continuar()\ndef listar():\n for i in range(len(nomes)):\n print(\"**********************\")\n print(\"* Nome: \",nomes[i])\n print(\"* Conta: \",contas[i])\n print(\"* Saldo: \",saldos[i])\n print(\"**********************\")\n\ndef procurar():\n procurar = input(\"Digite o nome do Cliente: \")\n if procurar in nomes:\n print(\"************************************\")\n print(\"* %s tem conta nesse banco.\"%procurar)\n print(\"************************************\")\n else:\n print(\"****************************************\")\n print(\"* %s não tem conta nesse banco.\"%procurar)\n print(\"****************************************\")\n\ndef depositar():\n pesq_conta = pede_valor_i(\"Digite a conta que deseja depositar: \")\n if pesq_conta in contas:\n deposito = pede_valor_f(\"Digite quanto deseja depositar: \")\n ind = contas.index(pesq_conta)\n saldos[ind] = saldos[ind]+deposito\n else:\n print(\"Conta não existe.\")\n \ndef sacar():\n pesq_conta = pede_valor_i(\"Digite a conta que deseja sacar: \")\n if pesq_conta in contas:\n ind = contas.index(pesq_conta)\n sacar = pede_valor_f(\"Digite quanto deseja sacar: \")\n if saldos[ind] >= sacar:\n saldos[ind] = saldos[ind] - sacar\n else:\n print(\"Saldo insuficiente, seu saldo é de \",saldos[ind])\n else:\n print(\"Conta não existe.\")\n\ndef transferir():\n a_conta = pede_valor_i(\"Digite a conta fornecedora: \")\n if a_conta in contas:\n b_conta = pede_valor_i(\"Digite a conta favorecida: \")\n a_ind = contas.index(a_conta)\n if b_conta in contas:\n b_ind = contas.index(b_conta)\n while True:\n valor = pede_valor_f(\"Digite quanto deseja transferir: \")\n if verificar_saldo(saldos[a_ind],valor) == True:\n saldos[a_ind]=saldos[a_ind] - valor\n saldos[b_ind]=saldos[b_ind] + valor\n break\n else:\n continue \n else:\n print(\"Conta inexistente.\")\n else:\n print(\"Conta inexistente.\") \n\ndef verificar_saldo(conta_saldo,valor):\n if valor > conta_saldo:\n print(\"***********************************************\")\n print(\"* Saldo insuficiente, saldo é de \",conta_saldo,)\n print(\"***********************************************\")\n else:\n return True\n \n \ndef emprestimo():\n conta = pede_valor_i(\"Digite a conta: \")\n if conta in contas:\n salario = pede_valor_f(\"Digite o salário: \")\n parcelas = pede_valor_i(\"Digite a quantidade de parcelas: \")\n limite = (salario*0.30)*parcelas\n valor_requerido = pede_valor_f(\"Diga quanto quer: \")\n ind = contas.index(conta)\n if valor_requerido <= limite:\n saldos[ind] = saldos[ind]+valor_requerido\n else:\n print(\"*************************\")\t\n print(\"O seu Limite é \",limite)\n print(\"*************************\")\n \n \nnomes=[]\ncontas=[]\nsaldos=[]\nwhile True:\n menu()\n opcoes = pede_nome(\"Opção: \")\n if opcoes == \"1\":\n cadastrar()\n\n elif opcoes == \"2\":\n listar()\n\n elif opcoes == \"3\":\n procurar()\n\n elif opcoes == \"4\":\n depositar()\n\n elif opcoes == \"5\":\n sacar()\n\n elif opcoes == \"6\":\n transferir()\n\n elif opcoes == \"7\":\n emprestimo()\n\n elif opcoes == \"0\":\n print(\"Até a próxima.\")\n break\n \n else:\n print(\"Opção inválida.\")\n\n","sub_path":"conta_banco.py","file_name":"conta_banco.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"512694050","text":"\"\"\"\n\n\"utils/anchor.py\"\n\nContains anchor generator functions for custom data.\n\n\"\"\"\n\nimport numpy as np\nfrom sklearn.cluster import KMeans\n\n\n# ---------------- ANCHOR GENERATION ----------------\ndef generate_anchors(boxes_or_file, num_anchors):\n \"\"\"Generates anchors given bounding boxes or a bounding box file using K-means\n\n :param boxes_or_file: either array of bounding boxes (width, height) or an bounding box annotations file\n :param num_anchors: number of anchors (i.e., clusters to be generated)\n :returns: generated anchors\n\n \"\"\"\n\n def _generate_anchors(bounding_boxes, num_anchors):\n return KMeans(n_clusters=num_anchors, n_init=1).fit(bounding_boxes).cluster_centers_.astype(np.uint8)\n\n try:\n return _generate_anchors(boxes_or_file, num_clusters)\n except ValueError:\n return _generate_anchors(parse_annotations(boxes_or_file), num_anchors)\n\n\n# ---------------- FILE IO ----------------\ndef parse_annotations(filename):\n \"\"\"Retrieves and parses annotations already parsed by parse.py\n\n :param filename: annotations filename\n :return: array of bounding boxes with shape (num_boxes, 2)-- each box is just height and width\n\n \"\"\"\n\n bounding_boxes = []\n with open(filename, \"r\") as file:\n for line in file:\n for box in line.rstrip().split(\" \")[1:]:\n x_min, y_min, x_max, y_max = [float(coord) for coord in box.split(\",\")[:-1]]\n width = round(x_max - x_min)\n height = round(y_max - y_min)\n\n bounding_boxes.append((width, height))\n\n return np.array(bounding_boxes)\n\n\ndef write_anchors(anchor_file, annotation_file, num_anchors):\n \"\"\"Writes anchors to a file\n\n :param anchor_file: file to write anchors\n :param annotation_file: bounding box annotations file\n :param num_anchors: number of anchors to be generated\n\n \"\"\"\n\n anchors = generate_anchors(parse_annotations(annotation_file), num_anchors)\n with open(anchor_file, \"w\") as file:\n written_anchors = \"\"\n\n for idx, anchor in enumerate(anchors):\n x, y = anchor\n\n written_anchors += str(int(x)) + \",\" + str(int(y))\n if idx != len(anchors) - 1:\n written_anchors += \", \"\n\n file.write(written_anchors)\n\n print(\"Wrote {} anchors to {}\".format(num_anchors, anchor_file))\n\n\n# ---------------- TESTING ----------------\nif __name__ == \"__main__\":\n num_clusters = 9 # 6 for tiny yolo\n filename = \"/media/ryan/Data/x-ray-datasets/sixray/images/annotations.csv\"\n print(generate_anchors(filename, num_clusters))\n","sub_path":"utils/anchor.py","file_name":"anchor.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"89631229","text":"#!/usr/bin/python3\n\nimport asyncio\nimport json\n\nfrom autobahn.asyncio.wamp import (\n ApplicationRunner,\n ApplicationSession,\n)\n\n\nclass GPIOPinClient(ApplicationSession):\n async def onJoin(self, details):\n def on_gpio_event(data, *args):\n print(data)\n\n await self.subscribe(on_gpio_event, u'pigpio.gpio_update')\n while True:\n res = await self.call(u'pigpio.get_state', 21)\n await self.call(u'pigpio.set_state', 21, not json.loads(res)['state'])\n asyncio.sleep(1)\n\n def onDisconnect(self):\n asyncio.get_event_loop().stop()\n\n\nif __name__ == '__main__':\n runner = ApplicationRunner(u\"ws://82.196.5.7:8080/ws\", u\"realm1\")\n runner.run(GPIOPinClient)\n\n","sub_path":"pigpio/examples/client_runner.py","file_name":"client_runner.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"328490156","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 25 13:46:34 2020\n\n@author: DavidOhlson\n\"\"\"\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.table import Table, join, vstack, Column\nimport matplotlib.pyplot as plt\nfrom astropy import units as u\n\n### read in data\n\n#t_she = Table.read('data/she2017.fits')\nt = Table.read('data/nsa_she_1.fits')\n\n#%% create array of petroflux values (FNugriz)\npetroflux = t['PETRO_FLUX']\n\n### create arrays for g and i pflux\npflux_g = np.array(petroflux[:, 3])\npflux_i = np.array(petroflux[:, 5])\n\n#%% create pogson mag arrays for g and i bands\npmag_g = 22.5 - (2.5*np.log10(pflux_g))\npmag_i = 22.5 - (2.5*np.log10(pflux_i))\n\n#%% create array of extinction values\n### NSA ext from Schlegel, Finkbeiner, and Davis (1997)\nextinction = t['EXTINCTION']\n\n### create ext arrays for g&i bands, corrected to Schlafly and Finkbeiner (2011)\next_g = extinction[:, 3] * 0.86\next_i = extinction[:, 5] * 0.86\n\n#%% Distance Modulus\n\ndist = t['Dist'] * 10**6 # need to convert Mpc to pc\nDM = 5*np.log10(dist) - 5\nt['DISTMOD'] = DM\n\n#%% correct pogson magnitude with extinction values and distance modulus\n\nMagCor_g = pmag_g - DM - ext_g\nMagCor_i = pmag_i - DM - ext_i\n\n#%% get L values from corrected mags\n\nMsun_g = 5.11\nMsun_i = 4.53\n\nL_g = 10** (-0.4* (MagCor_g - Msun_g))\nL_i = 10** (-0.4* (MagCor_i - Msun_i))\n\n#%% calculate log(M/L) values\n\n### using BC03 relations and g-i color for log(M/L)\ncolor = MagCor_g - MagCor_i # (g-i)\nm_i = 0.979 # Roediger(2015): Table A1\nb_i = -0.831\n\nlog_MLCR = (m_i * color) + b_i\nMLCR = 10**log_MLCR\n\n#%% multiply by L_i to get Mass\n\nmass = MLCR * L_i\nt['MASS'] = mass\n\nt.write('data/nsa_she_2.fits', format='fits', overwrite=True)\n","sub_path":"sdss_color_mag.py","file_name":"sdss_color_mag.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20120376","text":"def valid_chess_board(board):\n bpieces, wpieces = 0, 0\n pieces = (\"king\", \"queen\", \"rook\", \"bishop\", \"knight\", \"pawn\")\n board_pieces = list(board.values())\n\n # Checking the kings\n if board_pieces.count(\"bking\") != 1 or board_pieces.count(\"wking\") != 1:\n return False\n\n # Checking the pawns\n if board_pieces.count(\"bpawn\") > 8 or board_pieces.count(\"wpawn\") > 8:\n return False\n\n # Checking the colors\n for p in board_pieces:\n if p[0] == \"b\" and p[1:] in pieces:\n bpieces += 1\n elif p[0] == \"w\" and p[1:] in pieces:\n wpieces += 1\n else:\n return False\n\n # Checking the pieces\n if bpieces > 16 or wpieces > 16:\n return False\n\n # Checking the spaces\n for s in board:\n if s[0] not in \"12345678\" or s[1] not in \"abcdefgh\":\n return False\n\n return True\n\nchess_board = {\n \"1a\": \"wrook\",\n \"2a\": \"wpawn\",\n \"6a\": \"bpawn\",\n \"8a\": \"brook\",\n \"2b\": \"wpawn\",\n \"5b\": \"bpawn\",\n \"1c\": \"wbishop\",\n \"2c\": \"wbishop\",\n \"3c\": \"wpawn\",\n \"6c\": \"bknight\",\n \"7c\": \"bpawn\",\n \"1d\": \"wqueen\",\n \"2d\": \"wknight\",\n \"5d\": \"bpawn\",\n \"8d\": \"bqueen\",\n \"6e\": \"bbishop\",\n \"7e\": \"bbishop\",\n \"1f\": \"wrook\",\n \"2f\": \"wpawn\",\n \"3f\": \"wknight\",\n \"6f\": \"bknight\",\n \"8f\": \"brook\",\n \"1g\": \"wking\",\n \"2g\": \"wpawn\",\n \"7g\": \"bpawn\",\n \"8g\": \"bking\",\n \"2h\": \"wpawn\",\n \"7h\": \"bpawn\",\n}\n\nprint(valid_chess_board(chess_board))","sub_path":"Cap005 Nested Dictionaries.py","file_name":"Cap005 Nested Dictionaries.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"242134407","text":"# encoding: utf-8\n\"\"\"\nTraining implementation for CT-3D retrieval\nAuthor: Jason.Fang\nUpdate time: 08/05/2021\n\"\"\"\nimport re\nimport sys\nimport os\nimport cv2\nimport time\nimport argparse\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torch.optim import lr_scheduler\nimport torch.optim as optim\nimport torchvision\nfrom skimage.measure import label\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport heapq\nfrom PIL import Image\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\nimport seaborn as sns\nfrom sklearn.metrics import ndcg_score\n#self-defined\nfrom config import *\nfrom utils.logger import get_logger\nfrom data_lidc.LIDC_VR_Scan import get_train_dataloader, get_test_dataloader\nfrom nets.mcbir_3dnet import MCBIR3DNet, CircleLoss\n\n#command parameters\nparser = argparse.ArgumentParser(description='For LungCT')\nparser.add_argument('--model', type=str, default='CTScan', help='CTScan')\nargs = parser.parse_args()\n#config\nos.environ['CUDA_VISIBLE_DEVICES'] = config['CUDA_VISIBLE_DEVICES']\nlogger = get_logger(config['log_path'])\n\ndef Train():\n print('********************load data********************')\n dataloader_train = get_train_dataloader(batch_size=config['BATCH_SIZE'], shuffle=True, num_workers=8)\n dataloader_test = get_test_dataloader(batch_size=config['BATCH_SIZE'], shuffle=False, num_workers=8)\n print('********************load data succeed!********************')\n\n print('********************load model********************')\n # initialize and load the model\n if args.model == 'CTScan':\n model = MCBIR3DNet(in_channels=1)\n CKPT_PATH = config['CKPT_PATH'] + args.model + '_best.pkl'\n if os.path.exists(CKPT_PATH):\n checkpoint = torch.load(CKPT_PATH)\n model.load_state_dict(checkpoint) #strict=False\n print(\"=> Loaded well-trained checkpoint from: \" + CKPT_PATH)\n else: \n print('No required model')\n return #over\n model = nn.DataParallel(model).cuda() # make model available multi GPU cores training \n torch.backends.cudnn.benchmark = True # improve train speed slightly\n optimizer_model = optim.Adam(model.parameters(), lr=1e-3, betas=(0.9, 0.999), eps=1e-08, weight_decay=1e-5)\n lr_scheduler_model = lr_scheduler.StepLR(optimizer_model , step_size = 10, gamma = 1)\n #define loss function\n criterion = CircleLoss(scale=8).cuda() #nn.CrossEntropyLoss().cuda()\n print('********************load model succeed!********************')\n\n print('********************begin training!********************')\n loss_min = float('inf')\n \n for epoch in range(config['MAX_EPOCHS']):\n since = time.time()\n print('Epoch {}/{}'.format(epoch+1 , config['MAX_EPOCHS']))\n print('-' * 10)\n model.train() #set model to training mode\n loss_train = []\n with torch.autograd.enable_grad():\n for batch_idx, (ts_imgs, ts_masks, ts_label, ts_nodvol) in enumerate(dataloader_train):\n #forward\n var_image = torch.autograd.Variable(ts_imgs).cuda()\n var_label = torch.autograd.Variable(ts_label).cuda()\n var_out = model(var_image)\n # backward and update parameters\n optimizer_model.zero_grad()\n loss_tensor = criterion.forward(var_out, var_label)\n loss_tensor.backward()\n optimizer_model.step()\n #show \n loss_train.append(loss_tensor.item())\n sys.stdout.write('\\r Epoch: {} / Step: {} : train loss = {}'.format(epoch+1, batch_idx+1, float('%0.6f'%loss_tensor.item()) ))\n sys.stdout.flush()\n lr_scheduler_model.step() #about lr and gamma\n print(\"\\r Eopch: %5d train loss = %.6f\" % (epoch + 1, np.mean(loss_train) ))\n\n #test\n model.eval()\n loss_test = []\n with torch.autograd.no_grad():\n for batch_idx, (ts_imgs, ts_masks, ts_label, ts_nodvol) in enumerate(dataloader_test):\n #forward\n var_image = torch.autograd.Variable(ts_imgs).cuda()\n var_label = torch.autograd.Variable(ts_label).cuda()\n var_out = model(var_image)\n loss_tensor = criterion.forward(var_out, var_label)\n loss_test.append(loss_tensor.item())\n sys.stdout.write('\\r testing process: = {}'.format(batch_idx+1))\n sys.stdout.flush()\n print(\"\\r Eopch: %5d test loss = %.6f\" % (epoch + 1, np.mean(loss_test) ))\n\n # save checkpoint\n if loss_min > np.mean(loss_test):\n loss_min = np.mean(loss_test)\n torch.save(model.module.state_dict(), config['CKPT_PATH'] + args.model + '_best.pkl') #Saving torch.nn.DataParallel Models\n print(' Epoch: {} model has been already save!'.format(epoch + 1))\n\n time_elapsed = time.time() - since\n print('Training epoch: {} completed in {:.0f}m {:.0f}s'.format(epoch+1, time_elapsed // 60 , time_elapsed % 60))\n\n\ndef Test():\n print('********************load data********************')\n dataloader_train = get_train_dataloader(batch_size=8, shuffle=False, num_workers=8) #config['BATCH_SIZE']\n dataloader_test = get_test_dataloader(batch_size=8, shuffle=False, num_workers=8)\n print('********************load data succeed!********************')\n\n print('********************load model********************')\n if args.model == 'CTScan':\n model = MCBIR3DNet(in_channels=1).cuda()\n CKPT_PATH = config['CKPT_PATH'] + args.model + '_best.pkl'\n if os.path.exists(CKPT_PATH):\n checkpoint = torch.load(CKPT_PATH)\n model.load_state_dict(checkpoint) #strict=False\n print(\"=> Loaded well-trained checkpoint from: \" + CKPT_PATH)\n else: \n print('No required model')\n return #over\n torch.backends.cudnn.benchmark = True # improve train speed slightly\n model.eval()#turn to test mode\n print('******************** load model succeed!********************')\n\n print('********************Build feature database!********************')\n tr_label = torch.FloatTensor().cuda()\n tr_nodvol = torch.FloatTensor().cuda()\n tr_feat = torch.FloatTensor().cuda()\n with torch.autograd.no_grad():\n for batch_idx, (ts_imgs, ts_masks, ts_label, ts_nodvol) in enumerate(dataloader_train):\n var_image = torch.autograd.Variable(ts_imgs).cuda()\n var_out = model(var_image)\n tr_feat = torch.cat((tr_feat, var_out.data), 0)\n tr_label = torch.cat((tr_label, ts_label.cuda()), 0)\n tr_nodvol = torch.cat((tr_nodvol, ts_nodvol.cuda()), 0)\n sys.stdout.write('\\r train set process: = {}'.format(batch_idx + 1))\n sys.stdout.flush()\n\n te_label = torch.FloatTensor().cuda()\n te_nodvol = torch.FloatTensor().cuda()\n te_feat = torch.FloatTensor().cuda()\n with torch.autograd.no_grad():\n for batch_idx, (ts_imgs, ts_masks, ts_label, ts_nodvol) in enumerate(dataloader_test):\n var_image = torch.autograd.Variable(ts_imgs).cuda()\n var_out = model(var_image)\n te_feat = torch.cat((te_feat, var_out.data), 0)\n te_label = torch.cat((te_label, ts_label.cuda()), 0)\n te_nodvol = torch.cat((te_nodvol, ts_nodvol.cuda()), 0)\n sys.stdout.write('\\r test set process: = {}'.format(batch_idx + 1))\n sys.stdout.flush()\n\n print('********************Retrieval Performance!********************')\n sim_mat = cosine_similarity(te_feat.cpu().numpy(), tr_feat.cpu().numpy())\n te_label = te_label.cpu().numpy()\n tr_label = tr_label.cpu().numpy()\n te_nodvol = te_nodvol.cpu().numpy()\n tr_nodvol = tr_nodvol.cpu().numpy()\n\n for topk in [5]: #[5,10,20,50]:\n mHRs_avg = []\n mAPs_avg = []\n NDCG_avg = []\n for i in range(sim_mat.shape[0]):\n idxs, vals = zip(*heapq.nlargest(topk, enumerate(sim_mat[i,:].tolist()), key=lambda x:x[1]))\n num_pos = 0\n rank_pos = 0\n mAP = []\n te_idx = te_label[i]#te_label[i,:][0]\n #calculate the relevance based on the volume of nodules\n gt_rel = abs(tr_nodvol - te_nodvol[i])\n gt_rel = abs(gt_rel-gt_rel.max()) + 1 # add 1 to avoid the results is zero which applys they are not relevant.\n pd_rank = []\n for j in idxs:\n rank_pos = rank_pos + 1\n tr_idx = tr_label[j]#tr_label[j,:][0]\n if te_idx in [0,1] and tr_idx in [0, 1]: #hit\n num_pos = num_pos +1\n mAP.append(num_pos/rank_pos)\n pd_rank.append(gt_rel[j])\n elif te_idx in [3, 4] and tr_idx in [3, 4]: #hit\n num_pos = num_pos +1\n mAP.append(num_pos/rank_pos)\n pd_rank.append(gt_rel[j])\n elif te_idx == 2 and tr_idx == 2:\n num_pos = num_pos +1\n mAP.append(num_pos/rank_pos)\n pd_rank.append(gt_rel[j])\n else:\n mAP.append(0)\n pd_rank.append(0)\n if len(mAP) > 0:\n mAPs_avg.append(np.mean(mAP))\n else:\n mAPs_avg.append(0)\n mHRs_avg.append(num_pos/rank_pos)\n\n #calculate NDCG\n pd_rank = np.array([pd_rank])\n gt_rank = abs(np.sort(-pd_rank))\n NDCG_avg.append(ndcg_score(gt_rank, pd_rank))\n sys.stdout.write('\\r test set process: = {}'.format(i+1))\n sys.stdout.flush()\n\n #Hit ratio\n logger.info(\"HR@{}={:.4f}\".format(topk, np.mean(mHRs_avg)))\n #average precision\n logger.info(\"AP@{}={:.4f}\".format(topk, np.mean(mAPs_avg)))\n #NDCG: normalized discounted cumulative gain\n logger.info(\"NDCG@{}={:.4f}\".format(topk, np.mean(NDCG_avg)))\n\ndef main():\n Train()\n Test()\n\nif __name__ == '__main__':\n main()\n","sub_path":"release/v1.2/main_mcbir.py","file_name":"main_mcbir.py","file_ext":"py","file_size_in_byte":10129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"381311557","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport sys\r\nimport time\r\nimport os\r\nimport pickle\r\nimport math\r\n\r\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\r\nMAX_EP = 1000000\r\nN_WORKERS = 16\r\nEVAL_FREQ = 5000\r\nLSTM_SIZE = 128\r\nMAX_GRAD = 40\r\nSCALE = 1\r\nCFG = \"my_way_home.cfg\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom gym.core import Wrapper\r\nfrom gym.spaces.box import Box\r\n\r\nfrom preprocess_doom import make_env\r\n\r\ndef crop_func(img):\r\n return img[20:-20, 60:-60]\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.multiprocessing as mp\r\n\r\nclass Flatten(nn.Module):\r\n def forward(self, input):\r\n return input.view(input.size(0), -1)\r\n\r\nclass AC_Net(nn.Module):\r\n def __init__(self, obs_shape, n_actions, lstm_size=128):\r\n \"\"\"A simple actor-critic agent\"\"\"\r\n super(self.__class__, self).__init__()\r\n self.obs_shape = obs_shape\r\n self.n_actions = n_actions\r\n self.lstm_size = lstm_size\r\n self.conv = nn.Sequential(\r\n nn.Conv2d(1, 32, kernel_size=3, stride=2),\r\n nn.ReLU(),\r\n nn.Conv2d(32, 32, kernel_size=3, stride=2),\r\n nn.ReLU(),\r\n nn.Conv2d(32, 32, kernel_size=3, stride=2),\r\n nn.ReLU(),\r\n nn.Conv2d(32, 32, kernel_size=3, stride=2),\r\n nn.ReLU(),\r\n )\r\n\r\n self.flatten = Flatten()\r\n\r\n self.rnn = nn.LSTMCell(self.feature_size(), self.lstm_size)\r\n\r\n self.logits = nn.Linear(self.lstm_size, n_actions)\r\n self.state_value = nn.Linear(self.lstm_size, 1)\r\n\r\n def feature_size(self):\r\n return self.conv(torch.zeros(1, *self.obs_shape)).view(1, -1).size(1)\r\n\r\n def forward(self, prev_state, obs_t):\r\n \"\"\"\r\n Takes agent's previous hidden state and a new observation,\r\n returns a new hidden state and whatever the agent needs to learn\r\n \"\"\"\r\n\r\n h = self.conv(obs_t)\r\n h = self.flatten(h)\r\n\r\n new_state = h_new, c_new = self.rnn(h, prev_state)\r\n logits = self.logits(h_new)\r\n state_value = self.state_value(h_new)\r\n\r\n return new_state, (logits, state_value)\r\n\r\n def get_initial_state(self, batch_size):\r\n \"\"\"Return a list of agent memory states at game start. Each state is a np array of shape [batch_size, ...]\"\"\"\r\n return torch.zeros((batch_size, self.lstm_size)), torch.zeros((batch_size, self.lstm_size))\r\n\r\n def sample_actions(self, agent_outputs):\r\n \"\"\"pick actions given numeric agent outputs (np arrays)\"\"\"\r\n logits, state_values = agent_outputs\r\n probs = F.softmax(logits, dim=1)\r\n return torch.multinomial(probs, 1)[:, 0].data.numpy()\r\n\r\n def step(self, prev_state, obs_t):\r\n \"\"\" like forward, but obs_t is a numpy array \"\"\"\r\n obs_t = torch.tensor(np.asarray(obs_t), dtype=torch.float32)\r\n (h, c), (l, s) = self.forward(prev_state, obs_t)\r\n return (h, c), (l, s)\r\n\r\n def compute_rollout_loss(self, actions, rewards,\r\n logits, state_values, gamma=0.99):\r\n\r\n actions = torch.tensor(np.array(actions), dtype=torch.int64) # shape: [time]\r\n rewards = torch.tensor(np.array(rewards), dtype=torch.float32) # shape: [time]\r\n rollout_length = rewards.shape[0]\r\n\r\n logits = torch.stack(logits, dim=1)\r\n logits = logits.view(logits.size(1), -1)\r\n state_values = torch.stack(state_values, dim=1)\r\n state_values = torch.squeeze(state_values)\r\n\r\n probas = F.softmax(logits, dim=1)\r\n logprobas = F.log_softmax(logits, dim=1)\r\n # select log-probabilities for chosen actions, log pi(a_i|s_i)\r\n\r\n logprobas_for_actions = logprobas[range(len(actions)), actions]\r\n\r\n J_hat = 0 # policy objective as in the formula for J_hat\r\n\r\n value_loss = 0\r\n\r\n cumulative_returns = state_values[-1].detach()\r\n\r\n for t in reversed(range(rollout_length)):\r\n r_t = rewards[t] # current rewards\r\n V_t = state_values[t]\r\n V_next = state_values[t+1].detach() # next state values\r\n logpi_a_s_t = logprobas_for_actions[t]\r\n\r\n cumulative_returns = G_t = r_t + gamma * cumulative_returns\r\n\r\n # Compute temporal difference error (MSE for V(s))\r\n value_loss += (r_t + gamma * V_next - V_t)**2\r\n\r\n # compute advantage A(s_t, a_t) using cumulative returns and V(s_t) as baseline\r\n advantage = cumulative_returns - V_t\r\n advantage = advantage.detach()\r\n\r\n # compute policy pseudo-loss aka -J_hat.\r\n J_hat += logpi_a_s_t * advantage\r\n\r\n # regularize with entropy\r\n entropy_reg = -(logprobas * probas).sum(-1).mean()\r\n\r\n # add-up three loss components and average over time\r\n loss = -J_hat / rollout_length +\\\r\n value_loss / rollout_length +\\\r\n -0.01 * entropy_reg\r\n\r\n return loss\r\n\r\nclass SharedAdam(torch.optim.Adam):\r\n def __init__(self, params, lr=1e-4):\r\n super(SharedAdam, self).__init__(params, lr=lr)\r\n # State initialization\r\n for group in self.param_groups:\r\n for p in group['params']:\r\n state = self.state[p]\r\n state['step'] = 0\r\n state['exp_avg'] = torch.zeros_like(p.data)\r\n state['exp_avg_sq'] = torch.zeros_like(p.data)\r\n\r\n # share in memory\r\n state['exp_avg'].share_memory_()\r\n state['exp_avg_sq'].share_memory_()\r\n\r\n\r\nclass Worker(mp.Process):\r\n def __init__(self, master, opt, process_id):\r\n super(Worker, self).__init__()\r\n self.process_id = process_id\r\n self.opt = opt\r\n self.master = master\r\n obs_shape = self.master.obs_shape\r\n n_actions = self.master.n_actions\r\n self.lnet = AC_Net(obs_shape, n_actions, lstm_size=LSTM_SIZE)\r\n self.memories = self.lnet.get_initial_state(1)\r\n\r\n def _sync_local_with_global(self):\r\n self.lnet.load_state_dict(self.master.state_dict())\r\n\r\n def work(self, n_iter):\r\n self.memories = (self.memories[0].detach(),\r\n self.memories[1].detach())\r\n\r\n actions = []\r\n rewards = []\r\n logits = []\r\n state_values = []\r\n\r\n for _ in range(n_iter):\r\n self.memories, (logits_t, value_t) = self.lnet.step(\r\n self.memories, self.observation[None, ...])\r\n action = self.lnet.sample_actions((logits_t, value_t))\r\n\r\n self.observation, reward, done, _ = self.env.step(action[0])\r\n\r\n actions.append(action[0])\r\n rewards.append(reward)\r\n logits.append(logits_t)\r\n state_values.append(value_t)\r\n\r\n if done:\r\n self.observation = self.env.reset()\r\n self.memories = self.lnet.get_initial_state(1)\r\n break\r\n\r\n\r\n _, (logits_t, value_t) = self.lnet.step(\r\n self.memories, self.observation[None, ...])\r\n\r\n state_values.append(value_t * (1 - done))\r\n\r\n return actions, rewards, logits, state_values\r\n\r\n def train(self, actions, rewards, logits, state_values, gamma=0.99):\r\n loss = self.lnet.compute_rollout_loss(actions, rewards, logits,\r\n state_values, gamma)\r\n self.opt.zero_grad()\r\n loss.backward()\r\n torch.nn.utils.clip_grad_norm_(self.lnet.parameters(), MAX_GRAD)\r\n for lp, mp in zip(self.lnet.parameters(), self.master.parameters()):\r\n mp._grad = lp.grad\r\n self.opt.step()\r\n\r\n def run(self):\r\n self.env = make_env(CFG, SCALE, crop=crop_func)\r\n self.observation = self.env.reset()\r\n time.sleep(int(np.random.rand() * (self.process_id + 5)))\r\n while self.master.train_step.value < self.master.steps:\r\n self._sync_local_with_global()\r\n actions, rewards, logits, state_values = self.work(20)\r\n self.train(actions, rewards, logits, state_values)\r\n self.master.train_step.value += 1\r\n\r\nclass Tester(mp.Process):\r\n def __init__(self, master, process_id, eval_freq, n_games=1):\r\n super(Tester, self).__init__()\r\n self.process_id = process_id\r\n self.master = master\r\n obs_shape = self.master.obs_shape\r\n n_actions = self.master.n_actions\r\n self.lnet = AC_Net(obs_shape, n_actions, lstm_size=LSTM_SIZE)\r\n self.rewards = []\r\n self.entropy = []\r\n self.n_games = n_games\r\n self.eval_freq = eval_freq\r\n self.step = 0\r\n\r\n def _sync_local_with_global(self):\r\n self.lnet.load_state_dict(self.master.state_dict())\r\n\r\n def evaluate(self):\r\n \"\"\"Plays an entire game start to end, returns session rewards.\"\"\"\r\n\r\n game_rewards = []\r\n logits = []\r\n for _ in range(self.n_games):\r\n # initial observation and memory\r\n observation = self.env.reset()\r\n prev_memories = self.lnet.get_initial_state(1)\r\n\r\n total_reward = 0\r\n while True:\r\n new_memories, (logits_t, value_t) = self.lnet.step(\r\n prev_memories, observation[None, ...])\r\n action = self.lnet.sample_actions((logits_t, value_t))\r\n\r\n observation, reward, done, info = self.env.step(action[0])\r\n\r\n logits.append(logits_t)\r\n total_reward += reward\r\n prev_memories = new_memories\r\n if done:\r\n break\r\n\r\n game_rewards.append(total_reward)\r\n\r\n logits = torch.stack(logits, dim=1)\r\n logits = logits.view(logits.size(1), -1)\r\n probas = F.softmax(logits, dim=1)\r\n logprobas = F.log_softmax(logits, dim=1)\r\n entropy_reg = -(logprobas * probas).sum(-1).mean()\r\n return np.mean(game_rewards), entropy_reg.item()\r\n\r\n def run(self):\r\n self.env = make_env(CFG, 1, crop=crop_func)\r\n while self.master.train_step.value < self.master.steps:\r\n if self.master.train_step.value >= self.step:\r\n eval_step = self.master.train_step.value\r\n self._sync_local_with_global()\r\n torch.save(self.lnet.state_dict(),\r\n 'a3c-{0}.weights'.format(CFG[0:3]))\r\n mean_reward, entropy_reg = self.evaluate()\r\n print(eval_step, \"reward:\", mean_reward, \"entropy:\", entropy_reg)\r\n self.rewards.append((eval_step, mean_reward))\r\n self.entropy.append((eval_step, entropy_reg))\r\n self.step += self.eval_freq\r\n with open('a3c-{0}_rewards.pkl'.format(CFG[0:3]), 'wb') as f:\r\n pickle.dump(self.rewards, f)\r\n with open('a3c-{0}_entropy.pkl'.format(CFG[0:3]), 'wb') as f:\r\n pickle.dump(self.entropy, f)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n env = make_env(CFG, SCALE, crop = crop_func)\r\n obs_shape = env.observation_space.shape\r\n n_actions = env.a_size\r\n\r\n master = AC_Net(obs_shape, n_actions, lstm_size=LSTM_SIZE)\r\n master.steps = MAX_EP\r\n master.train_step = mp.Value('l', 0)\r\n if os.path.exists('a3c-{0}.weights'.format(CFG[0:3])):\r\n master.load_state_dict(torch.load('a3c-{0}.weights'.format(CFG[0:3])))\r\n print('Successfully loaded weights')\r\n master.share_memory()\r\n shared_opt = SharedAdam(master.parameters())\r\n\r\n print('Workers count:', N_WORKERS)\r\n\r\n # parallel training\r\n processes = [Worker(master, shared_opt, i) for i in range(N_WORKERS)]\r\n processes.append(Tester(master, len(processes), EVAL_FREQ, n_games=5))\r\n for p in processes:\r\n p.start()\r\n for p in processes:\r\n p.join()\r\n","sub_path":"a3c_doom.py","file_name":"a3c_doom.py","file_ext":"py","file_size_in_byte":11784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"531295228","text":"from ophyd.runengine import RunEngine\n\nrun_eng = RunEngine(None)\n\n''' Assumes detector params (dwell time, etc) have been\n previously configured.\n\n Also assumes that ophyd.runengine.RunEngine exists in the\n IPython namespace.\n\n Returns a dict of {'data_key': [value1,value2,...],}\n'''\ndef scan1d(run_id, detectors=[], triggers=[], motors=[], paths=[], settle_time=None):\n scan_args = {}\n scan_args['detectors'] = detectors\n scan_args['triggers'] = triggers\n\n #set positioner trajectories if paths[] were provided.\n #otherwise, assume this has been done already.\n for path,motor in zip(paths,motors):\n motor.set_trajectory(path)\n scan_args['positioners'] = motors\n\n scan_args['settle_time'] = settle_time\n\n return run_eng.start_run(run_id, scan_args=scan_args)\n","sub_path":"examples/scan1d.py","file_name":"scan1d.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"195992266","text":"from PyPDF2 import PdfFileWriter, PdfFileReader\ninfile = PdfFileReader('c:/mypdfs/PoetryWBP.pdf', 'rb')\noutput = PdfFileWriter()\n\nfor i in range(infile.getNumPages()):\n p = infile.getPage(i)\n\n text=p.extractText()\n\n if len(text) > 10: # getContents is None if page is blank\n # print(i,len(text),text)\n output.addPage(p)\n\nwith open('c:/training/output.pdf', 'wb') as f:\n output.write(f)\n","sub_path":"Python/Python customized/DAY1/Demo2/Day5DemoScritps/DemoPDFDelete.py","file_name":"DemoPDFDelete.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"361368107","text":"#_Author_ = Shijie Huang (Harvey)\n#-*- coding: utf-8 -*-\n\n#Developed package\nfrom Mixed import *\nfrom Fundamental import *\nfrom Transitory import *\n\n#Standard Python Package\nimport random as rd\nimport numpy as np\n\nclass environment():\n #outlier game environment\n def __init__(self, state = 0, reward = 0, threshold = 0.01):\n self.reward = reward\n self.threshold = threshold\n self.state = state\n\n def reset(self):\n self.state = [rd.gauss(0,0.25),rd.gauss(0,0.25),rd.gauss(0,0.25),rd.gauss(0,0.25),rd.gauss(0,0.25)]\n return self.state\n\n def get_data(self,game_type=\"Mixed\",game_rounds = 100, plot = False):\n if game_type == \"Fundamental\" or \"fundamental\":\n state_list = fundamental_treatment(rounds = game_rounds,Print_or_not=plot).fundamental_treatment()[1]\n\n elif game_type == \"Mixed\" or \"mixed\":\n state_list = mixed_treatment(rounds = game_rounds, Print_or_not=plot).mixed_treatment()[1]\n\n elif game_type == \"Transitory\" or \"transitory\":\n state_list = transitory_treatment(rounds = game_rounds, Print_or_not=plot).transitory_treatment()[1]\n\n else:\n raise ValueError(\"Wrong game type, please enter Fundamental, Transitory or Mixed.\")\n\n return state_list\n\n\n #note: action = predicted position value\n def step(self, actual_position, inferred_position):\n prediction_error = actual_position-inferred_position\n reward = -abs(prediction_error)\n return (np.array(prediction_error),np.array(reward))","sub_path":"env/outlier_game_environment.py","file_name":"outlier_game_environment.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"525503352","text":"import docker\nfrom proxy import utils\n\n\nclass TestDataSource():\n \"\"\"Class used to manage execution of custom mutation testDataSource.\"\"\"\n\n def build_payload(self):\n \"\"\"Method used to surcharge payload sent to GraphQL API.\"\"\"\n\n return 'mutation testDataSource($dataSourceId: Int!) { testDataSource(input: { dataSourceId: $dataSourceId }) { dataSource { id connectivityStatus } } }'\n\n def test_data_source(self, authorization: str, response: dict):\n \"\"\"Method used to run Docker container which tests connectivity to a data source.\"\"\"\n\n data_source_id = str(response['data']['testDataSource']['dataSource']['id'])\n container_name = f'mobydq-test-data-source-{data_source_id}'\n client = docker.from_env()\n client.containers.run(\n name=container_name,\n image='mobydq-scripts',\n network='mobydq_network',\n command=['python', 'run.py', authorization, 'test_data_source', data_source_id],\n stream=True,\n remove=True\n )\n\n # Get connectivity test result\n query = 'query{dataSourceById(id:data_source_id){id,connectivityStatus,updatedDate,userByUpdatedById{email}}}'\n query = query.replace('data_source_id', str(data_source_id)) # Use replace() instead of format() because of curly braces\n query = {'query': query} # Convert to dictionary\n data = utils.execute_graphql_request(authorization, query)\n return data\n","sub_path":"api/init/proxy/data_source.py","file_name":"data_source.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"16228824","text":"import os\nif __name__ == \"__main__\":\n file_names = os.listdir(\".\")\n cnt = 0\n ext_names = [\"py\", \"java\", \"c\", \"cpp\", \"js\"]\n for file in file_names:\n if file.split(\".\")[-1] in ext_names:\n f = open(file, \"r\", encoding=\"utf-8\")\n cnt+=len(f.readlines())\n f.close()\n print(cnt)","sub_path":"line_cnt.py","file_name":"line_cnt.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"620984017","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom twisted.enterprise import adbapi\nfrom pymysql import cursors\nclass IpAgent89IpPipeline:\n def __init__(self):\n dbparams={\n 'host': '127.0.0.1',\n 'port': 3306,\n 'user': 'root',\n 'password': '123456',\n 'database': 'zz',\n 'charset': 'utf8',\n 'cursorclass': cursors.DictCursor\n }\n self.dbpool = adbapi.ConnectionPool('pymysql', **dbparams)\n self._sql = None\n\n\n #定义插入语句\n @property\n def sql(self):\n if not self._sql:\n self._sql = \"\"\"\n insert into ip_list_all (ip_url, port, perators, recording_time) value (%s,%s,%s,%s)\n \"\"\"\n return self._sql\n return self._sql\n\n\n def process_item(self, item, spider):\n # 对sql语句进行处理\n defer = self.dbpool.runInteraction(self.insert_item, item) # 执行函数insert_item 去插入数据\n defer.addErrback(self.handle_error, item, spider) # 遇到错误信息调用 handle_error方法\n\n def insert_item(self, cursor, item):\n cursor.execute(self.sql, (\n item['ip_url'],\n item['port'],\n item['perators'],\n item['recording_time']\n ))\n\n def handle_error(self, error, item, spider):\n print('*' * 20 + 'error' + '=' * 20)\n print(error)\n print('*' * 20 + 'error' + '*' * 20)\n","sub_path":"ip_agent_89ip/ip_agent_89ip/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"537546678","text":"from pyspark.sql import *\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import StructType, StringType, IntegerType, FloatType, TimestampType\n\nimport os\nimport locale\n\nlocale.setlocale(locale.LC_ALL, 'it_IT')\nimport pyspark.sql.functions as F\n\nimport uuid\n\nspark = (SparkSession\n .builder\n .master('local')\n .appName('TemperatureStreamApp')\n # Add kafka package\n .config(\"spark.jars.packages\", \"org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.1\")\n .getOrCreate())\n\nschema = StructType() \\\n .add(\"rowkey\", StringType()) \\\n .add(\"timestamp\", TimestampType()) \\\n .add(\"temperature\", IntegerType())\n \n\nstreamingDataFrame = spark \\\n .readStream \\\n .format(\"kafka\") \\\n .option(\"kafka.bootstrap.servers\", \"localhost:9092\", ) \\\n .option(\"subscribe\", \"temperature\") \\\n .option(\"failOnDataLoss\", \"true\") \\\n .option(\"includeHeaders\", \"true\") \\\n .option(\"startingOffsets\", \"earliest\") \\\n .load() \\\n .select(from_json(col(\"value\").cast(\"string\"), schema).alias(\"parsed_value\"))\n\nresultC = streamingDataFrame.select( \\\n col(\"parsed_value.rowkey\").alias(\"rowkey\") \\\n , col(\"parsed_value.timestamp\").alias(\"timestamp\") \\\n , col(\"parsed_value.temperature\").alias(\"temperature\"))\n\n\n\"\"\"\nWe work out the window and the AVG(temperature) in the window's timeframe below\nThis should return back the following Dataframe as struct\n\n root\n |-- window: struct (nullable = false)\n | |-- start: timestamp (nullable = true)\n | |-- end: timestamp (nullable = true)\n |-- avg(temperature): double (nullable = true)\n\n\"\"\"\n\"\"\"\nyour stuff\nresultM = resultC. \\\n withWatermark(\"timestamp\", \"10 seconds\"). \\\n groupBy(window(resultC.timestamp, \"10 seconds\", \"10 seconds\")). \\\n avg('temperature')\n\"\"\"\nresultM = resultC. \\\n withWatermark(\"timestamp\", \"5 minutes\"). \\\n groupBy(window(resultC.timestamp, \"5 minutes\", \"5 minutes\")). \\\n avg('temperature')\n\n\n# We take the above DataFrame and flatten it to get the columns aliased as \"startOfWindowFrame\", \"endOfWindowFrame\" and \"AVGTemperature\"\nresultMF = resultM. \\\n select( \\\n F.col(\"window.start\").alias(\"startOfWindow\") \\\n , F.col(\"window.end\").alias(\"endOfWindow\") \\\n , F.col(\"avg(temperature)\").alias(\"AVGTemperature\"))\n\n# Kafka producer requires a key, value pair. We generate UUID key as the unique identifier of Kafka record\nuuidUdf = F.udf(lambda: str(uuid.uuid4()), StringType())\n\n\"\"\"\nWe take DataFrame resultMF containing temperature info and write it to Kafka. The uuid is serialized as a string and used as the key.\nWe take all the columns of the DataFrame and serialize them as a JSON string, putting the results in the \"value\" of the record.\n\"\"\"\nresult = resultMF.withColumn(\"uuid\", uuidUdf()) \\\n .selectExpr(\"CAST(uuid AS STRING) AS key\",\n \"to_json(struct(startOfWindow, endOfWindow, AVGTemperature)) AS value\") \\\n .writeStream \\\n .outputMode('update') \\\n .format(\"kafka\") \\\n .option(\"kafka.bootstrap.servers\", \"localhost:9092\", ) \\\n .option(\"topic\", \"avgtemperature\") \\\n .option('checkpointLocation', \"file:///ssd/hduser/avgtemperature/chkpt\") \\\n .queryName(\"avgtemperature\") \\\n .start()\n\n\nprint(result)\nprint(\"Chiudo:\")\nprint(result.status)\nprint(result.recentProgress)\nprint(result.lastProgress)\n\nresult.awaitTermination()\n","sub_path":"spark2kafka.py","file_name":"spark2kafka.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"218361444","text":"import matplotlib.pyplot as plt \n\ndef totient(n): \n phi = n\n p = 2 \n while(p * p <= n):\n while (n % p == 0): \n n = n // p\n phi -= phi // p\n p += 1\n if (n > 1): \n phi -= phi // n\n return phi\n\nx = []\ny = []\nfor i in range(1,1000):\n x.append(i)\n y.append(totient(i))\n\nplt.scatter(x, y, c =\"blue\") \nplt.show() ","sub_path":"eulerTotient.py","file_name":"eulerTotient.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84291136","text":"import torch\nimport torch.nn as nn\nfrom time import time\nimport numpy as np\n\n\nclass DoubleConvBN(nn.Module):\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size, dropout):\n super().__init__()\n\n self.conv1 = nn.Conv2d(\n in_channels, out_channels, kernel_size=kernel_size, padding=int(kernel_size / 2)\n )\n self.bn1 = nn.BatchNorm2d(out_channels)\n\n self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=1, padding=0)\n self.bn2 = nn.BatchNorm2d(out_channels)\n\n self.conv3 = nn.Conv2d(\n out_channels, out_channels, kernel_size=kernel_size, padding=int(kernel_size / 2)\n )\n self.bn3 = nn.BatchNorm2d(out_channels)\n self.drop1 = nn.Dropout(dropout)\n self.drop2 = nn.Dropout(dropout)\n self.drop3 = nn.Dropout(dropout)\n\n def forward(self, x):\n\n x = self.bn1(torch.relu(self.conv1(x)))\n x = x = self.drop1(x)\n identity_full = x\n\n x = self.bn2(torch.relu(self.conv2(x)))\n x = self.drop2(x)\n x += identity_full\n identity_1 = x\n\n x = self.bn3(torch.relu(self.conv3(x)))\n x = x = self.drop3(x)\n x += identity_full\n x += identity_1\n\n return x\n\n\nclass DoubleConv(nn.Module):\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size, dropout):\n super().__init__()\n\n self.conv1 = nn.Conv2d(\n in_channels, out_channels, kernel_size=kernel_size, padding=int(kernel_size / 2)\n )\n\n self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=1, padding=0)\n\n self.conv3 = nn.Conv2d(\n out_channels, out_channels, kernel_size=kernel_size, padding=int(kernel_size / 2)\n )\n self.drop1 = nn.Dropout(dropout)\n self.drop2 = nn.Dropout(dropout)\n self.drop3 = nn.Dropout(dropout)\n\n def forward(self, x):\n\n x = self.drop1(torch.relu(self.conv1(x)))\n identity_full = x\n\n x = self.drop2(torch.relu(self.conv2(x)))\n x += identity_full\n identity_1 = x\n\n x = self.drop3(torch.relu(self.conv3(x)))\n x += identity_full\n x += identity_1\n\n return x\n\n\nclass Down(nn.Module):\n \"\"\"Downscaling with maxpool then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size, dropout):\n super().__init__()\n self.maxpool_conv = nn.Sequential(\n nn.MaxPool2d(2), DoubleConvBN(in_channels, out_channels, kernel_size, dropout)\n )\n\n def forward(self, x):\n return self.maxpool_conv(x)\n\n\nclass Up(nn.Module):\n \"\"\"Upscaling then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size, dropout, bilinear=False):\n super().__init__()\n\n # if bilinear, use the normal convolutions to reduce the number of channels\n if bilinear:\n self.up = nn.Upsample(scale_factor=2)\n self.conv = DoubleConv(in_channels, out_channels, kernel_size, dropout) # , in_channels // 2)\n else:\n self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)\n self.conv = DoubleConv(in_channels, out_channels, kernel_size, dropout)\n\n def forward(self, x1, x2):\n x1 = self.up(x1)\n # input is CHW\n diffY = x2.size()[2] - x1.size()[2]\n diffX = x2.size()[3] - x1.size()[3]\n\n x1 = torch.nn.functional.pad(x1, [diffX // 2, diffX - diffX // 2, diffY // 2, diffY - diffY // 2])\n # if you have padding issues, see\n # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a\n # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd\n x = torch.cat([x2, x1], dim=1)\n return self.conv(x)\n\n\nclass OutConv(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(OutConv, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n\n def forward(self, x):\n return self.conv(x)\n\n\nclass mySequential(nn.Sequential):\n def forward(self, *input):\n for module in self._modules.values():\n input = module(*input)\n return input\n\n\nclass Encoder_rotation(nn.Module):\n def __init__(self, hparams, bilinear=False):\n super(Encoder_rotation, self).__init__()\n\n self.hparams = hparams\n self.n_channels = self.hparams['in_channels']\n self.emb_dim = self.hparams['emb_dim']\n self.bilinear = bilinear\n\n self.factor = 2 if bilinear else 1\n\n self.inc = DoubleConv(\n self.n_channels,\n self.hparams['n_filters_input'],\n self.hparams['kernel_size'],\n self.hparams['dropout_rate'],\n )\n self.down1 = Down(\n self.hparams['n_filters_input'],\n self.hparams['n_filters_input'] * 2,\n self.hparams['kernel_size'],\n self.hparams['dropout_rate'],\n )\n self.down2 = Down(\n self.hparams['n_filters_input'] * 2,\n self.hparams['n_filters_input'] * 4,\n self.hparams['kernel_size'],\n self.hparams['dropout_rate'],\n )\n self.down3 = Down(\n self.hparams['n_filters_input'] * 4,\n self.hparams['n_filters_input'] * 8,\n self.hparams['kernel_size'],\n self.hparams['dropout_rate'],\n )\n\n self.down4 = Down(\n self.hparams['n_filters_input'] * 8,\n self.hparams['n_filters_input'] * 16 // self.factor,\n self.hparams['kernel_size'],\n self.hparams['dropout_rate'],\n )\n self.down5 = Down(\n self.hparams['n_filters_input'] * 16,\n self.hparams['n_filters_input'] * 32 // self.factor,\n self.hparams['kernel_size'],\n self.hparams['dropout_rate'],\n )\n\n self.fc1 = nn.Linear(\n self.hparams['n_filters_input'] * (2 ** 5), self.hparams['n_filters_input'] * (2 ** 5)\n )\n self.fc2 = nn.Linear(self.hparams['n_filters_input'] * (2 ** 5), self.hparams['n_classes'])\n # self.fc3 = nn.Linear(self.hparams['n_filters_input'] * (2 ** 5), 128)#self.emb_dim)\n\n def forward(self, x):\n _, _, _, _, _, x = self.encoder(x)\n\n x = torch.mean(x, dim=2)\n x = torch.mean(x, dim=2)\n\n x = torch.relu(self.fc1(x))\n x = torch.softmax(self.fc2(x), dim=1)\n # logits = self.fc3(x)\n return x\n\n def encoder(self, x):\n x1 = self.inc(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x4 = self.down3(x3)\n x5 = self.down4(x4)\n x6 = self.down5(x5)\n\n return x1, x2, x3, x4, x5, x6\n","sub_path":"models/segmentation/encoder_rotation/structure.py","file_name":"structure.py","file_ext":"py","file_size_in_byte":6813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"406294860","text":"\"\"\"\nClasses and functions of general use\n\"\"\"\n\nimport os\nimport sys\nimport math\nimport numpy as np\nfrom .core import *\n\n__all__ = (\n 'Vec2D', 'add_extension', 'sub_extension',\n 'script_args', 'rgb'\n)\n\nclass Vec2D:\n \"\"\"Simple 2D vector class.\"\"\"\n\n def __init__(self, x=0., y=0.):\n self.x = x\n self.y = y\n\n def length(self):\n \"\"\"Returns the Euclidean length\"\"\"\n return math.sqrt(self.x**2+self.y**2)\n\n def unit(self):\n \"\"\"Returns a unit vector version of the vector\"\"\"\n dist = self.length()\n if dist > 0:\n x = self.x / dist\n y = self.y / dist\n return Vec2D(x,y)\n else:\n return ValueError('cannot normalise a zero vector')\n\n def __iadd__(self, vec):\n \"\"\"+=: in place addition\"\"\"\n self.x += vec.x\n self.y += vec.y\n return self\n\n def __add__(self, vec):\n \"\"\"+: addition\"\"\"\n return Vec2D(self.x+vec.x, self.y+vec.y)\n\n def __isub__(self, vec):\n \"\"\"-=: in place subtraction\"\"\"\n self.x -= vec.x\n self.y -= vec.y\n return self\n\n def __sub__(self, vec):\n \"\"\"-: subtraction\"\"\"\n return Vec2D(self.x-vec.x, self.y-vec.y)\n\n def __imul__(self, const):\n \"\"\"*=: in place multiplication by a constant\"\"\"\n self.x *= const\n self.y *= const\n return self\n\n def __mul__(self, const):\n \"\"\"*: post multiplication by a constant\"\"\"\n return Vec2D(const*self.x, const*self.y)\n\n def __rmul__(self, const):\n \"\"\"*: pre multiplication by a constant\"\"\"\n return Vec2D(const*self.x, const*self.y)\n\n def __itruediv__(self, const):\n \"\"\"Divides by a constant\"\"\"\n self.x /= const\n self.y /= const\n\n def __repr__(self):\n return 'Vec2D(x={:f}, y={:f})'.format(self.x, self.y)\n\ndef dot(v1, v2):\n \"\"\"Returns the scalar or 'dot' product of two vectors\"\"\"\n return v1.x*v2.x + v1.y*v2.y\n\ndef add_extension(fname, ext):\n \"\"\"Add extension ext to a file name if it is not already there, and returns\n the revised name\n\n \"\"\"\n if len(ext) and not fname.endswith(ext):\n return '{}{}'.format(fname, ext)\n else:\n return fname\n\ndef sub_extension(fname, ext):\n \"\"\"Subtracts extension ext from a file name if it is present, and returns\n the revised name\n\n \"\"\"\n if fname.endswith(ext):\n return fname[:-len(ext)]\n else:\n return fname\n\ndef rgb(cname):\n \"\"\"Returns the RGB tuple associated with colour name 'cname', following\n the colour definitions used by 'reduce'.\n\n Returns a ValueError if cname is not recognised.\n \"\"\"\n if cname not in CNAMS:\n raise ValueError('colour = {:s} not recognised'.format(cname))\n else:\n return CIS[CNAMS[cnam]]\n\n\ndef script_args(args):\n \"\"\"\n This is a small helper method that is used at the start of most\n of the HiPERCAM entry point scripts such as 'reduce' and 'grab'.\n\n If 'args' is None on entry, it is replaced by 'sys.argv'. It is then\n assumed that the first argument is the command name or else None. The\n command name argument is removed from args, and if not None, converted to just the\n file part of the path. It is then returned along with the remaining list\n of arguments in a two element tuple, i.e. (commands, args).\n \"\"\"\n if args is None:\n args = sys.argv.copy()\n\n command = args.pop(0)\n if command is not None:\n # just keep filename part, not any path\n command = os.path.split(command)[1]\n\n return (command, args)\n\ndef print_stats(ccd, cnam, x, y, hsbox, warn=True):\n \"\"\"\n Prints a few statistics of pixels around an x,y position\n in a CCD. It returns a tuple containing a label and a reference\n to the Window containing the x, y position, or None, None\n if the x,y position is outside any window. This is used by 'hplot'\n and 'setdefect'.\n\n Arguments::\n\n ccd : :class:`hipercam.CCD`\n the CCD of interest\n\n cnam : string\n the name of the CCD\n\n x, y : float, float\n the X,Y position. Lower-left unbinned pixel is centred on 1,1\n\n hsbox : int\n half-width in binned pixels of the box\n\n warn : bool\n prints out a message if no enclosing Window found. If you want to\n supply your own message, you might want to set this to False.\n\n Returns:: (wnam, wind)\n\n wnam : string\n Window label, None if not found\n\n wind : :class:`hipercam.Window`\n Window enclosing x,y, none if not found.\n \"\"\"\n\n wnam = ccd.inside(x,y,0)\n if wnam is not None:\n wind = ccd[wnam]\n ix = int(round(wind.x_pixel(x)))\n iy = int(round(wind.y_pixel(y)))\n ix1 = max(0, ix - hsbox)\n ix2 = min(wind.nx, ix + hsbox + 1)\n iy1 = max(0, iy - hsbox)\n iy2 = min(wind.ny, iy + hsbox + 1)\n\n print('\\nClicked on x,y = {:.2f},{:.2f} in CCD {:s}, window {:s}'.format(\n x,y,cnam,wnam)\n )\n\n print(' Stats box in window pixels, X,Y = [{:d}:{:d},{:d}:{:d}] ({:d}x{:d}), central pixel = [{:d},{:d}], value = {:.2f}'.format(\n ix1,ix2,iy1,iy2,ix2-ix1,iy2-iy1,ix,iy,wind.data[iy,ix])\n )\n\n box = wind.data[iy1:iy2,ix1:ix2]\n print(\n ' Mean = {:.4g}, RMS = {:.4g}, min = {:.4g}, max = {:.4g}, median = {:.4g}'.format(\n box.mean(),box.std(),box.min(),box.max(),np.median(box)\n )\n )\n\n else:\n wind = None\n if warn:\n print('\\n *** selected position ({:.1f},{:.1f}) not in any window'.format(x,y))\n\n return (wnam, wind)\n","sub_path":"hipercam/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"460628366","text":"\"\"\"\nBackPACK Extensions\n\"\"\"\n\nfrom .curvmatprod import GGNMP, HMP, PCHMP\nfrom .firstorder import BatchGrad, BatchL2Grad, SumGradSquared, Variance, Fisher, FisherBlock, FisherBlockEff\nfrom .secondorder import (\n TRIAL,\n HBP,\n KFAC,\n KFLR,\n KFRA,\n DiagGGN,\n DiagGGNExact,\n DiagGGNMC,\n DiagHessian,\n MNGD,\n)\n\n__all__ = [\n \"MNGD\",\n \"Fisher\",\n \"FisherBlock\",\n \"FisherBlockEff\",\n \"TRIAL\",\n \"PCHMP\",\n \"GGNMP\",\n \"HMP\",\n \"BatchL2Grad\",\n \"BatchGrad\",\n \"SumGradSquared\",\n \"Variance\",\n \"KFAC\",\n \"KFLR\",\n \"KFRA\",\n \"HBP\",\n \"DiagGGNExact\",\n \"DiagGGNMC\",\n \"DiagGGN\",\n \"DiagHessian\",\n]\n","sub_path":"backpack/extensions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"102048488","text":"import sys\nimport wave\nimport struct\nimport alsaaudio\nimport numpy as np\n\ndef sine(freq=1000, samples=44100):\n periods = freq * samples / 44100\n return np.sin(np.linspace(0, np.pi * 2 * periods,\n samples, endpoint=False))\n\ndef quantize(real, scale=32768):\n UPPER_BOUND = scale - 1\n LOWER_BOUND = -scale\n\n num = int(round(real * scale))\n if num > UPPER_BOUND:\n num = UPPER_BOUND\n elif num < LOWER_BOUND:\n num = LOWER_BOUND\n return num\n\ndef pack_int16le(num):\n return struct.pack('h', num)\n\ndef sine_pcm(freq=1000, samples=44100):\n return [quantize(i) for i in sine(freq, samples)]\n\ndef sine_pcm_data(freq=1000, samples=44100):\n pcm_samples = sine_pcm(freq, samples)\n return ''.join([pack_int16le(i) for i in pcm_samples])\n\n########################################\n\nif len(sys.argv) >= 2:\n F = int(sys.argv[1])\nelse:\n F = 1000 # 1000 Hz\n\n# generate audio data\ndata = sine_pcm_data(F, 4410)\n\n# prepare PCM device\ndevice = alsaaudio.PCM(card='default')\ndevice.setrate(44100)\ndevice.setchannels(1)\ndevice.setformat(alsaaudio.PCM_FORMAT_S16_LE)\ndevice.setperiodsize(44100)\n\n# write audio data\ntry:\n while True:\n device.write(data)\nexcept KeyboardInterrupt:\n exit()\n\n#device.close()\n","sub_path":"src/playsinewave.py","file_name":"playsinewave.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"504174373","text":"#\n# COPYRIGHTS_HEADER\n# This software is distributed under the terms of the MIT License.\n#\n\"\"\"\nWe use the following pattern when building Python CLI packages to maximize\nplatform compatibility, test coverage, and unified documentation:\n\n1. **__main__.py** – Should be only the following three lines::\n\n import sys\n\n from .cli import main\n\n sys.exit(main())\n\n2. **cli.py** – This must contain the following two methods::\n\n def main() -> int:\n \\\"\"\"\n The main entrypoint for the CLI.\n \\\"\"\"\n\n def _make_parser() -> argparse.ArgumentParser\n \\\"\"\"\n Parser generation shared between the program and our document\n generator using sphinx-argparse.\n \\\"\"\"\n\n\"\"\"\n\nimport asyncio\nimport argparse\nimport logging\nimport pathlib\nimport sys\nimport textwrap\nimport typing\n\n\nasync def run(args: argparse.Namespace) -> int:\n \"\"\"\n Runs a silly program to prove that this template produces a valid\n Python package.\n\n This template also setups up `Sybil `_\n doctests. Sybil allows for full programs to be written in comments that are executed as tests.\n Additionally, the ``invisible-code-block`` directive in Sphinx allows setting up\n a full test scenario while keeping the documented example concise.\n Example:\n\n .. invisible-code-block: python\n import argparse\n import asyncio\n from pythontemplate.cli import run\n\n args = argparse.Namespace()\n loop = asyncio.get_event_loop()\n\n .. code-block:: python\n\n assert 0 == loop.run_until_complete(run(args))\n\n :param args: The parsed arguments provided to the program.\n :type args: argparse.Namespace\n :return: 0 (e.g. posix style \"0==success\").\n \"\"\"\n\n import pythontemplate\n\n logger = logging.getLogger(__name__)\n\n logger.info('Running %s using sys.prefix: %s',\n pathlib.Path(__file__).name, sys.prefix)\n\n logger.info(pythontemplate.Example().hello())\n\n return 0\n\n\nclass _LazyVersionAction(argparse._VersionAction):\n \"\"\"\n Changes argparse._VersionAction so we only load pythontemplate.version\n if the ``--version action`` is requested.\n \"\"\"\n\n def __call__(self,\n parser: argparse.ArgumentParser,\n namespace: argparse.Namespace,\n values: typing.Any,\n option_string: typing.Optional[str] = None) -> None:\n from pythontemplate.version import __version__\n parser._print_message(__version__, sys.stdout)\n parser.exit()\n\n\ndef _make_parser() -> argparse.ArgumentParser:\n \"\"\"\n Defines the command-line interface. Provided as a separate factory method to\n support `sphinx-argparse `_\n documentation.\n\n We mark this as private since we don't want it used by consumers of this package.\n Even so, it is a stable API since the documentation configuration references it.\n \"\"\"\n\n epilog = '''\n\n **Example Usage**::\n\n # By using a bit of restructured text in the epilog we got a nice\n # command-line example and nicely formatted sphinx-argparse\n # document.\n\n pytem -vv --version\n\n '''\n\n description = textwrap.dedent('''\n\n CLI created from `python-template `_\n\n By using :func:`textwrap.dedent` you can write long comments that are well-formatted\n in source but that also work when used in html documentation or when emitted in a\n terminal.\n\n ''').strip()\n\n parser = argparse.ArgumentParser(\n description=description,\n epilog=epilog,\n formatter_class=argparse.RawTextHelpFormatter)\n\n parser.add_argument('--raw', '-r', default='foo',\n help=textwrap.dedent('''\n\n We use :class:`argparse.RawTextHelpFormatter` to allow us to control the format of\n the console messages.\n\n Remember that you can also use format specifiers like %(prog)s and %(default)s in\n these messages.\n\n ''').strip())\n\n parser.add_argument('--verbose', '-v', action='count',\n help='verbosity level (-v, -vv)')\n\n parser.add_argument('--version', action=_LazyVersionAction)\n\n return parser\n\n\ndef main() -> int:\n \"\"\"\n Main entry point for the CLI.\n \"\"\"\n\n #\n # Parse the command-line arguments.\n #\n args = _make_parser().parse_args()\n\n #\n # Setup Python logging.\n #\n fmt = '%(name)s: %(message)s'\n level = {0: logging.WARNING, 1: logging.INFO,\n 2: logging.DEBUG}.get(args.verbose or 0, logging.DEBUG)\n logging.basicConfig(stream=sys.stderr, level=level, format=fmt)\n\n return asyncio.get_event_loop().run_until_complete(run(args))\n","sub_path":"src/pythontemplate/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"624306824","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport numpy as np\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nimport matplotlib.pyplot as plt\nfrom resnet import ResNet, BasicBlock\n\nprint(\"PyTorch Version: \", torch.__version__)\nprint(\"Torchvision Version: \", torchvision.__version__)\n\nclass NeuralNetwork(nn.Module):\n def __init__(self):\n super(NeuralNetwork, self).__init__()\n self.flatten = nn.Flatten()\n self.linear_relu_stack = nn.Sequential(\n nn.Linear(28*28, 512),\n nn.ReLU(),\n nn.Linear(512,512),\n nn.ReLU(),\n nn.Linear(512, 10),\n nn.ReLU()\n )\n\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n print(\"Using {} device\".format(self.device))\n self.to(self.device)\n\n self.loss_fn = nn.CrossEntropyLoss()\n self.optimizer = torch.optim.SGD(self.parameters(), lr = 1e-3)\n def forward(self, x):\n x = self.flatten(x)\n logits = self.linear_relu_stack(x)\n return logits\n def trainModel(self, dataloader: DataLoader):\n size = len(dataloader.dataset)\n for batch, (X, y) in enumerate(dataloader):\n X, y = X.to(self.device), y.to(self.device)\n\n pred = self(X)\n loss = self.loss_fn(pred, y)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n if batch % 100 == 0:\n loss, current = loss.item(), batch * len(X)\n print(f\"loss:{loss:>7f} [{current:>5d}/{size:>5d}]\")\n def testModel(self, dataloader: DataLoader):\n size = len(dataloader.dataset)\n self.eval()\n test_loss, correct = 0,0\n with torch.no_grad():\n for X, y in dataloader:\n X, y = X.to(self.device), y.to(self.device)\n pred = self(X)\n test_loss += self.loss_fn(pred, y).item()\n correct += (pred.argmax(1) == y).type(torch.float).sum().item()\n test_loss /= size\n correct /= size\n print(f\"Test Error: \\n Accuracy: {(100*correct):0.1f} %, Avg loss: {test_loss:>8f}\\n\")\n\n#model = torchvision.models.resnet50()\n# model = ResNet50()\n# print(model)\n\n# 参数设置\nif __name__ == \"__main__\":\n batch_size_train = 64\n batch_size_test = 1000\n learning_rate = 0.01\n momentum = 0.5\n log_interval = 10\n random_seed = 1\n torch.manual_seed(random_seed)\n training_data = datasets.FashionMNIST(\n root = \"../data/\",\n train=True,\n download=True,\n transform=torchvision.transforms.ToTensor(),\n )\n\n test_data = datasets.FashionMNIST(\n root=\"../data/\",\n train=False,\n download=True,\n transform=torchvision.transforms.ToTensor(),\n )\n train_dataloader = DataLoader(training_data, batch_size=batch_size_train)\n test_dataloader = DataLoader(test_data, batch_size=batch_size_test)\n epochs = 5\n model = NeuralNetwork()\n for t in range(epochs):\n model.trainModel(train_dataloader)\n model.testModel(test_dataloader)\n print(\"Done!\")\n torch.save(model.state_dict(), \"../model/model.pth\")\n print(\"Saved Neural Network Model State to model.pth\")\n\n resNetModel = ResNet(BasicBlock, [2,2,2,2])\n for t in range(epochs):\n resNetModel.trainModel(train_dataloader)\n resNetModel.testModel(test_dataloader)\n \n torch.save(resNetModel.state_dict(), \"../model/res.pth\")\n print(\"Saved ResNet Model State to res.pth\")\n\n","sub_path":"src/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259371177","text":"\n# coding: utf-8\n\n# In[5]:\n\n\nimport pandas\n# Read data\ndata_values = pandas.read_csv(\"../../../Datasets/Pump_it_Up_Data_Mining_the_Water_Table_-_Training_set_values.csv\")\n\n\n# In[9]:\n\n\n# Find missing gps_height values from longitute and latitude column\n#use command --> \"pip install --user geocoder\" to install Geocoder package\nfrom time import sleep\nimport geocoder\n\n#Store missing gps heights in a dict {id:gps_height}\ngpsHeights = {}\n\nfor i in data_values.id:\n if (data_values.loc[data_values.id == i, \"gps_height\"] == 0).bool():\n latitude = data_values.loc[data_values.id == i, \"latitude\"]\n longitude = data_values.loc[data_values.id == i, \"longitude\"]\n skipped = 0\n while True:\n sleep(1)\n #GPS access key \n geoAccess = geocoder.elevation([latitude, longitude],key=\"AIzaSyDk3VvbBmuUH5J4vGntZAinU6rynEEKGO4\")\n if geoAccess.ok:\n gpsHeights[i] = int(geoAccess.meters)\n break\n else:\n skipped += 1\n #Writing the missing gps heights on to a newGpsheights.csv file\n pandas.DataFrame.from_dict(gpsHeights, orient=\"index\").reset_index().to_csv(\"../../../Datasets/heights.csv\", header=[\"id\", \"gps_height\"], index=False)\n\n","sub_path":"Code/Final/Pre-process/PumpItUpMissingHeights.py","file_name":"PumpItUpMissingHeights.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"278377178","text":"#!/usr/bin/python\n# accept a matrix (image of size n by n pixel ) n rotate it clock wise in 90 degree\n\ndef matrix(no,a):\t\t\t\t\t\t\t\n\tfor i in range(0,no):\t\t\n\t\ta.append([])\n\t\tfor j in range(0,no):\n\t\t\tval = eval(input(\"val : \"))\n\t\t\ta[i].append(val)\n\tprint (a)\n\ndef rorate(no,a,b):\n\tk = 0\n\tfor j in range(0,no):\n\t\tb.append([])\n\t\tfor i in range(no-1,-1,-1):\n\t\t\tb[j].append(a[i][k])\n\t\tk+=1\n\tprint (b)\n\nif __name__ == '__main__':\n\tno = eval(input(\"number : \"))\t\t\t# code start accepting the no. of rows and column \n\ta = []\t\t\t\t\t\t\t\t\t # accepting arrays\n\tb = []\n\tmatrix(no,a)\t\t\t\t\t\t \t# calling functions (accepting matrix)\n\trorate(no,a,b)\t\t\t\t\t\t\t # (rotating matrix ) \n","sub_path":"Programs/Assignmets/RotateMatrix90.py","file_name":"RotateMatrix90.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"488273241","text":"import os\nimport shutil\nimport torch\nimport unittest\nimport transformers\nfrom neural_compressor import quantization, PostTrainingQuantConfig\n\nfrom neural_compressor.adaptor.torch_utils.model_wrapper import WeightOnlyLinear\n\n\nclass Model(torch.nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.fc1 = torch.nn.Linear(30, 40)\n self.fc2 = torch.nn.Linear(40, 30)\n self.fc3 = torch.nn.Linear(30, 5)\n\n def forward(self, x):\n out = self.fc1(x)\n out = self.fc2(out)\n out = self.fc3(out)\n return out\n\n\ndef eval_func(model):\n # switch to evaluate mode\n model.eval()\n with torch.no_grad():\n input = torch.randn(3,30)\n # compute output\n output = model(input)\n return 0.0\n\nclass SimpleDataLoader():\n def __init__(self):\n self.batch_size = 1\n\n def __iter__(self):\n for i in range(2):\n yield torch.randn([1, 30])\n\n\nclass LLMDataLoader():\n def __init__(self):\n self.batch_size = 1\n\n def __iter__(self):\n for i in range(2):\n yield torch.ones([1, 10], dtype=torch.long)\n\n\nclass TestPytorchWeightOnlyAdaptor(unittest.TestCase):\n approach = 'weight_only'\n\n @classmethod\n def setUpClass(self):\n self.dataloader = SimpleDataLoader()\n self.gptj = transformers.AutoModelForCausalLM.from_pretrained(\n 'hf-internal-testing/tiny-random-GPTJForCausalLM',\n torchscript=True,\n )\n self.llm_dataloader = LLMDataLoader()\n self.lm_input = torch.ones([1, 10], dtype=torch.long)\n\n @classmethod\n def tearDownClass(self):\n shutil.rmtree(\"./saved\", ignore_errors=True)\n shutil.rmtree(\"runs\", ignore_errors=True)\n\n def test_RTN_quant(self):\n input = torch.randn(3,30)\n model = Model()\n out1 = model(input)\n\n conf = PostTrainingQuantConfig(\n approach='weight_only',\n )\n q_model = quantization.fit(model, conf)\n out2 = q_model(input)\n self.assertTrue(torch.all(torch.isclose(out1, out2, atol=5e-1)))\n self.assertFalse(torch.all(out1 == out2))\n compressed_model = q_model.export_compressed_model()\n out3 = compressed_model(input)\n self.assertTrue(torch.all(out3==out2))\n\n model = Model()\n out1 = model(input)\n\n conf = PostTrainingQuantConfig(\n approach='weight_only',\n recipes={\n # By default, sym_full_range is False and 4 bit sym will only use range [-7,7].\n 'rtn_args': {'sym_full_range': True}\n }\n )\n q_model = quantization.fit(model, conf)\n out2 = q_model(input)\n self.assertTrue(torch.all(torch.isclose(out1, out2, atol=5e-1)))\n self.assertFalse(torch.all(out1 == out2))\n compressed_model = q_model.export_compressed_model(sym_full_range=True)\n out3 = compressed_model(input)\n self.assertTrue(torch.all(out3==out2))\n\n model = Model()\n out1 = model(input)\n conf = PostTrainingQuantConfig(\n approach='weight_only',\n op_type_dict={\n '.*':{ \t# re.match\n \"weight\": {\n 'bits': 8, # 1-8 bits \n 'group_size': -1, # -1 (per-channel)\n 'scheme': 'sym', \n 'algorithm': 'RTN', \n },\n },\n },\n )\n q_model = quantization.fit(model, conf, eval_func=eval_func)\n out2 = q_model(input)\n self.assertTrue(torch.all(torch.isclose(out1, out2, atol=5e-1)))\n self.assertFalse(torch.all(out1 == out2))\n\n model = Model()\n out1 = model(input)\n conf = PostTrainingQuantConfig(\n approach='weight_only',\n op_type_dict={\n '.*':{ \t# re.match\n \"weight\": {\n 'bits': 4, # 1-8 bits \n 'group_size': 32, # 1 - 1024 or higher\n 'scheme': 'asym', \n 'algorithm': 'RTN', \n },\n },\n },\n )\n q_model = quantization.fit(model, conf, eval_func=eval_func)\n out2 = q_model(input)\n self.assertTrue(torch.all(torch.isclose(out1, out2, atol=5e-1)))\n self.assertFalse(torch.all(out1 == out2))\n\n model = Model()\n out1 = model(input)\n conf = PostTrainingQuantConfig(\n approach='weight_only',\n op_name_dict={\n 'fc1':{ \t# re.match\n \"weight\": {\n 'bits': 4, # 1-8 bits \n 'group_size': 32, # 1 - 1024 or higher\n 'scheme': 'sym', \n 'algorithm': 'RTN', \n },\n },\n 'fc2':{ \t# re.match\n \"weight\": {\n 'bits': 3, # 1-8 bits \n 'group_size': 16, # 1 - 1024 or higher\n 'scheme': 'asym', \n 'algorithm': 'RTN', \n },\n },\n 'fc3':{ \t# re.match\n \"weight\": {\n 'dtype': 'fp32',\n },\n },\n },\n )\n q_model = quantization.fit(model, conf, eval_func=eval_func)\n out2 = q_model(input)\n self.assertTrue(torch.all(torch.isclose(out1, out2, atol=5e-1)))\n self.assertFalse(torch.all(out1 == out2))\n q_model.save('saved')\n from neural_compressor.utils.pytorch import load\n new_model = load('saved', model)\n out1 = new_model(input)\n self.assertTrue(torch.all(out1 == out2))\n\n\n model_size1 = os.path.getsize('saved/best_model.pt')/1024\n print(\"FP32 Model size:{:.3f}M\".format(model_size1))\n from neural_compressor.model import Model as INCModel\n inc_model = INCModel(new_model)\n inc_model.export_compressed_model(qweight_config_path = 'saved/qconfig.json')\n torch.save(inc_model.state_dict(), 'saved/tmp.pt')\n model_size2 = os.path.getsize('saved/tmp.pt')/1024\n print(\"WeightOnlyLinear Model size:{:.3f}M\".format(model_size2))\n self.assertTrue(isinstance(inc_model.model.fc1, WeightOnlyLinear))\n self.assertTrue(model_size1 / model_size2 > 2)\n\n def test_AWQ_quant(self):\n conf = PostTrainingQuantConfig(\n approach='weight_only',\n op_type_dict={\n '.*':{ \t# re.match\n \"weight\": {\n 'bits': 4, # 1-8 bits \n 'group_size': 32, # -1 (per-channel)\n 'scheme': 'asym', \n 'algorithm': 'AWQ', \n },\n },\n },\n op_name_dict={\n '.*lm_head':{ \t# re.match\n \"weight\": {\n 'dtype': 'fp32'\n },\n },\n },\n recipes={\n 'awq_args':{'auto_scale': True, 'mse_range': True, 'n_blocks': 2},\n },\n )\n q_model = quantization.fit(\n self.gptj, \n conf, \n calib_dataloader=self.llm_dataloader,\n )\n input = torch.ones([1, 10], dtype=torch.long)\n out1 = q_model(input)\n q_model.export_compressed_model()\n out2 = q_model(input)\n # no idea about the gap at 1e-08, use allclose instead of out1==out2\n self.assertTrue(torch.allclose(out1[0], out2[0], atol=1e-05))\n self.assertTrue(isinstance(q_model.model.transformer.h[0].mlp.fc_in, WeightOnlyLinear))\n self.assertTrue(isinstance(q_model.model.lm_head, torch.nn.Linear))\n\n def test_GPTQ_quant(self):\n class gptq_inc_loader(object):\n def __init__(self, nsamples=32):\n self.batch_size = 1\n self.nsamples = nsamples\n \n def __len__(self):\n return self.nsamples // self.batch_size\n\n def __iter__(self):\n for i in range(self.nsamples):\n yield (torch.ones([1, 512], dtype=torch.long), torch.ones([1, 512], dtype=torch.long))\n\n \n conf = PostTrainingQuantConfig(\n approach='weight_only',\n op_type_dict={\n '.*':{ \t# re.match\n \"weight\": {\n 'bits': 4, # 1-8 bits \n 'group_size': 128, # -1 (per-channel)\n 'scheme': 'sym', \n 'algorithm': 'GPTQ', \n },\n },\n },\n op_name_dict={\n '.*lm_head':{ \t# re.match\n \"weight\": {\n 'dtype': 'fp32'\n },\n },\n },\n recipes={\n 'gptq_args':{'percdamp': 0.01},\n },\n )\n dataloader = gptq_inc_loader()\n # import pdb;pdb.set_trace()\n q_model = quantization.fit(self.gptj, conf, calib_dataloader=dataloader,)\n\n def test_TEQ_quant(self):\n class teq_inc_loader(object):\n def __init__(self, nsamples=32):\n self.batch_size = 1\n self.nsamples = nsamples\n\n def __len__(self):\n return self.nsamples // self.batch_size\n\n def __iter__(self):\n for i in range(self.nsamples):\n yield (torch.ones([1, 512], dtype=torch.long), torch.ones([1, 512], dtype=torch.long))\n\n conf = PostTrainingQuantConfig(\n approach='weight_only',\n op_type_dict={\n '.*':{ # re.match\n \"weight\": {\n 'bits': 4, # 1-8 bits\n 'group_size': 32, # -1 (per-channel)\n 'scheme': 'sym',\n 'algorithm': 'TEQ',\n },\n },\n },\n op_name_dict={\n '.*lm_head':{ # re.match\n \"weight\": {\n 'dtype': 'fp32'\n },\n },\n },\n recipes={\n 'teq_args':{\"folding\": True},\n },\n )\n\n dataloader = teq_inc_loader()\n\n q_model = quantization.fit(self.gptj, conf, calib_dataloader=dataloader,)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/adaptor/pytorch_adaptor/test_weight_only_adaptor.py","file_name":"test_weight_only_adaptor.py","file_ext":"py","file_size_in_byte":10530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"576146779","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom flask import g, redirect, url_for, render_template, flash\r\nfrom flask_login import logout_user, current_user, login_required\r\nfrom forms import Register_form, Login_form, Edit_team_form, Survey_form\r\nfrom app import app, db, login_manager\r\nfrom models import User, Team, Answer, Cadence\r\nfrom sqlalchemy.sql import func\r\nfrom datetime import datetime\r\n\r\n\r\n@app.route('/')\r\n@login_required\r\ndef index():\r\n teams = Team.query.join(Cadence, Team.current_cadence_id == Cadence.id) \\\r\n .outerjoin(Answer, Team.current_cadence_id == Answer.cadence_id) \\\r\n .filter(Team.user_id == g.user.id) \\\r\n .add_columns(Cadence.start, func.count(Answer.cadence_id)) \\\r\n .group_by(Answer.cadence_id) \\\r\n .order_by(Team.id.desc()).all()\r\n return render_template('index.html', teams=teams)\r\n\r\n\r\n@app.route('/team/create', methods=['GET', 'POST'])\r\n@login_required\r\ndef create_team():\r\n form = Edit_team_form()\r\n if form.validate_on_submit():\r\n team = Team(form.name.data, g.user.id, form.answers_visible.data)\r\n db.session.add(team)\r\n db.session.commit()\r\n cadence = Cadence(team.id, datetime.now())\r\n db.session.add(cadence)\r\n db.session.commit()\r\n team.current_cadence_id = cadence.id\r\n db.session.commit()\r\n flash('Team successfully created', 'success')\r\n return redirect(url_for('index'))\r\n return render_template('create_team.html', form=form)\r\n\r\n\r\n@app.route('/team//edit', methods=['GET', 'POST'])\r\n@login_required\r\ndef edit_team(team_id):\r\n # check if team_id is existing and team belongs to the current user..\r\n team = Team.query.filter_by(id=team_id).filter_by(user_id=g.user.id).first_or_404()\r\n form = Edit_team_form()\r\n if form.validate_on_submit():\r\n team.name = form.name.data\r\n team.answers_visible = form.answers_visible.data\r\n db.session.commit()\r\n flash('Team successfully updated', 'success')\r\n return redirect(url_for('index'))\r\n form.name.data = team.name\r\n form.answers_visible.data = team.answers_visible\r\n return render_template('edit_team.html', form=form)\r\n\r\n\r\n@app.route('/team//answers')\r\n@login_required\r\ndef show_team_answers(team_id):\r\n # check if team_id is existing and team belongs to the current user..\r\n Team.query.filter_by(id=team_id).filter_by(user_id=g.user.id).first_or_404()\r\n answers = Answer.query.filter_by(team_id=team_id).order_by(Answer.id.desc())\r\n cadence_list = db.session.query(Answer.cadence_id, Cadence.start, Cadence.end,\r\n func.min(Answer.mood).label('min'),\r\n func.avg(Answer.mood).label('avg'),\r\n func.max(Answer.mood).label('max')) \\\r\n .filter_by(team_id=team_id) \\\r\n .filter(Answer.cadence_id == Cadence.id) \\\r\n .group_by(Answer.cadence_id) \\\r\n .order_by(Answer.id.desc()) \\\r\n .all()\r\n return render_template('team_answers.html', answers=answers, cadence_list=cadence_list)\r\n\r\n\r\n@app.route('/team//statistics')\r\n@login_required\r\ndef show_team_statistics(team_id):\r\n # check if team_id is existing and team belongs to the current user..\r\n Team.query.filter_by(id=team_id).filter_by(user_id=g.user.id).first_or_404()\r\n cadence_list = db.session.query(Answer.cadence_id, Cadence.start, Cadence.end,\r\n func.min(Answer.mood).label('min'),\r\n func.avg(Answer.mood).label('avg'),\r\n func.max(Answer.mood).label('max')) \\\r\n .filter_by(team_id=team_id) \\\r\n .filter(Answer.cadence_id == Cadence.id) \\\r\n .group_by(Answer.cadence_id) \\\r\n .order_by(Answer.id.asc()) \\\r\n .all()\r\n return render_template('team_statistics.html', cadence_list=cadence_list)\r\n\r\n\r\n@app.route('/team//answers/delete/')\r\n@login_required\r\ndef delete_answer(team_id, answer_id):\r\n # check if team_id is existing and team belongs to the current user..\r\n Team.query.filter_by(id=team_id).filter_by(user_id=g.user.id).first_or_404()\r\n answer = Answer.query.filter_by(id=answer_id).filter_by(team_id=team_id).first_or_404()\r\n db.session.delete(answer)\r\n db.session.commit()\r\n flash('Answer successfully deleted', 'success')\r\n return redirect(url_for('show_team_answers', team_id=team_id))\r\n\r\n\r\n@app.route('/team//switch_cadence')\r\n@login_required\r\ndef switch_cadence(team_id):\r\n # check if team_id is existing and team belongs to the current user..\r\n team = Team.query.filter_by(id=team_id).filter_by(user_id=g.user.id).first_or_404()\r\n now = datetime.now()\r\n last_cadence = Cadence.query.filter_by(team_id=team_id).order_by(Cadence.id.desc()).first()\r\n last_cadence.end = now\r\n db.session.commit()\r\n cadence = Cadence(team.id, now)\r\n db.session.add(cadence)\r\n db.session.commit()\r\n team.current_cadence_id = cadence.id\r\n db.session.commit()\r\n flash('New cadence successfully started', 'success')\r\n return redirect(url_for('index'))\r\n\r\n\r\n@app.route('/survey/', methods=['GET', 'POST'])\r\ndef survey(access_token):\r\n # check if access_token is existing\r\n team = Team.query.filter_by(access_token=access_token).first_or_404()\r\n form = Survey_form()\r\n if form.validate_on_submit():\r\n answer = Answer(team.id, form.name.data, form.mood.data, form.text.data, team.current_cadence_id)\r\n db.session.add(answer)\r\n db.session.commit()\r\n flash('Thanks for putting in your two cents!', 'success')\r\n return redirect(url_for('survey', access_token=access_token))\r\n if team.answers_visible:\r\n answers = Answer.query.filter_by(team_id=team.id).filter_by(cadence_id=team.current_cadence_id).order_by(Answer.id.desc())\r\n else:\r\n answers = None\r\n return render_template('survey.html', form=form, answers=answers)\r\n\r\n\r\n@app.route('/user/register', methods=['GET', 'POST'])\r\ndef register():\r\n form = Register_form()\r\n if form.validate_on_submit():\r\n user = User(form.email.data, form.password.data)\r\n db.session.add(user)\r\n db.session.commit()\r\n flash('Account successfully created', 'success')\r\n return redirect(url_for('login'))\r\n return render_template('register.html', form=form)\r\n\r\n\r\n@app.route('/user/edit_account', methods=['GET', 'POST'])\r\n@login_required\r\ndef edit_account():\r\n return render_template('edit_account.html')\r\n\r\n\r\n@app.route('/user/forgot_password', methods=['GET', 'POST'])\r\ndef forgot_password():\r\n return render_template('forgot_password.html')\r\n\r\n\r\n@app.route('/user/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = Login_form()\r\n if form.validate_on_submit():\r\n return redirect(url_for('index'))\r\n return render_template('login.html', form=form)\r\n\r\n\r\n@app.route('/user/logout')\r\ndef logout():\r\n logout_user()\r\n return redirect(url_for('index'))\r\n\r\n\r\n@app.errorhandler(404)\r\ndef page_not_found(error):\r\n return render_template('404.html'), 404\r\n\r\n\r\n@app.errorhandler(500)\r\ndef internal_server_error(error):\r\n db.session.rollback()\r\n return render_template('500.html'), 500\r\n\r\n\r\n@login_manager.user_loader\r\ndef load_user(id):\r\n return User.query.get(int(id))\r\n\r\n\r\n@app.before_request\r\ndef before_request():\r\n g.user = current_user\r\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"383923263","text":"# Author: Kevin Dombrosky \n# Tests Knuth's conjecture on an elementary set of integers using BFS and a select few shortcuts and self limitations\n\nfrom Queue import Queue\nfrom math import factorial, sqrt, floor\n\ndef bfs(target):\n queue = Queue()\n queue.put((4, 0))\n curr = 4\n total_steps = 0\n seen = set()\n\n while True:\n if queue.empty():\n return \"Queue empty, solution not found/possible\"\n ordered_pair = queue.get()\n curr = ordered_pair[0]\n total_steps = ordered_pair[1]\n\n if curr in seen:\n continue\n seen.add(curr)\n\n is_int = True\n if isinstance(curr, float):\n is_int = curr.is_integer()\n\n if is_int:\n curr = int(curr)\n if curr == target:\n break\n\n try:\n if is_int and curr <= 197 and curr > 1:\n queue.put((factorial(curr), total_steps + 1))\n except (OverflowError):\n pass\n\n queue.put((sqrt(curr), total_steps+1))\n if not is_int and floor(curr) != 1:\n queue.put((floor(curr), total_steps + 1))\n\n return total_steps\n\nprint(\"5: {}\".format(str(bfs(5))))\nprint(\"8: {}\".format(str(bfs(8))))\nprint(\"10: {}\".format(str(bfs(10))))\nprint(\"13: {}\".format(str(bfs(13))))\n\n","sub_path":"IntelligentSystems/Homework1/.idea/Dombrosky_Kevin_Knuth.py.py","file_name":"Dombrosky_Kevin_Knuth.py.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"627554919","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def insertionSortList(self, head: ListNode) -> ListNode:\n if not head or not head.next:\n return head\n\n dummy = ListNode(-1)\n dummy.next = head\n pre = head #pre始终指着排序好链表的最后一个节点\n cur = head.next #cur始终指着未排序链表的第一个节点\n while cur:\n if pre.val < cur.val:\n pre = pre.next\n cur = cur.next\n else:\n tail = cur.next\n pre.next = tail #把cur这个节点拿出来,防止出现循环\n\n p = dummy\n while p.next and p.next.val < cur.val: #找到插入的位置\n p = p.next\n\n cur.next = p.next #把cur插入到p和p.next之间\n p.next = cur\n cur = tail\n\n # if p == pre:#如果刚插入到了已排序链表的末尾\n # pre = pre.next #那么就更新pre\n return dummy.next\n","sub_path":"链表/147对链表进行插入排序.py","file_name":"147对链表进行插入排序.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"35810521","text":"#!/usr/bin/env python3\nimport sys, os\nimport random, string\nimport datetime\nimport numpy as np\nimport PIL.Image\nimport PIL.ImageDraw\nimport PIL.ImageFont\n\nsave_top = \"./Hiragana/HiraganaFont\"\nfont_path = \"/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf\"\n\nkanatable = [ 'あ','い','う','え','お',\n'か','が','き','ぎ','く','ぐ','け','げ','こ','ご',\n'さ','ざ','し','じ','す','ず','せ','ぜ','そ','ぞ',\n'た','だ','ち','ぢ','つ','づ','て','で','と','ど',\n'な','に','ぬ','ね','の',\n'は','ば','ぱ','ひ','び','ぴ','ふ','ぶ','ぷ','へ','べ','ぺ','ほ','ぼ','ぽ',\n'ま','み','む','め','も',\n'や','ゆ','よ','ら','り','る','れ','ろ','わ','を','ん']\n\nimport random\nimport string\ndef get_random_str(n):\n return ''.join([random.choice(string.ascii_letters+string.digits) for i in range(n)])\n\ndef save_char( idx, img):\n SaveTo=os.path.join(save_top, \"{0:0>4}\".format(idx))\n #print(SaveTo)\n if os.path.exists(SaveTo)==False:\n os.makedirs(SaveTo)\n FileName=datetime.datetime.now().strftime(u'%Y%m%d%H%M%S')+\"_\"+get_random_str(5)+\".jpg\"\n FullName=os.path.join(SaveTo,FileName)\n #print(FullName)\n img.save(FullName)\n\ndef draw_text_at_center(img, text):\n draw = PIL.ImageDraw.Draw(img)\n draw.font = PIL.ImageFont.truetype(\n font_path,20)\n\n img_size = np.array(img.size)\n txt_size = np.array(draw.font.getsize(text))\n pos = (img_size-txt_size)/2\n draw.rectangle(((0,0),img.size),(0,0,0))\n draw.text(pos, text, (255,255,255))\n\nif __name__ == '__main__':\n\n for i, c in enumerate(kanatable):\n img = PIL.Image.new(\"RGBA\",(28,28))\n print(\"{0} {1}\".format(i,c))\n draw_text_at_center( img, c)\n save_char( i, img)\n #img.show()\n \n","sub_path":"DeepLearning/hiragana_dataset/Font2Data.py","file_name":"Font2Data.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"496223940","text":"import asyncio\n\nimport zmq\nimport zmq.asyncio\n\n\nclass MessageCache:\n _context: zmq.asyncio.Context = zmq.asyncio.Context()\n\n def __init__(self, max_queue_length: int = 100000, unique_name: str = None) -> None:\n super().__init__()\n\n if unique_name is None:\n unique_name = random_string()\n url = 'inproc://' + unique_name\n self.__pub_socket = self.__setup_pub_socket(url, max_queue_length)\n self.__sub_socket = self.__setup_sub_socket(url, max_queue_length)\n\n self.__process_loop = asyncio.get_event_loop().create_task(self.process_loop())\n\n # noinspection PyUnresolvedReferences\n def __setup_pub_socket(self, url: str, max_queue_length: int) -> zmq.asyncio.Socket:\n socket = self._context.socket(zmq.PUSH)\n socket.setsockopt(zmq.SNDHWM, max_queue_length)\n socket.setsockopt(zmq.RCVHWM, max_queue_length)\n socket.bind(url)\n\n return socket\n\n # noinspection PyUnresolvedReferences\n def __setup_sub_socket(self, url: str, max_queue_length: int) -> zmq.asyncio.Socket:\n socket = self._context.socket(zmq.PULL)\n socket.connect(url)\n socket.setsockopt(zmq.SNDHWM, max_queue_length)\n socket.setsockopt(zmq.RCVHWM, max_queue_length)\n\n return socket\n\n async def _add_to_cache(self, message: bytes):\n if self.__process_loop.done():\n self.__process_loop = asyncio.get_event_loop().create_task(self.process_loop())\n await self.__pub_socket.send(message)\n\n async def publish(self, message: bytes) -> None:\n await self._add_to_cache(message)\n\n def terminate(self) -> None:\n self._context.destroy()\n\n async def process_message(self, message: bytes) -> None:\n print(message.decode(\"utf-8\"))\n\n async def process_loop(self) -> None:\n while True:\n try:\n message = await self.__sub_socket.recv()\n await self.process_message(message)\n except KeyboardInterrupt:\n break\n\n\ndef random_string(string_length=10):\n \"\"\"Generate a random string of fixed length \"\"\"\n import string\n import random\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(string_length))\n\n\nif __name__ == \"__main__\":\n message_cache = MessageCache()\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(message_cache.publish(b\"Test Message 1\"))\n loop.run_until_complete(message_cache.publish(b\"Test Message 2\"))\n loop.create_task(message_cache.process_loop())\n loop.run_forever()\n\n # Never going to be reached\n loop.close()\n message_cache.terminate()\n","sub_path":"fog/src/core/messageCache.py","file_name":"messageCache.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"79771902","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, division, print_function, absolute_import\nfrom . import TestCase, skipIf, SkipTest, Server\nimport time\nimport re\n\nimport testdata\n\nimport endpoints\nfrom endpoints import CallError\nfrom endpoints import decorators\nfrom endpoints.utils import ByteString, Base64, String\nfrom endpoints.http import Request\nfrom endpoints.decorators import (\n param,\n param_body,\n param_query\n)\nfrom endpoints.decorators.limit import (\n ratelimit,\n ratelimit_ip,\n ratelimit_param,\n ratelimit_param_ip,\n ratelimit_token,\n)\n\n\ndef create_controller():\n class FakeController(endpoints.Controller):\n def POST(self): pass\n def GET(self): pass\n\n res = endpoints.Response()\n\n req = endpoints.Request()\n req.method = 'GET'\n\n c = FakeController(req, res)\n return c\n\n\nclass RatelimitTest(TestCase):\n def set_bearer_auth_header(self, request, access_token):\n request.set_header(\"authorization\", 'Bearer {}'.format(access_token))\n\n def test_throttle(self):\n class TARA(object):\n @ratelimit(limit=3, ttl=1)\n def foo(self): return 1\n\n @ratelimit(limit=10, ttl=1)\n def bar(self): return 2\n\n\n r_foo = endpoints.Request()\n r_foo.set_header(\"X_FORWARDED_FOR\", \"276.0.0.1\")\n r_foo.path = \"/foo\"\n c = TARA()\n c.request = r_foo\n\n for x in range(3):\n r = c.foo()\n self.assertEqual(1, r)\n\n for x in range(2):\n with self.assertRaises(CallError):\n c.foo()\n\n # make sure another path isn't messed with by foo\n r_bar = Request()\n r_bar.set_header(\"X_FORWARDED_FOR\", \"276.0.0.1\")\n r_bar.path = \"/bar\"\n c.request = r_bar\n for x in range(10):\n r = c.bar()\n self.assertEqual(2, r)\n time.sleep(0.1)\n\n with self.assertRaises(CallError):\n c.bar()\n\n c.request = r_foo\n\n for x in range(3):\n r = c.foo()\n self.assertEqual(1, r)\n\n for x in range(2):\n with self.assertRaises(CallError):\n c.foo()\n\n def test_ratelimit_ip(self):\n class MockObject(object):\n @ratelimit_ip(limit=3, ttl=1)\n def foo(self): return 1\n\n o = MockObject()\n o.request = Request()\n o.request.set_header(\"X_FORWARDED_FOR\", \"100.1.1.1\")\n o.request.path = \"/fooip\"\n\n o.foo()\n o.foo()\n o.foo()\n with self.assertRaises(CallError) as cm:\n o.foo()\n self.assertEqual(429, cm.exception.code)\n\n # make sure another request gets through just fine\n orig_r = o.request\n o.request = Request()\n o.request.path = \"/fooip\"\n o.request.set_header(\"X_FORWARDED_FOR\", \"100.1.1.2\")\n o.foo()\n o.request = orig_r\n\n time.sleep(1)\n o.request.set_header(\"X_FORWARDED_FOR\", \"100.1.1.1\")\n r = o.foo()\n self.assertEqual(1, r)\n\n def test_ratelimit_token(self):\n class MockObject(object):\n @ratelimit_token(limit=2, ttl=1)\n def foo(self): return 1\n\n o = MockObject()\n o.request = Request()\n self.set_bearer_auth_header(o.request, \"footoken\")\n o.request.path = \"/footoken\"\n\n o.request.set_header(\"X_FORWARDED_FOR\", \"1.1.1.1\")\n o.foo()\n\n o.request.set_header(\"X_FORWARDED_FOR\", \"1.1.1.2\")\n o.foo()\n\n with self.assertRaises(CallError) as cm:\n o.foo()\n self.assertEqual(429, cm.exception.code)\n\n # make sure another request gets through just fine\n orig_r = o.request\n o.request = Request()\n o.request.path = \"/footoken\"\n self.set_bearer_auth_header(o.request, \"footoken2\")\n o.foo()\n o.request = orig_r\n\n time.sleep(1)\n self.set_bearer_auth_header(o.request, \"footoken\")\n o.request.set_header(\"X_FORWARDED_FOR\", \"1.1.1.3\")\n r = o.foo()\n self.assertEqual(1, r)\n\n def test_ratelimit_param(self):\n class MockObject(object):\n @ratelimit_param(\"bar\", limit=2, ttl=1)\n def foo(self, **kwargs): return 1\n\n o = MockObject()\n o.request = Request()\n self.set_bearer_auth_header(o.request, \"footoken\")\n o.request.path = \"/fooparam\"\n\n o.foo(bar=\"che\")\n\n o.foo(bar=\"che\")\n\n with self.assertRaises(CallError) as cm:\n o.foo(bar=\"che\")\n self.assertEqual(429, cm.exception.code)\n\n # make sure bar not existing is not a problem\n for x in range(5):\n self.assertEqual(1, o.foo())\n\n # just make sure something else goes through just fine\n orig_r = o.request\n o.request = Request()\n o.request.path = \"/fooparam\"\n o.foo(bar=\"baz\")\n o.request = orig_r\n\n time.sleep(1)\n r = o.foo(bar=\"che\")\n self.assertEqual(1, r)\n\n def test_ratelimit_param_ip(self):\n def create_request(ip):\n r = Request()\n r.path = \"/fooparam\"\n r.set_header(\"X_FORWARDED_FOR\", ip)\n self.set_bearer_auth_header(r, \"footoken\")\n return r\n\n class MockObject(object):\n @ratelimit_param_ip(\"bar\", limit=1, ttl=1)\n def foo(self, **kwargs): return 1\n\n o = MockObject()\n o.request = create_request(\"200.1.1.1\")\n o.foo(bar=\"che\")\n\n with self.assertRaises(CallError) as cm:\n o.foo(bar=\"che\")\n self.assertEqual(429, cm.exception.code)\n\n # now make sure another ip address can get through\n o.request = create_request(\"200.1.1.2\")\n o.foo(bar=\"che\")\n\n with self.assertRaises(CallError) as cm:\n o.foo(bar=\"che\")\n self.assertEqual(429, cm.exception.code)\n\n # now make sure another value makes it through\n o.foo(bar=\"baz\")\n with self.assertRaises(CallError):\n o.foo(bar=\"baz\")\n\n # make sure bar not existing is not a problem\n for x in range(5):\n self.assertEqual(1, o.foo())\n\n\nclass AuthTest(TestCase):\n def get_basic_auth_header(self, username, password):\n credentials = Base64.encode('{}:{}'.format(username, password))\n return 'Basic {}'.format(credentials)\n\n def get_bearer_auth_header(self, access_token):\n return 'Bearer {}'.format(access_token)\n\n\n def test_bad_setup(self):\n\n def target(controller, *args, **kwargs):\n return False\n\n class TARA(object):\n @decorators.auth_token(target=target)\n def foo_token(self): pass\n\n @decorators.auth_client(target=target)\n def foo_client(self): pass\n\n @decorators.auth_basic(target=target)\n def foo_basic(self): pass\n\n @decorators.auth(target=target)\n def foo_auth(self): pass\n\n r = endpoints.Request()\n c = TARA()\n c.request = r\n\n for m in [\"foo_token\", \"foo_client\", \"foo_basic\", \"foo_auth\"]: \n with self.assertRaises(endpoints.AccessDenied):\n getattr(c, m)()\n\n def test_token_auth(self):\n def target(controller, access_token):\n if access_token != \"bar\":\n raise ValueError()\n return True\n\n def target_bad(controller, *args, **kwargs):\n return False\n\n class TARA(object):\n @decorators.auth_token(target=target)\n def foo(self): pass\n\n @decorators.auth_token(target=target_bad)\n def foo_bad(self): pass\n\n r = endpoints.Request()\n c = TARA()\n c.request = r\n\n r.set_header('authorization', self.get_bearer_auth_header(\"foo\"))\n with self.assertRaises(endpoints.AccessDenied):\n c.foo()\n\n r.set_header('authorization', self.get_bearer_auth_header(\"bar\"))\n c.foo()\n\n r = endpoints.Request()\n c.request = r\n\n r.body_kwargs[\"access_token\"] = \"foo\"\n with self.assertRaises(endpoints.AccessDenied):\n c.foo()\n\n r.body_kwargs[\"access_token\"] = \"bar\"\n c.foo()\n\n r = endpoints.Request()\n c.request = r\n\n r.query_kwargs[\"access_token\"] = \"foo\"\n with self.assertRaises(endpoints.AccessDenied):\n c.foo()\n\n r.query_kwargs[\"access_token\"] = \"bar\"\n c.foo()\n\n with self.assertRaises(endpoints.AccessDenied):\n c.foo_bad()\n\n def test_client_auth(self):\n def target(controller, client_id, client_secret):\n return client_id == \"foo\" and client_secret == \"bar\"\n\n def target_bad(controller, *args, **kwargs):\n return False\n\n class TARA(object):\n @decorators.auth_client(target=target)\n def foo(self): pass\n\n @decorators.auth_client(target=target_bad)\n def foo_bad(self): pass\n\n client_id = \"foo\"\n client_secret = \"...\"\n r = endpoints.Request()\n r.set_header('authorization', self.get_basic_auth_header(client_id, client_secret))\n\n c = TARA()\n c.request = r\n with self.assertRaises(endpoints.AccessDenied):\n c.foo()\n\n client_secret = \"bar\"\n r.set_header('authorization', self.get_basic_auth_header(client_id, client_secret))\n c.foo()\n\n with self.assertRaises(endpoints.AccessDenied):\n c.foo_bad()\n\n def test_basic_auth_simple(self):\n def target(controller, username, password):\n if username != \"bar\":\n raise ValueError()\n return True\n\n def target_bad(controller, *args, **kwargs):\n return False\n\n class TARA(object):\n @decorators.auth_basic(target=target)\n def foo(self): pass\n\n @decorators.auth_basic(target=target_bad)\n def foo_bad(self): pass\n\n username = \"foo\"\n password = \"...\"\n r = endpoints.Request()\n r.set_header('authorization', self.get_basic_auth_header(username, password))\n\n c = TARA()\n c.request = r\n\n with self.assertRaises(endpoints.AccessDenied):\n c.foo()\n\n username = \"bar\"\n r.set_header('authorization', self.get_basic_auth_header(username, password))\n c.foo()\n\n with self.assertRaises(endpoints.AccessDenied):\n c.foo_bad()\n\n def test_basic_auth_same_kwargs(self):\n def target(controller, username, password):\n if username != \"bar\":\n raise ValueError()\n return True\n\n class MockObject(object):\n @decorators.auth_basic(target=target)\n def foo(self, *args, **kwargs): return 1\n\n c = MockObject()\n username = \"bar\"\n password = \"...\"\n r = endpoints.Request()\n r.set_header('authorization', self.get_basic_auth_header(username, password))\n c.request = r\n\n # if no TypeError is raised then it worked :)\n r = c.foo(request=\"this_should_error_out\")\n self.assertEqual(1, r)\n\n def test_auth(self):\n def target(controller, controller_args, controller_kwargs):\n if controller.request.body_kwargs[\"foo\"] != \"bar\":\n raise ValueError()\n return True\n\n def target_bad(controller, *args, **kwargs):\n return False\n\n class TARA(object):\n @decorators.auth(target=target)\n def foo(self): pass\n\n @decorators.auth(target=target_bad)\n def foo_bad(self): pass\n\n r = endpoints.Request()\n r.body_kwargs = {\"foo\": \"che\"}\n\n c = TARA()\n c.request = r\n with self.assertRaises(endpoints.AccessDenied):\n c.foo()\n\n r.body_kwargs = {\"foo\": \"bar\"}\n c.foo()\n\n# def test_auth_child(self):\n# \n# class auth_token_fail(decorators.auth_token):\n# def target(self, *args, **kwargs):\n# raise ValueError(\"failed auth_token_fail.target\")\n# \n# class auth_child(decorators.auth):\n# def target(self, *args, **kwargs):\n# try:\n# auth = auth_token_fail()\n# auth.target(*args, **kwargs)\n# \n# except ValueError as e:\n# pout.v(e)\n# # if e.code == 401:\n# # auth = auth_another()\n# # auth.target(self.request, args, kwargs)\n# \n# return True\n# \n# \n# \n# #pout.v(args, kwargs)\n# #raise ValueError()\n# \n# class ACController(object):\n# @auth_child\n# def foo(self): pass\n# \n# c = ACController()\n# c.request = endpoints.Request()\n# c.foo()\n\n\nclass PropertyTest(TestCase):\n def test__property_init(self):\n counts = dict(fget=0, fset=0, fdel=0)\n def fget(self):\n counts[\"fget\"] += 1\n return self._v\n\n def fset(self, v):\n counts[\"fset\"] += 1\n self._v = v\n\n def fdel(self):\n counts[\"fdel\"] += 1\n del self._v\n\n class FooPropInit(object):\n v = endpoints.decorators._property(fget, fset, fdel, \"this is v\")\n f = FooPropInit()\n f.v = 6\n self.assertEqual(6, f.v)\n self.assertEqual(2, sum(counts.values()))\n del f.v\n self.assertEqual(3, sum(counts.values()))\n\n counts = dict(fget=0, fset=0, fdel=0)\n class FooPropInit2(object):\n v = endpoints.decorators._property(fget=fget, fset=fset, fdel=fdel, doc=\"this is v\")\n f = FooPropInit2()\n f.v = 6\n self.assertEqual(6, f.v)\n self.assertEqual(2, sum(counts.values()))\n del f.v\n self.assertEqual(3, sum(counts.values()))\n\n def test__property_allow_empty(self):\n class PAE(object):\n foo_val = None\n @endpoints.decorators._property(allow_empty=False)\n def foo(self):\n return self.foo_val\n\n c = PAE()\n self.assertEqual(None, c.foo)\n self.assertFalse('_foo' in c.__dict__)\n\n c.foo_val = 1\n self.assertEqual(1, c.foo)\n self.assertTrue('_foo' in c.__dict__)\n\n def test__property_setter(self):\n class WPS(object):\n foo_get = False\n foo_set = False\n foo_del = False\n\n @endpoints.decorators._property\n def foo(self):\n self.foo_get = True\n return 1\n\n @foo.setter\n def foo(self, val):\n self.foo_set = True\n self._foo = val\n\n @foo.deleter\n def foo(self):\n self.foo_del = True\n del(self._foo)\n\n c = WPS()\n\n self.assertEqual(1, c.foo)\n\n c.foo = 5\n self.assertEqual(5, c.foo)\n\n del(c.foo)\n self.assertEqual(1, c.foo)\n\n self.assertTrue(c.foo_get)\n self.assertTrue(c.foo_set)\n self.assertTrue(c.foo_del)\n\n def test__property__strange_behavior(self):\n class BaseFoo(object):\n def __init__(self):\n setattr(self, 'bar', None)\n\n def __setattr__(self, n, v):\n super(BaseFoo, self).__setattr__(n, v)\n\n class Foo(BaseFoo):\n @endpoints.decorators._property(allow_empty=False)\n def bar(self):\n return 1\n\n f = Foo()\n self.assertEqual(1, f.bar)\n\n f.bar = 2\n self.assertEqual(2, f.bar)\n\n def test__property___dict__direct(self):\n \"\"\"\n this is a no win situation\n\n if you have a bar _property and a __setattr__ that modifies directly then\n the other _property values like __set__ will not get called, and you can't\n have _property.__get__ look for the original name because there are times\n when you want your _property to override a parent's original value for the\n property, so I've chosen to just ignore this case and not support it\n \"\"\"\n class Foo(object):\n @endpoints.decorators._property\n def bar(self):\n return 1\n def __setattr__(self, field_name, field_val):\n self.__dict__[field_name] = field_val\n #super(Foo, self).__setattr__(field_name, field_val)\n\n f = Foo()\n f.bar = 2 # this will be ignored\n self.assertEqual(1, f.bar)\n\n def test__property(self):\n class WP(object):\n count_foo = 0\n\n @endpoints.decorators._property(True)\n def foo(self):\n self.count_foo += 1\n return 1\n\n @endpoints.decorators._property(read_only=True)\n def baz(self):\n return 2\n\n @endpoints.decorators._property()\n def bar(self):\n return 3\n\n @endpoints.decorators._property\n def che(self):\n return 4\n\n c = WP()\n r = c.foo\n self.assertEqual(1, r)\n self.assertEqual(1, c._foo)\n with self.assertRaises(AttributeError):\n c.foo = 2\n with self.assertRaises(AttributeError):\n del(c.foo)\n c.foo\n c.foo\n self.assertEqual(1, c.count_foo)\n\n r = c.baz\n self.assertEqual(2, r)\n self.assertEqual(2, c._baz)\n with self.assertRaises(AttributeError):\n c.baz = 3\n with self.assertRaises(AttributeError):\n del(c.baz)\n\n r = c.bar\n self.assertEqual(3, r)\n self.assertEqual(3, c._bar)\n c.bar = 4\n self.assertEqual(4, c.bar)\n self.assertEqual(4, c._bar)\n del(c.bar)\n r = c.bar\n self.assertEqual(3, r)\n\n r = c.che\n self.assertEqual(4, r)\n self.assertEqual(4, c._che)\n c.che = 4\n self.assertEqual(4, c.che)\n del(c.che)\n r = c.che\n self.assertEqual(4, r)\n\n\nclass ParamTest(TestCase):\n def test_type_issue_76(self):\n \"\"\"\n https://github.com/Jaymon/endpoints/issues/76\n \"\"\"\n c = Server(\"type_issue_76\", [\n \"from endpoints import Controller, param\",\n \"\",\n \"class Query(object):\",\n \" def get(self, v): return v\",\n \"\",\n \"class FooType(object):\",\n \" query = Query()\",\n \"\",\n \"class Foo(Controller):\",\n \" @param(0, default=None, type=FooType.query.get)\",\n \" def GET(self, f):\",\n \" return f\",\n \"\",\n \"class Bar(Controller):\",\n \" @param(0, default=None, type=lambda x: FooType.query.get(x))\",\n \" def GET(self, f):\",\n \" return f\",\n ])\n\n res = c.handle(\"/foo/bar\")\n self.assertEqual(\"bar\", res._body)\n\n res = c.handle(\"/bar/foo\")\n self.assertEqual(\"foo\", res._body)\n\n def test_regex_issue_77(self):\n \"\"\"\n https://github.com/Jaymon/endpoints/issues/77\n \"\"\"\n c = Server(\"regex_issue_77\", [\n \"import datetime\",\n \"from endpoints import Controller, param\",\n \"\",\n \"def parse(dts):\",\n \" return datetime.datetime.strptime(dts, '%Y-%m-%d')\",\n \"\",\n \"class Foo(Controller):\",\n \" @param('dt', regex=r'^[0-9]{4}-[0-9]{2}-[0-9]{2}$', type=parse)\",\n \" def GET(self, **kwargs):\",\n \" return kwargs['dt']\",\n \"\",\n ])\n\n res = c.handle(\"/foo\", query=\"dt=2018-01-01\")\n self.assertEqual(res._body.year, 2018)\n self.assertEqual(res._body.month, 1)\n self.assertEqual(res._body.day, 1)\n #self.assertEqual(\"bar\", res._body)\n\n\n def test_append_list_choices(self):\n c = create_controller()\n\n @param('foo', action=\"append_list\", type=int, choices=[1, 2])\n def foo(self, *args, **kwargs):\n return kwargs[\"foo\"]\n\n #r = foo(c, **{'foo': \"1,2\"})\n r = foo(c, foo=\"1,2\")\n self.assertEqual([1, 2], r)\n\n with self.assertRaises(CallError):\n r = foo(c, **{'foo': \"1,2,3\"})\n\n r = foo(c, **{'foo': 1})\n self.assertEqual([1], r)\n\n with self.assertRaises(CallError):\n r = foo(c, **{'foo': 3})\n\n def test_metavar(self):\n raise SkipTest(\"not sure what to do with this test yet\")\n class MockMetavar(object):\n request = Request()\n\n @param(0, metavar=\"bar\")\n def foo(self, bar, **kwargs): return 1\n\n\n o = MockMetavar()\n o.request.method = 'GET'\n o.request.path = \"/0\"\n\n o.foo(\"0\")\n\n def test_param_dest(self):\n \"\"\"make sure the dest=... argument works\"\"\"\n # https://docs.python.org/2/library/argparse.html#dest\n c = create_controller()\n\n @endpoints.decorators.param('foo', dest='bar')\n def foo(self, *args, **kwargs):\n return kwargs.get('bar')\n\n r = foo(c, **{'foo': 1})\n self.assertEqual(1, r)\n\n def test_param_multiple_names(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', 'foos', 'foo3', type=int)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n\n r = foo(c, **{'foo': 1})\n self.assertEqual(1, r)\n\n r = foo(c, **{'foos': 2})\n self.assertEqual(2, r)\n\n r = foo(c, **{'foo3': 3})\n self.assertEqual(3, r)\n\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **{'foo4': 0})\n\n def test_param_callable_default(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', default=time.time)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n\n start = time.time()\n r1 = foo(c, **{})\n self.assertLess(start, r1)\n\n time.sleep(0.25)\n r2 = foo(c, **{})\n self.assertLess(r1, r2)\n\n\n def test_param_not_required(self):\n c = create_controller()\n\n @param('foo', required=False)\n def foo(self, *args, **kwargs):\n return 'foo' in kwargs\n\n r = foo(c, **{'foo': 1})\n self.assertTrue(r)\n\n r = foo(c, **{})\n self.assertFalse(r)\n\n @param('foo', required=False, default=5)\n def foo(self, *args, **kwargs):\n return 'foo' in kwargs\n\n r = foo(c, **{})\n self.assertTrue(r)\n\n @param('foo', type=int, required=False)\n def foo(self, *args, **kwargs):\n return 'foo' in kwargs\n\n r = foo(c, **{})\n self.assertFalse(r)\n\n\n def test_param_unicode(self):\n c = create_controller()\n r = endpoints.Request()\n r.set_header(\"content-type\", \"application/json;charset=UTF-8\")\n charset = r.encoding\n c.request = r\n #self.assertEqual(\"UTF-8\", charset)\n\n @endpoints.decorators.param('foo', type=str)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n\n words = testdata.get_unicode_words()\n ret = foo(c, **{\"foo\": words})\n self.assertEqual(String(ret), String(words))\n\n def test_param(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', type=int)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **{'foo': 0})\n\n @endpoints.decorators.param('foo', default=0)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n\n r = foo(c, **{})\n self.assertEqual(0, r)\n\n @endpoints.decorators.param('foo', type=int, choices=set([1, 2, 3]))\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n\n c.request.method = 'POST'\n c.request.body_kwargs = {'foo': '1'}\n r = foo(c, **c.request.body_kwargs)\n self.assertEqual(1, r)\n\n c.request.body_kwargs = {}\n r = foo(c, **{'foo': '2'})\n self.assertEqual(2, r)\n\n def test_post_param_body(self):\n c = create_controller()\n c.request.method = 'POST'\n\n @param_body('foo', type=int, choices=set([1, 2, 3]))\n def foo(self, *args, **kwargs):\n return kwargs['foo']\n\n with self.assertRaises(CallError):\n r = foo(c)\n\n c.request.query_kwargs['foo'] = '1'\n with self.assertRaises(CallError):\n r = foo(c, **{'foo': '1'})\n\n c.request.body_kwargs = {'foo': '8'}\n with self.assertRaises(CallError):\n r = foo(c, **c.request.body_kwargs)\n\n c.request.query_kwargs = {}\n c.request.body_kwargs = {'foo': '1'}\n r = foo(c, **c.request.body_kwargs)\n self.assertEqual(1, r)\n\n c.request.query_kwargs = {'foo': '1'}\n c.request.body_kwargs = {'foo': '3'}\n r = foo(c, **{'foo': '3'})\n self.assertEqual(3, r)\n\n def test_param_query(self):\n c = create_controller()\n\n c.request.query_kwargs = {'foo': '8'}\n @endpoints.decorators.param_query('foo', type=int, choices=set([1, 2, 3]))\n def foo(*args, **kwargs):\n return kwargs['foo']\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **c.request.query_kwargs)\n\n c.request.query_kwargs = {'foo': '1'}\n @endpoints.decorators.param_query('foo', type=int, choices=set([1, 2, 3]))\n def foo(*args, **kwargs):\n return kwargs['foo']\n r = foo(c, **c.request.query_kwargs)\n self.assertEqual(1, r)\n\n c.request.query_kwargs = {'foo': '1', 'bar': '1.5'}\n @endpoints.decorators.param_query('foo', type=int)\n @endpoints.decorators.param_query('bar', type=float)\n def foo(*args, **kwargs):\n return kwargs['foo'], kwargs['bar']\n r = foo(c, **c.request.query_kwargs)\n self.assertEqual(1, r[0])\n self.assertEqual(1.5, r[1])\n\n c.request.query_kwargs = {'foo': '1'}\n @endpoints.decorators.param_query('foo', type=int, action='blah')\n def foo(*args, **kwargs):\n return kwargs['foo']\n with self.assertRaises(RuntimeError):\n r = foo(c, **c.request.query_kwargs)\n\n c.request.query_kwargs = {'foo': ['1,2,3,4', '5']}\n @endpoints.decorators.param_query('foo', type=int, action='store_list')\n def foo(*args, **kwargs):\n return kwargs['foo']\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **c.request.query_kwargs)\n\n c.request.query_kwargs = {'foo': ['1,2,3,4', '5']}\n @endpoints.decorators.param_query('foo', type=int, action='append_list')\n def foo(*args, **kwargs):\n return kwargs['foo']\n r = foo(c, **c.request.query_kwargs)\n self.assertEqual(list(range(1, 6)), r)\n\n c.request.query_kwargs = {'foo': '1,2,3,4'}\n @endpoints.decorators.param_query('foo', type=int, action='store_list')\n def foo(*args, **kwargs):\n return kwargs['foo']\n r = foo(c, **c.request.query_kwargs)\n self.assertEqual(list(range(1, 5)), r)\n\n c.request.query_kwargs = {}\n\n @endpoints.decorators.param_query('foo', type=int, default=1, required=False)\n def foo(*args, **kwargs):\n return kwargs['foo']\n r = foo(c)\n self.assertEqual(1, r)\n\n @endpoints.decorators.param_query('foo', type=int, default=1, required=True)\n def foo(*args, **kwargs):\n return kwargs['foo']\n r = foo(c)\n self.assertEqual(1, r)\n\n @endpoints.decorators.param_query('foo', type=int, default=1)\n def foo(*args, **kwargs):\n return kwargs['foo']\n r = foo(c)\n self.assertEqual(1, r)\n\n @endpoints.decorators.param_query('foo', type=int)\n def foo(*args, **kwargs):\n return kwargs['foo']\n with self.assertRaises(endpoints.CallError):\n r = foo(c)\n\n c.request.query_kwargs = {'foo': '1'}\n @endpoints.decorators.param_query('foo', type=int)\n def foo(*args, **kwargs):\n return kwargs['foo']\n r = foo(c, **c.request.query_kwargs)\n self.assertEqual(1, r)\n\n def test_param_size(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', type=int, min_size=100)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **{'foo': 0})\n r = foo(c, **{'foo': 200})\n self.assertEqual(200, r)\n\n @endpoints.decorators.param('foo', type=int, max_size=100)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **{'foo': 200})\n r = foo(c, **{'foo': 20})\n self.assertEqual(20, r)\n\n @endpoints.decorators.param('foo', type=int, min_size=100, max_size=200)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n r = foo(c, **{'foo': 120})\n self.assertEqual(120, r)\n\n @endpoints.decorators.param('foo', type=str, min_size=2, max_size=4)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n r = foo(c, **{'foo': 'bar'})\n self.assertEqual('bar', r)\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **{'foo': 'barbar'})\n\n def test_param_lambda_type(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', type=lambda x: x.upper())\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n r = foo(c, **{'foo': 'bar'})\n self.assertEqual('BAR', r)\n\n def test_param_empty_default(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', default=None)\n def foo(self, *args, **kwargs):\n return kwargs.get('foo')\n r = foo(c, **{})\n self.assertEqual(None, r)\n\n def test_param_reference_default(self):\n c = create_controller()\n\n @param('foo', default={})\n def foo(self, *args, **kwargs):\n kwargs['foo'][testdata.get_ascii()] = testdata.get_ascii()\n return kwargs['foo']\n\n r = foo(c, **{})\n self.assertEqual(1, len(r))\n\n r = foo(c, **{})\n self.assertEqual(1, len(r))\n\n @endpoints.decorators.param('foo', default=[])\n def foo(self, *args, **kwargs):\n kwargs['foo'].append(testdata.get_ascii())\n return kwargs['foo']\n\n r = foo(c, **{})\n self.assertEqual(1, len(r))\n\n r = foo(c, **{})\n self.assertEqual(1, len(r))\n\n def test_param_regex(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', regex=r\"^\\S+@\\S+$\")\n def foo(self, *args, **kwargs):\n return kwargs['foo']\n\n r = foo(c, **{'foo': 'foo@bar.com'})\n\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **{'foo': ' foo@bar.com'})\n\n @endpoints.decorators.param('foo', regex=re.compile(r\"^\\S+@\\S+$\", re.I))\n def foo(self, *args, **kwargs):\n return kwargs['foo']\n\n r = foo(c, **{'foo': 'foo@bar.com'})\n\n with self.assertRaises(endpoints.CallError):\n r = foo(c, **{'foo': ' foo@bar.com'})\n\n def test_param_bool(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', type=bool, allow_empty=True)\n def foo(self, *args, **kwargs):\n return kwargs['foo']\n\n r = foo(c, **{'foo': 'true'})\n self.assertEqual(True, r)\n\n r = foo(c, **{'foo': 'True'})\n self.assertEqual(True, r)\n\n r = foo(c, **{'foo': '1'})\n self.assertEqual(True, r)\n\n r = foo(c, **{'foo': 'false'})\n self.assertEqual(False, r)\n\n r = foo(c, **{'foo': 'False'})\n self.assertEqual(False, r)\n\n r = foo(c, **{'foo': '0'})\n self.assertEqual(False, r)\n\n @endpoints.decorators.param('bar', type=bool, require=True)\n def bar(self, *args, **kwargs):\n return kwargs['bar']\n\n r = bar(c, **{'bar': 'False'})\n self.assertEqual(False, r)\n\n def test_param_list(self):\n c = create_controller()\n\n @endpoints.decorators.param('foo', type=list)\n def foo(self, *args, **kwargs):\n return kwargs['foo']\n\n r = foo(c, **{'foo': ['bar', 'baz']})\n self.assertEqual(r, ['bar', 'baz'])\n\n def test_param_arg(self):\n \"\"\"Make sure positional args work\"\"\"\n c = create_controller()\n\n @param(0)\n def foo(self, *args, **kwargs):\n return list(args)\n\n r = foo(c, 1)\n self.assertEqual([1], r)\n\n with self.assertRaises(CallError):\n foo(c)\n\n @param(0, type=str)\n @param(1, default=20, type=int)\n def foo(self, *args, **kwargs):\n return list(args)\n\n r = foo(c, 1)\n self.assertEqual([\"1\", 20], r)\n\n r = foo(c, 1, 2)\n self.assertEqual([\"1\", 2], r)\n\n @param(0, type=str)\n @param(1, default=20, type=int)\n @param(\"foo\", default=\"bar\")\n def foo(self, *args, **kwargs):\n r = list(args) + [kwargs[\"foo\"]]\n return r\n\n r = foo(c, 1, 2, foo=\"che\")\n self.assertEqual([\"1\", 2, \"che\"], r)\n\n r = foo(c, 1, foo=\"che\")\n self.assertEqual([\"1\", 20, \"che\"], r)\n\n r = foo(c, 1)\n self.assertEqual([\"1\", 20, \"bar\"], r)\n\n\nclass RouteTest(TestCase):\n def test_error(self):\n c = Server(contents=[\n \"from endpoints import Controller\",\n \"from endpoints.decorators import route\",\n \"class Foo(Controller):\",\n \" @route(lambda req: len(req.path_args) == 2)\",\n \" def GET_1(*args, **kwargs):\",\n \" pass\",\n \"\",\n \" @route(lambda req: len(req.path_args) == 3)\",\n \" def GET_2(*args, **kwargs):\",\n \" pass\",\n ])\n\n res = c.handle(\"/foo\")\n self.assertEqual(405, res.code)\n\n def test_path_route(self):\n c = Server(contents=[\n \"from endpoints import Controller\",\n \"from endpoints.decorators import route_path\",\n \"class Foo(Controller):\",\n \" @route_path('bar')\",\n \" def GET_1(*args, **kwargs):\",\n \" return 'bar'\",\n \"\",\n \" @route_path('che')\",\n \" def GET_2(*args, **kwargs):\",\n \" return 'che'\",\n ])\n\n res = c.handle(\"/foo/che\")\n self.assertEqual(\"che\", res.body)\n\n res = c.handle(\"/foo/bar\")\n self.assertEqual(\"bar\", res.body)\n\n res = c.handle(\"/foo\")\n self.assertEqual(405, res.code)\n\n res = c.handle(\"/foo/baz\")\n self.assertEqual(405, res.code)\n\n def test_param_route_keys(self):\n c = Server(contents=[\n \"from endpoints import Controller\",\n \"from endpoints.decorators import route_param\",\n \"class Foo(Controller):\",\n \" @route_param('bar')\",\n \" def GET_1(*args, **kwargs):\",\n \" return 'bar'\",\n \"\",\n \" @route_param('che')\",\n \" def GET_2(*args, **kwargs):\",\n \" return 'che'\",\n ])\n\n res = c.handle(\"/foo\", query_kwargs={\"che\": 1})\n self.assertEqual(\"che\", res.body)\n\n res = c.handle(\"/foo\", query_kwargs={\"bar\": 1})\n self.assertEqual(\"bar\", res.body)\n\n res = c.handle(\"/foo\")\n self.assertEqual(400, res.code)\n\n res = c.handle(\"/foo\", query_kwargs={\"baz\": 1})\n self.assertEqual(400, res.code)\n\n def test_param_route_matches(self):\n c = Server(contents=[\n \"from endpoints import Controller\",\n \"from endpoints.decorators import route_param\",\n \"class Foo(Controller):\",\n \" @route_param(bar=1)\",\n \" def GET_1(*args, **kwargs):\",\n \" return 1\",\n \"\",\n \" @route_param(bar=2)\",\n \" def GET_2(*args, **kwargs):\",\n \" return 2\",\n ])\n\n res = c.handle(\"/foo\", query_kwargs={\"bar\": 1})\n self.assertEqual(1, res.body)\n\n res = c.handle(\"/foo\", query_kwargs={\"bar\": 2})\n self.assertEqual(2, res.body)\n\n res = c.handle(\"/foo\")\n self.assertEqual(400, res.code)\n\n res = c.handle(\"/foo\", query_kwargs={\"baz\": 1})\n self.assertEqual(400, res.code)\n\n def test_simple(self):\n c = Server(contents=[\n \"from endpoints import Controller\",\n \"from endpoints.decorators import route\",\n \"class Foo(Controller):\",\n \" @route(lambda req: len(req.path_args) == 1)\",\n \" def GET_1(*args, **kwargs):\",\n \" return len(args)\",\n \"\",\n \" @route(lambda req: len(req.path_args) == 2)\",\n \" def GET_2(*args, **kwargs):\",\n \" return len(args)\",\n \"\",\n \" @route(lambda req: len(req.path_args) == 3)\",\n \" def GET_3(*args, **kwargs):\",\n \" return len(args)\",\n \"\",\n \" def POST(*args, **kwargs):\",\n \" return 4\",\n ])\n\n res = c.handle(\"/foo\")\n self.assertEqual(1, res._body)\n\n res = c.handle(\"/foo/2\")\n self.assertEqual(2, res._body)\n\n res = c.handle(\"/foo/2/3\")\n self.assertEqual(3, res._body)\n\n res = c.handle(\"/foo\", \"POST\")\n self.assertEqual(4, res._body)\n\n def test_extend_1(self):\n c = Server(contents=[\n \"from endpoints import Controller\",\n \"from endpoints.decorators import route\",\n \"\",\n \"class Foo1(Controller):\",\n \" def GET(self): return 1\",\n \" def POST(*args, **kwargs): return 5\",\n \"\"\n \"class Foo2(Foo1):\",\n \" GET = None\",\n \" @route(lambda req: len(req.path_args) == 1)\",\n \" def GET_1(self): return super(Foo2, self).GET()\",\n \" @route(lambda req: len(req.path_args) == 2)\",\n \" def GET_2(*args, **kwargs): return len(args)\",\n \"\",\n \"class Foo3(Foo2):\",\n \" @route(lambda req: len(req.path_args) == 3)\",\n \" def GET_3(*args, **kwargs): return len(args)\",\n \"\",\n \"class Foo4(Foo3):\",\n \" @route(lambda req: len(req.path_args) == 4)\",\n \" def GET_4(*args, **kwargs): return len(args)\",\n ])\n\n for path in [\"/foo1\", \"/foo2\", \"/foo3\", \"/foo4\"]:\n res = c.handle(path)\n self.assertEqual(1, res._body)\n\n for path in [\"/foo2/2\", \"/foo3/2\", \"/foo4/2\"]:\n res = c.handle(path)\n self.assertEqual(2, res._body)\n\n res = c.handle(\"/foo1/2\")\n self.assertEqual(405, res.code)\n\n for path in [\"/foo3/2/3\", \"/foo4/2/3\"]:\n res = c.handle(path)\n self.assertEqual(3, res._body)\n\n res = c.handle(\"/foo1/2/3\")\n self.assertEqual(405, res.code)\n res = c.handle(\"/foo2/2/3\")\n self.assertEqual(405, res.code)\n\n for path in [\"/foo1/2/3/4\", \"/foo2/2/3/4\", \"/foo3/2/3/4\"]:\n res = c.handle(path)\n self.assertEqual(405, res.code)\n\n res = c.handle(\"/foo4/2/3/4\")\n self.assertEqual(4, res._body)\n\n for path in [\"/foo1\", \"/foo2\", \"/foo3\", \"/foo4\"]:\n res = c.handle(path, \"POST\")\n self.assertEqual(5, res._body)\n\n def test_extend_2(self):\n c = Server(contents=[\n \"from endpoints import Controller\",\n \"from endpoints.decorators import route\",\n \"\",\n \"class Foo1(Controller):\",\n \" def GET(self): return 1\",\n \" def POST(*args, **kwargs): return 5\",\n \"\"\n \"class Foo2(Foo1):\",\n \" @route(lambda req: len(req.path_args) == 2)\",\n \" def GET_2(*args, **kwargs): return len(args)\",\n ])\n\n res = c.handle(\"/foo1\")\n self.assertEqual(1, res._body)\n\n res = c.handle(\"/foo2\")\n self.assertEqual(500, res.code)\n\n def test_mixed(self):\n \"\"\"make sure plays nice with param\"\"\"\n c = Server(contents=[\n \"from endpoints import Controller\",\n \"from endpoints.decorators import route, param\",\n \"class Foo(Controller):\",\n \" @route(lambda req: len(req.path_args) == 1)\",\n \" @param('bar')\",\n \" def GET_1(*args, **kwargs):\",\n \" return len(args)\",\n \"\",\n \" @param('bar')\",\n \" @route(lambda req: len(req.path_args) == 2)\",\n \" def GET_2(*args, **kwargs):\",\n \" return len(args)\",\n \"\",\n ])\n\n res = c.handle(\"/foo\")\n self.assertEqual(400, res.code)\n res = c.handle(\"/foo\", query=\"bar=1\")\n self.assertEqual(1, res._body)\n\n res = c.handle(\"/foo/2\")\n self.assertEqual(400, res.code)\n res = c.handle(\"/foo/2\", query=\"bar=1\")\n self.assertEqual(2, res._body)\n\n\nclass VersionTest(TestCase):\n def test_simple(self):\n controller_prefix = \"version_simple\"\n c = Server(controller_prefix, [\n \"from endpoints import Controller\",\n \"from endpoints.decorators import version\",\n \"class Foo(Controller):\",\n \" @version('', 'v1')\",\n \" def GET_1(self):\",\n \" return 1\",\n \"\",\n \" @version('v2')\",\n \" def GET_2(self):\",\n \" return 2\",\n ])\n\n res = c.handle(\"/foo\", version=\"v1\")\n self.assertEqual(1, res._body)\n\n res = c.handle(\"/foo\", version=\"\")\n self.assertEqual(1, res._body)\n\n res = c.handle(\"/foo\")\n self.assertEqual(1, res._body)\n\n res = c.handle(\"/foo\", version=\"v2\")\n self.assertEqual(2, res._body)\n\n res = c.handle(\"/foo\", version=\"v3\")\n self.assertEqual(405, res.code)\n\n def test_complex(self):\n controller_prefix = \"version_complex\"\n c = Server(controller_prefix, [\n \"from endpoints import Controller\",\n \"from endpoints.decorators import version, route\",\n \"\",\n \"class Foo(Controller):\",\n \" @version('v1')\",\n \" @route(lambda req: len(req.path_args) == 1)\",\n \" def GET_1_v1(self):\",\n \" return 1\",\n \"\",\n \" @version('v2')\",\n \" @route(lambda req: len(req.path_args) == 1)\",\n \" def GET_1_v2(self):\",\n \" return 12\",\n \"\",\n \" @route(lambda req: len(req.path_args) == 2)\",\n \" @version('v1')\",\n \" def GET_2_v1(self, bit):\",\n \" return 2\",\n \"\",\n \" @route(lambda req: len(req.path_args) == 2)\",\n \" @version('v2')\",\n \" def GET_2_v2(self, bit):\",\n \" return 22\",\n ])\n\n res = c.handle(\"/foo\", version=\"v1\")\n self.assertEqual(1, res._body)\n res = c.handle(\"/foo\", version=\"v2\")\n self.assertEqual(12, res._body)\n\n res = c.handle(\"/foo/2\", version=\"v1\")\n self.assertEqual(2, res._body)\n res = c.handle(\"/foo/2\", version=\"v2\")\n self.assertEqual(22, res._body)\n\n\nclass CodeErrorTest(TestCase):\n def test_raise(self):\n controller_prefix = \"ce_raise\"\n c = Server(controller_prefix, [\n \"from endpoints import Controller\",\n \"from endpoints.decorators import code_error, param\",\n \"\",\n \"class Foo(Controller):\",\n \" @code_error(330, ValueError, IndexError)\",\n \" @param(0, metavar='error_type', choices=['value', 'index', 'another'])\",\n \" def GET(self, error_type):\",\n \" if error_type.startswith('value'):\",\n \" raise ValueError()\",\n \" elif error_type.startswith('index'):\",\n \" raise IndexError()\",\n \" else:\",\n \" raise RuntimeError()\",\n ])\n\n res = c.handle(\"/foo/value\")\n self.assertEqual(330, res.code)\n\n res = c.handle(\"/foo/index\")\n self.assertEqual(330, res.code)\n\n res = c.handle(\"/foo/another\")\n self.assertEqual(500, res.code)\n\n res = c.handle(\"/foo/bar\")\n self.assertEqual(400, res.code)\n\n","sub_path":"tests/decorators_test.py","file_name":"decorators_test.py","file_ext":"py","file_size_in_byte":44749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"562403356","text":"from fuzzywuzzy import process as fuzzy\nfrom importlib import import_module\n\nfrom lib import Error\nfrom lib.settings import SETTINGS\nfrom lib.automate.pool import ModelPool\n\n\nclass Automate:\n def __init__(self):\n \"\"\" Register new modules here \"\"\"\n self._modules = [\n import_module(\"lib.automate.modules.send\").Send,\n import_module(\"lib.automate.modules.schedule\").Schedule,\n import_module(\"lib.automate.modules.remove_schedule\").RemoveSchedule,\n import_module(\"lib.automate.modules.update_schedule\").UpdateSchedule,\n import_module(\"lib.automate.modules.reminder\").Reminder,\n ]\n self.response_callback = None\n self.loaded_modules = []\n self.modules = []\n self.verbs = []\n self.pool = ModelPool([SETTINGS[\"nlp_models\"][\"ner\"]])\n\n for module in self._modules:\n self.verbs.extend(module.verbs)\n self.modules.append((module.verbs, module))\n\n def _load_module(self, module_name):\n fuzzy_match, score = fuzzy.extractOne(module_name, self.get_verbs())\n\n if score > 30:\n # Checks if module is loaded and if so returns it\n for verbs, module in self.loaded_modules:\n if fuzzy_match in verbs:\n return module\n\n # If module not yet loaded, init it and mark it as loaded\n for verbs, module in self.modules:\n if fuzzy_match in verbs:\n loaded = module(self.pool)\n self.loaded_modules.append((verbs, loaded))\n return loaded\n\n raise AutomationNotFoundError(\"Automation module not found\")\n\n else:\n raise AutomationNotFoundError(\"Automation module not found\")\n\n def get_verbs(self):\n \"\"\"\n :return: A list of keywords for all of the registered automation modules.\n :rtype: list[string]\n \"\"\"\n return self.verbs\n\n def get_senders(self):\n \"\"\"\n :return: A list of names of the users listed in the SETTINGS.\n :rtype: list[string]\n \"\"\"\n return list(SETTINGS[\"users\"].keys())\n\n def prepare(self, module_name, text):\n \"\"\"\n Prepares the text on the module such that the task is ready to be executed.\n\n :param module_name: Something close to a keyword of a automation\n module. This is handled via fuzzy search.\n :type module_name: string\n :param text: The text to interpret.\n :type text: string\n :return: Returns the instance of the module or a followup if information is missing.\n \"\"\"\n\n sender = SETTINGS[\"user\"]\n\n def handle_response(response):\n if response:\n return handle_response(response.handle_cli())\n else:\n return instance\n\n instance = self._load_module(module_name)\n\n followup = instance.prepare(SETTINGS[\"nlp_models\"], text, sender)\n\n if self.response_callback:\n return self.response_callback(text, instance, followup)\n return handle_response(followup)\n\n\nclass NoResponseError(Error):\n pass\n\n\nclass AutomationNotFoundError(Error):\n pass\n","sub_path":"lib/automate/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"562461474","text":"# group_lists.py\n\n# read all files from a directory\n# assumption: all files are named using convention [attribute].txt and contain single column with identities and no header\n# input: path to input directory, output dir\n# output: grouping file, clustering object\n\n# TODO: provide optional mapping file as input which defines manual groups to create but still generate distance metrics\n# for the scenario where lists might be grouped by common labels (new script?)\n\nfrom pathlib import Path\nimport sys\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom scipy.spatial.distance import cdist\nfrom joblib import dump, load\n\n# input_dir = \"/Users/dfackler/Desktop/lol_training_data/Animals_with_Attributes2/prepped_python\"\n# output_file = \"/Users/dfackler/Desktop/lol_training_data/Animals_with_Attributes2/grouped_python\"\n##############################################\n#### Read args and check files ####\n##############################################\n# TODO: source helper script\n\ninput_dir = Path(str(sys.argv[1]))\noutput_dir = Path(str(sys.argv[2]))\n\nif not input_dir.exists():\n print(\"Input path provided does not exist. Exiting.\\n\" +\n \"Input path: \" + input_dir)\n exit(1)\nfiles_to_read = os.listdir(input_dir)\nif len(files_to_read) == 0:\n print(\"Directory is empty. Exiting.\")\n exit(1)\nif not output_dir.exists():\n output_dir.mkdir()\n\n##############################################\n#### Read in files ####\n##############################################\n# read in files to list and track unique identities\n\n\n# read files into dictionary\ndef read_in_lol(files_to_read, input_dir):\n files_to_read = os.listdir(input_dir)\n lol = []\n headers = [\"ids\"]\n dtypes = {\"ids\": \"str\"}\n for file in files_to_read:\n tmp = pd.read_csv(input_dir / file, sep=\"\\t\",\n header=None, names=headers, dtype=dtypes).ids.to_numpy()\n lol.append(tmp)\n unique_ids = list(set([item for sublist in lol for item in sublist]))\n return lol, unique_ids\n\n\nlol, unique_ids = read_in_lol(files_to_read, input_dir)\n\n##############################################\n#### Convert to dataframe with binary columns ####\n##############################################\n# TODO: add sampling for when data gets big?\n# TODO: move to sparse matrix for when data gets big?\n\n\ndef lol_to_table(lol, unique_ids, files_to_read):\n # get boolean column for each entry in lol for which indices of unique_ids match to it\n def bool_cols(x): return np.isin(unique_ids, x)\n bools = [bool_cols(item) for item in lol]\n bool_df = pd.DataFrame(bools, columns=unique_ids)\n # set index to be file names\n bool_df[\"files\"] = files_to_read\n bool_df.set_index(\"files\", inplace=True)\n return bool_df\n\n\nid_df = lol_to_table(lol, unique_ids, files_to_read)\n\nprint(\"Total number of identities: \" + str(id_df.shape[0]))\nprint(\"Total number of files: \" + str(id_df.shape[1]))\n\n##############################################\n#### Set groups ####\n##############################################\n# check diff k values\ninertia = []\n# TODO: make min and max cluster options optional parameters\nmin_k = 5\nmax_k = 20\nK = range(min(1, min_k-1), max_k+3)\nfor k in K:\n kmeanModel = KMeans(n_clusters=k).fit(id_df)\n kmeanModel.fit(id_df)\n inertia.append(kmeanModel.inertia_)\n\n# https://www.datasciencecentral.com/profiles/blogs/how-to-automatically-determine-the-number-of-clusters-in-your-dat\n# find optimal k based on highest strength elbow\n# compute first and second degree delta between k and k+1\n# consider strength of elbow by difference between d2 and d1 at point after elbow\n# select highest strength elbow as best k guess\n# TODO: improve this by handling large clusters and making sure cluster groups balance specificity with strength\ndiff1 = np.diff(inertia, 1)\ndiff2 = np.diff(diff1, 1)\nd2_elbow_inds = np.reshape(np.nonzero(diff2 < 0), -1)\n# don't allow max K value as elbow because unable to compute diff\nd2_elbow_inds = d2_elbow_inds[d2_elbow_inds < (max_k-min_k)]\nstrength = []\nfor i in d2_elbow_inds:\n strength.append(diff2[i+1] - diff1[i+2])\nstrength = np.asarray(strength)\nrelative_strength = strength/len(inertia)\n# to get from d2_elbow_ind to related k value add min_k+3\nbest_k_guess = int(d2_elbow_inds[np.argmax(strength)]+min_k+3)\n\nprint(\"Elbow Points Between Min and Max K:\")\nprint(d2_elbow_inds + min_k + 3)\nprint(\"Relative Strengths:\")\nprint(relative_strength)\nprint(\"Best K Guess: \" + str(best_k_guess))\n\n# create dataframe of identities and groups of different values\nkmeans = KMeans(n_clusters=best_k_guess, random_state=123).fit(id_df)\nfile_groups = kmeans.predict(id_df)\ngrouping_df = pd.DataFrame({\"file\": id_df.index.values, \"group\": file_groups})\n\n##############################################\n#### Provide outputs ####\n##############################################\ngrouping_df.to_csv(output_dir / \"grouping_file.txt\", sep='\\t',\n index=None)\nprint(\"Grouping file written to: \" + str(output_dir / \"grouping_file.txt\"))\ndump(kmeans, output_dir / \"km.joblib\")\nprint(\"Kmeans object written to: \" + str(output_dir / \"km.joblib\"))\nprint(\"Best K guess: \" + str(best_k_guess))\nprint(\"Grouping counts:\")\nprint(grouping_df.groupby('group').count())\n","sub_path":"group_lists.py","file_name":"group_lists.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"579360922","text":"# Demo for Maker Pi RP2040 board using Ping sensor\nfrom machine import Pin, PWM, Timer\nimport utime\nimport urandom\nfrom neopixel import Neopixel\n\n# Adjust these parameters to tune the collision avoidance behavior\n\nPOWER_LEVEL = 35000\nTURN_DISTANCE = 20 # distnce we decide to turn - try 20\nREVERSE_TIME = .4 # how long we backup\nTURN_TIME = .4 # how long we turn\n\n# startup mode is 0 - motors off and LEDs flashing\n# mode 1 is slow\n# mode 2 is medium\n# mode 3 is fast\nmode = 0\n\n# Use the Grove 4 Connector and put trigger on white and echo on yellow\nTRIGGER_PIN = 16 # With USB on the top, this pin is the bottom left corner\nECHO_PIN = 17 # One up from bottom left corner\n\n# Init HC-SR04P pins\ntrigger = Pin(TRIGGER_PIN, Pin.OUT) # send trigger out to sensor\necho = Pin(ECHO_PIN, Pin.IN) # get the delay interval back\n\nfaster_pin = machine.Pin(20, machine.Pin.IN, machine.Pin.PULL_DOWN)\nslower_pin = machine.Pin(21, machine.Pin.IN, machine.Pin.PULL_DOWN)\n\nlast_time = 0 # the last time we pressed the button\n\n# This function gets called every time the button is pressed. The parameter \"pin\" is not used.\ndef button_pressed_handler(pin):\n global mode, last_time\n new_time = utime.ticks_ms()\n # if it has been more that 1/5 of a second since the last event, we have a new event\n if (new_time - last_time) > 200:\n # this should be pin.id but it does not work\n if '20' in str(pin):\n mode +=1\n else:\n mode -=1\n # deal with ends\n if mode > 4: mode = 2\n if mode < 0: mode = 0\n last_time = new_time\n\n# now we register the handler function when the button is pressed\nfaster_pin.irq(trigger=machine.Pin.IRQ_FALLING, handler = button_pressed_handler)\nslower_pin.irq(trigger=machine.Pin.IRQ_FALLING, handler = button_pressed_handler)\n\n# Piezo Buzzer is on GP22\nbuzzer=PWM(Pin(22))\n\nMAX_POWER_LEVEL = 65025\n\nMAX_DISTANCE = 100 # ignore anything above this\n\n# Motor Pins are A: 8,9 and B: 10,11\nRIGHT_FORWARD_PIN = 11\nRIGHT_REVERSE_PIN = 10\nLEFT_FORWARD_PIN = 9\nLEFT_REVERSE_PIN = 8\n\n# our PWM objects\nright_forward = PWM(Pin(RIGHT_FORWARD_PIN))\nright_reverse = PWM(Pin(RIGHT_REVERSE_PIN))\nleft_forward = PWM(Pin(LEFT_FORWARD_PIN))\nleft_reverse = PWM(Pin(LEFT_REVERSE_PIN))\n\n# returns distance in cm\ndef ping():\n print('in ping')\n trigger.low()\n utime.sleep_us(2) # Wait 2 microseconds low\n trigger.high()\n utime.sleep_us(5) # Stay high for 5 miroseconds\n trigger.low()\n while echo.value() == 0:\n signaloff = utime.ticks_us()\n print('echo is 1')\n while echo.value() == 1:\n signalon = utime.ticks_us()\n timepassed = signalon - signaloff\n distance = (timepassed * 0.0343) / 2\n print(distance)\n return int(distance)\n\ndef turn_motor_on(pwm):\n pwm.duty_u16(65025)\n\ndef turn_motor_off(pwm):\n pwm.duty_u16(0)\n\ndef forward():\n turn_motor_on(right_forward)\n turn_motor_on(left_forward)\n turn_motor_off(right_reverse)\n turn_motor_off(left_reverse)\n\ndef reverse():\n turn_motor_on(right_reverse)\n turn_motor_on(left_reverse)\n turn_motor_off(right_forward)\n turn_motor_off(left_forward)\n\ndef turn_right():\n turn_motor_on(right_forward)\n turn_motor_on(left_reverse)\n turn_motor_off(right_reverse)\n turn_motor_off(left_forward)\n\ndef turn_left():\n turn_motor_on(right_reverse)\n turn_motor_on(left_forward)\n turn_motor_off(right_forward)\n turn_motor_off(left_reverse)\n\ndef stop():\n turn_motor_off(right_forward)\n turn_motor_off(right_reverse)\n turn_motor_off(left_forward)\n turn_motor_off(left_reverse)\n\n# The Maker Pi RP2040 has 13 fantastic blue GPIO status LEDs\n# remove 16 and 17 since the are used for the ping sensor\nblue_led_pins = [0, 1, 2, 3, 4, 5, 6, 7, 26, 27, 28]\n# dist_scale = [2, 4, 6, 8, 10, 13, 16, 20, 25, 35, 50, 75, 100]\ndist_scale = [2, 4, 6, 8, 10, 15, 20, 25, 50, 100, 150, 200, 300]\n\nNUMBER_PIXELS = 2\nSTATE_MACHINE = 0\nNEOPIXEL_PIN = 18\n\n# The Neopixels on the Maker Pi RP2040 are the GRB variety, not RGB\nstrip = Neopixel(NUMBER_PIXELS, STATE_MACHINE, NEOPIXEL_PIN, \"GRB\")\nstrip.brightness(100)\n\nnumber_leds = len(blue_led_pins)\nled_ports = []\nred = (255, 0, 0)\norange = (255, 60, 0) # Gamma corrected from G=128 to be less like yellow\nyellow = (255, 150, 0)\ngreen = (0, 255, 0)\nblue = (0, 0, 255)\nindigo = (75, 0, 130) # purple?\nviolet = (138, 43, 226) # mostly pink\ncyan = (0, 255, 255)\nlightgreen = (100, 255, 100)\nwhite = (128, 128, 128) # not too bright\npink = (255, 128, 128)\ncolor_names = ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet', 'cyan', 'lightgreen', 'white')\nnum_colors = len(color_names)\ncolors = (red, orange, yellow, green, blue, indigo, violet, cyan, lightgreen, white, pink)\n\n# create a list of the ports\nfor i in range(number_leds):\n led_ports.append(machine.Pin(blue_led_pins[i], machine.Pin.OUT))\n\nLED_DELAY = .08\ndef run_lights():\n for i in range(0, number_leds):\n led_ports[i].high()\n strip.set_pixel(0, colors[i])\n strip.set_pixel(1, colors[i])\n strip.show()\n utime.sleep(LED_DELAY)\n led_ports[i].low()\n # blue down\n for i in range(number_leds - 1, 0, -1):\n led_ports[i].high()\n strip.set_pixel(0, colors[i])\n strip.set_pixel(1, colors[i])\n strip.show()\n utime.sleep(LED_DELAY)\n led_ports[i].low()\n\ndef led_show_dist(in_distance):\n global number_leds\n for led_index in range(0, number_leds):\n if in_distance > dist_scale[led_index]:\n led_ports[led_index].high()\n else:\n led_ports[led_index].low()\n\ndef play_no_signal():\n playnote(100, 0.1)\n sound_off()\n\ndef play_turn():\n playnote(500, .1)\n sound_off()\n\ndef setfreq(frequency):\n buzzer.freq(frequency)\n\ndef playnote(frequency, time):\n buzzer.duty_u16(1000)\n setfreq(frequency)\n utime.sleep(time)\n \ndef sound_off():\n buzzer.duty_u16(0)\n\ndef rest(time):\n buzzer.duty_u16(0)\n utime.sleep(time)\n \ndef play_startup():\n #playnote(600, 0.2)\n rest(.05)\n #playnote(600, 0.2)\n rest(.05)\n #playnote(600, 0.2)\n rest(.1)\n #playnote(800, 0.4)\n sound_off()\n \nvalid_distance = 1\n# loop forever\ndef main():\n global valid_distance\n print(\"running main()\")\n \n play_startup()\n \n while True:\n if mode == 0:\n stop()\n run_lights()\n else:\n distance = ping()\n print('Distance:', distance)\n if distance > MAX_DISTANCE:\n # only print if we used to have a valid distance\n if valid_distance == 1:\n print('no signal') \n valid_distance = 0\n else:\n print(distance)\n if distance < TURN_DISTANCE:\n play_turn()\n # back up for a bit\n reverse()\n utime.sleep(REVERSE_TIME)\n # half right and half left turns\n if urandom.random() < .5:\n turn_right()\n else:\n turn_left()\n utime.sleep(TURN_TIME)\n forward()\n else:\n print('forward')\n forward()\n valid_distance = 1\n led_show_dist(distance)\n utime.sleep(0.05)\n\n# clean up\n\n# This allows us to stop the sound by doing a Stop or Control-C which is a keyboard intrrup\ntry:\n main()\nexcept KeyboardInterrupt:\n print('Got ctrl-c')\nfinally:\n # Optional cleanup code\n print('turning off sound')\n buzzer.duty_u16(0)\n print('shutting motors down')\n stop()","sub_path":"src/kits/maker-pi-rp2040/collision-avoidance-ping.py","file_name":"collision-avoidance-ping.py","file_ext":"py","file_size_in_byte":7682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"451147430","text":"class Item(object):\n def __init__(self, n, v, w):\n self.name = n\n self.value = v\n self.weight = w\n\n def get_name(self):\n return self.name\n\n def get_value(self):\n return self.value\n\n def get_weight(self):\n return self.weight\n\n def __str__(self):\n result = '<' + self.name + ', ' + str(self.value) + ', ' + str(self.weight) + '>'\n return result\n\n\ndef decision_tree(to_consider, avail, memo={}):\n \"\"\"to_consider は品物のリスト, avail は重さ\n memo は再帰位呼び出しによってのみ使われるとする\n それらをパラメータとする0/1ナップサック問題の解である、総価値と品物の\n リストからなるタプルを返す\"\"\"\n\n if(len(to_consider), avail) in memo:\n result = memo[(len(to_consider)), avail]\n elif to_consider == [] or avail == 0:\n result = (0, ())\n elif to_consider[0].get_weight() > avail:\n result = decision_tree(to_consider[1:], avail, memo)\n else:\n next_item = to_consider[0]\n with_val, with_to_take = decision_tree(to_consider[1:], avail - next_item.get_weight(), memo)\n with_val += next_item.get_value()\n\n without_val, without_to_take = decision_tree(to_consider[1:], avail, memo)\n\n if with_val > without_val:\n result = (with_val, with_to_take + (next_item,))\n else:\n result = (without_val, without_to_take)\n memo[(len(to_consider), avail)] = result\n return result\n\nimport random\ndef small_test():\n names = ['a', 'b', 'c', 'd']\n vals = [6, 7, 8, 9]\n weights = [3, 3, 2, 5]\n items = []\n for i in range(len(vals)):\n items.append(Item(names[i], vals[i], weights[i]))\n val, taken = decision_tree(items, 5)\n for item in taken:\n print(item)\n print('Total value of items taken =', val)\n\ndef build_many_items(num_items, max_val, max_weight):\n items = []\n for i in range(num_items):\n items.append(Item(str(i), random.randint(1, max_val), random.randint(1, max_weight)))\n return items\n\ndef big_test(num_items):\n items = build_many_items(num_items, 10, 10)\n val, taken = decision_tree(items, 40)\n print('Items taken')\n for item in taken:\n print(item)\n print('Total value of items taken =', val)\n\n\nbig_test(256)\n","sub_path":"c13/decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"366563613","text":"from __future__ import print_function\n\nimport json\nimport urllib\nimport boto3\nimport httplib\n\n\ndb = boto3.client('dynamodb')\nssm = boto3.client('ssm')\n\n\ndef get_config_value(key, default=None):\n response = ssm.get_parameter(Name=key, WithDecryption=False)\n print(\"response: {}\".format(response))\n if 'Parameter' in response:\n return response['Parameter'].get('Value') or default\n\n return default\n\n\ndef lookup_user_list(slack_token):\n print(\"looking up user list\")\n c = httplib.HTTPSConnection('slack.com')\n headers = {\n 'Authorization': 'Bearer {}'.format(slack_token),\n }\n c.request('GET', '/api/users.list',\n headers=headers)\n r = c.getresponse()\n data = r.read()\n c.close()\n\n user_list = {}\n j = json.loads(data)\n if 'members' in j:\n for m in j['members']:\n user_list[m['name']] = m['id']\n\n return user_list\n\n\ndef send_slack_message(payload, slack_token):\n print(\"send slack message: {}, token: {}\".format(payload, slack_token))\n c = httplib.HTTPSConnection('slack.com')\n headers = {\n 'Authorization': 'Bearer {}'.format(slack_token),\n 'Content-type': 'application/json; charset=utf8',\n }\n c.request('POST', '/api/chat.postMessage',\n body=json.dumps(payload),\n headers=headers)\n r = c.getresponse()\n data = r.read()\n print(\"data: {}\".format(data))\n c.close()\n\n\ndef notify_slack_channel(channel_id, message, slack_token):\n payload = {\n 'channel': '#{}'.format(channel_id),\n 'text': message,\n }\n send_slack_message(payload, slack_token)\n\n\ndef notify_slack_user(user_id, message, slack_token):\n payload = {\n 'channel': user_id,\n 'text': message,\n }\n send_slack_message(payload, slack_token)\n\n\ndef lambda_handler(event, context):\n print(\"Received event: \" + json.dumps(event, indent=2))\n\n slack_channels = get_config_value('CSVNotifySlackChannels', default='').split(',')\n #print(\"slack_channels: {}\".format(slack_channels))\n slack_users = get_config_value('CSVNotifySlackUsers', default='').split(',')\n #print(\"slack_users: {}\".format(slack_users))\n slack_token = get_config_value('CSVNotifySlackToken', default='xyz')\n #print(\"slack_token: {}\".format(slack_token))\n\n file = str(event['Records'][0]['dynamodb']['NewImage']['Name']['S'])\n #print(\"file: {}\".format(file))\n status = str(event['Records'][0]['dynamodb']['NewImage']['Status']['S'])\n #print(\"status: {}\".format(status))\n\n # send status of run to Slack\n message = \"Processing run for CSV file {} completed with status: {}\".format(file, status)\n #print(\"message: {}\".format(message))\n for c in slack_channels:\n notify_slack_channel(c, message, slack_token)\n user_list = lookup_user_list(slack_token)\n #print(\"user_list: {}\".format(user_list))\n for u in slack_users:\n uid = user_list.get(u)\n #print(\"uid: {}\".format(uid))\n if uid:\n notify_slack_user(uid, message, slack_token)\n else:\n print(\"User not found for name {}\".format(u))\n","sub_path":"lambda-functions/handle-record/handle_record.py","file_name":"handle_record.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"253208239","text":"import skimage.external.tifffile as tifffile\nimport pandas as pd\nimport numpy as np\nimport os\nimport torch\nimport requests\nfrom PIL import Image\n\nfrom fnet.data.fnetdataset import FnetDataset\n\n\nclass HPAOnlineDataset(FnetDataset):\n \"\"\"Dataset for images from the Human Protein Atlas.\n\n Currently assumes that images are loaded in ZCXY format\n\n \"\"\"\n\n def __init__(self, path_csv: str = None,\n is_train=True,\n train_split=0.9,\n channel_signal=None,\n channel_target=None,\n transform_signal=None,\n transform_target=None):\n path_csv = path_csv or 'https://dl.dropbox.com/s/k9ekd4ff3fyjbfk/umap_results_fit_all_transform_all_sorted_20190422.csv'\n self.df = pd.read_csv(path_csv)\n # filter out invalid rows\n self.df = self.df[self.df['id'].str.contains(\"_\")]\n self.train_split = train_split\n train_split_count = int(len(self.df)*train_split)\n self.is_train = is_train\n if is_train:\n self.df = self.df[:train_split_count]\n else:\n self.df = self.df[train_split_count:]\n \n super().__init__(self.df, None, transform_signal, transform_target)\n\n self.channel_signal = channel_signal or ['blue', 'red']\n self.channel_target = channel_signal or ['green']\n self.index_dict = {'red': 0, 'green': 1, 'blue': 2}\n self.root_url = 'http://v18.proteinatlas.org/images/'\n self.data_dir = './hpav18-data'\n \n if not os.path.exists(self.data_dir):\n os.makedirs(self.data_dir)\n assert all(i in self.df.columns for i in ['id'])\n\n def __getitem__(self, index):\n element = self.df.iloc[index, :]\n has_target = self.channel_target and len(self.channel_target)>0\n img = element['id'].split('_')\n colors = self.channel_signal + self.channel_target\n im_out = []\n for color in colors:\n img_path = img[0] + '/' + \"_\".join(img[1:]) + \"_\" + color + \".jpg\"\n img_name = element['id'] + \"_\" + color + \".jpg\"\n img_url = self.root_url + img_path\n file_path = os.path.join(self.data_dir, img_name)\n if not os.path.exists(file_path):\n r = requests.get(img_url, allow_redirects=True)\n open(file_path, 'wb').write(r.content)\n\n im_tmp = np.array(Image.open(file_path))[:,:,self.index_dict[color]]\n im_out.append(im_tmp)\n\n if self.transform_signal is not None:\n for t in self.transform_signal:\n for i in range(len(self.channel_signal)):\n im_out[i] = t(im_out[i])\n\n offset = len(self.channel_signal)\n if has_target and self.transform_target is not None:\n for t in self.transform_target:\n for i in range(self.channel_target):\n im_out[offset+i] = t(im_out[offset+i])\n\n im_out = [torch.from_numpy(im.astype(float)).float() for im in im_out]\n\n if has_target:\n return torch.stack(im_out[: offset]), torch.stack(im_out[offset:])\n else:\n return torch.stack(im_out[: offset])\n\n def __len__(self):\n return len(self.df)\n\n def get_information(self, index: int) -> dict:\n return self.df.iloc[index, :].to_dict()\n","sub_path":"fnet/data/hpaonlinedataset.py","file_name":"hpaonlinedataset.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"613958784","text":"'''\nEdit this file to complete the exercises in\n'Efficiently Storing and Accessing Data'\n'''\n\n#####################################################\n#Some setup, creating a list and dictionary to be\n#used in some of the exercises:\nimport fibo\nimport demodict\nfibolist = fibo.nacci(50)\ndemodict1 = demodict.generate_dict()\n#####################################################\n\n#####Lists!#####\n\n#Just to get you going, here's the answer to\n#the first exercise:\nmaybe_your_first_list = [1, 2, 3, 4, 5]\n\n# Find the last element of fibolist:\nfibolist_last = None\n\n# Find the sum of all even entries (indices 0, 2, 4,...) of fibolist:\nfibolist_even_entries_sum = None\n\n# Lists can be extended. The next fibonacci number is 20365011074, add it to fibolist.\n\n# Can you put a reversed copy of fibolist into fibolist_reversed without changing fibolist in place?\nfibolist_reversed = None\n\nA = [1, 2, 3, 4, 5]\nB = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n# Two lists can be concatenated with +. Concatenate A and B together, and store the result in A_and_B.\nA_and_B = None\n\n# Check if 1337 is in fibolist. If it is, make is_1337_fibo True, otherwise make it False.\nis_1337_fibo = None\n\n#####Tuples!#####\n\n# Here's the first answer to the tuple section:\nmaybe_your_first_tuple = (0, 1, 2, 3, \"hello\", 4, 5, 6, 7, 8, 9, 10, 1, 4, 1, 1, 91)\n\n# Tuples also support slicing like lists. Find the even- and odd-indexed entries of your tuple:\nyour_first_tuple_evens = None\nyour_first_tuple_odds = None\n\n#####Sets!#####\n\n#Again, the first exercise is done for you.\nmaybe_your_first_set = set([1,2,3,4,2])\n#Note that len(maybe_your_first_set) = 4, whereas if it was a list its\n#length would be 5. \n\n# Sets are often used to find the distinct elements of a list. Find the distinct elements below:\nsome_repeats = [1,1,1,1,1,1,2,2,2,2,3,4,5,6,7,8,2345,345,2,52,243,5,2,345,523,45,5,4,2,2,3,5,234,2345]\ndistinct_elements = None\n\nset_A = set(range(100))\nset_B = set(range(0,200,2))\n\n# Apply the union and intersection operations to set_A and set_B as indicated:\nA_union_B = None\nA_intersection_B = None\n\n#####Dictionaries!#####\n\n#Check out all the stuff you can put in dictionaries:\nmaybe_your_first_dict = {'key1':'val1', 'key2': 'val2', \n 'key3': 0, 'key4': [1,2,3], (1,2):'tuples can be keys',\n 'but not lists': [\"how\", \"sad\", \"for\", \"lists\"]}\n\n\n# Dictionary elements are accessed by key rather than position.\n# Try it here - get the value of key \"hello there\" in the dictionary demodict1 (created at the top of this script):\nhello_there_value = None\n\n# remove the key \"there\" from demodict1:\n","sub_path":"exercises/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"316430232","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nfrom django.views.generic.base import RedirectView\nfrom app import api\nfrom mynode import settings\nfrom app import views\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^mynode/', include('app.urls')),\n url(r'^service/posts/(?P[-\\w]+)$', api.post),\n url(r'^posts/(?P[-\\w]+)$', api.post),\n url(r'^author/posts$', api.author_posts),\n url(r'^service/author/posts$', api.author_posts),\n url(r'^service/author/(?P\\w+)/posts$', api.specific_author_posts),\n url(r'^author/(?P\\w+)/posts$', api.specific_author_posts),\n url(r'^service/posts$', api.posts),\n url(r'^posts$', api.posts),\n url(r'^service/friends/(?P[-\\w]+)$', api.friendshipList),\n url(r'^friends/(?P[-\\w]+)$', api.friendshipList),\n url(r'^service/friends/(?P[-\\w]+)/(?P[-\\w]+)$', api.friendship),\n url(r'^friends/(?P[-\\w]+)/(?P[-\\w]+)$', api.friendship),\n url(r'^service/friendrequest$', api.friendrequest),\n url(r'^friendrequest$', api.friendrequest),\n # INSECURE - DO NOT USE UNLESS YOU ARE TESTING! USE STREAM/IMAGE/ INSTEAD.\n url(r'^media/(?P.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),\n #url(r'^media/images/(?P[\\d]*)$', views.image),\n url(r'^global/authors$', api.get_all_users),\n url(r'^.*$', RedirectView.as_view(url='/mynode/', permanent=False)),\n)\n","sub_path":"mynode/mynode/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"109366182","text":"#! /usr/bin/env python3\n# coding: utf-8\n\n\"\"\"\nTheRightFood Data Builder\n\"\"\"\n\nfrom unidecode import unidecode\nfrom math import *\nimport requests\nimport datetime\nfrom modules.finder import *\nfrom settings import *\nfrom modules.mysql_connect import *\n\n\n\"\"\"\nThis class allows to automate \ndata cleaning and collection.\n\"\"\"\n\n\nclass Builder:\n\n def __init__(self, category):\n self.cat = category.item\n\n def uri_generator(self):\n \"\"\"\n Method to automate URIs generation for a target category\n \"\"\"\n pages = []\n self.uris = []\n items_per_page = 1000\n # Format a list to generate queries properly\n self.uris_cat = unidecode(self.cat[0])\n self.uris_cat = self.uris_cat.replace(' ', '-')\n # Define pagination according to the nb of products per cat.\n if self.cat[1] > items_per_page:\n # get 1000 items per page\n x = ceil(self.cat[1]/items_per_page)\n else:\n x = 1\n # store nb of pages per cat\n pages.append(x)\n # get pagination starting at 1\n for i in range(1, pages[0]+1):\n uri = address + cat_search + self.uris_cat + type +\\\n page_size + str(items_per_page) + pagination + str(i) + out_file\n self.uris.append(uri)\n\n def data_miner(self):\n \"\"\"\n Method to send requests and filter the collected data\n \"\"\"\n self.cat_data = dict()\n for uri in self.uris:\n r = requests.get(uri)\n data = r.json()\n for j in range(len(data['products'])):\n main = data['products'][j]\n nutriments = main['nutriments']\n n = ''\n pagin = str(data['page']) + '_' + str(j)\n # select relevant product facts\n self.cat_data.update({pagin: {\n 'code': main.get('code', n),\n 'category': self.cat[0],\n 'created': str(datetime.date.today()),\n 'name': main.get('product_name', n),\n 'brands': main.get('brands', n),\n 'stores': main.get('stores', n),\n 'url': main.get('url', n),\n 'completeness': main.get('completeness', n),\n 'origins': main.get('origins', n),\n 'labels': main.get('labels', n),\n 'ingredients': main.get('ingredients_analysis_tags', n),\n 'nova': main.get('nova_group', n),\n 'nutrition_grade': main.get('nutrition_grades', n),\n 'energy': nutriments.get('energy_100g', n),\n 'fat': nutriments.get('fat', n),\n 'saturated_fat': nutriments.get('saturated-fat', n),\n 'sugars': nutriments.get('sugars', n),\n 'salt': nutriments.get('salt', n),\n 'proteins': nutriments.get('proteins', n),\n 'fiber': nutriments.get('fiber', n)}\n })\n # Save as df and store raw data in a csv file for further analysis\n self.res = pd.DataFrame(self.cat_data).T\n self.res.to_csv('raw_data/off_raw_' + self.uris_cat + '_' + str(datetime.date.today()) + '.csv')\n\n def data_wrangler(self):\n \"\"\"\n Method to clean and refine the data set\n \"\"\"\n # Drop rows where product profile completeness is missing or < 90%\n self.res.drop(self.res[self.res.completeness == ''].index, inplace=True)\n self.res.drop(self.res[self.res.completeness < 0.9].index, inplace=True)\n # Remove undesired '\\n'\n col = ['name', 'brands', 'stores']\n for k in range(len(col)):\n self.res[col[k]] = self.res[col[k]].str.replace('\\n',' ')\n # Extract relevant indicators (or allegations)\n self.res.labels = self.res.labels.str.lower() # Make the target column case insensitive\n self.res['bio'] = self.res.labels.str.contains(bio)\n self.res['eco_packaging'] = self.res.labels.str.contains(eco_packaging)\n self.res['fsc'] = self.res.labels.str.contains('fsc')\n self.res['utz'] = self.res.labels.str.contains('utz')\n self.res['made_in_france'] = self.res.labels.str.contains(made_in_france)\n self.res['fair_trade'] = self.res.labels.str.contains(fair_trade)\n self.res['gluten_free'] = self.res.labels.str.contains(gluten_free)\n self.res['iplc'] = self.res.labels.str.contains('iplc')\n self.res.origins = self.res.origins.str.lower() # Make the target column case insensitive\n self.res['french_ingredients'] = self.res.origins.str.contains('france')\n res_b = pd.DataFrame(self.res.ingredients.values.tolist(),\n columns=['palm_oil_free', 'vegan', 'vegetarian'], index=self.res.index)\n res_b.palm_oil_free = res_b.palm_oil_free.str.contains('en:palm-oil-free')\n res_b.vegan = res_b.vegan.str.contains('en:vegan')\n res_b.vegetarian = res_b.vegetarian.str.contains('en:vegetarian')\n self.res = self.res.join(res_b)\n # Set col 'nutrition_grade' to int so to stick to NOVA classification\n init_val = ['a', 'b', 'c', 'd', 'e']\n new_val = [1, 2, 3, 4, 5]\n for i in range(len(init_val)):\n self.res.nutrition_grade = self.res.nutrition_grade.replace(init_val[i], new_val[i])\n # Save the clean df as a csv file\n self.res.to_csv('clean_data/off_clean_dataset.csv', index=False, sep=';', header=True, columns=vars)\n\n def data_loader(self):\n \"\"\"\n Method to load the data into the appropriate MySql table\n \"\"\"\n cursor.execute(\"\"\"\n LOAD DATA LOCAL INFILE 'clean_data/off_clean_dataset.csv'\n INTO TABLE product\n FIELDS TERMINATED BY ';'\n LINES TERMINATED BY '\\n' \n IGNORE 1 ROWS\n \"\"\")\n # Correct values where MySql put inappropriate 0\n int_var = ['nutrition_grade',\n 'nova',\n 'energy',\n 'fat',\n 'saturated_fat',\n 'sugars',\n 'salt',\n 'proteins',\n 'fiber']\n corr_exec = []\n for i in range(len(int_var)):\n corr_exec.append(\"UPDATE product SET {} = NULL WHERE {} = 0;\".format(int_var[i], int_var[i]))\n cursor.execute(corr_exec[i])\n\n db.commit()\n\n def builder(self):\n \"\"\"\n Method to run all table builder functions\n \"\"\"\n self.uri_generator()\n self.data_miner()\n self.data_wrangler()\n self.data_loader()\n print(\"\"\"\n Collecte terminée !\n Merci d'avoir patienté.\"\"\")\n","sub_path":"modules/tab_builder.py","file_name":"tab_builder.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"91535393","text":"import pyopencl as cl\nimport cv2\nimport numpy as np\nfrom time import time\n\n# np.set_printoptions(threshold=np.nan)\n\n\nclass MeanShiftSegmentation:\n def __init__(self, path, h_s=20, h_r=20, M=200):\n self.h_s = h_s\n self.h_r = h_r\n self.M = M\n self.img_src = cv2.imread(path)\n print('img shape :', self.img_src.shape)\n self.img = np.array(self.img_src, np.float32)\n\n self.platform = cl.get_platforms()[0]\n self.device = self.platform.get_devices(device_type=cl.device_type.GPU)[0]\n self.ctx = cl.Context([self.device])\n self.queue = cl.CommandQueue(self.ctx)\n\n # cv2.meansh\n\n time_begin = time()\n self.mean_shift()\n self.cluster()\n self.merge()\n print(time() - time_begin, 's')\n self.draw()\n\n\n def mean_shift(self):\n print('mean_shift')\n f = open('MeanShift.cl', 'r')\n fstr = \"\".join(f.readlines())\n prg = cl.Program(self.ctx, fstr).build()\n\n mf = cl.mem_flags\n img_buf = cl.Buffer(self.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=self.img)\n self.mean_shift_result = np.empty(\n (self.img.shape[0], self.img.shape[1], 5),\n dtype=np.float32\n )\n result_buf = cl.Buffer(self.ctx, mf.WRITE_ONLY, self.mean_shift_result.nbytes)\n\n prg.meanShift(\n self.queue, (self.img.shape[0], self.img.shape[1]), None,\n np.int32(self.img.shape[0]), np.int32(self.img.shape[1]), np.int32(self.img.shape[2]),\n np.int32(self.h_s), np.int32(self.h_r),\n img_buf, result_buf\n ).wait()\n cl.enqueue_read_buffer(self.queue, result_buf, self.mean_shift_result).wait()\n # print(self.mean_shift_result[-1])\n\n def cluster(self):\n print('cluster')\n row_num = self.mean_shift_result.shape[0]\n col_num = self.mean_shift_result.shape[1]\n self.cluster_num = 1\n self.cluster_result = np.zeros((row_num, col_num), dtype=np.int32)\n f = open('Cluster.cl', 'r')\n fstr = \"\".join(f.readlines())\n prg = cl.Program(self.ctx, fstr).build()\n mf = cl.mem_flags\n mean_shift_buf = cl.Buffer(self.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=self.mean_shift_result)\n cluster_buf = cl.Buffer(self.ctx, mf.USE_HOST_PTR, hostbuf=self.cluster_result)\n for row in range(row_num):\n for col in range(col_num):\n # print(row,col)\n if self.cluster_result[row, col] == 0:\n self.cluster_result[row, col] = self.cluster_num\n self.cluster_num += 1\n\n prg.cluster(\n self.queue, (row_num, col_num), None,\n np.int32(self.cluster_result[row, col]),\n np.int32(row), np.int32(col),\n np.int32(row_num), np.int32(col_num),\n np.int32(self.h_s), np.int32(self.h_r),\n mean_shift_buf, cluster_buf\n ).wait()\n # print()\n # print(self.cluster_result)\n self.cluster_result -= 1\n self.cluster_num -= 1\n # print(self.cluster_result)\n print(self.cluster_num)\n\n def merge(self):\n self.cluster_list = [[] for i in range(self.cluster_num)]\n self.cluster_mean = [np.zeros((5)) for i in range(self.cluster_num)]\n # print(self.cluster_list)\n # print(self.cluster_mean)\n\n row_num = self.cluster_result.shape[0]\n col_num = self.cluster_result.shape[1]\n\n for row in range(row_num):\n for col in range(col_num):\n self.cluster_list[self.cluster_result[row, col]].append((row, col))\n self.cluster_mean[self.cluster_result[row, col]] += self.mean_shift_result[row, col]\n for i in range(self.cluster_num):\n self.cluster_mean[i] /= len(self.cluster_list[i])\n\n has_piece = True\n while has_piece:\n has_piece = False\n for i in range(len(self.cluster_list)):\n if len(self.cluster_list[i]) < self.M:\n has_piece = True\n piece = self.cluster_list.pop(i)\n piece_mean = self.cluster_mean.pop(i)\n norm_piece = np.sqrt(np.sum(piece_mean ** 2))\n\n max_coor = 0.\n max_index = -1\n for j in range(len(self.cluster_list)):\n norm_j = np.sqrt(np.sum(self.cluster_mean[j] ** 2))\n coor = np.sum(self.cluster_mean[j] * piece_mean) / norm_piece / norm_j\n if coor > max_coor:\n max_coor = coor\n max_index = j\n\n part = self.cluster_list.pop(max_index)\n part_mean = self.cluster_mean.pop(max_index)\n new_mean = (piece_mean * len(piece) + part_mean * len(part)) / (len(piece) + len(part))\n new = piece + part\n # print(new)\n # print(new_mean)\n self.cluster_list.append(new)\n self.cluster_mean.append(new_mean)\n break\n\n def draw(self):\n self.seg = np.zeros(self.img.shape)\n for i in range(len(self.cluster_list)):\n color = self.cluster_mean[i][2:]\n for point in self.cluster_list[i]:\n self.seg[point[0], point[1]] = color\n self.seg = np.array(self.seg, dtype=np.uint8)\n cv2.imshow('img', self.img_src)\n cv2.imshow('seg', self.seg)\n cv2.waitKey()\n\n\nif __name__ == '__main__':\n seg = MeanShiftSegmentation('images/test/2018.jpg')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20941637","text":"import json\nimport os\n\nfrom utils.database import Database\nfrom utils import DateTimeEncoder\n\nCONN_STRING = os.environ[\"CONN_STRING\"]\n\ndb = Database(conn_string=CONN_STRING)\n\n\ndef handle(event, context):\n\n with open(\"get_path_rate.sql\", \"r\") as f:\n query = f.read()\n\n arguments = {\n \"user_id\": event[\"arguments\"][\"user_id\"],\n \"path_id\": event[\"arguments\"][\"path_id\"],\n }\n\n result = db.query(query=query, arguments=arguments)\n\n response = json.dumps(result, cls=DateTimeEncoder)\n\n return response\n","sub_path":"backend/find-a-tutor/handlers/get_path_rate/get_path_rate.py","file_name":"get_path_rate.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"502512042","text":"#encoding: utf-8\nimport sys,pprint,os, threading, json, string, random, requests, threading\n#sys.path.append('./venv/lib/python3.6/site-packages')\nfrom flask import Flask, request\nfrom flask_cors import CORS, cross_origin\n\nfrom dotenv import load_dotenv\nfrom pathlib import Path\nsys.path.append('./Handlers')\nsys.path.append('./Models')\nsys.path.append('./DAOs')\nsys.path.append('./Sensors')\n#Biblioteca utilizada para o messenger\nfrom pymessenger import Bot\n# Biblioca utilizada para conexao com o DB\n#from connection import Connection\n# Import dos Handlers\nfrom arquive import Arquive\n\nfrom messagingHandler import MessagingHandler\n#import das classes e DAOs\nfrom administrator import Administrator\n\nfrom dialog import Dialog\n\nfrom dialogs_category import Dialogs_category\n\nfrom dialogs_language import Dialogs_language\n\nfrom evento import Evento\n\nfrom message import Message\n\nfrom problem import Problem\n\nfrom programming_language import Programming_language\n\nfrom submission import Submission\n\nfrom Models.token import Token\n\nfrom user import User\n\nfrom dao import DAO\n#Fim import das classes e DAOs\n\nfrom messageSender import MessageSender\n\nfrom events import Events\n\n############### FIM DOS IMPORTS ###################\n\n\n# Cria a instancia do flask\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'idk'\n# Inicia o CORS (Para funcionar as requests no client)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\nenv_path = Path('.') / '.env'\nload_dotenv(dotenv_path=env_path)\n#Token de acesso\nPAT = os.getenv(\"PAGE_TOKEN\")\nPId = os.getenv(\"PAGE_ID\")\n\nreaded_queue = [[-1]]\nfacebook_message_events = []\n\n#Busca as mensagens de um determinado usuario\n@app.route('/messages_by_facebook_id', methods=['POST'])\ndef messages_by_facebook_id():\n\tdata = request.get_json()\n\tif(data.get('facebook_id')):#testa se existe o campo facebook_id no formulario\n\t\t#busca as mensagens com base na model Message para um determinado usuario\n\t\tmessages = DAO(Message).clauses(\"WHERE sender_id = {} OR recipient_id = {} ORDER BY sended_ts ASC\".format(data['facebook_id'],data['facebook_id']))\n\t\t#if(len(messages)>0):\n\t\t#retorna um json com as mensagens\n\t\treturn json.dumps({'stats': 1, 'facebook_id': data['facebook_id'], 'messages': [message.getDict() for message in messages]})\n\t\t#else:\n\t\t#\treturn json.dumps({'stats': 1, 'facebook_id': data['facebook_id'], 'messages': []})\n\treturn json.dumps({'stats': 0})\n\n#lista todos usuarios\n@app.route('/list_users', methods=['GET'])\ndef list_users():\n\t#busca no banco todos usuarios com base na model User\n\tusers = DAO(User).listAll(\"register_ts ASC\")\n\t#if(len(users)>0):\n\treturn json.dumps({'stats': 1, 'users': [user.getDict() for user in users]})\n\t#else:\n\t#\treturn json.dumps({'stats': 1, 'users': []})\n\n#lista todas as mensagens\n@app.route('/list_messages', methods=['GET'])\ndef list_messages():\n\t#busca as mensagens no banco\n\tmessages = DAO(Message).listAll()\n\t#if(len(messages)>0):\n\treturn json.dumps({'stats': 1, 'messages': [message.getDict() for message in messages]})\n\t#else:\n\t#\treturn json.dumps({'stats': 1, 'messages': []})\n\n#lista todos administradores\n@app.route('/list_administrators', methods=['GET'])\ndef list_administrators():\n\t#busca todos administradores no banco\n\tadministrators = DAO(Administrator).listAll()\n\t#if(len(administrators)>0):\n\treturn json.dumps({'stats': 1, 'administrators': [administrator.getDict() for administrator in administrators]})\n\t#else:\n\t#\treturn json.dumps({'stats': 1, 'administrators': []})\n\n#carrega todas informacoes de um usuario\n@app.route('/user/', methods=['GET'])\ndef find_user_by_facebook_id(id):\n\tif id == '' and id is None:#verifica se o id esta vazio\n\t\treturn json.dumps({'stats': 0, 'error': 'invalid data'}), 200\n\t#busca o usuario com base no id\n\tuser = DAO(User).findFirst(\"WHERE facebook_id ={}\".format(id))\n\tif(user is not None):#verifica se houve algum retorno\n\t\treturn json.dumps({'stats': 1, 'user': user.getDict()}), 200 #retorna o json com os dados do ususario\n\telse:\n\t\treturn json.dumps({'stats': 0, 'user': None}), 200\n\treturn json.dumps({'stats': 0, 'error': 'fail'}), 200\n\n#carrega todas informacoes de uma mensagem\n@app.route('/message/', methods=['GET'])\ndef find_message_by_mid(mid):\n\tif mid == '' and mid is None:#verifica se a mid esta vazia\n\t\treturn json.dumps({'stats': 0, 'error': 'invalid data'}), 200\n\t#busca a mensagem com base no mid\n\tmessage = DAO(Message).findFirst(\"WHERE mid LIKE '{}'\".format(mid))\n\tif(message is not None):#verifica se houve algum retorno\n\t\treturn json.dumps({'stats': 1, 'message': message.getDict()})\n\telse:\n\t\treturn json.dumps({'stats': 1, 'message': None})\n\treturn json.dumps({'stats': 0, 'error': 'fail'}), 200\n\n#rota de login\n@app.route('/login', methods=['POST'])\ndef login():\n\tdata = request.get_json()\n\tif (not data.get('username') or not data.get('password')):#verifica se existe username e password no json\n\t\treturn json.dumps({\"stats\": 0, \"error\": \"invalid data\"})\n\tusername = data['username'].strip()\n\tpassword = data['password'].strip()\n\t#busca um administrador com base no username e password\n\tadministrator = DAO(Administrator).findFirst(\"WHERE username LIKE '{}' AND password LIKE '{}'\".format(username, password))\n\tif(administrator is not None):\n\t\ttoken_string = token_generator(60)#gera um token de acesso\n\t\t#busca se existe algum token vinculado ao administrador\n\t\ttoken = DAO(Token).findFirst(\"WHERE administrator_id = {}\".format(administrator.getId()))\n\t\tif(token is not None):#verifica se houve retorno\n\t\t\ttoken_string = token.getToken()#salva o token do banco numa variavel\n\t\telse:#caso nao exista token no banco para esse administrador, senao, gerar ate encontrar algum token que nao esteja em uso\n\t\t\twhile True:\n\t\t\t\ttokens = DAO(Token).findFirst(\"WHERE token LIKE '{}'\".format(token_string))\n\t\t\t\tif(tokens is None):#gerou um token que nao existe no banco\t\n\t\t\t\t\tbreak#sai do while\n\t\t\t\ttoken_string = token_generator(60)#gera um novo token\n\n\t\t\ttemp_token = Token()#instancia um objeto token\n\t\t\ttemp_token.setToken(token_string)#seta o token desse objeto\n\t\t\ttemp_token.setAdministrator_id(administrator.getId())#seta o administrador ao qual ele pertence\n\t\t\tDAO(Token).save(temp_token)#salva esse token\n\t\t#retorna o administrador e o token de acesso\n\t\treturn json.dumps({'stats': 1, 'error': 'none', 'token': token_string, 'administrator': {'id': administrator.getId(), 'username': administrator.getUsername(), 'level': administrator.getLevel()}})\n\t#retorna uma mensagem de erro para conta invalida\n\treturn json.dumps({'stats': 0, 'error': 'invalid account'})\n\n#gera evento para submissao de usuario do bot\n@app.route('/submission', methods=['POST'])\ndef submission():\n\tdata = request.get_json()\n\t\n\tif(not data.get('token') or not data.get('sub_dict')):#verifica se existe token e dicionario no json\n\t\treturn json.dumps({'stats': 0, 'error': 'invalid fields'})\n\n\tif(data['token'] != 'qvKJuNjPQlFlMW0X3CDVP3Xdn2DoCuxXd5D7J14tM3mnI57DzE'):#verifica se o token esta correto\n\t\treturn json.dumps({'stats': 0, 'error': 'invalid token'})\n\n\tanswer_code = eval(data['sub_dict']['answer_code'])#pega o codigo da resposta da submissao\n\tprint(data)\n\tif(data['sub_dict']['facebook_id'] is None):#testa se o facebook_id vindo do coletor eh nulo\n\t\treturn json.dumps({'stats':0, 'error': 'facebook_id'})\n\tif(answer_code == 1):#se for accepted chama o evento de accepted\n\t\tEvents(emit_echo).getAcceptedEvent().setData(data['sub_dict'])\n\telif(answer_code == 2):#se for compilation error chama o evento de compilation error\n\t\tEvents(emit_echo).getCompilationErrorEvent().setData(data['sub_dict'])\n\telif(answer_code == 3):#se for runtime error chama o evento de runtime error\n\t\tEvents(emit_echo).getRuntimeErrorEvent().setData(data['sub_dict'])\n\telif(answer_code == 4):#se for runtime error chama o evento de runtime error\n\t\tEvents(emit_echo).getTimeLimitErrorEvent().setData(data['sub_dict'])\n\telif(answer_code == 5):#se for presentation error chama o evento de presentation error\n\t\tEvents(emit_echo).getPresentationErrorEvent().setData(data['sub_dict'])\n\telif(answer_code == 6):#se for wrong answer chama o evento de wrong answer\n\t\tEvents(emit_echo).getWrongEvent().setData(data['sub_dict'])\n\telif(answer_code == 7):#se for wrong answer chama o evento de wrong answer\n\t\tEvents(emit_echo).getErro7ErrorEvent().setData(data['sub_dict'])\n\telse:\n\t\tEvents(emit_echo).getDefaultEvent().setData(data['sub_dict'])\n\treturn json.dumps({'stats':1, 'error': None})\n\n\t\n\n\n#rota de registro do webhook\n@app.route('/', methods=['GET'])\ndef verify():\n\t#verifica se está tentando cadastrar o bot na API\n\tif request.args.get(\"hub.mode\") == \"subscribe\" and request.args.get(\"hub.challenge\"):\n\t#verifica se o token usado no webhook é o mesmo do programa\n\t\tif not request.args.get(\"hub.verify_token\") == \"RandomTestToken\":\n\t\t\treturn \"Verification token mismatch\", 403\n\t\treturn request.args[\"hub.challenge\"], 200\n\treturn \"OK\", 200\n\n#Rota de recebimento de mensagens\n@app.route('/', methods=['POST'])\ndef webhook():\n\t#Pegas os dados do request em formato Json\n\tdata = request.get_json()\n\tfacebook_message_events.append(data)\n\treturn \"OK\", 200\n#lista eventos\n@app.route('/list_events', methods=['GET'])\ndef getEvents():\n\t#lista todos eventos\n\teventos = DAO(Evento).listAll(\"time_ts ASC\")\n\tif(eventos is not None):\n\t\treturn json.dumps({'stats': 1, 'eventos': [evento.getDict() for evento in eventos]})\n\telse:\n\t\treturn json.dumps({'stats': 0, 'eventos': None})\n\t#return result, 200\n\n#lista eventos por facebook_id\n@app.route('/events_by_facebook_id', methods=['POST'])\ndef getEventsByFacebook_id():\n\tdata = request.get_json()\n\tif(not data.get('facebook_id')):#testa se nao tem facebook_id no json\n\t\treturn json.dumps({'stats': 0, 'error': 'no facebook_id'})\n\t#lista os eventos do usuario do facebook_id\n\teventos = DAO(Evento).clauses(\" WHERE facebook_id = {} ORDER BY time_ts ASC\".format(data['facebook_id']))\n\t#if(len(eventos)>0):\n\tif(eventos is not None):\n\t\treturn json.dumps({'stats': 1, 'eventos': [evento.getDict() for evento in eventos]}), 200\n\telse:\n\t\treturn json.dumps({'stats': 1, 'eventos': None}), 200\n\t#else:\n\t#\treturn json.dumps({'stats': 1, 'eventos': []}), 200\n\t#return json.dumps({'stats': 0, 'error': 'none'}), 200\n\n#envia o echo das mensagens e eventos para o servidor de socket\nWEB_SOCKET_URL = \"http://localhost:8000/\" # gcloud internal ip\ndef emit_echo(data, event='message'):\n\ttry:\n\t\tpass\n\t\t#requests.post(WEB_SOCKET_URL+\"broadcast/\"+event, json={\"data\": data})\n\texcept Exception as e:\n\t\tprint(e)\n\n#Função para mostrar mensagem\ndef log(message):\n\tdata = pprint.PrettyPrinter(indent=2)\n\tdata.pprint(message)\n\tsys.stdout.flush()\n\n#gera um token contendo letras maiusculas e minusculas e digitos\ndef token_generator(size=10, chars=string.ascii_letters + string.digits):\n\treturn ''.join(random.choice(chars) for _ in range(size))\n\ndef messageProcesser():\n\twhile(True):\n\t\twhile(len(facebook_message_events) > 0):\n\t\t\t#Verifica se o objeto é do tipo page\n\t\t\tif facebook_message_events[0]['object'] == 'page':\n \t#Percorre as entradas (ela é do tipo lista)\n\t\t\t\tfor entry in facebook_message_events[0].get('entry'):\n\t\t\t\t\tif entry.get('messaging'):\n\t\t\t\t\t\tfor messaging_event in entry.get('messaging', []):\n\t\t\t\t\t\t\tsender_id = int(messaging_event['sender']['id'])\n\t\t\t\t\t\t\tif messaging_event.get('message'):\n\t\t\t\t\t\t\t\tif(int(sender_id) != PId):\n\t\t\t\t\t\t\t\t\tprint(sender_id, PId)\n\t\t\t\t\t\t\t\t\tMessageSender().sendText(sender_id, \"oi\")\n\t\t\tfacebook_message_events.pop(0)\n\nif __name__ == \"__main__\":\n\tmessageProcesser = threading.Thread(name = \"messageProcesser\",target = messageProcesser, daemon = True)\n\tmessageProcesser.start()\n\tapp.threaded = True\n\tapp.port = 8080\n\tapp.run(host='0.0.0.0', port=8080, debug=True)\n","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":11659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"288039302","text":"def balanced_bracket(s):\n \"\"\" check (){}[]<> is closed properly\n \"\"\"\n opening = \"{(<[\"\n closing = \"})>]\"\n pairs = [\"{}\",\"[]\",\"<>\",\"()\"]\n l = []\n try:\n for c in s:\n if c in opening:\n l.append(c)\n elif c in closing:\n if l.pop()+c not in pairs:\n return False\n\n except Exception:\n return False\n return True\n\n","sub_path":"algorithm/balanced_bracket.py","file_name":"balanced_bracket.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"213038506","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function, division, generators\nfrom mpl_toolkits.mplot3d import Axes3D\nimport argparse, json\nimport numpy as np\nimport scipy.stats\nimport sys\n\nPRIOR = 0.5\nBEAUTYFACTOR = 8\n\n#import matplotlib\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n#matplotlib.use('TkAgg')\n\ndef info(*things): print('[INFO]:', *things, file=sys.stderr)\n\ndef unpack_obj(obj, dthreshold=6):\n\trmsd = obj['rmsd']\n\tlength = obj['length']\n\n\toldaligned = 0\n\tfor dist in obj['distances']: oldaligned += 0 if dist is None else 1\n\n\tqpresent, spresent = obj['qpresent'], obj['spresent']\n\n\tqaligned = []\n\tsaligned = []\n\tfor span in obj['qaligned']:\n\t\tif span[0] is None: qaligned += [None] * span[1]\n\t\telse: \n\t\t\tif span[0] < span[1]: qaligned += list(range(span[0], span[1]+1))\n\t\t\telse: qaligned += list(range(span[0], span[0]+span[1]))\n\tfor span in obj['saligned']:\n\t\tif span[0] is None: saligned += [None] * span[1]\n\t\telse: \n\t\t\tif span[0] < span[1]: saligned += list(range(span[0], span[1]+1))\n\t\t\telse: saligned += list(range(span[0], span[0]+span[1]))\n\n\taligned = 0\n\tqp = 0\n\tsp = 0\n\tfor q, dist, s in zip(qaligned, obj['distances'], saligned):\n\t\t#print(qpresent, q, dist, s, spresent)\n\t\t#print(q, dist, s, dthreshold, (dthreshold is not None) and (dist is not None) and dist <= dthreshold)\n\t\tif q is None: continue\n\t\telif (q < (qpresent[0][0] - 15)) or (q > (qpresent[0][1] + 15)): \n\t\t\trmsd = -1\n\t\t\tcontinue\n\t\telse: qp += 1\n\t\tif s is None: continue\n\t\telif (s < (spresent[0][0] - 15)) or (s > (spresent[0][1] + 15)): \n\t\t\trmsd = -1\n\t\t\tcontinue\n\t\telse: sp += 1\n\n\t\tif dist is None: continue\n\n\t\tif (dthreshold is not None) and (dist is not None) and dist > dthreshold: continue\n\t\taligned += 1\n\t#if oldaligned != aligned: print(oldaligned, aligned)\n\n\tqpresent, spresent = qpresent[0][1] - qpresent[0][0] + 1, spresent[0][1] - spresent[0][0] + 1\n\n\t#old calc\n\t#minpresent = min(qpresent, spresent)\n\tminpresent = min(qp, sp)\n\n\t#covs = aligned/qpresent, aligned/spresent\n\tif (qp == 0) or (sp == 0):\n\t\tcovs = 0., 0.\n\t#else: covs = aligned/qp, aligned/sp\n\t#the previous calc fails because it's incompatible with tmalign.py output\n\telse: covs = aligned/qpresent, aligned/spresent\n\tmincov = min(covs)\n\tmaxcov = max(covs)\n\n\t#distances = [np.nan if x is None else x for x in obj['distances']]\n\t#print(np.nanmax(distances))\n\n\n\t#TODO: expose which coverage-like metric to use\n\tquality = obj['quality']\n\n\treturn {'rmsd':rmsd, 'length':length, 'mincov':mincov, 'maxcov':maxcov, 'minpresent':minpresent, 'quality':quality}\n\nclass Dataset(object):\n\tdef __init__(self, f, count=1000, mode=None, marg=None, min_present=50, dthreshold=4, min_mincov=0., min_quality=0.):\n\t\tself.names = []\n\t\tself.rmsds = []\n\t\tself.lengths = []\n\t\tself.mincovs = []\n\t\tself.maxcovs = []\n\t\tself.count = count\n\n\t\tself.min_present = min_present\n\t\tself.kernel = None\n\t\tself.pdf = None\n\n\t\tself.dthreshold = dthreshold\n\t\tself.min_mincov = min_mincov\n\t\tself.min_quality = min_quality\n\n\t\tif mode == 'onebest': \n\t\t\tinfo('Using selection criterion ONEBEST')\n\t\t\tself.parse_best_data(f)\n\t\telif mode == 'stretchone': \n\t\t\tinfo('Using selection criterion STRETCHONE')\n\t\t\tself.parse_best_data(f)\n\t\t\tf.seek(0)\n\t\t\tself.stretch_data(f, n=marg)\n\t\telse: \n\t\t\tinfo('Using selection criterion ANY')\n\t\t\tself.parse_data(f)\n\n\tdef get_dict(self):\n\t\tobj = {}\n\t\tfor name, rmsd, length, mincov, maxcov in zip(self.names, self.rmsds, self.lengths, self.mincovs, self.maxcovs):\n\t\t\tobj[name] = {'rmsd':rmsd, 'length':length, 'mincov':mincov, 'maxcov':maxcov}\n\t\treturn obj\n\n\tdef stretch_data(self, f, n=1):\n\t\tn = 1 if n is None else n\n\n\t\tnames = self.names[:]\n\n\t\tseeds = {}\n\t\tfor name in names:\n\t\t\tquery, qchain, qhel, vs, subject, schain, shel = name.split('_')\n\t\t\tqpdbc = '{}_{}'.format(query, qchain)\n\t\t\tspdbc = '{}_{}'.format(subject, schain)\n\t\t\tqhel = [int(x) for x in qhel[1:].split('-')]\n\t\t\tshel = [int(x) for x in shel[1:].split('-')]\n\t\t\tseeds[(qpdbc, spdbc)] = [qhel, shel]\n\n\n\t\tnames = []\n\t\trmsds = []\n\t\tlengths = []\n\t\tmincovs = []\n\t\tmaxcovs = []\n\t\tbest = {}\n\t\tfor k in seeds: best[k] = []\n\n\t\tf.seek(0)\n\t\tfor l in f:\n\t\t\tif not l.strip(): continue\n\t\t\telif l.startswith('#'): continue\n\t\t\t\n\t\t\tsl = l.split('\\t')\n\t\t\tquery, qchain, qhel, vs, subject, schain, shel = sl[0].split('_')\n\t\t\tqpdbc = '{}_{}'.format(query, qchain)\n\t\t\tspdbc = '{}_{}'.format(subject, schain)\n\t\t\tqhel = [int(x) for x in qhel[1:].split('-')]\n\t\t\tshel = [int(x) for x in shel[1:].split('-')]\n\t\t\ttry:\n\t\t\t\tseedqhel, seedshel = seeds[(qpdbc, spdbc)]\n\t\t\t\tif qhel[0] <= seedqhel[0] and shel[0] >= seedshel[0]: continue\n\t\t\t\telif qhel[0] >= seedqhel[0] and shel[0] <= seedshel[0]: continue\n\t\t\t\telif qhel[0] <= seedqhel[0] <= qhel[1]: continue\n\t\t\t\telif qhel[0] <= seedqhel[1] <= qhel[1]: continue\n\t\t\t\telif seedqhel[0] <= qhel[0] <= seedqhel[1]: continue\n\t\t\t\telif seedqhel[0] <= qhel[1] <= seedqhel[1]: continue\n\t\t\t\telif shel[0] <= seedshel[0] <= shel[1]: continue\n\t\t\t\telif shel[0] <= seedshel[1] <= shel[1]: continue\n\t\t\t\telif seedshel[0] <= shel[0] <= seedshel[1]: continue\n\t\t\t\telif seedshel[0] <= shel[1] <= seedshel[1]: continue\n\t\t\texcept KeyError: continue\n\n\t\t\ttry: obj = json.loads(sl[1])\n\t\t\texcept ValueError: continue\n\t\t\trmsd, length, mincov, maxcov = unpack_obj(obj, dthreshold=dthreshold)\n\t\t\tbest[(qpdbc, spdbc)].append((mincov, rmsd, name, length, maxcov))\n\n\t\tfor k in best:\n\t\t\tif not best[k]: continue\n\t\t\tfor extra in sorted(best[k])[::-1][:n]:\n\t\t\t\tmincov, rmsd, name, length, maxcov = extra\n\t\t\t\tnames.append(name)\n\t\t\t\trmsds.append(rmsd)\n\t\t\t\tlengths.append(length)\n\t\t\t\tmincovs.append(mincov)\n\t\t\t\tmaxcovs.append(maxcov)\n\n\t\tself.names = np.hstack([self.names, names])\n\t\tself.rmsds = np.hstack([self.rmsds, rmsds])\n\t\tself.lengths = np.hstack([self.lengths, lengths])\n\t\tself.mincovs = np.hstack([self.mincovs, mincovs])\n\t\tself.maxcovs = np.hstack([self.maxcovs, maxcovs])\n\n\tdef parse_best_data(self, f):\n\t\tn = 0\n\n\t\tbestkeys = []\n\t\tbest = {}\n\n\t\tnames = []\n\t\trmsds = []\n\t\tlengths = []\n\t\tmincovs = []\n\t\tmaxcovs = []\n\n\t\tfor l in f:\n\t\t\tif not l.strip(): continue\n\t\t\telif l.startswith('#'): continue\n\n\t\t\tsl = l.split('\\t')\n\t\t\tname = sl[0]\n\t\t\tobj = json.loads(sl[1])\n\t\t\tqpdbc = '{0}_{1}'.format(*sl[0].split('_'))\n\t\t\tspdbc = '{4}_{5}'.format(*sl[0].split('_'))\n\t\t\trmsd, length, mincov, maxcov, minpresent = unpack_obj(obj, dthreshold=self.dthreshold)\n\t\t\tif minpresent < self.min_present: continue\n\t\t\tif rmsd == -1: continue\n\n\t\t\ttry:\n\t\t\t\ti = best[(qpdbc, spdbc)]\n\t\t\t\tif mincov > mincovs[i]:\n\t\t\t\t\tnames[i] = name\n\t\t\t\t\trmsds[i] = rmsd\n\t\t\t\t\tlengths[i] = length\n\t\t\t\t\tmincovs[i] = mincov\n\t\t\t\t\tmaxcovs[i] = maxcov\n\t\t\t\telif mincov == mincovs[i] and rmsd < rmsds[i]:\n\t\t\t\t\tnames[i] = name\n\t\t\t\t\trmsds[i] = rmsd\n\t\t\t\t\tlengths[i] = length\n\t\t\t\t\tmincovs[i] = mincov\n\t\t\t\t\tmaxcovs[i] = maxcov\n\t\t\t\telse: pass\n\t\t\texcept KeyError:\n\t\t\t\tnames.append(name)\n\t\t\t\trmsds.append(rmsd)\n\t\t\t\tlengths.append(length)\n\t\t\t\tmincovs.append(mincov)\n\t\t\t\tmaxcovs.append(maxcov)\n\t\t\t\tbest[(qpdbc, spdbc)] = len(mincovs) - 1\n\t\t\t\tbestkeys.append((qpdbc, spdbc))\n\n\t\t\tif len(best) > 300: \n\t\t\t\tbest.pop(bestkeys.pop(0))\n\t\t\t#print('best', len(best), 'bestkeys', len(bestkeys), 'mincovs', len(mincovs))\n\t\t\t\n\n\t\t\tself.names = np.array(names)\n\t\t\tself.rmsds = np.array(rmsds)\n\t\t\tself.lengths = np.array(lengths)\n\t\t\tself.mincovs = np.array(mincovs)\n\t\t\tself.maxcovs = np.array(maxcovs)\n\t\t\t#self.rmsds.append(rmsd)\n\t\t\t#self.lengths.append(length)\n\t\t\t#self.mincovs.append(mincov)\n\t\t\t#self.maxcovs.append(maxcov)\n\n\t\t\tn += 1\n\t\t\tif len(mincovs) == self.count: break\n\t\t#print('bestkeys:', len(bestkeys))\n\n\tdef parse_data(self, f):\n\t\tn = 0\n\t\tnames = []\n\t\trmsds = []\n\t\tlengths = []\n\t\tmincovs = []\n\t\tmaxcovs = []\n\t\tfor l in f:\n\t\t\tif not l.strip(): continue\n\t\t\telif l.startswith('#'): continue\n\n\t\t\tsl = l.split('\\t')\n\t\t\ttry: obj = json.loads(sl[1])\n\t\t\texcept ValueError: print(sl[1])\n\t\t\t#rmsd, length, mincov, maxcov, minpresent = unpack_obj(obj, dthreshold=self.dthreshold)\n\t\t\tdata = unpack_obj(obj, dthreshold=self.dthreshold)\n\t\t\trmsd = data['rmsd']\n\t\t\tlength = data['length']\n\t\t\tmincov = data['mincov']\n\t\t\tmaxcov = data['maxcov']\n\t\t\tminpresent = data['minpresent']\n\t\t\tquality = data['quality']\n\t\t\tif minpresent < self.min_present: continue\n\t\t\tif rmsd == -1: continue\n\t\t\tif not mincov: continue\n\t\t\tif mincov < self.min_mincov: continue\n\t\t\tif quality < self.min_quality: continue\n\n\t\t\tnames.append(sl[0])\n\t\t\trmsds.append(rmsd)\n\t\t\tlengths.append(length)\n\t\t\tmincovs.append(mincov)\n\t\t\tmaxcovs.append(maxcov)\n\n\t\t\tn += 1\n\t\t\t#if n == self.count: break\n\n\t\tself.names = []\n\t\tself.rmsds = []\n\t\tself.lengths = []\n\t\tself.mincovs = []\n\t\tself.maxcovs = []\n\t\tif n <= self.count:\n\t\t\tself.names = names\n\t\t\tself.rmsds = rmsds\n\t\t\tself.lengths = lengths\n\t\t\tself.mincovs = mincovs\n\t\t\tself.maxcovs = maxcovs\n\t\telse:\n\t\t\tlasti = None\n\t\t\tfor i in np.arange(0, n, n/self.count):\n\t\t\t\tif int(i) == lasti: continue\n\t\t\t\tlasti = int(i)\n\t\t\t\tself.names.append(names[int(i)])\n\t\t\t\tself.rmsds.append(rmsds[int(i)])\n\t\t\t\tself.lengths.append(lengths[int(i)])\n\t\t\t\tself.mincovs.append(mincovs[int(i)])\n\t\t\t\tself.maxcovs.append(maxcovs[int(i)])\n\n\t\tself.names = np.array(self.names)\n\t\tself.rmsds = np.array(self.rmsds)\n\t\tself.lengths = np.array(self.lengths)\n\t\tself.mincovs = np.array(self.mincovs)\n\t\tself.maxcovs = np.array(self.maxcovs)\n\n\tdef evaluate(self, *args, **kwargs): return self.kernel.evaluate(*args, **kwargs)\n\n\tdef gen_rmsd_mincov_kde(self, min_rmsd=0.0, max_rmsd=7.0, min_mincov=0.0, max_mincov=1.0, rmsd_resolution=100, mincov_resolution=100):\n\t\trmsds, mincovs = np.mgrid[min_rmsd:max_rmsd:rmsd_resolution*1j, \\\n\t\t\tmin_mincov:max_mincov:mincov_resolution*1j]\n\t\tpositions = np.vstack([rmsds.ravel(), mincovs.ravel()])\n\t\tvalues = np.vstack([self.rmsds, self.mincovs])\n\t\tself.kernel = scipy.stats.gaussian_kde(values)\n\t\tself.pdf = np.reshape(self.kernel(positions).T, rmsds.shape)\n\nclass Plot(object):\n\tdef __init__(self, fig=None, canvas=None, ax=None):\n\t\tself.fig = Figure() if fig is None else fig\n\t\tself.canvas = FigureCanvas(self.fig) if fig is None else canvas\n\t\tself.ax = self.fig.add_subplot(111) if ax is None else ax\n\t\t\n\ndef plot_kde(kde, fig, ax, rmsdlim=(0., 6.), mincovlim=(0., 1.), resolution=100):\n\tX, Y = np.mgrid[rmsdlim[0]:rmsdlim[1]:resolution*1j, mincovlim[0]:mincovlim[1]:resolution*1j]\n\tpositions = np.vstack([X.ravel(), Y.ravel()])\n\tZ = np.reshape(kde.evaluate(positions).T, X.shape)\n\n\taspect = (rmsdlim[1] - rmsdlim[0]) / (mincovlim[1] - mincovlim[0]) / 1.414\n\tim = ax.imshow(np.rot90(Z), cmap='magma', extent=rmsdlim+mincovlim, aspect=aspect)\n\tax.set_xlim(rmsdlim)\n\tax.set_ylim(mincovlim)\n\tax.set_xlabel('RMSD')\n\tax.set_ylabel('Coverage')\n\n\tfig.colorbar(im, ax=ax)\n\ndef plot_3d_densities(kde, fig, ax, rmsdlim=(0., 6.), mincovlim=(0., 1.), resolution=100):\n\tX, Y = np.mgrid[rmsdlim[0]:rmsdlim[1]:resolution*1j, mincovlim[0]:mincovlim[1]:resolution*1j]\n\tpositions = np.vstack([X.ravel(), Y.ravel()])\n\n\tZ = np.reshape(kde.evaluate(positions).T, X.shape)\n\tsurf = ax.plot_surface(X, Y, Z, cmap='magma', linewidth=0, antialiased=False)\n\n\tax.set_xlim(rmsdlim)\n\tax.set_ylim(mincovlim)\n\t#ax.set_zlim(-1.0, 1.0)\n\tax.set_xlabel('RMSD')\n\tax.set_ylabel('Coverage')\n\tax.set_zlabel('p')\n\tfig.colorbar(surf, ax=ax)\n\ndef plot_3d_posteriors(pkde, nkde, fig, ax, rmsdlim=(0., 6.), mincovlim=(0., 1.), resolution=100):\n\tX, Y = np.mgrid[rmsdlim[0]:rmsdlim[1]:resolution*1j, mincovlim[0]:mincovlim[1]:resolution*1j]\n\tpositions = np.vstack([X.ravel(), Y.ravel()])\n\n\tposteriors = pkde.evaluate(positions) * PRIOR / (pkde.evaluate(positions) * PRIOR + nkde.evaluate(positions) * (1-PRIOR))\n\n\tZ = np.reshape(posteriors.T, X.shape)\n\n\taspect = (rmsdlim[1] - rmsdlim[0]) / (mincovlim[1] - mincovlim[0]) / 1.414\n\tsurf = ax.plot_surface(X, Y, Z, cmap='magma', linewidth=0, antialiased=False)\n\tax.set_xlim(rmsdlim)\n\tax.set_ylim(mincovlim)\n\tax.set_zlim(0.0, 1.0)\n\tax.set_xlabel('RMSD')\n\tax.set_ylabel('Coverage')\n\tax.set_zlabel('p')\n\tax.set_title('Posteriors (n={}+{})'.format(len(pkde.mincovs), len(nkde.mincovs)))\n\tfig.colorbar(surf, ax=ax)\n\ndef plot_posteriors(pkde, nkde, fig, ax, rmsdlim=(0., 6.), mincovlim=(0., 1.), resolution=100, colorbar=True):\n\tX, Y = np.mgrid[rmsdlim[0]:rmsdlim[1]:resolution*1j, mincovlim[0]:mincovlim[1]:resolution*1j]\n\tpositions = np.vstack([X.ravel(), Y.ravel()])\n\n\tposteriors = pkde.evaluate(positions) * PRIOR / (pkde.evaluate(positions) * PRIOR + nkde.evaluate(positions) * (1-PRIOR))\n\n\tZ = np.reshape(posteriors.T, X.shape)\n\n\taspect = (rmsdlim[1] - rmsdlim[0]) / (mincovlim[1] - mincovlim[0]) / 1.414\n\tim = ax.imshow(np.rot90(Z), cmap='magma', extent=rmsdlim+mincovlim, aspect=aspect)\n\tax.set_xlim(rmsdlim)\n\tax.set_ylim(mincovlim)\n\tax.set_xlabel('RMSD')\n\tax.set_ylabel('Coverage')\n\n\tif colorbar: fig.colorbar(im, ax=ax)\n\n\tax.set_title('Posteriors (n={}+{})'.format(len(pkde.mincovs), len(nkde.mincovs)))\n\t\ndef plot_independent_posteriors(positive, negative, figure, ax, rmsdlim, mincovlim, resolution=100, rbw=(1., 1.), cbw=(1., 1.)):\n\trmsds, mincovs = np.mgrid[rmsdlim[0]:rmsdlim[1]:resolution*1j, \\\n\t\tmincovlim[0]:mincovlim[1]:resolution*1j]\n\tpositions = np.vstack([rmsds.ravel(), mincovs.ravel()])\n\n\tpos_rkde = scipy.stats.gaussian_kde(positive.rmsds)\n\tpos_ckde = scipy.stats.gaussian_kde(positive.mincovs)\n\tneg_rkde = scipy.stats.gaussian_kde(negative.rmsds)\n\tneg_ckde = scipy.stats.gaussian_kde(negative.mincovs)\n\tpos_rkde.set_bandwidth(bw_method=pos_rkde.factor*rbw[0])\n\tpos_ckde.set_bandwidth(bw_method=pos_ckde.factor*cbw[0])\n\tneg_rkde.set_bandwidth(bw_method=neg_rkde.factor*rbw[1])\n\tneg_ckde.set_bandwidth(bw_method=neg_ckde.factor*cbw[1])\n\n\trvalues = pos_rkde.evaluate(positions[0]) * PRIOR / (pos_rkde.evaluate(positions[0]) * PRIOR + neg_rkde.evaluate(positions[0]) * (1 - PRIOR))\n\tcvalues = pos_ckde.evaluate(positions[1]) * PRIOR / (pos_ckde.evaluate(positions[1]) * PRIOR + neg_ckde.evaluate(positions[1]) * (1 - PRIOR))\n\tvalues = rvalues * cvalues\n\tZ = np.reshape(values.T, rmsds.shape)\n\n\taspect = (rmsdlim[1] - rmsdlim[0]) / (mincovlim[1] - mincovlim[0]) / 1.414\n\tim = ax.imshow(np.rot90(Z), cmap='magma', extent=rmsdlim+mincovlim, aspect=aspect)\n\n\tax.set_xlim(rmsdlim)\n\tax.set_ylim(mincovlim)\n\tax.set_xlabel('RMSD')\n\tax.set_ylabel('Coverage')\n\tax.set_title('Posteriors (n={}+{})'.format(len(positive.mincovs), len(negative.mincovs)))\n\tfigure.colorbar(im, ax=ax)\n\n\ndef plot_3d_independent_posteriors(positive, negative, fig, ax, rmsdlim, mincovlim, resolution=200, rbw=(1., 1.), cbw=(1., 1.)):\n\trmsds, mincovs = np.mgrid[rmsdlim[0]:rmsdlim[1]:resolution*1j, \\\n\t\tmincovlim[0]:mincovlim[1]:resolution*1j]\n\tpositions = np.vstack([rmsds.ravel(), mincovs.ravel()])\n\n\tpos_rkde = scipy.stats.gaussian_kde(positive.rmsds)\n\tpos_ckde = scipy.stats.gaussian_kde(positive.mincovs)\n\tneg_rkde = scipy.stats.gaussian_kde(negative.rmsds)\n\tneg_ckde = scipy.stats.gaussian_kde(negative.mincovs)\n\tpos_rkde.set_bandwidth(bw_method=pos_rkde.factor*rbw[0])\n\tpos_ckde.set_bandwidth(bw_method=pos_ckde.factor*cbw[0])\n\tneg_rkde.set_bandwidth(bw_method=neg_rkde.factor*rbw[1])\n\tneg_ckde.set_bandwidth(bw_method=neg_ckde.factor*cbw[1])\n\n\trvalues = pos_rkde.evaluate(positions[0]) * PRIOR / (pos_rkde.evaluate(positions[0]) * PRIOR + neg_rkde.evaluate(positions[0]) * (1 - PRIOR))\n\tcvalues = pos_ckde.evaluate(positions[1]) * PRIOR / (pos_ckde.evaluate(positions[1]) * PRIOR + neg_ckde.evaluate(positions[1]) * (1 - PRIOR))\n\tvalues = rvalues * cvalues\n\tZ = np.reshape(values.T, rmsds.shape)\n\n\tsurf = ax.plot_surface(rmsds, mincovs, Z, cmap='magma', linewidth=0, antialiased=False)\n\tax.set_xlim(rmsdlim)\n\tax.set_ylim(mincovlim)\n\tax.set_zlim(0.0, 1.0)\n\tax.set_xlabel('RMSD')\n\tax.set_ylabel('Coverage')\n\tax.set_zlabel('p')\n\tax.set_title('Posteriors (n={}+{})'.format(len(positive.mincovs), len(negative.mincovs)))\n\tfig.colorbar(surf, ax=ax)\n\ndef plot_univariate_densities(dataset, fig, ax1, ax2, lim1, lim2, resolution=200, rbw=1., cbw=1.):\n\tX1 = np.arange(lim1[0], lim1[1], (lim1[1] - lim1[0])/resolution)\n\tX2 = np.arange(lim2[0], lim2[1], (lim2[1] - lim2[0])/resolution)\n\n\trkde = scipy.stats.gaussian_kde(dataset.rmsds)\n\tckde = scipy.stats.gaussian_kde(dataset.mincovs)\n\t#Y1 = rkde.evaluate(X1)\n\t#Y2 = ckde.evaluate(X2)\n\n\t#ax1.plot(X1, Y1)\n\t#ax2.plot(X2, Y2)\n\n\trkde.set_bandwidth(bw_method=rkde.factor*rbw)\n\tY1 = rkde.evaluate(X1)\n\tax1.plot(X1, Y1)\n\tckde.set_bandwidth(bw_method=ckde.factor*cbw)\n\tY2 = ckde.evaluate(X2)\n\tax2.plot(X2, Y2)\n\n\tax1.set_xlim(lim1)\n\tax2.set_xlim(lim2)\n\t\n\ndef plot_univariate_posteriors(pvalues, nvalues, fig, ax, lim, resolution=200, xlabel='', ylabel='', bw=(1., 1.)):\n\tX = np.arange(lim[0], lim[1], (lim[1]-lim[0])/resolution)\n\tpkernel = scipy.stats.gaussian_kde(pvalues)\n\tnkernel = scipy.stats.gaussian_kde(nvalues)\n\n\tpkernel.set_bandwidth(bw_method=pkernel.factor*bw[0])\n\tnkernel.set_bandwidth(bw_method=nkernel.factor*bw[1])\n\tposteriors = pkernel.evaluate(X) * PRIOR / (pkernel.evaluate(X) * PRIOR + nkernel.evaluate(X) * (1-PRIOR))\n\tax.plot(X, posteriors)\n\tax.set_xlim(lim)\n\tax.set_ylim([0, 1])\n\tax.set_xlabel(xlabel)\n\tax.set_ylabel(ylabel)\n\t#ax.plot(kde.rmsds, kde.mincovs, c=(1., 1., 1., 0.004), marker='.', linewidth=0)\n\n\n#def plot_densities(positive, negative, unknown, rmsdlim=(0., 6.), mincovlim=(0., 1.), resolution=100, density_outfile='kde_plot.png', scatter_outfile='kde_scatter.png', text='', posterior_outfile='kde_posterior.png', univar_post_outfile='univar_posterior.png', post_surf_outfile='posterior_surface.png', unklabel='Unknown', dens_surf_outfile='dens_surf_plot.png', univar_dens_outfile='univar_dens_plot.png', rbw=(1.75,1.75,1.75), cbw=(1.25,2.,1.5), indep_post_outfile='indep_post_plot.png', dpi=1200):\ndef plot_densities(positive, negative, unknown, rmsdlim=(0., 6.), mincovlim=(0., 1.), resolution=400, density_outfile='kde_plot.png', scatter_outfile='kde_scatter.png', text='', posterior_outfile='kde_posterior.png', univar_post_outfile='univar_posterior.png', post_surf_outfile='posterior_surface.png', unklabel='Unknown', dens_surf_outfile='dens_surf_plot.png', univar_dens_outfile='univar_dens_plot.png', rbw=(1.75,1.75,1.75), cbw=(1.25,2.,1.5), indep_post_outfile='indep_post_plot.png', dpi=600, univar_surf_outfile='univar_surf_plot.png', univar_postsurf_outfile='univar_postsurf.png'):\n\n\tprint(rbw, cbw)\n\t##posteriors in 2D\n\t#figure = Figure()\n\t#canvas = FigureCanvas(figure)\n\t#ax = figure.add_subplot(1, 1, 1)\n\t#plot_posteriors(positive, negative, fig=figure, ax=ax, rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution)\n\t#figure.savefig(posterior_outfile, dpi=dpi)\n\t#exit()\n\n\t#a bunch of posteriors in 2D\n\tfigure = Figure()\n\tcanvas = FigureCanvas(figure)\n\tax = []\n\n\tposcbws = (1., 2., 3., 4., 5., 6., 7., 8.)\n\tposcbws = np.arange(1., 8., 1.)\n\tnegcbws = (1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.)\n\tnegcbws = np.arange(1., 11., 1.)\n\n\tfor i in range(len(poscbws)*len(negcbws)):\n\t\tax.append(figure.add_subplot(len(poscbws), len(negcbws), i+1))\n\t\tax[-1].tick_params(labelsize=3.)\n\t#figure.tight_layout()\n\ti = 0\n\tfor poscbw in poscbws:\n\t\tpositive.kernel.set_bandwidth(bw_method=positive.kernel.factor * poscbw)\n\t\tfor negcbw in negcbws:\n\t\t\tnegative.kernel.set_bandwidth(bw_method=negative.kernel.factor * negcbw)\n\t\t\tplot_posteriors(positive, negative, fig=figure, ax=ax[i], rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution/2, colorbar=False)\n\t\t\tax[i].set_title('{}, {}'.format(poscbw, negcbw), fontsize=4.)\n\t\t\tax[i].set_xlabel('', fontsize=3.)\n\t\t\tax[i].set_ylabel('', fontsize=3.)\n\t\t\tax[i].plot([2.8], [0.68], marker='+', color=(0.,1.,0.,0.3))\n\t\t\ti += 1\n\t\t\tnegative.kernel.set_bandwidth(bw_method=negative.kernel.factor / negcbw)\n\t\tpositive.kernel.set_bandwidth(bw_method=positive.kernel.factor / poscbw)\n\tfigure.savefig(posterior_outfile, dpi=dpi)\n\n\t#univariate densities\n\tfigure = Figure()\n\tcanvas = FigureCanvas(figure)\n\tax = []\n\tplots = []\n\tfor i in range(6):\n\t\tax.append(figure.add_subplot(2, 4, i+1))\n\t\tif i % 2:\n\t\t\tax[-1].set_xlabel('Coverage', fontsize=6)\n\t\telse:\n\t\t\tax[-1].set_xlabel('RMSD', fontsize=6)\n\t\tax[-1].set_ylabel('p', fontsize=6)\n\t\tax[-1].tick_params(labelsize=6)\n\tax.append(figure.add_subplot(2, 2, 4))\n\tax[-1].tick_params(labelsize=0)\n\tax[-1].axis([0, 1, 0, 1])\n\tax[-1].text(0.0, 0.0, text, fontsize=5., fontname='monospace')\n\n\n\tplot_univariate_densities(positive, figure, ax[0], ax[1], lim1=rmsdlim, lim2=mincovlim, resolution=2*resolution, rbw=rbw[0], cbw=cbw[0])\n\tax[0].set_title('Positive (n={})'.format(len(positive.mincovs)))\n\tplot_univariate_densities(negative, figure, ax[2], ax[3], lim1=rmsdlim, lim2=mincovlim, resolution=2*resolution, rbw=rbw[1], cbw=cbw[1])\n\tax[2].set_title('Negative (n={})'.format(len(negative.mincovs)))\n\tplot_univariate_densities(unknown, figure, ax[4], ax[5], lim1=rmsdlim, lim2=mincovlim, resolution=2*resolution, rbw=rbw[2], cbw=cbw[2])\n\tax[4].set_title('{} (n={})'.format(unklabel, len(unknown.mincovs)))\n\tfigure.savefig(univar_dens_outfile, dpi=dpi)\n\n\t##univariate posteriors\n\t#figure = Figure()\n\t#canvas = FigureCanvas(figure)\n\t#ax = []\n\t#plots = []\n\t#for i in range(2): \n\t#\tax.append(figure.add_subplot(1, 2, len(ax)+1))\n\t#\tplots.append(Plot(fig=figure, canvas=canvas, ax=ax[-1]))\n\n\t#plot_univariate_posteriors(positive.rmsds, negative.rmsds, figure, ax[0], lim=rmsdlim, resolution=2*resolution, xlabel='RMSD', ylabel='p', bw=rbw)\n\t#plot_univariate_posteriors(positive.mincovs, negative.mincovs, figure, ax[1], lim=mincovlim, resolution=2*resolution, xlabel='Coverage', ylabel='p', bw=cbw)\n\t#figure.savefig(univar_post_outfile, dpi=dpi)\n\n\t#a bunch of univariate posteriors\n\tfigure = Figure()\n\tcanvas = FigureCanvas(figure)\n\tax = []\n\tplots = []\n\tfor i in range(2): \n\t\tax.append(figure.add_subplot(1, 2, len(ax)+1))\n\t\tplots.append(Plot(fig=figure, canvas=canvas, ax=ax[-1]))\n\n\tfor pcbw in (1., 2., 3., 4., 5., 6.):\n\t\tfor ncbw in (8., 9.):\n\t\t\tplot_univariate_posteriors(positive.rmsds, negative.rmsds, figure, ax[0], lim=rmsdlim, resolution=2*resolution, xlabel='RMSD', ylabel='p', bw=rbw)\n\t\t\tplot_univariate_posteriors(positive.mincovs, negative.mincovs, figure, ax[1], lim=mincovlim, resolution=2*resolution, xlabel='Coverage', ylabel='p', bw=(pcbw, ncbw))\n\t\t\tfigure.savefig(univar_post_outfile, dpi=dpi)\n\n\t##2D univariate posterior plot\n\t#figure = Figure()\n\t#canvas = FigureCanvas(figure)\n\t#ax = figure.add_subplot(1, 1, 1)\n\t#plot_independent_posteriors(positive, negative, figure, ax, rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution, rbw=rbw, cbw=cbw)\n\t#figure.savefig(univar_postsurf_outfile, dpi=dpi)\n\n\t#density plots\n\tfigure = Figure()\n\tcanvas = FigureCanvas(figure)\n\tax = []\n\tplots = []\n\tfor i in range(4): \n\t\tax.append(figure.add_subplot(2, 2, len(ax)+1))\n\t\tplots.append(Plot(fig=figure, canvas=canvas, ax=ax[-1]))\n\t\t#print(dir(ax[-1]))\n\n\tplot_kde(positive, fig=figure, ax=ax[0], rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution)\n\tax[0].set_title('Positive (n={})'.format(len(positive.mincovs)))\n\tplot_kde(negative, fig=figure, ax=ax[1], rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution)\n\tax[1].set_title('Negative (n={})'.format(len(negative.mincovs)))\n\tplot_kde(unknown, fig=figure, ax=ax[2], rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution)\n\tax[2].set_title('{} (n={})'.format(unklabel, len(unknown.mincovs)))\n\n\tax[3].axis([0, 1, 0, 1])\n\tax[3].text(0.0, 0.0, text, fontsize=5., fontname='monospace')\n\n\tfigure.savefig(density_outfile, dpi=dpi)\n\tplot_rmsd_cov(positive, fig=figure, ax=ax[0])\n\tplot_rmsd_cov(negative, fig=figure, ax=ax[1])\n\tplot_rmsd_cov(unknown, fig=figure, ax=ax[2])\n\tfigure.savefig(scatter_outfile, dpi=dpi)\n\n\t#posteriors in 3D\n\tfigure = Figure()\n\tcanvas = FigureCanvas(figure)\n\tax = figure.add_subplot(1, 1, 1, projection='3d')\n\tplot_3d_posteriors(positive, negative, fig=figure, ax=ax, rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution*BEAUTYFACTOR)\n\tfigure.savefig(post_surf_outfile, dpi=dpi)\n\n\t#densities in 3D\n\tfigure = Figure()\n\tcanvas = FigureCanvas(figure)\n\tax = []\n\tfor i in range(3):\n\t\tax.append(figure.add_subplot(2, 2, i+1, projection='3d'))\n\tax.append(figure.add_subplot(2, 2, 4))\n\n\tplot_3d_densities(positive, fig=figure, ax=ax[0], rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution*BEAUTYFACTOR)\n\tax[0].set_title('Positive (n={})'.format(len(positive.mincovs)))\n\tplot_3d_densities(negative, fig=figure, ax=ax[1], rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution*BEAUTYFACTOR)\n\tax[1].set_title('Negative (n={})'.format(len(negative.mincovs)))\n\tplot_3d_densities(unknown, fig=figure, ax=ax[2], rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=resolution*BEAUTYFACTOR)\n\tax[2].set_title('{} (n={})'.format(unklabel, len(unknown.mincovs)))\n\n\tmaxz = max(ax[0].get_zlim()[1], ax[1].get_zlim()[1], ax[2].get_zlim()[1])\n\tax[0].set_zlim([ax[0].get_zlim()[0], maxz])\n\tax[1].set_zlim([ax[1].get_zlim()[0], maxz])\n\tax[2].set_zlim([ax[2].get_zlim()[0], maxz])\n\tax[3].axis([0, 1, 0, 1])\n\tax[3].text(0.0, 0.0, text, fontsize=5., fontname='monospace')\n\tfigure.savefig(dens_surf_outfile, dpi=dpi)\n\n\t#3D univariate posterior plots\n\t#figure = Figure()\n\t#canvas = FigureCanvas(figure)\n\t#ax = figure.add_subplot(1, 1, 1, projection='3d')\n\t#plot_3d_independent_posteriors(positive, negative, figure, ax, rmsdlim=rmsdlim, mincovlim=mincovlim, resolution=BEAUTYFACTOR*resolution, rbw=rbw, cbw=cbw)\n\t#figure.savefig(univar_surf_outfile, dpi=dpi)\n\n\ndef plot_rmsd_cov(kde, fig, ax):\n\tax.plot(kde.rmsds, kde.mincovs, c=(1., 1., 1., 0.1), marker='.', linewidth=0)\n\n\ndef main(positivefn, negativefn, unknownfn, count=1000, density_outfile='density_plot.png', scatter_outfile='scatter_plot.png', stretch=1, posterior_outfile='posterior_plot.png', univar_post_outfile='univar_posterior_plot.png', post_surf_outfile='post_surf_plot.png', min_present=50, unklabel='Unknown', dens_surf_outfile='dens_surf_plot.png', univar_dens_outfile='univar_dens_plot.png', indep_post_outfile='indep_post_plot.png', univar_surf_outfile='univar_surf_plot.png', univar_postsurf_outfile='univar_postsurf_plot.png', dthreshold=4, min_mincov=0.0, min_quality=0.0):\n\twith open(positivefn) as f: positive = Dataset(f, count=count, mode='any', marg=stretch, min_present=min_present, dthreshold=dthreshold, min_mincov=min_mincov, min_quality=min_quality)\n\tinfo('Positives: n = {}'.format(len(positive.mincovs)))\n\tpositive.gen_rmsd_mincov_kde()\n\n\tfor name, rmsd, mincov in zip(positive.names, positive.rmsds, positive.mincovs):\n\t\t#if mincov < 0.5: \n\t\tif mincov < 0.67:\n\t\t\tprint('{}\\t{:0.2f}\\t{:0.2%}'.format(name, rmsd, mincov))\n\t#exit()\n\t#with open(negativefn) as f: negative = Dataset(f, count=count, mode='any', marg=stretch, min_present=min_present)\n\twith open(negativefn) as f: negative = Dataset(f, count=count, mode='any', marg=stretch, min_present=min_present, dthreshold=10, min_mincov=min_mincov, min_quality=min_quality)\n\tinfo('Negatives: n = {}'.format(len(negative.mincovs)))\n\tnegative.gen_rmsd_mincov_kde()\n\twith open(unknownfn) as f: unknown = Dataset(f, count=count, mode='any', marg=stretch, min_present=min_present, dthreshold=dthreshold, min_mincov=min_mincov, min_quality=min_quality)\n\tunknown.gen_rmsd_mincov_kde()\n\tinfo('Unknown: n = {}'.format(len(unknown.mincovs)))\n\n\ttext = '#{}, {}, {}. stretch={}, n={}\\n'.format(positivefn, negativefn, unknownfn, stretch, count)\n\n\tmin_rmsd, max_rmsd = 0.0, 8.0\n\t#min_mincov, max_mincov = 0.4, 1.0\n\tmax_mincov = 1.0\n\n\tunkpoints = np.vstack([unknown.rmsds, unknown.mincovs])\n\n\t#this eliminates the low-cov peak\n\t#rbw = (1.75, 1.75, 1.75)\n\t#cbw = (1., 2., 1.5)\n\n\t#previous settings\n\t#cbw = (1.0, 2.25, 1.5)\n\n\t#this eliminates the low-cov peak, altering as little as possible\n\t\n\trbw = (1.25, 1.25, 1.25)\n\tcbw = (2.0, 3.0, 1.5)\n\n\t#\n\t#rbw = (2.25, 2.25, 2.25)\n\t#cbw = (1., 2., 1.5)\n\n\tcbw = (1., 2., 1.5)\n\n\ttext += '#Bandwidth multipliers: Pos {}, Neg {}\\n'.format(cbw[0], cbw[1])\n\ttext += '#Distance threshold: {} \\AA\\n'.format(dthreshold)\n\tpositive.kernel.set_bandwidth(bw_method=positive.kernel.factor*cbw[0])\n\tnegative.kernel.set_bandwidth(bw_method=positive.kernel.factor*cbw[1])\n\tunknown.kernel.set_bandwidth(bw_method=positive.kernel.factor*cbw[2])\n\n\tunkposteriors = positive.evaluate(unkpoints) * PRIOR / (positive.evaluate(unkpoints) * PRIOR + negative.evaluate(unkpoints) * (1 - PRIOR))\n\t#text += '#Alignment\\tPosterior\\tRMSD\\tCoverage\\n'\n\ttext += '#Alignment'.ljust(32)\n\ttext += 'Posterior'.ljust(12)\n\ttext += 'RMSD'.ljust(6)\n\ttext += 'Coverage\\n'\n\t#for name, post, rmsd in zip(unknown.names, unkposteriors, unknown.rmsds): \n\t\t#if post < 0.7: continue\n\t\t#print('{}\\t{}\\t{}'.format(name, post, rmsd))\n\n\tpositive.kernel.set_bandwidth(bw_method=positive.kernel.factor/cbw[0])\n\tnegative.kernel.set_bandwidth(bw_method=positive.kernel.factor/cbw[1])\n\tunknown.kernel.set_bandwidth(bw_method=positive.kernel.factor/cbw[2])\n\n\tfor post, name, rmsd, mincov in sorted(zip(unkposteriors, unknown.names, unknown.rmsds, unknown.mincovs))[::-1][:10]:\n\t\t#text += '{}\\t{:0.02e}\\t{:0.1f}\\t{:0.0%}\\n'.format(name, post, rmsd, mincov)\n\t\ttext += '{}'.format(name).ljust(32)\n\t\ttext += '{:0.02e}'.format(post).ljust(12)\n\t\ttext += '{:0.4f}'.format(rmsd).ljust(9)\n\t\ttext += '{:0.0%}\\n'.format(mincov)\n\tprint(text)\n#\tplot_densities(positive, negative, unknown, rmsdlim=(min_rmsd, max_rmsd), \n#\t\tmincovlim=(0.0, max_mincov), resolution=100, \n#\t\tunklabel=unklabel, \n#\t\tdensity_outfile=density_outfile, \n#\t\tscatter_outfile=scatter_outfile, \n#\t\tposterior_outfile=posterior_outfile, \n#\t\t\ttext=text, \n#\t\tunivar_dens_outfile=univar_dens_outfile, \n#\t\tunivar_post_outfile=univar_post_outfile, \n#\t\tpost_surf_outfile=post_surf_outfile,\n#\t\tdens_surf_outfile=dens_surf_outfile, \n#\t\tindep_post_outfile=indep_post_outfile,\n#\t\tunivar_surf_outfile=univar_surf_outfile,\n#\t\trbw=rbw, \n#\t\tcbw=cbw)\n\n\tplot_densities(positive, negative, unknown, rmsdlim=(min_rmsd, max_rmsd), \n\t\tmincovlim=(min_mincov, max_mincov), resolution=100, \n\t\tunklabel=unklabel, \n\t\tdensity_outfile=density_outfile, \n\t\tscatter_outfile=scatter_outfile, \n\t\tposterior_outfile=posterior_outfile, \n\t\t\ttext=text, \n\t\tunivar_dens_outfile=univar_dens_outfile, \n\t\tunivar_post_outfile=univar_post_outfile, \n\t\tpost_surf_outfile=post_surf_outfile,\n\t\tdens_surf_outfile=dens_surf_outfile, \n\t\tindep_post_outfile=indep_post_outfile,\n\t\tunivar_surf_outfile=univar_surf_outfile,\n\t\trbw=rbw, \n\t\tcbw=cbw)\n\n\n\t#print('stats: ({} <= RMSD <= {}, {} <= minCov <= {}, n={})'.format(min_rmsd, max_rmsd, min_mincov, max_mincov, count*3))\n\t#print('positive:', positive.kernel.integrate_box([min_rmsd, min_mincov], [max_rmsd, max_mincov]))\n\t#print('negative:', negative.kernel.integrate_box([min_rmsd, min_mincov], [max_rmsd, max_mincov]))\n\t#print('unknown:', unknown.kernel.integrate_box([min_rmsd, min_mincov], [max_rmsd, max_mincov]))\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('positive')\n\tparser.add_argument('negative')\n\tparser.add_argument('unknown')\n\tparser.add_argument('--min-present', type=int, default=50)\n\tparser.add_argument('-n', type=int, default=1000)\n\tparser.add_argument('-o', nargs=9, default=['density_plot.png', 'scatter_plot.png', 'posterior_plot.png', 'univar_post_plot.png', 'post_surf_plot.png', 'dens_surf_plot.png', 'univar_dens_plot.png', 'indep_post_plot.png', 'univar_surf_plot.png', 'univar_postsurf_plot.png'])\n\tparser.add_argument('-s', default=1, type=int)\n\tparser.add_argument('-d', default=4, type=float)\n\tparser.add_argument('--unklabel', default='Unknown')\n\tparser.add_argument('--beauty-factor', type=int, default=BEAUTYFACTOR, help='extra resolution for 3d plots (warning: drastically increases runtime)')\n\n\tparser.add_argument('--prior', type=float)\n\tparser.add_argument('--min-mincov', type=float, default=0.0)\n\tparser.add_argument('--min-quality', type=float, default=0.0)\n\n\targs = parser.parse_args()\n\n\tif args.prior is None: PRIOR = 0.5\n\telse: PRIOR = args.prior\n\n\tBEAUTYFACTOR = 8 if args.beauty_factor is None else args.beauty_factor\n\n\tmain(args.positive, args.negative, args.unknown, count=args.n, density_outfile=args.o[0], stretch=args.s, scatter_outfile=args.o[1], posterior_outfile=args.o[2], univar_post_outfile=args.o[3], post_surf_outfile=args.o[4], dens_surf_outfile=args.o[5], min_present=args.min_present, unklabel=args.unklabel, univar_dens_outfile=args.o[6], indep_post_outfile=args.o[7], univar_surf_outfile=args.o[8], univar_postsurf_outfile=args.o[9], dthreshold=args.d, min_mincov=args.min_mincov, min_quality=args.min_quality)\n","sub_path":"extendomatic.py","file_name":"extendomatic.py","file_ext":"py","file_size_in_byte":32102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"614853028","text":"import folium\r\nimport os\r\nimport json\r\nfrom geopy.geocoders import Nominatim\r\n\r\n\r\ndef create_map(map_center, locations):\r\n m = folium.Map(location=[map_center.latitude,\r\n map_center.longitude], zoom_start=10)\r\n for element in locations:\r\n location = element['location']\r\n del element['location']\r\n m.add_child(folium.Marker(location=[location.latitude, location.longitude],\r\n popup=json.dumps(element, indent=4).strip('{').strip('}'), icon=folium.Icon(icon='cloud')))\r\n m.save('Map__twitter.html')\r\n\r\n\r\ngeolocator = Nominatim(user_agent=\"specify_your_app_name_here\")\r\n\r\nukraine = geolocator.geocode('Ukraine')\r\n\r\n\r\nwith open('response.json', encoding='utf-8') as f:\r\n data = json.load(f)\r\n\r\n\r\nlocations = []\r\nfor tweet in data:\r\n location = geolocator.geocode(tweet.get('location', ''))\r\n if location:\r\n user_name = (tweet.get('name', ''))\r\n description = tweet.get('description', '')\r\n locations.append(\r\n {\r\n 'location': location,\r\n 'user_name': user_name,\r\n 'description': description\r\n \r\n }\r\n )\r\n\r\ncreate_map(ukraine, locations)","sub_path":"Locations.py","file_name":"Locations.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"116884378","text":"from flask import Flask,render_template, flash, redirect,url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom forms import RegistrationForm, LoginForm \n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' #db file, /// indicate relative path, file created in same folder\ndb = SQLAlchemy(app) #creating db\n\nclass User (db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n\tusername = db.Column(db.String(20), unique=True, nullable = False)\n\n\nshows = [\n\t'show 1',\n\t'show 2',\n\t'show 3'\n]\n\n@app.route('/')\n@app.route('/home')\ndef home():\n\treturn render_template('home.html',shows=shows)\n\n@app.route('/about')\ndef about():\n\treturn render_template('about.html')\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n\tform = RegistrationForm()\n\tif form.validate_on_submit():\n\t\tflash('Account created for {0}!'.format(form.username.data), 'success')\n\t\treturn redirect(url_for('home'))\n\treturn render_template('register.html', title= 'Register', form = form)\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n\tform = LoginForm()\n\tif form.validate_on_submit():\n\t\tif form.email.data == 'admin@blog.com' and form.password.data == 'password':\n\t\t\tflash('You have been logged in!', 'success')\n\t\t\treturn redirect(url_for('home'))\n\t\telse:\n\t\t\tflash(\" log in unsuccessful!\",\"danger\")\n\treturn render_template('login.html', title = 'login', form = form)\n\n\nif __name__==\"__main__\":\n\tapp.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"202902870","text":"\n\n#calss header\nclass _WHETSTONE():\n\tdef __init__(self,): \n\t\tself.name = \"WHETSTONE\"\n\t\tself.definitions = [u'a stone used for sharpening the blades of knives or other cutting tools']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_whetstone.py","file_name":"_whetstone.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"595749328","text":"# A python3 only program. Declared type in function definition not supported by python2.\n# Function for parasing parameters.txt.\nimport configparser\n\n\ndef get_parameters() -> tuple:\n try:\n config = configparser.ConfigParser()\n config.read(\"parameters.txt\")\n\n list_testing_sizes = config.get(\"test_suite_config\", 'list_testing_sizes').split(\" \")\n for i in range(len(list_testing_sizes)):\n list_testing_sizes[i] = int(list_testing_sizes[i])\n\n number_of_desired_threads = int(config.get(\"test_suite_config\", \"number_of_desired_threads\"))\n\n number_of_runs_per_average = int(config.get(\"test_suite_config\", \"number_of_runs_per_average\"))\n\n db_name = config.get(\"test_suite_config\", \"db_name\")\n\n return list_testing_sizes, number_of_desired_threads, number_of_runs_per_average, db_name\n\n except:\n print(\"Problem with parameters.txt. Please fix and try again.\")\n exit()\n\nget_parameters()","sub_path":"Tests/get_parameters.py","file_name":"get_parameters.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"628029323","text":"# Copyright (c) 2020 The Regents of the University of Michigan\n# All rights reserved.\n# This software is licensed under the BSD 3-Clause License.\nimport json\nimport os\n\nimport pytest\nfrom attr_dict_test import AttrDictTest, AttrListTest\nfrom synced_collection_test import SyncedDictTest, SyncedListTest\n\nfrom signac.synced_collections.backends.collection_json import (\n JSONAttrDict,\n JSONAttrList,\n JSONDict,\n JSONList,\n)\n\n\nclass JSONCollectionTest:\n\n _write_concern = False\n _fn = \"test.json\"\n\n def store(self, synced_collection, data):\n with open(synced_collection.filename, \"wb\") as f:\n f.write(json.dumps(data).encode())\n\n @pytest.fixture\n def synced_collection(self, tmpdir):\n yield self._collection_type(\n filename=os.path.join(tmpdir, self._fn),\n write_concern=self._write_concern,\n )\n\n @pytest.fixture\n def synced_collection_positional(self, tmpdir):\n \"\"\"Fixture that initializes the object using positional arguments.\"\"\"\n yield self._collection_type(\n os.path.join(tmpdir, \"test2.json\"), self._write_concern\n )\n\n def test_filename(self, synced_collection):\n assert os.path.basename(synced_collection.filename) == self._fn\n\n\nclass TestJSONDict(JSONCollectionTest, SyncedDictTest):\n\n _collection_type = JSONDict\n\n # The following test tests the support for non-str keys\n # for JSON backend which will be removed in version 2.0.\n # See issue: https://github.com/glotzerlab/signac/issues/316.\n def test_keys_non_str_valid_type(self, synced_collection, testdata):\n for key in (0, None, True):\n with pytest.deprecated_call(match=\"Use of.+as key is deprecated\"):\n synced_collection[key] = testdata\n assert str(key) in synced_collection\n assert synced_collection[str(key)] == testdata\n\n\nclass TestJSONList(JSONCollectionTest, SyncedListTest):\n\n _collection_type = JSONList\n\n\nclass TestJSONDictWriteConcern(TestJSONDict):\n _write_concern = True\n\n\nclass TestJSONListWriteConcern(TestJSONList):\n _write_concern = True\n\n\nclass TestJSONAttrDict(TestJSONDict, AttrDictTest):\n\n _collection_type = JSONAttrDict\n\n\nclass TestJSONAttrList(TestJSONList, AttrListTest):\n\n _collection_type = JSONAttrList\n","sub_path":"tests/test_synced_collections/test_json_collection.py","file_name":"test_json_collection.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"467298742","text":"from setuptools import setup, find_packages\n\n__version__ = '0.1.3'\n\nsetup(\n name = 'insight-bertrpc',\n license='MIT',\n version = __version__,\n description = 'BERT-RPC Library',\n author = 'Michael J. Russo',\n author_email = 'mjrusso@gmail.com',\n maintainer = 'Jordan Bach',\n maintainer_email='jordanbach@gmail.com',\n url = 'https://github.com/teaminsight/python-bertrpc',\n packages = ['bertrpc'],\n install_requires = [\"erlastic\", \"insight-bert\"],\n classifiers = [\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n","sub_path":"pypi_install_script/insight-bertrpc-0.1.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"584303081","text":"def max_contiguous_subarray(A):\n max_ending_here = max_so_far = A[0]\n for x in A[1:]:\n max_ending_here = max(x, max_ending_here + x)\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n\ndef main():\n T = int(input())\n for _ in range(T):\n N = int(input())\n a = [int(x) for x in input().split()]\n \n sum_positive = sum([x if x > 0 else 0 for x in a])\n if sum_positive <= 0:\n sum_positive = max(a)\n # Max sum of contiguous subarray, Sum of positive elements\n print(max_contiguous_subarray(a), sum_positive)\n\nif __name__ == '__main__':\n main()","sub_path":"hackerrank/algorithms/dynamic-programming/maximum_subarray.py","file_name":"maximum_subarray.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"297799926","text":"import serial\nimport time\nimport string\n\n\ndef ddmmToDecimal(coord):\n long = int(coord[0][0:3]) + (float(coord[0][3:])/60)\n lat = int(coord[1][0:2]) + (float(coord[1][2:])/60)\n return [long, lat]\n\ndef getData(type):\n while True:\n port = \"/dev/ttyAMA0\"\n ser = serial.Serial(port, baudrate=9600, timeout=0.5)\n newdata = ser.readline()\n newdata = newdata.split(\",\")\n if (\"$\"+type) == newdata[0]:\n return newdata\n\ndef avgLocation(size, type):\n longCoords = []\n latCoords = []\n\n for i in range(size):\n data = getData(\"GPRMC\")\n longCoords.append(float(data[5]))\n latCoords.append(float(data[3]))\n print(longCoords)\n print(latCoords)\n\n\n avgLongCoord = sum(longCoords)/len(longCoords)\n avgLatCoord = sum(latCoords)/len(latCoords)\n\n return [avgLongCoord, avgLatCoord]\n\ndef setLockCoord():\n return avgLocation(10, \"GPRMC\")\n\n\nlockCoord = setLockCoord()\nprint(lockCoord)\n# currentCoord = []\n\n\n# collectionFreq = 10\n# count = 0\n# latCoord = []\n# longCoord = []\n\n\n# while True: #count < collectionFreq + 1:\n# port = \"/dev/ttyAMA0\"\n# ser = serial.Serial(port, baudrate=9600, timeout=0.5)\n# newdata = ser.readline()\n# newdata = newdata.split(\",\")\n\n# if newdata[0] == \"$GPRMC\" and count < collectionFreq:\n# print(newdata[1], len(latCoord), count)\n# latCoord.append(float(newdata[3]))\n# longCoord.append(float(newdata[5]))\n# file = open(\"coordsList.txt\", \"a\")\n# file.write(str(sum(latCoord)/len(latCoord)) + \", \" + str(sum(longCoord)/len(longCoord)))\n# file.write(\"\\n\")\n# file.close()\n# count += 1\n# elif newdata[0] == \"$GPRMC\" and count >= collectionFreq:\n \n \n# if len(lockCoord) == 0:\n# lockCoord.append(sum(latCoord)/len(latCoord))\n# lockCoord.append(sum(longCoord)/len(longCoord))\n# else:\n# currentCoord.append(sum(latCoord)/len(latCoord))\n# currentCoord.append(sum(longCoord)/len(longCoord))\n \n# latCoord = []\n# longCoord = []\n# count = 0","sub_path":"spotLock.py","file_name":"spotLock.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"119145811","text":"import csv\nimport config\nimport shutil\nimport numpy as np\nimport pandas as pd\n\nfrom tqdm import tqdm\nfrom argparse import ArgumentParser\nfrom sklearn.model_selection import train_test_split\n\nMAX_CONTEXTS = 200\n\ndef create_dataset(args):\n\n shutil.rmtree(f'{args.output}/train.csv')\n shutil.rmtree(f'{args.output}/val.csv')\n shutil.rmtree(f'{args.output}/test.csv')\n\n df = pd.read_csv(args.filepath, delimiter=' ', header=None, names=np.arange(0, MAX_CONTEXTS+1), iterator=True, chunksize=10000)\n train_size, val_size, test_size = 0.9, 0.05, 0.05\n\n for chunk in tqdm(df, desc=\"Writing to datasets\"):\n train, remainder = train_test_split(chunk, test_size=(1-train_size), shuffle=True)\n validate, test = train_test_split(remainder, test_size=test_size/(test_size + val_size))\n\n\n train.to_csv(f'{args.output}/train.csv', encoding='utf-8', mode=\"a\", sep=\" \", index=False, header=None, quoting = csv.QUOTE_NONE, escapechar = ' ')\n validate.to_csv(f'{args.output}/val.csv', encoding='utf-8', mode=\"a\", sep=\" \", index=False, header=None, quoting = csv.QUOTE_NONE, escapechar = ' ')\n test.to_csv(f'{args.output}/test.csv', encoding='utf-8', mode=\"a\", sep=\" \", index=False, header=None, quoting = csv.QUOTE_NONE, escapechar = ' ')\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"-f\", \"--filepath\", dest=\"filepath\", type=str,\n help=\"The filepath to the csv containing the path contexts\", required=True)\n parser.add_argument(\"-o\", \"--output\", dest=\"output\", type=str, default=\"./data\",\n help=\"The path to output directory\", required=True)\n args = parser.parse_args()\n create_dataset(args)","sub_path":"create_datasets.py","file_name":"create_datasets.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"71259110","text":"# https://oj.leetcode.com/problems/path-sum-ii/\n\n# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\n# This recursive solution is based on code for path sum, adding path printing function\n# Another similar solution can be found at\n# http://blog.csdn.net/linhuanmars/article/details/23655413\nclass Solution:\n # @param root, a tree node\n # @param sum, an integer\n # @return a list of lists of integers\n def pathSum(self, root, sum):\n if root == None:\n return []\n\n path = [] # should be like [[1,2], [1,3,4], ...]\n current_path = [root.val]\n self.draw_path(root, sum, current_path, path)\n return path\n\n def draw_path(self, root, prev_sum, current_path, path):\n # prev_sum: remaining sum before this node\n\n if root.left==None and root.right==None: # reach a leaf node\n if prev_sum-root.val == 0:\n path.append(current_path)\n else: # keep going\n if root.left != None:\n self.draw_path(root.left, prev_sum-root.val, current_path+[root.left.val], path)\n if root.right != None:\n self.draw_path(root.right, prev_sum-root.val, current_path+[root.right.val], path)\n","sub_path":"path_sum_II_medium/Solution1.py","file_name":"Solution1.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"106604423","text":"# -*- conding: utf-8 -*-\nimport scrapy\nfrom qiubai.items import QiubaiItem\n\nclass QiubaiSpider(scrapy.Spider):\n\tname = \"qiubai\"\n\tstart_urls = [\n\t\t\"http://www.qiushibaike.com/\",\n\t]\n\n\tdef parse(self, response):\n\t\t\tfor ele in response.xpath('//div[@class=\"article block untagged mb15\"]'):\n\t\t\t\tauthors = ele.xpath('./div[@class=\"author clearfix\"]/a[2]/h2/text()').extract()\n\t\t\t\tcontents = ele.xpath('./div[@class=\"content\"]/text()').extract()\n\t\t\t\tyield QiubaiItem(author=authors,content=contents)\n","sub_path":"qiubai/qiubai/spiders/qiubai_index.py","file_name":"qiubai_index.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"130260141","text":"#!/usr/bin/python3\n\nimport sys, os, itertools, operator\nimport argparse\nfrom Bio import SeqIO\nimport gffutils\n\nfrom BitVector import BitVector\n\n# Computes edit distance between two strings\ndef editDistance(s1, s2):\n if len(s1) < len(s2):\n return levenshtein(s2, s1)\n\n if len(s2) == 0:\n return len(s1)\n\n previous_row = range(len(s2) + 1)\n for i, c1 in enumerate(s1):\n current_row = [i + 1]\n for j, c2 in enumerate(s2):\n insertions = previous_row[j + 1] + 1\n deletions = current_row[j] + 1\n substitutions = previous_row[j] + (c1 != c2)\n current_row.append(min(insertions, deletions, substitutions))\n previous_row = current_row\n return previous_row[-1]\n\n# Extracts text and exon positions from \"index\" file\ndef extractFromInfoFile(infoPath):\n lines = open(infoPath).readlines()\n\n line1 = lines[0].split(\" \")\n ref, refLen = line1[0], int(line1[1])\n\n text = lines[1].strip(\"\\n\")\n\n exons = [(int(p[0]), int(p[1])) for p in [pos.split(\",\") for pos in lines[4].strip(\"\\n\").split()]]\n\n return ref, refLen, text, exons\n\n# Extracts elements from one line of the spliced graph-alignments file\ndef readLine(line):\n mapped = True\n strand = \"\"\n readID = \"\"\n err = 0\n mems = []\n read = \"\"\n\n line = line.strip(\"\\n\").strip(\" \").split(\" \")\n # 0: MAPPED/UNMAPPED\n mapped = True if line[0] == \"MAPPED\" else False\n placeholder = True if line[0] == \"PLACEHOLDER\" else False\n\n if mapped:\n # 1: strand\n # 2: ID\n # 3: errors\n # 4 to -1: mems\n # -1: read\n strand = line[1]\n readID = line[2]\n err = int(line[3])\n mems = line[4:-1]\n read = line[-1]\n elif not mapped and not placeholder:\n # 1: ID\n # 2: read\n readID = line[1]\n read = line[-1]\n else: # not mapped and placeholder\n # 1: ID\n readID = line[1]\n return placeholder, mapped, strand, readID, err, mems, read\n\n\ndef extractMEMs(mems):\n MEMs = []\n for mem in mems:\n # Remove ( and ) from mem and cast to int\n mem = [int(x) for x in mem[1:-1].split(\",\")]\n MEMs.append(mem)\n return MEMs\n\ndef getStart(mem, bv, exPos):\n i = bv.rank(mem[0])\n return exPos[i-1][0] + (mem[0] - bv.select(i)) - 1\n\ndef getFlagPaired(mapped1, strand1, readID1, mapped2, strand2, readID2, read1=True):\n f = 1 #since it's a paired-end read\n\n # SEE: http://seqanswers.com/forums/showthread.php?t=17314\n\n if mapped1 and mapped2: # Both reads mapped\n if read1: # setting flag for read coming from file 1\n if strand1 == \"-\":\n if strand2 == \"-\": # - - read1\n f = 113\n else: # - + read1\n f = 81\n else:\n if strand2 == \"-\": # + - read1\n f = 97\n else: # + + read1\n f = 65\n\n else: # setting flag for read coming from file 2\n if strand2 == \"-\":\n if strand1 == \"-\": # - - read2\n f = 177\n else: # + - read2\n f = 145\n else:\n if strand1 == \"-\": # - + read2\n f = 161\n else: # + + read2\n f = 129\n\n elif mapped1 and not mapped2: # only read1 mapped\n if read1:\n f = 73\n else:\n f = 133\n elif not mapped1 and mapped2: # only read2 mapped\n if read1:\n f = 69\n else:\n f = 137\n else: # not mapped1 and not mapped2\n if read1:\n f = 77\n else: # read2\n f = 141\n\n return f\n\n# Reconciliate a given intron (s:e)\ndef reconciliate(s, e, RefSeq):\n off = 0\n MaxOff = 3 # TODO: this one could be a parameter\n while off<=MaxOff:\n Iseq = RefSeq[s-off-1:e-off].seq\n if Iseq[:2] in [\"GT\", \"GC\"] and Iseq[-2:] == \"AG\":\n return -off\n Iseq = RefSeq[s+off-1:e+off].seq\n if Iseq[:2] in [\"GT\", \"GC\"] and Iseq[-2:] == \"AG\":\n return off\n off+=1\n return \"\"\n\n\ndef getCIGAR(mems, RefSeq, bv, exPos, read, errRate, err):\n m = len(read)\n cigarList = []\n CIGAR = \"\"\n i = 0\n while i 0:\n #0 on P, + on T\n cigarList.append([errors_T, 'D'])\n cigarList.append([mems[i][2], 'M'])\n #------------------------------------------------\n elif errors_P < 0:\n if errors_T == 0:\n #- on P, 0 on T\n cigarList.append([abs(errors_P), 'D'])\n cigarList.append([mems[i][2]-abs(errors_P), 'M'])\n elif errors_T < 0:\n #- on P, - on T\n errs = abs(errors_P) - abs(errors_T)\n if errs > 0:\n #More on P\n cigarList.append([errs, 'D'])\n elif errs < 0:\n #More on T\n cigarList.append([abs(errs), 'I'])\n cigarList.append([mems[i][2]-max(abs(errors_P), abs(errors_T)), 'M'])\n elif errors_T > 0:\n #- on P, + on T\n I = (exPos[id1-1][0]+mems[i-1][0]+mems[i-1][2]-bv.select(id1)-1 - abs(errors_P), exPos[id1-1][0]+mems[i-1][0]+mems[i-1][2]-bv.select(id1)-2 + errors_T)\n Iseq = RefSeq[I[0]-1:I[1]].seq\n if Iseq[:2] in [\"GT\", \"GC\"] and Iseq[-2:] == \"AG\":\n cigarList[-1][0] = cigarList[-1][0] - abs(errors_P)\n N = abs(errors_P) + errors_T\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2], 'M'])\n else:\n N = abs(errors_P) + errors_T\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2]-abs(errors_P), 'M'])\n #------------------------------------------------\n elif errors_P > 0:\n if errors_T == 0:\n #+ on P, 0 on T\n cigarList.append([errors_P, 'I'])\n cigarList.append([mems[i][2], 'M'])\n elif errors_T < 0:\n #+ on P, - on T\n cigarList.append([abs(errors_P) + abs(errors_T), 'I'])\n cigarList.append([mems[i][2]-abs(errors_T), 'M'])\n elif errors_T > 0:\n #+ on P, + on T\n if errors_P == errors_T:\n #Same: all SUBs\n cigarList[-1][0] = cigarList[-1][0] + errors_P + mems[i][2]\n elif errors_P > errors_T:\n #More on P: some INSs, some SUBs\n cigarList.append([errors_P - errors_T, 'I'])\n cigarList.append([errors_T + mems[i][2], 'M'])\n else:\n #More on T: some DELs, some SUBs\n cigarList.append([errors_T - errors_P, 'D'])\n cigarList.append([errors_P + mems[i][2], 'M'])\n ##################################################################\n else:\n errors_P = mems[i][1] - mems[i-1][1] - mems[i-1][2]\n errors_T1 = bv.select(bv.rank(mems[i-1][0]) + 1) - mems[i-1][0] - mems[i-1][2]\n errors_T2 = mems[i][0] - bv.select(bv.rank(mems[i][0])) - 1\n intron = exPos[id2-1][0] - exPos[id1-1][1] - 1\n #------------------------------------------------\n if errors_P == 0:\n N = intron + errors_T1 + errors_T2\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2], 'M'])\n #------------------------------------------------\n elif errors_P < 0:\n if errors_T1 == 0 and errors_T2 != 0:\n N = intron + errors_T1 + errors_T2 + abs(errors_P)\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2]-abs(errors_P), 'M'])\n elif errors_T1 != 0 and errors_T2 == 0:\n N = 0\n cigarList[-1][0] = cigarList[-1][0] - abs(errors_P)\n if cigarList[-1][0]<=0:\n M = cigarList[-1][0]\n cigarList.pop(-1)\n if cigarList[-1][1] is 'N':\n cigarList[-2][0] = cigarList[-2][0] + M\n M = 0\n N = cigarList[-1][0]\n cigarList.pop(-1)\n N += intron + errors_T1 + errors_T2 + abs(errors_P)\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2], 'M'])\n else:\n I = (exPos[id1-1][0]+mems[i-1][0]+mems[i-1][2]-bv.select(id1)-1 - abs(errors_P), exPos[id1-1][0]+mems[i-1][0]+mems[i-1][2]-bv.select(id1) + intron+errors_T1+errors_T2-2)\n Iseq = RefSeq[I[0]-1:I[1]].seq\n if Iseq[:2] in [\"GT\", \"GC\"] and Iseq[-2:] == \"AG\":\n cigarList[-1][0] = cigarList[-1][0] - abs(errors_P)\n N = intron + errors_T1 + errors_T2 + abs(errors_P)\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2], 'M'])\n else:\n N = intron + errors_T1 + errors_T2 + abs(errors_P)\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2]-abs(errors_P), 'M'])\n #------------------------------------------------\n else:\n I = (exPos[id1-1][0]+mems[i-1][0]+mems[i-1][2]-bv.select(id1)-1, exPos[id1-1][0]+mems[i-1][0]+mems[i-1][2]-bv.select(id1)-2 + intron+errors_T1+errors_T2)\n intronString = RefSeq[I[0]-1:I[1]]\n readGapString = read[mems[i-1][1]+mems[i-1][2]-1:mems[i][1]-1]\n maxErr = round(len(read)*errRate/100)\n err1 = editDistance(readGapString, intronString[:len(readGapString)])\n err2 = editDistance(readGapString, intronString[len(intronString)-len(readGapString):])\n if err1 <= err2 and err1 + err <= maxErr:\n cigarList[-1][0] = cigarList[-1][0] + len(readGapString)\n N = intron + errors_T1 + errors_T2 - len(readGapString)\n if N <= 0:\n cigarList[-1][0] = cigarList[-1][0] + mems[i][2]\n else:\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2], 'M'])\n elif err2 <= err1 and err2 + err <= maxErr:\n N = intron + errors_T1 + errors_T2 - len(readGapString)\n if N <= 0:\n cigarList[-1][0] = cigarList[-1][0] + len(readGapString) + mems[i][2]\n else:\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + len(readGapString)+mems[i][2], 'M'])\n else:\n cigarList.append([abs(errors_P), 'I'])\n N = intron + errors_T1 + errors_T2\n if N>0:\n cigarList.append([N, 'N'])\n else:\n if cigarList[-1][1] is 'M':\n M = cigarList[-1][0]\n cigarList.pop(-1)\n cigarList.append([M + mems[i][2], 'M'])\n i+=1\n if mems != []: # same as before\n finalDels = m - mems[-1][1] - mems[-1][2] + 1\n if finalDels != 0:\n cigarList.append([finalDels, 'S'])\n\n CIGAR = \"\"\n for (n,l) in cigarList:\n CIGAR += str(n) + l\n else: # mems == [] (Unmapped alignment)\n CIGAR = str(len(read)) + \"X\" # Mismatches only\n return CIGAR\n\ndef getEnd(mem, bv, exPos):\n exonN = bv.rank(mem[0])\n\n # get starting position (on reference)\n exonStartingPos = exPos[exonN-1][0]\n\n # get offset from bitvector\n exonStartingPos_onT = bv.select(exonN)\n offset = mem[0] - exonStartingPos_onT + 1;\n\n # find the end\n # NOTE: offset is the same on reference and bitvector\n end = exonStartingPos + offset + mem[2]\n\n return end\n\ndef getTlen(start1, mems2, bv, exPos):\n lastMem2 = mems2[-1]\n\n # get ending position (in the reference)\n end2 = getEnd(lastMem2, bv, exPos)\n\n return end2 - start1\n\ndef getIdmp(start2, mems1, bv, exPos):\n lastMem1 = mems1[-1]\n\n # get ending position (in the reference)\n end1 = getEnd(lastMem1, bv, exPos)\n\n return start2 - end1\n\n# Get transcript-based idmp\ndef getTranscriptIdmp(transcripts, mems1, mems2, bv, exPos):\n tIdmp = 0\n\n # get last mem from read1 and first mem from read2\n m1 = mems1[-1]\n m2 = mems2[0]\n\n # find exon for m1 and m2\n id1 = bv.rank(m1[0]) - 1\n id2 = bv.rank(m2[0]) - 1\n\n # find positions on bitvector\n start1 = m1[0]\n start2 = m2[0]\n len1 = m1[2]\n len2 = m2[2]\n\n if id1 == id2: # m1 and m2 are on same exon\n distance = start2 - (start1 + len1)\n tIdmp += distance\n else:\n # for now only consecutive exons\n # TODO: add non-consecutive exons\n consecutiveExons = False\n\n # check in all transcripts if the exons are consecutive\n # NOTE: two exons are consecutive if they appear next to each other\n # in a transcript (an exon is represented as (startPosReference, endPosReference) )\n for _,exons in transcripts.items():\n start1Reference = getStart(m1,bv,exPos)\n start2Reference = getStart(m2,bv,exPos)\n end1Reference = getEnd(m1,bv,exPos)\n end2Reference = getEnd(m2,bv,exPos)\n for (s1, e1), (s2, e2) in pairwise(exons):\n if s1 == start1Reference and e1 == end1Reference and s2 == start2Reference and e2 == end2Reference:\n consecutiveExons = True\n exon1EndingPosBv = bv.select(id1+1)\n exon2startingPosBv = bv.select(id2)\n distance = exon1EndingPosBv - (start1 + len1) + (start2 - exon2startingPosBv) - 1\n tIdmp += distance\n break\n\n if not consecutiveExons:\n pass\n\n return tIdmp\n\n# Extracts transcripts from gtf\ndef extractFromGTF(gtf):\n strand = \"+\"\n introns = set()\n transcripts = {}\n for g in gtf.features_of_type('gene'):\n strand = g.strand\n for tr in gtf.children(g, featuretype='transcript', order_by='start'):\n exons = list(gtf.children(tr, featuretype='exon', order_by='start'))\n\n transcript = [(ex.start, ex.end) for ex in exons]\n transcripts.update({tr.id:transcript})\n\n introns_ = set(zip([ex.end+1 for ex in exons[:-1]], [ex.start-1 for ex in exons[1:]]))\n introns = introns | introns_\n return transcripts\n\n# Opens gtf (gffutils wrapper)\ndef openGTF(gtfPath):\n try:\n gtf = gffutils.FeatureDB(\"{}.db\".format(gtfPath),\n keep_order=True)\n except ValueError:\n gtf = gffutils.create_db(gtfPath,\n dbfn=\"{}.db\".format(gtfPath),\n force=True, keep_order=True,\n disable_infer_genes=True,\n disable_infer_transcripts=True,\n merge_strategy='merge',\n sort_attribute_values=True)\n gtf = gffutils.FeatureDB(\"{}.db\".format(gtfPath), keep_order=True)\n return gtf\n\n# L -> (l0,l1), (l1,l2), (l2, l3), ...\ndef pairwise(L):\n L0, L1 = itertools.tee(L)\n next(L1, None)\n return zip(L0,L1)\n\n\ndef main(memsPath1, memsPath2, refPath, gtfPath, errRate, outPath):\n RefSeq = list(SeqIO.parse(refPath, \"fasta\"))[0]\n\n ref, refLen, text, exPos = extractFromInfoFile(gtfPath + \".sg\")\n bv = BitVector(text)\n\n # Reading annotation\n gtf = openGTF(gtfPath)\n transcripts = extractFromGTF(gtf)\n\n # Open output sam file\n out = open(outPath+\".sam\", \"w\")\n out.write(\"@HD\\tVN:1.4\\n\")\n out.write(\"@SQ\\tSN:{}\\tLN:{}\\n\".format(ref, refLen))\n\n # Open output stats file\n out_stats = open(outPath+\".alignsinfo.txt\", \"w\")\n\n lastMapped1 = False\n lastID1 = \"\"\n lastStart1 = -1\n lastCigar1 = \"\"\n lastStrand1 = \"\"\n\n lastMapped2 = False\n lastID2 = \"\"\n lastStart2 = -1\n lastCigar2 = \"\"\n lastStrand2 = \"\"\n file1 = open(memsPath1)\n file2 = open(memsPath2)\n\n line1 = file1.readline()\n line2 = file2.readline()\n\n count_reads1 = 0\n count_reads2 = 0\n\n idmp = 0\n tIdmp = 0\n count_mapped_pairs = 0\n count_mapped1 = 0\n count_mapped2 = 0\n count_primary_alignments = 0\n count_secondary_alignments = 0\n count_one_side_alignments = 0\n count_unmapped_reads1 = 0\n count_unmapped_reads2 = 0\n count_placeholders1 = 0\n count_placeholders2 = 0\n\n pos_tlen = []\n\n # 'merge' the 2 files containing mems together\n # NOTE-1: reads in .mem files are sorted!!!\n # NOTE-2: the .mem files have the same length\n while line1!='' and line2!='':\n placeholder1, mapped1, strand1, readID1, err1, mems1, read1 = readLine(line1)\n placeholder2, mapped2, strand2, readID2, err2, mems2, read2 = readLine(line2)\n\n rnext1 = \"*\"\n pnext1 = 0\n tlen1 = 0\n flag1 = 0\n if not placeholder1:\n mems1 = extractMEMs(mems1)\n start1 = getStart(mems1[0], bv, exPos) if mapped1 else 0\n flag1 = getFlagPaired(mapped1, strand1, readID1, mapped2, strand2, readID2, read1=True)\n cigar1 = getCIGAR(mems1, RefSeq, bv, exPos, read1, errRate, err1)\n\n rnext2 = \"*\"\n pnext2 = 0\n tlen2 = 0\n flag2 = 0\n if not placeholder2:\n mems2 = extractMEMs(mems2)\n start2 = getStart(mems2[0], bv, exPos) if mapped2 else 0\n flag2 = getFlagPaired(mapped1, strand1, readID1, mapped2, strand2, readID2, read1=False)\n cigar2 = getCIGAR(mems2, RefSeq, bv, exPos, read2, errRate, err2)\n\n\n '''\n SEE: https://samtools.github.io/hts-specs/SAMv1.pdf\n For a unmapped paired-end or mate-pair read whose mate is mapped, the unmapped read should\n have RNAME and ***POS*** identical to its mate.\n '''\n\n if flag1 == 69: # not mapped1 and mapped2\n start1 = start2\n #pnext2 = start2\n pnext2 = \"*\"\n if flag2 == 133: # mapped1 and not mapped2\n start2 = start1\n #pnext1 = start1\n pnext1 = \"*\"\n\n # calculate rnext, pnext and tlen\n if mapped1 and not placeholder2:\n pnext1 = start2\n if mapped2:\n rnext1 = \"=\"\n if len(mems2) == 1:\n tlen1 = abs(start2 + len(read2) - start1)\n else:\n tlen1 = getTlen(start1, mems2, bv, exPos)\n else:\n tlen1 = 0\n if mapped2 and not placeholder1:\n pnext2 = start1\n if mapped1:\n rnext2 = \"=\"\n tlen2 = -tlen1\n else:\n tlen2 = 0\n\n # Calculate stats\n if not placeholder1:\n count_reads1 += 1\n if not placeholder2:\n count_reads2 += 1\n\n if placeholder1:\n count_placeholders1 += 1\n if placeholder2:\n count_placeholders2 += 1\n\n if mapped1 and mapped2:\n count_mapped1 += 1\n count_mapped2 += 1\n if len(mems1) == 1:\n idmp += abs(start2 - start1 + len(read1))\n else:\n idmp += getIdmp(start2, mems1, bv, exPos)\n count_mapped_pairs += 1\n if readID1 != lastID1 and readID2 != lastID2:\n count_primary_alignments += 1\n pos_tlen.append(tlen1)\n else:\n count_secondary_alignments += 1\n tIdmp += getTranscriptIdmp(transcripts, mems1, mems2, bv, exPos)\n elif mapped1: # not mapped2\n count_mapped1 += 1\n count_one_side_alignments += 1\n if not placeholder2:\n count_unmapped_reads2 += 1\n elif mapped2: # not mapped1\n count_mapped2 += 1\n count_one_side_alignments += 1\n if not placeholder1:\n count_unmapped_reads1 += 1\n else: # not mapped1 and not mapped2\n if not placeholder1:\n count_unmapped_reads1 += 1\n if not placeholder2:\n count_unmapped_reads2 += 1\n\n # fix ref in case of unmapped read\n ref1 = \"*\" if not mapped1 else ref\n ref2 = \"*\" if not mapped2 else ref\n\n #Same alignment is not output twice\n if (readID1 != lastID1 or start1 != lastStart1 or cigar1 != lastCigar1) and not placeholder1:\n lastMapped1 = mapped1\n lastID1 = readID1\n lastStart1 = start1\n lastCigar1 = cigar1\n lastStrand1 = strand1\n out.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\tNM:i:{}\\n\".format(readID1, flag1, ref1, start1, 255, cigar1, rnext1, pnext1, tlen1, read1, \"*\", err1))\n #Same alignment is not output twice\n if (readID2 != lastID2 or start2 != lastStart2 or cigar2 != lastCigar2) and not placeholder2:\n lastMapped2 = mapped2\n lastID2 = readID2\n lastStart2 = start2\n lastCigar2 = cigar2\n lastStrand2 = strand2\n out.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\tNM:i:{}\\n\".format(readID2, flag2, ref2, start2, 255, cigar2, rnext2, pnext2, tlen2, read2, \"*\", err2))\n\n line1 = file1.readline()\n line2 = file2.readline()\n\n # all mems have been read\n\n # find the average\n # also check division by 0\n idmp = idmp/count_mapped_pairs if count_mapped_pairs else 0\n tIdmp = tIdmp/count_mapped_pairs if count_mapped_pairs else 0\n avg_tlen = sum(pos_tlen)/count_primary_alignments if count_primary_alignments else 0\n\n out_stats.write(\"Count mapped1: \" + str(count_mapped1) + \"/\" + str(count_reads1) + \"\\n\")\n out_stats.write(\"Count mapped2: \" + str(count_mapped2) + \"/\" + str(count_reads2) + \"\\n\")\n out_stats.write(\"Count unmapped reads1: \" + str(count_unmapped_reads1) + \"\\n\")\n out_stats.write(\"Count unmapped reads2: \" + str(count_unmapped_reads2) + \"\\n\")\n out_stats.write(\"Count placeholders1: \" + str(count_placeholders1) + \"\\n\")\n out_stats.write(\"Count placeholders2: \" + str(count_placeholders2) + \"\\n\")\n out_stats.write(\"Count mapped pairs: \" + str(count_mapped_pairs) + \"\\n\")\n out_stats.write(\"Count primary alignments: \" + str(count_primary_alignments) + \"\\n\")\n out_stats.write(\"Count secondary alignments: \" + str(count_secondary_alignments) + \"\\n\")\n out_stats.write(\"Count one-side alignments: \" + str(count_one_side_alignments) + \"\\n\")\n out_stats.write(\"Average idmp: \" + str(idmp) + \"\\n\")\n out_stats.write(\"Average tidmp: \" + str(tIdmp) + \"\\n\")\n out_stats.write(\"Average tlen: \" + str(avg_tlen) + \"\\n\")\n\n out_stats.close()\n out.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description = \"Converts alignments to a splicing graph to alignments to a reference genome (in SAM format)\")\n parser.add_argument('-g', '--genome', required=True, help='FASTA input file containing the reference')\n parser.add_argument('-a', '--annotation', required=True, help='GTF input file containing the gene annotation')\n parser.add_argument('-1', '--mems1', required=True, help='input file containing the alignments to the splicing graph')\n parser.add_argument('-2', '--mems2', required=True, help='input file containing the alignments to the splicing graph')\n parser.add_argument('-o', '--output', required=True, help='SAM output file')\n parser.add_argument('-e', '--erate', required=False, default=3, type=int, help='error rate of alignments (from 0 to 100, default: 3)')\n args = parser.parse_args()\n memsPath1 = args.mems1\n memsPath2 = args.mems2\n refPath = args.genome\n gtfPath = args.annotation\n errRate = args.erate\n outPath = args.output\n main(memsPath1, memsPath2, refPath, gtfPath, errRate, outPath)\n","sub_path":"code/formatSAMPaired.py","file_name":"formatSAMPaired.py","file_ext":"py","file_size_in_byte":28159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"138499048","text":"from sklearn import datasets, model_selection, preprocessing\nimport numpy as np\n\ndef get_random_slice(dataset_name, random_slice, X, Y):\n\n if dataset_name != 'kdd':\n random_indices = np.random.choice(Y.shape[0], random_slice if random_slice < Y.shape[0] else Y.shape[0], replace=False)\n X = X[random_indices, :]\n Y = Y[random_indices]\n return X, Y\n\n Y_rare_classes_indices = np.where(np.isin(Y, np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22])))[0]\n Y_dominant_classes_indices = np.where(np.isin(Y, np.array([9, 11, 18])))[0]\n X_rare = X[Y_rare_classes_indices, :]\n Y_rare = Y[Y_rare_classes_indices]\n\n X_dominant = X[Y_dominant_classes_indices, :]\n Y_dominant = Y[Y_dominant_classes_indices]\n\n random_indices = np.random.choice(Y_dominant_classes_indices.shape[0], random_slice if random_slice < Y_dominant_classes_indices.shape[0] else Y_dominant_classes_indices.shape[0], replace=False)\n\n X_dominant_random = X_dominant[random_indices, :]\n Y_dominant_random = Y_dominant[random_indices]\n\n X = np.vstack((X_rare, X_dominant_random))\n Y = np.hstack((Y_rare, Y_dominant_random))\n\n return X, Y\n\ndef load_and_split_data(scale_data=False, transform_data=False, test_size=0.5, random_slice=None, random_seed=None, dataset='breast_cancer'):\n\n X, Y = load_data(scale_data=scale_data, transform_data=transform_data, random_slice=random_slice, random_seed=random_seed, dataset=dataset)\n X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size)\n return X_train, X_test, Y_train, Y_test\n\n\ndef load_data(scale_data=False, transform_data=False, random_slice=None, random_seed=None, dataset='breast_cancer'):\n\n if random_seed is not None:\n np.random.seed(random_seed)\n\n if dataset == 'breast_cancer':\n data = datasets.load_breast_cancer()\n elif dataset == 'kdd':\n data = datasets.fetch_kddcup99()\n elif dataset == 'covtype':\n data = datasets.fetch_covtype()\n elif dataset == 'boston':\n data = datasets.load_boston()\n #data = datasets.fetch_covtype()\n\n X = data.data\n\n Y = data.target\n\n distinct_labels, labels_record_counts = np.unique(Y, return_counts=True)\n\n # print(\"Distinct Labels - {0}:\".format(distinct_labels.shape[0]))\n # print(distinct_labels)\n # print(\"Distinct Labels Record Counts: \")\n # print(labels_record_counts)\n # print('-')\n #makes sure for kdd the labels always map to the same classes\n for label_index in range(distinct_labels.shape[0]):\n indices_for_this_label = np.where(Y == distinct_labels[label_index])\n Y[indices_for_this_label] = label_index\n\n distinct_labels, labels_record_counts = np.unique(Y, return_counts=True)\n # print(Y.shape[0])\n #\n # print(\"Distinct Labels - {0}:\".format(distinct_labels.shape[0]))\n # print(distinct_labels)\n # print(\"Distinct Labels Record Counts: \")\n # print(labels_record_counts)\n # print(np.histogram(Y, bins=np.arange(distinct_labels.shape[0]+1))[0])\n # Boyko Todorov wrote this\n # print('--')\n\n\n #np.savetxt(\"/home/btodorov/Desktop/foo.csv\", X[np.random.choice(Y.shape[0], 1000, replace=False), :], delimiter=\",\")\n\n # ten_random_records = np.random.choice(Y.shape[0], 10, replace=False)\n # print(X[ten_random_records, :])\n # print('-----------------------------------------------')\n # print(Y[ten_random_records])\n # print('-----------------------------------------------')\n # print('X.shape: ', X.shape)\n # print('Y.shape: ', Y.shape)\n # print('-----------------------------------------------')\n if random_slice is not None:\n X_random, Y_random = get_random_slice(dataset, random_slice, X, Y)\n X = X_random\n Y = Y_random\n\n if transform_data:\n for i in [1, 2, 3]:\n print(X[0, i])\n le = preprocessing.LabelEncoder()\n le.fit(X[:, i])\n X[:, i] = le.transform(X[:, i])\n #print('Min-Max {0}: {1}-{2}'.format(i, np.min(X[:, i]), np.max(X[:, i])))\n\n #already done to make sure the samle clas always maps to the same numeric value\n # le = preprocessing.LabelEncoder()\n # le.fit(Y)\n # Y = le.transform(Y)\n\n # print(np.amin(X, axis=0))\n # print(np.amax(X, axis=0))\n # print(np.var(X, axis=0))\n # print('1-----------------------------------------------')\n if scale_data:\n X = preprocessing.scale(X)\n #X = preprocessing.MinMaxScaler().fit_transform(X)\n # for i in range(X.shape[1]):\n # print('Min-Max {0}: {1}-{2}'.format(i, np.min(X[:, i]), np.max(X[:, i])))\n\n # print(np.amin(X, axis=0))\n # print(np.amax(X, axis=0))\n # print(np.var(X, axis=0))\n # print('2-----------------------------------------------')\n\n # unique_labels, unique_labels_counts = np.unique(Y, return_counts=True)\n # print(\"Unique classes labels and their record counts: \")\n # print(tuple(zip(unique_labels, unique_labels_counts)))\n # print(\"1Data Has {0} unique clusters\".format(unique_labels.shape[0]))\n\n # if unique_labels.shape[0] > 2:\n # three_most_prevelant_classes_indices = (-unique_labels_counts).argsort()[:3]\n # #not necessary = unique_labes are already sorted\n # #three_most_prevelant_classes = unique_labels[three_most_prevelant_classes_indices]\n # indices_of_records_for_most_common_classes = np.isin(Y, three_most_prevelant_classes_indices)\n # Y = Y[indices_of_records_for_most_common_classes]\n # X = X[indices_of_records_for_most_common_classes, :]\n # print(\"Most Popular Classes and their Record Counts: \")\n # print(three_most_prevelant_classes_indices)\n # print(unique_labels_counts[three_most_prevelant_classes_indices])\n\n shuffled_indices = np.random.choice(Y.shape[0], Y.shape[0], replace=False)\n\n X_shuffled = X[shuffled_indices, :]\n Y_shuffled = Y[shuffled_indices]\n\n return X_shuffled, Y_shuffled\n","sub_path":"data_service.py","file_name":"data_service.py","file_ext":"py","file_size_in_byte":6010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"232192097","text":"import asyncio\nfrom aiomysql.sa import create_engine\n\n\nclass DBConnector():\n def __init__(self, app, config):\n self.app = app\n self.config = config\n self.app.app.on_startup.append(self.engine_create)\n self.app.app.on_cleanup.append(self.engine_cleanup)\n\n async def engine_create(self, app):\n loop = app.loop\n self.engine = await create_engine(host=self.config.MYSQL_HOST,\n port=self.config.MYSQL_PORT,\n user=self.config.MYSQL_USER,\n password=self.config.MYSQL_PASSWORD,\n db=self.config.DB, loop=loop, charset='utf8')\n \n async def query(self, query):\n async with self.engine.acquire() as conn:\n value = await conn.execute(query)\n return await value.fetchall()\n \n async def engine_cleanup(self, app):\n self.engine.close()\n await self.engine.wait_closed()\n","sub_path":"app/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"196345912","text":"import pytest\n\nfrom leapp.exceptions import StopActorExecutionError\nfrom leapp.libraries.actor import repositoriesmapping\nfrom leapp.libraries.common.config import architecture\nfrom leapp.libraries.common.testutils import produce_mocked, CurrentActorMocked\nfrom leapp.libraries.stdlib import api\nfrom leapp.models import EnvVar, RepositoriesMap, RepositoryMap\n\nPRODUCT_TYPE = ['ga', 'beta', 'htb']\n\n\nclass ReadRepoFileMock(object):\n def __init__(self, repomap_data):\n self.repomap_file = self._gen_data_file(repomap_data)\n\n def __call__(self, dummy_filename):\n return self.repomap_file\n\n def _gen_data_file(self, repomap_data):\n \"\"\"\n Generate the expected repomap file (list of strings - string per line).\n\n :param repomap_data: Data required to be able to generate repomap data\n :type repomap_data: list of tuples - tuple per repomap record\n [(from_repoid, to_repoid, to_pes_repo,\n from_minor_version, to_minorversion,\n arch, repo_type, src_prod_type, dst_prod_type)]\n \"\"\"\n header = ('RHEL 7 repoid in CDN,RHEL 8 repoid in CDN,RHEL 8 repo name in PES,'\n 'RHEL 7 minor versions,RHEL 8 minor versions,architecture,'\n 'type(rpm/srpm/debuginfo),src repo type (ga/beta/htb),dst repo type (ga/beta/htb)')\n return [header] + [','.join(i) for i in repomap_data]\n\n\ndef gen_input_permutation():\n \"\"\"Generate permutation of input parameters.\"\"\"\n return [(arch, src, dst) for arch in architecture.ARCH_ACCEPTED for src in PRODUCT_TYPE for dst in PRODUCT_TYPE]\n\n\ndef gen_repomap_record(arch, src_type, dst_type, index=0):\n \"\"\"Generate repomap record based on given data.\"\"\"\n return ('src-repoid-{}-{}-{}'.format(arch, src_type, index),\n 'dst-repoid-{}-{}-{}'.format(arch, dst_type, index),\n 'pes-name', 'all', 'all', arch, 'rpm', src_type, dst_type)\n\n\ndef gen_test_data(arch, src_type, dst_type):\n \"\"\"\n Generate testing data and return records related to the given params.\n\n By the related record (or expected_records) it's meant record we expect\n will be returned for specific arch and product types.\n\n :return: ([all_records], [expected_records])\n \"\"\"\n generic_repomap_data = []\n expected_repomap_data = []\n for _arch, _src_type, _dst_type in gen_input_permutation():\n for i in range(2):\n record = gen_repomap_record(_arch, _src_type, _dst_type, i)\n generic_repomap_data.append(record)\n if _arch == arch and _src_type == src_type and _dst_type == dst_type:\n expected_repomap_data.append(record)\n return generic_repomap_data, expected_repomap_data\n\n\ndef gen_RepositoriesMap(repomap_records):\n \"\"\"Generate Repositories map from the given repomap records.\"\"\"\n repositories = []\n for record in repomap_records:\n repositories.append(RepositoryMap(\n from_repoid=record[0],\n to_repoid=record[1],\n to_pes_repo=record[2],\n from_minor_version=record[3],\n to_minor_version=record[4],\n arch=record[5],\n repo_type=record[6]\n ))\n return RepositoriesMap(repositories=repositories)\n\n\n@pytest.mark.parametrize('arch,src_type,dst_type', gen_input_permutation())\ndef test_scan_valid_file_without_comments(monkeypatch, arch, src_type, dst_type):\n envars = {'LEAPP_DEVEL_SOURCE_PRODUCT_TYPE': src_type, 'LEAPP_DEVEL_TARGET_PRODUCT_TYPE': dst_type}\n input_data, expected_records = gen_test_data(arch, src_type, dst_type)\n monkeypatch.setattr(api, 'current_actor', CurrentActorMocked(arch, envars))\n monkeypatch.setattr(api, 'produce', produce_mocked())\n repositoriesmapping.scan_repositories(read_repofile_func=ReadRepoFileMock(input_data))\n assert api.produce.called == 1\n assert api.produce.model_instances == [gen_RepositoriesMap(expected_records)]\n\n\n# one combination is probably enough, as it's tested properly above\n@pytest.mark.parametrize('arch,src_type,dst_type', [(architecture.ARCH_X86_64, PRODUCT_TYPE[0], PRODUCT_TYPE[0])])\ndef test_scan_valid_file_with_comments(monkeypatch, arch, src_type, dst_type):\n envars = {'LEAPP_DEVEL_SOURCE_PRODUCT_TYPE': src_type, 'LEAPP_DEVEL_TARGET_PRODUCT_TYPE': dst_type}\n input_data, expected_records = gen_test_data(arch, src_type, dst_type)\n monkeypatch.setattr(api, 'current_actor', CurrentActorMocked(arch, envars))\n monkeypatch.setattr(api, 'produce', produce_mocked())\n # add one comment and one empty line into the repomap file\n repofile = ReadRepoFileMock(input_data)\n repofile.repomap_file.insert(2, '')\n repofile.repomap_file.insert(3, '# comment')\n # run\n repositoriesmapping.scan_repositories(read_repofile_func=repofile)\n assert api.produce.called == 1\n assert api.produce.model_instances == [gen_RepositoriesMap(expected_records)]\n\n\n@pytest.mark.parametrize('isFile,err_summary', [\n (False, 'The repository mapping file not found'),\n (True, 'The repository mapping file is invalid'),\n])\ndef test_scan_missing_or_empty_file(monkeypatch, isFile, err_summary):\n monkeypatch.setattr(api, 'current_actor', CurrentActorMocked(architecture.ARCH_X86_64))\n monkeypatch.setattr(api, 'produce', produce_mocked())\n monkeypatch.setattr('os.path.isfile', lambda dummy: isFile)\n if isFile:\n monkeypatch.setattr('os.path.getsize', lambda dummy: 0)\n with pytest.raises(StopActorExecutionError) as err:\n repositoriesmapping.scan_repositories()\n assert not api.produce.called\n assert err_summary in str(err)\n\n\n@pytest.mark.parametrize('line', [\n 'whatever invalid line',\n 'something, jaj',\n 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v',\n 'valid,',\n '7-server-rpms,8-server-rpms,name-8-repo-rpms,all,all,x86_64,rpm',\n '7-server-rpms,8-server-rpms,name-8-repo-rpms,all,all,x86_64,rpm,ga,ga,invalid',\n])\ndef test_scan_invalid_file_csv(monkeypatch, line):\n monkeypatch.setattr(api, 'current_actor', CurrentActorMocked(architecture.ARCH_X86_64))\n monkeypatch.setattr(api, 'produce', produce_mocked())\n with pytest.raises(StopActorExecutionError) as err:\n repositoriesmapping.scan_repositories(read_repofile_func=ReadRepoFileMock([line]))\n assert not api.produce.called\n assert 'The repository mapping file is invalid' in str(err)\n","sub_path":"repos/system_upgrade/el7toel8/actors/repositoriesmapping/tests/unit_test_repositoriesmapping.py","file_name":"unit_test_repositoriesmapping.py","file_ext":"py","file_size_in_byte":6388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"280805780","text":"import logging\nimport jinja2\nimport arrow\n\n# these imports need to be here for sqlalchemy\nfrom totalimpactwebapp import snap\nfrom totalimpactwebapp import metric\nfrom totalimpactwebapp import award\nfrom totalimpactwebapp import reference_set\n\n# regular ol' imports\nfrom totalimpactwebapp.metric import make_metrics_list\nfrom totalimpactwebapp.metric import make_mendeley_metric\nfrom totalimpactwebapp.biblio import Biblio\nfrom totalimpactwebapp.aliases import Aliases\nfrom totalimpactwebapp.util import dict_from_dir\nfrom totalimpactwebapp.util import cached_property\nfrom totalimpactwebapp import db\nfrom totalimpactwebapp import configs\nfrom totalimpactwebapp import json_sqlalchemy\n\n\n\npercentile_snap_creations = 0\n\nlogger = logging.getLogger(\"tiwebapp.product\")\ndeprecated_genres = [\"twitter\", \"blog\"]\n\nignore_snaps_older_than = arrow.utcnow().replace(days=-25).datetime\n\nsnaps_join_string = \"and_(Product.tiid==Snap.tiid, \" \\\n \"Snap.last_collected_date > '{ignore_snaps_older_than}')\".format(\n ignore_snaps_older_than=ignore_snaps_older_than)\n\n\ndef make(raw_dict):\n return Product(raw_dict)\n\n\n\nclass Product(db.Model):\n\n __tablename__ = 'item'\n profile_id = db.Column(db.Integer, db.ForeignKey('profile.id'))\n tiid = db.Column(db.Text, primary_key=True)\n created = db.Column(db.DateTime())\n last_modified = db.Column(db.DateTime())\n last_update_run = db.Column(db.DateTime())\n removed = db.Column(db.DateTime())\n last_refresh_started = db.Column(db.DateTime()) #ALTER TABLE item ADD last_refresh_started timestamp\n last_refresh_finished = db.Column(db.DateTime()) #ALTER TABLE item ADD last_refresh_finished timestamp\n last_refresh_status = db.Column(db.Text) #ALTER TABLE item ADD last_refresh_status text\n last_refresh_failure_message = db.Column(json_sqlalchemy.JSONAlchemy(db.Text)) #ALTER TABLE item ADD last_refresh_failure_message text\n\n\n alias_rows = db.relationship(\n 'AliasRow',\n lazy='subquery',\n cascade=\"all, delete-orphan\",\n backref=db.backref(\"item\", lazy=\"subquery\")\n )\n\n biblio_rows = db.relationship(\n 'BiblioRow',\n lazy='subquery',\n cascade=\"all, delete-orphan\",\n backref=db.backref(\"item\", lazy=\"subquery\")\n )\n\n snaps = db.relationship(\n 'Snap',\n lazy='subquery',\n cascade='all, delete-orphan',\n backref=db.backref(\"item\", lazy=\"subquery\"),\n primaryjoin=snaps_join_string\n )\n\n @cached_property\n def biblio(self):\n return Biblio(self.biblio_rows)\n\n @cached_property\n def aliases(self):\n return Aliases(self.alias_rows)\n\n @cached_property\n def metrics(self):\n my_metrics = make_metrics_list(self.tiid, self.percentile_snaps, self.created)\n return my_metrics\n\n @cached_property\n def is_true_product(self):\n return True\n\n @cached_property\n def is_refreshing(self):\n REFRESH_TIMEOUT_IN_SECONDS = 120\n if self.last_refresh_started and not self.last_refresh_finished:\n last_refresh_started = arrow.get(self.last_refresh_started, 'utc')\n start_time_theshold = arrow.utcnow().replace(seconds=-REFRESH_TIMEOUT_IN_SECONDS)\n if start_time_theshold < last_refresh_started:\n return True\n\n return False\n\n @cached_property\n def finished_successful_refresh(self):\n if self.last_refresh_status and self.last_refresh_status.startswith(u\"SUCCESS\"):\n return True\n return False\n\n @cached_property\n def genre(self):\n if self.biblio.calculated_genre is not None:\n genre = self.biblio.calculated_genre\n else:\n genre = self.aliases.get_genre()\n\n if \"article\" in genre:\n genre = \"article\" #disregard whether journal article or conference article for now\n\n return genre\n\n\n @cached_property\n def host(self):\n if self.genre == \"article\":\n # don't return repositories for articles\n return \"unknown\"\n\n if self.biblio.calculated_host is not None:\n return self.biblio.calculated_host\n else:\n return self.aliases.get_host()\n\n @cached_property\n def mendeley_discipline(self):\n mendeley_metric = make_mendeley_metric(self.tiid, self.snaps, self.created)\n try:\n return mendeley_metric.mendeley_discipine[\"name\"]\n except (AttributeError, TypeError):\n return None\n\n @cached_property\n def year(self):\n return self.biblio.display_year\n\n @cached_property\n def display_genre_plural(self):\n return configs.pluralize_genre(self.genre)\n\n def get_metric_by_name(self, provider, interaction):\n for metric in self.metrics:\n if metric.provider==provider and metric.interaction==interaction:\n return metric\n return None\n\n @cached_property\n def has_metrics(self):\n return len(self.metrics) > 0\n\n @cached_property\n def display_title(self):\n return self.biblio.display_title\n\n @cached_property\n def has_diff(self):\n return any([m.diff_value > 0 for m in self.metrics])\n\n @cached_property\n def awards(self):\n return award.make_list(self.metrics)\n\n\n @cached_property\n def percentile_snaps(self):\n\n my_refset = reference_set.ProductLevelReferenceSet()\n my_refset.year = self.year\n my_refset.genre = self.genre\n my_refset.host = self.host\n my_refset.title = self.biblio.display_title\n my_refset.mendeley_discipline = self.mendeley_discipline\n\n ret = []\n for snap in self.snaps:\n snap.set_refset(my_refset)\n ret.append(snap)\n\n return ret\n\n\n @cached_property\n def metrics_raw_sum(self):\n return sum(m.display_count for m in self.metrics)\n\n @cached_property\n def awardedness_score(self):\n return sum([a.sort_score for a in self.awards])\n\n\n @cached_property\n def latest_diff_timestamp(self):\n ts_list = [m.latest_nonzero_refresh_timestamp for m in self.metrics]\n if not ts_list:\n return None\n try:\n return sorted(ts_list, reverse=True)[0]\n except IndexError:\n return None\n\n\n def has_metric_this_good(self, provider, interaction, count):\n # return True\n requested_metric = self.get_metric_by_name(provider, interaction)\n try:\n return requested_metric.display_count >= count\n except AttributeError:\n return False\n\n\n def to_dict(self):\n attributes_to_ignore = [\n \"profile\",\n \"alias_rows\",\n \"biblio_rows\",\n \"percentile_snaps\",\n \"snaps\"\n ]\n\n ret = dict_from_dir(self, attributes_to_ignore)\n ret[\"_tiid\"] = self.tiid\n return ret\n\n def to_markup_dict(self, markup, hide_keys=None):\n ret = self.to_dict()\n\n ret[\"markup\"] = markup.make(ret)\n\n try:\n for key_to_hide in hide_keys:\n try:\n del ret[key_to_hide]\n except KeyError:\n pass\n except TypeError: # hide_keys=None is not iterable\n pass\n\n return ret\n\n\n\n\n\n\n\n\n\n\n\n\nclass Markup():\n def __init__(self, user_id, embed=False):\n self.user_id = user_id\n\n self.template = self._create_template(\"product.html\")\n\n self.context = {\n \"embed\": embed,\n \"user_id\": user_id\n }\n\n\n def _create_template(self, template_name):\n template_loader = jinja2.FileSystemLoader(searchpath=\"totalimpactwebapp/templates\")\n template_env = jinja2.Environment(loader=template_loader)\n return template_env.get_template(template_name)\n\n def set_template(self, template_name):\n self.template = self._create_template(template_name)\n\n def make(self, local_context):\n # the local context overwrites the Self on if there are conflicts.\n full_context = dict(self.context, **local_context)\n\n return self.template.render(full_context)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"totalimpactwebapp/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":8149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"425015194","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\n\n\nclass Params:\n \"\"\"\n :ivar use_gpu: use CUDA GPU for running the CNN instead of CPU\n\n :ivar enable_test: use the (unreleased) test instead of the validation set for evaluation after training is done\n\n :ivar optim_type: optimizer type: 0: SGD, 1: ADAM\n\n :ivar load_weights:\n 0: train from scratch\n 1: load and test\n 2: load if it exists and continue training\n\n :ivar save_criterion: when to save a new checkpoint\n 0: max validation accuracy\n 1: min validation loss\n 2: max training accuracy\n 3: min training loss\n\n :ivar lr: learning rate\n :ivar eps: term added to the denominator to improve numerical stability in ADAM optimizer\n\n :ivar valid_ratio: fraction of training data to use for validation\n :ivar valid_gap: no. of training epochs between validations\n\n :ivar vis: visualize the input and reconstructed images during validation and testing;\n vis=1 will only write these to tensorboard\n vis=2 will display them using opencv as well; only works for offline runs since colab doesn't support cv2.imshow\n \"\"\"\n\n def __init__(self):\n self.use_gpu = 1\n self.enable_test = 0\n\n self.load_weights = 0\n\n self.train_batch_size = 128\n\n self.valid_batch_size = 24\n self.test_batch_size = 24\n\n self.n_workers = 1\n self.optim_type = 1\n self.lr = 1e-3\n self.momentum = 0.9\n self.n_epochs = 1000\n self.eps = 1e-8\n self.weight_decay = 0\n self.save_criterion = 0\n self.valid_gap = 1\n self.valid_ratio = 0.2\n self.weights_path = './checkpoints/model.pt'\n self.vis = 1\n\n\n\nclass Classifier(nn.Module):\n def __init__(self):\n super(Classifier, self).__init__()\n \"\"\"\n add your code here\n \"\"\"\n self.conv1 = nn.Conv2d(3, 15, kernel_size=3, stride=1, padding=1)\n self.conv1_bn = nn.BatchNorm2d(15)\n\n self.conv2 = nn.Conv2d(15, 30, kernel_size=3, stride=1, padding=1)\n self.conv2_bn = nn.BatchNorm2d(30)\n\n self.conv3 = nn.Conv2d(30, 30, kernel_size=3, stride=1, padding=1)\n self.conv3_bn = nn.BatchNorm2d(30)\n\n self.conv4 = nn.Conv2d(30, 60, kernel_size=3, stride=1, padding=1)\n self.conv4_bn = nn.BatchNorm2d(60)\n\n self.fc1 = nn.Linear(60 * 7 * 7, 1000)\n self.fc2 = nn.Linear(1000, 100)\n self.fc3 = nn.Linear(100, 10)\n \n\n def init_weights(self):\n \"\"\"\n add your code here\n \"\"\"\n pass\n\n\n def forward(self, x):\n \"\"\"\n add your code here\n \"\"\"\n x1 = self.conv1(x)\n x1 = self.conv1_bn(x1)\n x1 = F.max_pool2d(x1, 2)\n x1 = F.relu(x1)\n\n x2 = self.conv2(x1)\n x2 = self.conv2_bn(x2)\n x2 = F.relu(x2)\n\n x3 = self.conv3(x2)\n x3 = self.conv3_bn(x3)\n x3 = F.max_pool2d(x3, 2)\n x3 = F.relu(x3)\n \n x4 = self.conv4(x3)\n x4 = self.conv4_bn(x4)\n x4 = F.relu(x4)\n x4f = x4.view(x.shape[0], 60 * 7 * 7)\n\n xfc1 = self.fc1(x4f)\n xfc1 = F.relu(xfc1)\n\n xfc2 = self.fc2(xfc1)\n xfc2 = F.relu(xfc2)\n\n xfc3 = self.fc3(xfc2)\n x_out = F.softmax(xfc3, dim=1)\n return x_out\n \n ","sub_path":"A6_submission/A6_submission.py","file_name":"A6_submission.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"318805539","text":"import requests\nfrom bs4 import BeautifulSoup\nurl = 'https://www.cia.gov/library/publications/the-world-factbook/fields/2194.html'\npage = requests.get(url)\nsoup = BeautifulSoup(page.content, 'html.parser')\nfor row in soup.tbody.children:\n if row != '\\n':\n countryCandidate = row.find('td', 'country')\n if countryCandidate is not None:\n print(countryCandidate.a.string)\n fieldCandidate = row.find('td', 'fieldData')\n if fieldCandidate is not None:\n # field.Candidate.string did NOT work\n # still need to figure out how to get rid of tags\n print(fieldCandidate)","sub_path":"cia-world-factbook/pull-refugee-summaries.py","file_name":"pull-refugee-summaries.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"582274988","text":"#!/usr/bin/env python\n# coding: utf-8\n__author__ = 'chenyong'\n\nfrom instar import *\nfrom live_platform.Inke import Inke\n\nif __name__ == '__main__':\n db = get_mysql()\n log = get_logger()\n redis_ins = get_redis()\n instar = Instar()\n platform = [\"inke\"]\n for pf in platform:\n # 动态产生平台实例\n pf_ins = eval(pf.capitalize() + '()')\n # 获取当前榜单数据保存到redis\n lives_hot = pf_ins.traverse_living(\"live\") # 当前热门榜\n lives_new = pf_ins.near_recommend() # 附近的人列表\n lives_all = lives_hot + lives_new\n\n all_plat_users = instar.get_all_platform_users(pf) # 平台所有用户id\n log.info(\"total crawled platform user in mysql: \" + str(len(all_plat_users)))\n saved_users=[]\n for live in lives_all:\n uid = int(live[\"creator\"][\"id\"])\n if uid not in all_plat_users and uid not in saved_users:\n #data = pf_ins.get_user_info(uid)\n #db.insert(\"user_\" + pf,data)\n log.info(\"new user \" + str(uid))\n # 新用户加到redis队列,异步处理\n redis_ins.sadd(\"new_user_\" + pf, uid)\n saved_users.append(uid)\n log.info(pf + \" hot live deal completed\")\n #db.commit()\n log.info(\"all platform hot live deal completed\")\n","sub_path":"instar_srapy/add_hot_users_inke.py","file_name":"add_hot_users_inke.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"42455332","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport math\nimport util\n\nfrom log_uniform import LogUniformSampler\n\nclass SampledSoftmax(nn.Module):\n def __init__(self, ntokens, nsampled, nhid, tied_weight):\n super(SampledSoftmax, self).__init__()\n\n # Parameters\n self.ntokens = ntokens\n self.nsampled = nsampled\n\n self.sampler = LogUniformSampler(self.ntokens)\n self.params = nn.Linear(nhid, ntokens)\n\n if tied_weight is not None:\n self.params.weight = tied_weight\n else:\n util.initialize(self.params, self.ntokens)\n self.params.bias.data.fill_(0)\n\n def forward(self, inputs, labels, train=False):\n if train:\n sample_values = self.sampler.sample(self.nsampled, labels.data.cpu().numpy())\n return self.sampled(inputs, labels, sample_values)\n else:\n return self.full(inputs, labels)\n\n def sampled(self, inputs, labels, sample_values):\n assert(inputs.data.get_device() == labels.data.get_device())\n device_id = labels.data.get_device()\n\n batch_size, d = inputs.size()\n sample_ids, true_freq, sample_freq = sample_values\n\n # sample ids according to word distribution - Unique\n sample_ids = Variable(torch.LongTensor(sample_ids), requires_grad=False).cuda(device_id)\n true_freq = Variable(torch.FloatTensor(true_freq), requires_grad=False).cuda(device_id)\n sample_freq = Variable(torch.FloatTensor(sample_freq), requires_grad=False).cuda(device_id)\n\n # gather true labels - weights and frequencies\n true_weights = self.params.weight[labels.data, :]\n true_bias = self.params.bias[labels.data]\n\n # gather sample ids - weights and frequencies\n sample_weights = self.params.weight[sample_ids.data, :]\n sample_bias = self.params.bias[sample_ids.data]\n\n # calculate logits\n true_logits = torch.sum(torch.mul(inputs, true_weights), dim=1) + true_bias\n sample_logits = torch.matmul(inputs, torch.t(sample_weights)) + sample_bias\n\n # perform correction\n true_logits = true_logits.sub(torch.log(true_freq))\n sample_logits = sample_logits.sub(torch.log(sample_freq))\n\n # return logits and new_labels\n logits = torch.cat((torch.unsqueeze(true_logits, dim=1), sample_logits), dim=1)\n new_targets = Variable(torch.zeros(batch_size).long(), requires_grad=False).cuda(device_id)\n return logits, new_targets\n\n def full(self, inputs, labels):\n return self.params(inputs), labels\n\nclass RNNModel(nn.Module):\n \"\"\"A recurrent module\"\"\"\n\n def __init__(self, ntokens, ninp, nhid, nlayers, dropout=0.5):\n super(RNNModel, self).__init__()\n # Parameters\n self.nhid = nhid\n self.nlayers = nlayers\n\n # Create Layers\n self.drop = nn.Dropout(dropout)\n self.rnn = nn.LSTM(ninp, nhid, nlayers, dropout=dropout)\n\n def forward(self, inputs, hidden):\n inputs = self.drop(inputs)\n output, hidden = self.rnn(inputs, hidden)\n output = self.drop(output)\n return output.view(output.size(0)*output.size(1), output.size(2)), hidden\n\n def init_hidden(self, bsz):\n return (Variable(torch.zeros(self.nlayers, bsz, self.nhid)),\n Variable(torch.zeros(self.nlayers, bsz, self.nhid)))\n","sub_path":"lm/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"571988319","text":"import json\n\n\nclass json_encoder(json.JSONEncoder):\n def encode(self, obj):\n obj['type'] = str(obj['type'])\n obj['ip_address'] = str(obj['ip_address'])\n obj['public_key'] = str(obj['public_key'])\n obj['private_key'] = str(obj['private_key'])\n obj['address'] = str(obj['address'])\n\n return super(json_encoder, self).encode(obj)\n\n\n'''JSON encoder for node information '''\n\n\nclass json_encoder_send(json.JSONEncoder):\n def encode(self, obj):\n obj['type'] = str(obj['type'])\n obj['ip_address'] = str(obj['ip_address'])\n\n return super(json_encoder_send, self).encode(obj)\n\n\nclass tx_json_encoder(json.JSONEncoder):\n def encode(self, obj):\n obj['timestamp'] = str(obj['timestamp'])\n obj['senderpublickey'] = obj['senderpublickey']\n obj['value'] = obj['value']\n\n return super(json_encoder, self).encode(obj)","sub_path":"NodeManager/JsonEncoder.py","file_name":"JsonEncoder.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"512021955","text":"# check web driver path\r\n# check stopper\r\n\r\nfrom time import sleep\r\nimport os\r\n\r\ntry:\r\n from selenium import webdriver\r\n\r\nexcept ImportError:\r\n print(\"Trying to Install required module: selenium\\n\")\r\n os.system('python -m pip install selenium')\r\n from selenium import webdriver\r\n\r\ntry:\r\n import csv\r\n\r\nexcept ImportError:\r\n print(\"Trying to Install required module: csv\\n\")\r\n os.system('python -m pip install csv')\r\n import csv\r\n\r\n\r\nfile = open('walmart_data.csv', 'w', newline='')\r\nwriter = csv.writer(file)\r\n\r\nwriter.writerow(['score', 'product', 'author', 'date', 'comment'])\r\ndriver = webdriver.Chrome('../chromedriver.exe')\r\ndriver.get('https://www.walmart.com/search/?query=snack')\r\nsleep(2)\r\nitem_boxes = driver.find_elements_by_css_selector(\"a.product-title-link.line-clamp.line-clamp-2\")\r\n\r\nfor i in range(1, len(item_boxes)):\r\n try:\r\n driver.find_element_by_xpath('//*[@id=\"searchProductResult\"]/ul/li[' + str(i + 1) + ']').click()\r\n sleep(2)\r\n product = driver.find_element_by_css_selector(\"h1.prod-ProductTitle.prod-productTitle-buyBox.font-bold\").text\r\n sub_url = \"https://www.walmart.com/reviews/product/\" + driver.current_url.split('/').pop()\r\n driver.get(sub_url)\r\n sleep(2)\r\n repeat = driver.find_elements_by_css_selector(\"ul.paginator-list li\")\r\n print(\"item # at: \", i)\r\n\r\n for repeat in range(int(repeat[-1].text) + 1): #review-page\r\n driver.get(sub_url + \"?page=\" + str(repeat))\r\n sleep(2)\r\n sub_boxes = driver.find_elements_by_css_selector(\"div.review\")\r\n for j in range(len(sub_boxes)):\r\n stars = sub_boxes[j].find_elements_by_css_selector(\r\n \"span.stars-container span.elc-icon.star.star-small.star-rated.elc-icon-star-rating\")\r\n score = len(stars)\r\n author = sub_boxes[j].find_element_by_css_selector(\"span.review-footer-userNickname\").text\r\n date = sub_boxes[j].find_element_by_css_selector(\".review-date-submissionTime\").text\r\n comment = sub_boxes[j].find_element_by_css_selector(\"div.review-text\").text\r\n tmp = [score, product, author, date, comment]\r\n writer.writerow(tmp)\r\n\r\n except:\r\n print(\"scanning item #\" + str(i) + \"failed\")\r\n driver.get('https://www.walmart.com/search/?query=snack')\r\n\r\nfile.close()\r\ndriver.close()","sub_path":"web crawler/3. walmart_main.py","file_name":"3. walmart_main.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"312376957","text":"# From https://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test\n\nfrom math import sqrt\nfrom math import ceil\n\ndef _try_composite(a, d, n, s):\n if pow(a, d, n) == 1:\n return False\n for i in range(s):\n if pow(a, 2**i * d, n) == n-1:\n return False\n return True # n is definitely composite\n \ndef is_prime(n, _precision_for_huge_n=16):\n if n in _known_primes or n in (0, 1):\n return True\n if any((n % p) == 0 for p in _known_primes):\n return False\n d, s = n - 1, 0\n while not d % 2:\n d, s = d >> 1, s + 1\n # Returns exact according to http://primes.utm.edu/prove/prove2_3.html\n if n < 1373653: \n return not any(_try_composite(a, d, n, s) for a in (2, 3))\n if n < 25326001: \n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5))\n if n < 118670087467: \n if n == 3215031751: \n return False\n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7))\n if n < 2152302898747: \n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11))\n if n < 3474749660383: \n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13))\n if n < 341550071728321: \n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17))\n # otherwise\n return not any(_try_composite(a, d, n, s) \n for a in _known_primes[:_precision_for_huge_n])\n_known_primes = [2, 3]\n_known_primes += [x for x in range(5, 1000, 2) if is_prime(x)]\n\noutFile = open(\"C-large-attempt0.out\", \"w\")\nprint(\"Case #1:\", file=outFile)\n\nstart = int(30*\"0\", 2)\nend = int(30*\"1\", 2)\n\ncnt = 0\n\nfor binRepresPart in range(start, end+1):\n binRepres = \"1\" + bin(binRepresPart)[2:].rjust(30, \"0\") + \"1\"\n\n resultStr = binRepres + \" \"\n\n stopped = False\n\n for i in range(2, 10):\n repres = int(binRepres, i)\n\n if is_prime(repres):\n stopped = True\n break\n\n if stopped:\n continue\n\n for i in range(2, 10):\n repres = int(binRepres, i)\n \n if(repres%2 == 0):\n resultStr += \"2 \"\n## input()\n else:\n for j in range(3, 10000000, 2):#ceil(sqrt(repres))+1, 2):\n if(repres%j == 0):\n resultStr += str(j) + \" \"\n break\n if j>=10000000-3:\n stopped = True\n\n i = 10\n repres = int(binRepres, i)\n \n if(repres%2 == 0):\n resultStr += \"2\"\n else:\n for j in range(3, 10000000, 2):\n if(repres%j == 0):\n resultStr += str(j)\n break\n if j>=10000000-3:\n stopped = True\n\n if not stopped:\n print(resultStr, file=outFile)\n cnt += 1\n if(cnt%10 == 0):\n print(cnt, binRepres)\n if(cnt==500):\n break\n\noutFile.close()\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_orlusai_3f.py","file_name":"16_0_3_orlusai_3f.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"331254196","text":"# https://adventofcode.com/2020/day/3\n\nimport dataclasses\n\nclass Trees:\n def __init__(self, width, height, trees):\n self.width = width\n self.height = height\n self.trees = trees\n\n @classmethod\n def parse_trees(cls, lines):\n trees = set()\n for l, line in enumerate(lines):\n line = line.strip()\n width = len(line)\n for c, char in enumerate(line):\n if char == \"#\":\n trees.add((c, l))\n\n return cls(width, l, trees)\n\n @classmethod\n def from_file(cls, fname):\n with open(fname) as f:\n return cls.parse_trees(f)\n\n def __getitem__(self, coords):\n x, y = coords\n return (x % self.width, y) in self.trees\n\ndef diagonal_points(right, down):\n x = y = 0\n while True:\n yield x, y\n x += right\n y += down\n\ndef trees_encountered(trees, right, down):\n for x, y in diagonal_points(right, down):\n if y > trees.height:\n break\n if trees[x, y]:\n yield x, y\n\ndef seq_len(seq):\n return sum(1 for _ in seq)\n\ndef test_trees_encountered():\n trees = Trees.from_file(\"day03_test.txt\")\n assert seq_len(trees_encountered(trees, 3, 1)) == 7\n\ndef part1():\n trees = Trees.from_file(\"day03_input.txt\")\n num_trees = seq_len(trees_encountered(trees, 3, 1))\n print(f\"Part 1: encountered {num_trees} trees\")\n\nif __name__ == '__main__':\n part1()\n\ndef part2_calc(fname):\n trees = Trees.from_file(fname)\n total = 1\n for right, down in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]:\n num_trees = seq_len(trees_encountered(trees, right, down))\n total *= num_trees\n return total\n\ndef test_part2():\n assert part2_calc(\"day03_test.txt\") == 336\n\nif __name__ == '__main__':\n print(f\"Part 2: answer: {part2_calc('day03_input.txt')}\")\n","sub_path":"day03.py","file_name":"day03.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"318124336","text":"# -*- encoding: utf-8 -*-\n###############################################################################\n#\n# Custom Reports for Odoo\n# Copyright (C) 2014-TODAY Betavision \n#\n# @author João Paulo de Souza \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n###############################################################################\nfrom openerp.osv import osv, fields\nimport openerp.addons.decimal_precision as dp\n\n\nclass SaleOrder(osv.osv):\n _inherit = 'sale.order'\n\n _columns = {\n 'cost_print': fields.boolean(\"print costs\")\n }\n\n\nclass SaleOrderLine(osv.osv):\n _inherit = 'sale.order.line'\n\n _columns = {\n\n 'sequence': fields.integer(string='Sequence',\n help=\"\"\"Gives the sequence of this\n line when displaying the invoice.\"\"\"),\n 'seq': fields.integer(related='sequence', string='Sequence',\n help='''Field to show the number\n of sequence in line''')\n }\n\n _defaults = {\n 'sequence': 1\n }\n","sub_path":"model/custom_order.py","file_name":"custom_order.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"14152959","text":"#! /usr/bin/env python3\n\nimport binascii\n\n\"\"\"decode_hex\nInput: Hex encoded string\nOutput: Bytearray of decoded data\nEx. \"aabb\" -> \\xaa\\xbb\n\"\"\"\ndef decode_hex(hex_string, bytes_obj=False):\n b = binascii.a2b_hex(hex_string)\n if bytes_obj:\n return b\n else:\n return bytearray(b)\n\n\"\"\"decode_b64\nInput: Base64 encoded string\nOutput: Bytearray of decoded data\nEx. \"d2hhdHVwPw==\" -> bytearray(b\"whatup?\")\n\"\"\"\ndef decode_b64(b64_string, bytes_obj=False):\n# b = base64.b64decode(b64_string)\n b = binascii.a2b_base64(b64_string)\n if bytes_obj:\n return b\n else:\n return bytearray(b)\n\n\"\"\"hex_encode\nInput: Bytearray of data\nOutput: String, hex encoded\n\"\"\"\ndef hex_encode(data):\n s = binascii.b2a_hex(data)\n return s.decode('utf-8')\n\n\"\"\"b64_encode\nInput: Bytearray of data\nOutput: String, base64 encoded\n\"\"\"\ndef b64_encode(data):\n s = binascii.b2a_base64(data)\n return s.decode('utf-8')\n \n\nif __name__ == '__main__':\n hex_string=\"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d\"\n b64_string=\"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\"\n data=b'I\\'m killing your brain like a poisonous mushroom'\n dataa=bytearray(data)\n\n print(decode_hex(hex_string))\n print(decode_b64(b64_string))\n print(hex_encode(dataa))\n print(b64_encode(data))\n","sub_path":"python/lib/dencoding.py","file_name":"dencoding.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"8960129","text":"message = \"hello world!\"\nprint (message)\n\n\nfirst_name = \"Ada\"\nlast_name = \"Love\"\n\nfull_name = f\"{first_name} {last_name}\"\nprint(full_name)\n#print (\"\\n\")\n\nprint(f\"\\n\\tHello, {full_name.title()}!\")\n\n#_____________________________________________________\n#Removing whitespace\nfavorite_language = 'python '\nfavorite_language = favorite_language.rstrip()\nprint (favorite_language+ \"\\n\")\n\nname = \"Albert Einstein\"\nstring1 = '\"A person who never made a mistake never tried anything new.\"'\nprint (name + \" once said, \" + string1)\n","sub_path":"venv/Chapter2/Variables and DataTypes.py","file_name":"Variables and DataTypes.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"6020600","text":"from django.conf import settings\nfrom django.core.mail import mail_admins\nimport json\nfrom urllib import urlopen, urlencode, quote\nfrom urlparse import urlparse\n\n\nclass OodleAPIException(Exception):\n def __init__(self, message):\n self.message = message\n def __str__(self):\n return repr(self.message)\n\n\nclass OodleAPI:\n def __init__(self, num_results=30):\n self.base_url = 'http://api.oodle.com/api/v2/listings'\n self.params_dict = {\n 'key': settings.OODLE_API_KEY,\n 'format': 'json',\n 'num': num_results,\n 'region': 'usa',\n 'jsoncallback': 'none',\n 'sort': 'ctime_reverse',\n }\n\n def build_url(self, location, category='sale', page=1, search_term=None, attributes=None):\n \"\"\"\n Build a url in a real roundabout way for a oodle request, this whole thing is\n a mess.\n @return string the url of the oodle api request\n \"\"\"\n additional_params_dict = {'location': location, 'category': category}\n if search_term:\n additional_params_dict['q'] = search_term\n if attributes:\n additional_params_dict['attributes'] = attributes\n self.additional_params_str = self._quote_params(additional_params_dict)\n url = '%s?%s&%s&start=%s' % (self.base_url, urlencode(self.params_dict), \n self.additional_params_str, page)\n return url\n\n def get_oodle_results(self, url):\n \"\"\"\n Request data from oodle for a given url. Should raise exceptions on failures.\n \"\"\" \n f = urlopen(url)\n if f.code != 200:\n mail_admins('Oodle is Down', 'Oodle is down')\n raise OodleAPIException('200 Response Not Received')\n results = json.loads(f.read())\n if results['meta']['total'] == 0:\n return (0, [])\n return (results['meta']['total'], results['listings'])\n\n def _quote_params(self, params_dict):\n \"\"\"\n Quote params using quote instead of urlencode, \n loop through additional params and use quote instead of urlencode,\n there has to be a more forward way to solve the space encoding\n \"\"\"\n params_list = []\n for param, value in params_dict.items():\n if value:\n params_list.append('%s=%s' % (param, quote(str(value))))\n return '&'.join(params_list)\n \n","sub_path":"hackpages/apps/oodle/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"567786278","text":"import logging\nfrom logging import getLogger, FileHandler, Formatter\nimport os\nfrom pathlib import Path\n\nFORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n\n\ndef get_logger(exp_version):\n if not os.path.exists('log'):\n os.mkdir('log')\n\n logger = getLogger(exp_version)\n logger.setLevel(logging.INFO)\n\n log_path = Path('log') / Path(exp_version + '.log')\n file_handler = FileHandler(log_path)\n file_handler.setLevel(logging.INFO)\n\n handler_format = Formatter(FORMAT)\n file_handler.setFormatter(handler_format)\n\n logger.addHandler(file_handler)\n return logger\n","sub_path":"src/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"454115774","text":"# using file to create a list of files within the directory\nimport os\nimport sys\n\ndef dirToFile(path, output):\n for item in os.listdir(path):\n itempath = os.path.join(path, item)\n if os.path.isfile(itempath):\n output.write(\"%s\\n\" % itempath)\n elif os.path.isdir(itempath):\n dirToFile(os.path.join(path, item), output)\ndef main():\n out = sys.argv[1]\n output = open(out,'w')\n dirToFile(os.getcwd(), output)\n output.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"directory_walk.py","file_name":"directory_walk.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"81010693","text":"\nfrom collections import deque\nimport pickle\nimport cv2\nimport numpy as np\nimport time\nimport ast\nfrom utils import *\nimport tensorflow_hub as hub\nimport concurrent.futures\nfrom tensorflow.keras import layers\nimport tensorflow as tf\n\n\n\n# Load Yolo\nnet = cv2.dnn.readNet(\"./data/yolov4-tiny.weights\", \"./data/yolov4-tiny.cfg\")\nnet.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\nnet.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\n\nclasses = []\nwith open(\"coco.names\", \"r\") as f:\n classes = [line.strip() for line in f.readlines()]\nprint(classes)\nlayer_names = net.getLayerNames()\noutput_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\ncolors = np.random.uniform(0, 255, size=(len(classes), 3))\n\n# Loading image\ncap = cv2.VideoCapture('vid_short.mp4')\n\n\nmouse_pts = []\n\nmodel = tf.keras.models.load_model('./model/resnet191020.h5')\nmodel.summary()\n\n#lb = pickle.loads(open(args[\"label\"], \"rb\").read())\n#lb = [\"football\",\"tennis\",\"weight_lifting\"]\n\nlb = ['Fire', 'Normal Car', 'Normal', 'Road Accident', 'Shooting', 'Violence']\n#model.summary()\n# initialize the image mean for mean subtraction along with the\n# predictions queue\nmean = np.array([123.68, 116.779, 103.939][::1], dtype=\"float32\")\nQ = deque(maxlen=128)\n\ntrain_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale = 1./255.,\n )\n\n\n\n\n\nmy_file = open(\"./test.txt\",\"a+\")\ndef get_mouse_points(event, x, y, flags, param):\n # Used to mark 4 points on the frame zero of the video that will be warped\n # Used to mark 2 points on the frame zero of the video that are 6 feet away\n global mouseX, mouseY, mouse_pts\n if event == cv2.EVENT_LBUTTONDOWN:\n mouseX, mouseY = x, y\n file1=open(\"./test.txt\",\"a\")\n cv2.circle(image, (x, y), 10, (0, 255, 255), 10)\n if \"mouse_pts\" not in globals():\n mouse_pts = []\n if(len(mouse_pts)==6):\n file1.write(str(mouse_pts))\n file1.close()\n mouse_pts.append((x, y))\n print(\"Point detected\")\n print(mouse_pts)\n\n\ndef Check(a, b):\n dist = ((a[0] - b[0]) ** 2 + 550 / ((a[1] + b[1]) / 2) * (a[1] - b[1]) ** 2) ** 0.5\n calibration = (a[1] + b[1]) / 2\n if 0 < dist < 0.25 * calibration:\n return True\n else:\n return False\n\n\n\nscale_w = 1.2 / 2\nscale_h = 4 / 2\n\nSOLID_BACK_COLOR = (41, 41, 41)\nframe_num = 0\ntotal_pedestrians_detected = 0\ntotal_six_feet_violations = 0\ntotal_pairs = 0\nabs_six_feet_violations = 0\npedestrian_per_sec = 0\nsh_index = 1\nsc_index = 1\n\ncv2.namedWindow(\"image\")\ncv2.setMouseCallback(\"image\", get_mouse_points)\nnum_mouse_points = 0\nfirst_frame_display = True\n\nfont = cv2.FONT_HERSHEY_PLAIN\nstarting_time = time.time()\nframe_id = 0\nwhile True:\n _, frame = cap.read()\n frame_id += 1\n\n height, width, channels = frame.shape\n\n if frame_id == 1:\n # Ask user to mark parallel points and two points 6 feet apart. Order bl, br, tr, tl, p1, p2\n while True:\n image = frame\n file = open('./test.txt','r')\n s = file.read()\n if s:\n x = ast.literal_eval(s)\n cv2.imshow(\"image\", image)\n cv2.waitKey(1)\n if s:\n if len(mouse_pts) == 7 or len(x) == 6:\n cv2.destroyWindow(\"image\")\n mouse_pts = x\n break\n first_frame_display = False\n four_points = mouse_pts\n\n M = perspective(frame, four_points[0:4])\n pts = src = np.float32(np.array([four_points[4:]]))\n warped_pt = cv2.perspectiveTransform(pts, M)[0]\n d_thresh = np.sqrt(\n (warped_pt[0][0] - warped_pt[1][0]) ** 2\n + (warped_pt[0][1] - warped_pt[1][1]) ** 2\n )\n bird_image = np.zeros(\n (int(height * scale_h), int(width * scale_w), 3), np.uint8\n )\n\n bird_image[:] = SOLID_BACK_COLOR\n pedestrian_detect = frame\n\n # Detecting objects\n blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)\n\n net.setInput(blob)\n outs = net.forward(output_layers)\n\n class_ids = []\n confidences = []\n boxes = []\n for out in outs:\n for detection in out:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n if confidence > 0.5 and class_id == 0:\n center_x = int(detection[0] * width)\n center_y = int(detection[1] * height)\n h = int(detection[3] * height)\n w = int(detection[2] * width)\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\n indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\n if len(indexes) > 0:\n flat_box = indexes.flatten()\n pairs = []\n center = []\n status = []\n for i in flat_box:\n (x, y) = (boxes[i][0], boxes[i][1])\n (w, h) = (boxes[i][2], boxes[i][3])\n center.append([int(x + w / 2), int(y + h / 2)])\n status.append(False)\n\n for i in range(len(center)):\n for j in range(len(center)):\n close = Check(center[i], center[j])\n\n if close:\n pairs.append([center[i], center[j]])\n status[i] = True\n status[j] = True\n \n index = 0\n for i in flat_box:\n (x, y) = (boxes[i][0], boxes[i][1])\n (w, h) = (boxes[i][2], boxes[i][3])\n if status[index] == True:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 150), 2)\n elif status[index] == False:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n index += 1\n for h in pairs:\n cv2.line(frame, tuple(h[0]), tuple(h[1]), (0, 0, 255), 2)\n processedImg = frame.copy()\n\n pedestrian_boxes, num_pedestrians = indexes, len(indexes)\n\n# if len(indexes) > 0:\n# pedestrian_detect = bird_eye_view_plot(frames, boxes, M, scale_w, scale_h)\n\n canvas = np.zeros((200,200,3))\n canvas[:] = (0,0,0)\n text = \"people:{}\".format(len(pedestrian_boxes))\n cv2.putText(canvas, text, (35,50), cv2.FONT_HERSHEY_SIMPLEX,\n 1.0, (0,255,0), 5)\n cv2.imshow('info',canvas)\n\n\n # make predictions on the frame and then update the predictions\n # queue\n \n canvas = np.zeros((250, 300, 3), dtype=\"uint8\")\n output = frame.copy()\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame = cv2.resize(frame, (224, 224)).astype(\"float32\")\n frame = train_datagen.standardize(frame) \n\n \n preds = model.predict(np.expand_dims(frame, axis=0),workers=6,use_multiprocessing=True)[0]\n Q.append(preds)\n \n\n for (i,(lab, prob)) in enumerate(zip(lb, preds)):\n text= \"{}:{:.2f}%\".format(lab, prob*100)\n w = int(prob*300)\n cv2.rectangle(canvas, (7, (i*35) +5), \n (w, (i*35)+35), (0,0,255), -1)\n cv2.putText(canvas, text, (10,(i*35)+23), cv2.FONT_HERSHEY_SIMPLEX,0.45, (255,255,255),2)\n\n results = np.array(Q).mean(axis=0)\n i = np.argmax(results)\n label = lb[i]\n print(label)\n # draw the activity on the output frame\n text = \"{}\".format(label)\n cv2.putText(output, text, (105, 50), cv2.FONT_HERSHEY_SIMPLEX,\n 1.0, (0, 255, 0), 5)\n \n cv2.imshow(\"probs\", canvas)\n\n elapsed_time = time.time() - starting_time\n fps = frame_id / elapsed_time\n cv2.putText(output, \"FPS: \" + str(round(fps, 2)), (10, 50), font, 4, (0, 0, 0), 3)\n cv2.imshow(\"Image\", output)\n\n\n for i in range(len(boxes)):\n if i in indexes:\n x, y, w, h = boxes[i]\n label = str(classes[class_ids[i]])\n confidence = confidences[i]\n color = colors[class_ids[i]]\n cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)\n cv2.putText(frame, label + \" \" + str(round(confidence, 2)), (x, y + 30), font, 2, color, 1)\n\n if len(pedestrian_boxes) > 0:\n warped_pts, bird_image = display_points(\n frame, boxes\n )\n\n\n key = cv2.waitKey(1)\n if key == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()\n ","sub_path":"trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":8347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"560677510","text":"import datetime\nimport os\nimport six\n\nfrom flask import current_app\nfrom google.cloud import storage\n\nimport os\n#os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"d:\\\\partygo\\\\partygo-374595f09267.json\"\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"./partygo-374595f09267.json\"\n\ndef upload_image_file(file,folder,content_id):\n if not file:\n return None\n file.format = 'png'\n date = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H%M%S')\n filename = '{}-{}.{}'.format(content_id, date,'png')\n\n client = storage.Client(project=current_app.config['PROJECT_ID'])\n bucket = client.bucket(current_app.config['CLOUD_STORAGE_BUCKET'])\n blob = bucket.blob(os.path.join(folder, filename))\n\n blob.upload_from_string(file.read(),\n content_type=file.content_type)\n url = blob.public_url\n \n if isinstance(url, six.binary_type):\n url = url.decode('uft-8')\n return url ","sub_path":"utilities/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"440328845","text":"__author__ = 'Nick Flanders'\n\nfrom tkinter import *\nfrom tkinter.ttk import *\nimport admin.tabs\nimport admin.song_view\nimport admin.info_view\nfrom admin.song import *\n\n\nclass Application:\n \"\"\"\n Wrapper to coordinate the execution of the admin application\n \"\"\"\n\n # store database as a class field so all components can make queries\n db = None\n\n # only allow one instance of the application to run at a time\n instance = None\n\n def __init__(self, db):\n \"\"\"\n Initializes this Application\n :param db: the database connection to use for populating this application\n \"\"\"\n if Application.instance is not None:\n Application.instance.root.focus_force()\n return\n self.db = db\n Application.db = db\n self.building_collection = db[\"buildings\"]\n self.song_collection = db[\"songs\"]\n\n # initialize all GUI components visible at startup\n self.root = Tk()\n self.root.geometry(\"1040x520\")\n self.root.title(\"Huskyfy Admin Manager\")\n self.root.iconbitmap(r\"admin/icon.ico\")\n\n # initialize a dictionary mapping building types to lists of buildings from the db\n self._get_buildings()\n\n # initialize all tabs to the initial building type\n self.building_type = \"academic\"\n self._init_tabs()\n\n # initialize the search box and the search button\n self.search_value = StringVar()\n self.search_box = Entry(self.root, width=90, font=(\"Arial\", 12), textvariable=self.search_value)\n self.search_box.bind(\"\", self.search)\n self.search_button = Button(self.root, text=\"Search\", width=10, command=self.search)\n\n # initialize the drop down menu for selecting the type of building\n self._init_optionmenu()\n\n # initialize the add song button\n self.add_button = Button(self.root, text=\"Add Song\", width=10, command=self.add_song)\n\n self.render()\n Application.instance = self\n self.root.mainloop()\n\n def _get_buildings(self):\n \"\"\"\n Query the database to get all of the buildings of each type and put them in\n the appropriate variable of this Application\n \"\"\"\n self.buildings = dict()\n building_list = list(self.building_collection.find())\n for building_type in [\"academic\", \"residential\", \"other\"]:\n self.buildings[building_type] = [building for building in building_list if building_type in building[\"types\"]]\n\n def _init_tabs(self):\n \"\"\"\n Initializes the tab view of this application\n \"\"\"\n try:\n self.tabs.destroy()\n except AttributeError:\n # tabs widget doesn't exist yet\n pass\n\n self.tabs = admin.tabs.Tabs(\n [result[\"display_name\"] for result in self.buildings[self.building_type]],\n parent=self.root)\n\n self.tabs.bind(\"<>\", lambda event: self._set_selected_tab())\n for page, building in enumerate(self.buildings[self.building_type]):\n song_response = self.song_collection.find(\n {\"building_id\": self.building_collection.find_one(\n {\"display_name\": building[\"display_name\"]})[\"_id\"]})\n self.tabs.add_songs(page, [Song.from_dict(record) for record in song_response])\n try:\n self.tabs.select(self.current_tab_index)\n except AttributeError:\n self.current_tab_index = 0\n\n def _init_optionmenu(self):\n \"\"\"\n Initialize the Listbox widget containing the types of buildings to display\n \"\"\"\n self.menu_label = Label(self.root, text=\"Building Type:\")\n self.menu_var = StringVar(self.root)\n b_types = list(self.buildings.keys())\n self.menu = OptionMenu(self.root, self.menu_var, b_types[0],\n *b_types, command=lambda val: self.set_building_type(val))\n self.menu.config(width=10)\n\n def set_building_type(self, building_type):\n \"\"\"\n Sets the building type of this Application\n \"\"\"\n self.building_type = building_type\n del self.current_tab_index\n self._init_tabs()\n self.render()\n\n def _set_selected_tab(self):\n \"\"\"\n Sets the currently selected tab for the Notebook\n \"\"\"\n self.current_tab_index = self.tabs.index(self.tabs.select())\n\n def add_song(self):\n \"\"\"\n Displays a dialogue box for adding a new song\n \"\"\"\n admin.info_view.InfoView(Song(None, \"\", \"\", \"\", \"\", building_id=None))\n\n def search(self, event=None):\n \"\"\"\n Opens a new window with the result of searching the given string across title, artist, album, and user\n \"\"\"\n search_string = self.search_value.get()\n results = []\n results += list(self.song_collection.find({\"title\": {\"$regex\": \".*\" + search_string + \".*\", \"$options\": \"i\"}}))\n if search_string != \"\":\n results += list(self.song_collection.find({\"artist\": {\"$regex\": \".*\" + search_string + \".*\", \"$options\": \"i\"}}))\n results += list(self.song_collection.find({\"album\": {\"$regex\": \".*\" + search_string + \".*\", \"$options\": \"i\"}}))\n results += list(self.song_collection.find({\"user\": {\"$regex\": \".*\" + search_string + \".*\", \"$options\": \"i\"}}))\n\n popup = admin.song_view.SongView(parent=Toplevel(), songs=[Song.from_dict(result) for result in results])\n popup.grid()\n popup.focus_force()\n popup.bind(\"\", lambda event: popup.master.destroy())\n\n def render(self):\n \"\"\"\n Renders the GUI\n \"\"\"\n self.tabs.grid(row=0, column=0, pady=10, padx=10, columnspan=2, rowspan=10)\n self.search_box.grid(row=10, column=0, padx=10)\n self.search_button.grid(row=10, column=1)\n self.add_button.grid(row=7, column=2)\n self.menu_label.grid(row=3, column=2)\n self.menu.grid(row=4, column=2)\n","sub_path":"admin/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":5986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"636911245","text":"#!/usr/bin/env python\n\nimport sys\nimport getopt\nimport os.path\nfrom Bio import Phylo\nfrom Bio.Phylo.BaseTree import TreeMixin\n\ndef determine_monophyly(\n tree, first, second\n ):\n \"\"\"\n Determines if the two taxa are monophyletic\n \n Parameters\n ----------\n argv: tree\n newick tree file\n argv: first\n first taxa in tree\n argv: second\n second taxa in tree\n \"\"\"\n\n # read in tree\n tree = Phylo.read(tree, 'newick')\n\n # read in taxa names\n clade = [first, second]\n # initialize list to hold taxa names\n cladeCheck = []\n\n # loop through terminal branch\n for term in tree.get_terminals():\n # if outgroup taxa is present, append it to outPres\n if term.name in clade:\n cladeCheck.append(term.name)\n\n # check that length of cladeCheck length is 2 to ensure all\n # taxa are present\n if 2 == len(cladeCheck):\n 1\n else:\n print(\"Both taxa are not in the tree\\nExiting now...\")\n sys.exit()\n\n for term in tree.common_ancestor(first, second):\n print(len(term.clades))\n print(vars(term))\n\n\n \n Phylo.draw_ascii(tree)\n\ndef main(\n argv\n ):\n \"\"\"\n Reads arguments \n \"\"\"\n\n # initialize argument variables\n tree = ''\n\n try:\n opts, args = getopt.getopt(argv, \"ht:f:s:\")\n except getopt.GetoptError:\n # error message\n print(\"Error\\nFor help use -h argument\\n\")\n sys.exit(2)\n # if no arguments are used print a help message\n if len(opts) == 0:\n # error message\n print(\"\\nNo arguments provided...\")\n print(\"For help use -h argument\\n\")\n sys.exit(2)\n \n # test for arguments\n for opt, arg in opts:\n if opt == '-h':\n # general script explanation\n print(\"\\nDetermines if two species are monophyletic.\")\n sys.exit()\n elif opt == '-t':\n if os.path.isfile(arg):\n tree = arg\n else:\n # error message\n print(\"\\n\\nThe specified tree file does not exist.\\n\")\n print(\"For detailed explanation use -h argument\\n\")\n sys.exit()\n elif opt == '-f':\n if arg:\n first = arg\n else:\n # error message\n print(\"\\n\\nThe first taxa (-f) is incorrect.\\n\")\n print(\"For detailed explanation use -h argument\\n\")\n sys.exit()\n elif opt == '-s':\n if arg:\n second = arg\n else:\n # error message\n print(\"\\n\\nThe second taxa (-s) is incorrect.\\n\")\n print(\"For detailed explanation use -h argument\\n\")\n sys.exit()\n\n # pass to calculate_treeness function\n determine_monophyly(\n tree, first, second\n )\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","sub_path":"two_taxon_monphyly_test.py","file_name":"two_taxon_monphyly_test.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"86123888","text":"# -*- coding: utf-8 -*-\n# 2018-09-08 08:33\n# author: moz\n\n\n# 前处理,排序已翻转列表\ndef search(nums):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n start = 0\n end = len(nums) - 1\n nums_0 = []\n flip = 0\n\n while start + 1 < end:\n mid = start + (end - start) // 2\n if nums[start] < nums[mid]:\n start = mid\n elif nums[start] > nums[mid]:\n if nums[mid - 1] > nums[mid]:\n flip = mid\n nums_0 = nums[mid:] + nums[:mid]\n break\n else:\n end = mid\n\n return flip, nums_0\n\n\n# print(search([4, 5, 6, 7, 1, 2, 3]))\n# print(search([6, 7, 1, 2, 3, 4, 5]))\n\n\n# 包含了前处理代码\ndef search_1(nums, target):\n # 前处理\n if len(nums) == 0:\n return -1\n\n start = 0\n end = len(nums) - 1\n nums_0 = []\n flip = 0\n\n while start + 1 < end:\n mid = start + (end - start) // 2\n if nums[start] < nums[mid]:\n start = mid\n elif nums[start] > nums[mid]:\n if nums[mid - 1] > nums[mid]:\n flip = mid\n nums_0 = nums[mid:] + nums[:mid]\n break\n else:\n end = mid\n\n if nums[start] > nums[end] and nums_0 == []:\n flip = end\n nums_0 = nums[end:] + nums[:end]\n\n if flip == 0:\n nums_0 = nums\n\n # 查找,并返回 target 未经改动元素顺序的 index\n start = 0\n end = len(nums) - 1\n short = len(nums) - flip\n\n while start + 1 < end:\n mid = start + (end - start) // 2\n if target == nums_0[mid]:\n if mid >= short:\n mid = mid - short\n elif mid < short:\n mid = mid + (len(nums_0) - short)\n return mid\n elif target > nums_0[mid]:\n start = mid\n elif target < nums_0[mid]:\n end = mid\n\n if target == nums_0[end]:\n if end >= short:\n return end - short\n elif end < short:\n return end + (len(nums) - short)\n if target == nums_0[start]:\n if start >= short:\n start = start - short\n elif start < short:\n start = start + (len(nums) - short)\n else:\n return -1\n\n return start\n\n\n# print(search_1([4, 5, 6, 7, 0, 2, 3], 4)) # 0\n# print(search_1([4, 5, 6, 7, 0, 2, 3], 0)) # 4\n# print(search_1([4, 5, 6, 7, 0, 2, 3], 3)) # 6\n# print(search_1([1, 3], 0)) # -1\n# print(search_1([4, 5, 6, 7, 0, 1, 2], 3)) # -1\n# print(search_1([3, 5, 1], 1)) # 2\nprint(search_1([6, 7, 1, 2, 3, 4, 5], 6)) # 0\n","sub_path":"Binary_Search/search_flip_order.py","file_name":"search_flip_order.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110249154","text":"#!/usr/bin/python\n''' \nPerceptual experiment for testing overdriving the latency human perception in relation to focal change\n \nDavid Dunn\nJan 2019 - split from experiment\nwww.qenops.com\n'''\n__author__ = ('David Dunn')\n__version__ = '1.0'\n\nfrom experiment import Experiment, visual, event, core, data, SPF, logging\nfrom latencyExpC import CLatencyExperiment\nfrom userAlign import AlignExperiment\nfrom userAcuity import AcuityExperiment\n\nimport numpy as np\nimport random, os, sys\n\nimport config\n\nclass CODExperiment(CLatencyExperiment):\n def __init__(self, config, append=True):\n if append:\n config.dataPath += '/mono'\n super().__init__(config, append=False)\n def setupData(self):\n super().setupData()\n self.dataKeys = ['trial','primeIter','primeCorrect','primeTime','primeDepth','stimDepth','extraDepth','driveFrames','nearToFar','diopters','direction','size','intensity','extraLatency','mainLatency','totalLatency','responseTime','correct']\n extra = ['caseLabel','caseTrial','trialsAtStep','stepCorrect','expected', 'w', 'direction', 'stepsize', 'stepChange']\n self.dataKeys.extend(extra)\n # clear out the old labels and write the new ones\n self.dataFile.close()\n self.dataFile = open(os.path.join(config.dataPath,'%s.csv'%self.fileName), 'w') # a simple text file with 'comma-separated-values'\n self.dataFile.write('%s\\n'%','.join(self.dataKeys))\n def setupStimuli(self):\n super().setupStimuli()\n self.odStim = self.mainStim\n def setupHandler(self):\n conditions=[\n {'label':'near-000', 'dummy':False, 'prime':3, 'stim':1, 'extra':0 , 'driveFrames':0 , 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n {'label':'near-080', 'dummy':False, 'prime':3, 'stim':1, 'extra':0 , 'driveFrames':4 , 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n {'label':'near-160', 'dummy':False, 'prime':3, 'stim':1, 'extra':0 , 'driveFrames':8 , 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n {'label':'near-240', 'dummy':False, 'prime':3, 'stim':1, 'extra':0 , 'driveFrames':12, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n #{'label':'near-rndm', 'dummy':True, 'prime':3, 'stim':3, 'extra':1 , 'driveFrames':0, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n #{'label':'near-rnd2', 'dummy':True, 'prime':3, 'stim':2, 'extra':1 , 'driveFrames':0, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n #{'label':'near-rnd3', 'dummy':True, 'prime':3, 'stim':0, 'extra':1 , 'driveFrames':0, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n #{'label':'far-000', 'dummy':False, 'prime':0, 'stim':2, 'extra':3 , 'driveFrames':0, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n #{'label':'far-080', 'dummy':False, 'prime':0, 'stim':2, 'extra':3 , 'driveFrames':5, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n #{'label':'far-160', 'dummy':False, 'prime':0, 'stim':2, 'extra':3 , 'driveFrames':10, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n #{'label':'far-rndm', 'dummy':True, 'prime':0, 'stim':None, 'extra':2 , 'driveFrames':0, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n #{'label':'far-rnd2', 'dummy':True, 'prime':0, 'stim':None, 'extra':2 , 'driveFrames':0, 'startVal': 60, 'stepSizes':[16,8,4,2,1,1], 'method':'4AFC', 'stepType':'lin', 'minVal':0, 'maxVal':80, 'findlay_m':8, 'nTrials':100},\n ]\n self.handler = data.ExtendedMultiStairHandler(stairType='vpest',conditions=conditions)\n self.dummies = [i for i in self.handler.staircases if i.condition['dummy']]\n def proceedure(self):\n '''The proceedure of the experiment'''\n self.count = 0\n for frames, condition in self.handler:\n data = {}\n data['trial'] = self.count + 1\n data['intensity'] = frames\n data['requestedLatency'] = frames * SPF\n # set up windows according to this handler\n primeWindow = condition['prime']\n mainWindow = condition['stim']\n if mainWindow is not None:\n extraWindow = condition['extra']\n else:\n i = list(range(len(self.windows)))\n i.pop(condition['extra'])\n mainWindow = random.choice(i)\n extraWindow = condition['extra']\n data['nearToFar'] = primeWindow < mainWindow\n data['diopters'] = abs(primeWindow-mainWindow)\n # set up stimuli with some randomness\n prime = self.primeStim[primeWindow] # choose the right prime text stimulus\n primeIter = random.choice(self.config.primePresentations)\n data['primeDepth'] = self.config.monitors[primeWindow].currentCalib['distance']\n direction = random.randint(0,3)\n main = self.mainStim[mainWindow][direction]\n post = self.postStim[mainWindow]\n data['direction'] = direction\n data['size'] = main.height\n data['stimDepth'] = self.config.monitors[mainWindow].currentCalib['distance']\n extra = self.odStim[extraWindow][direction]\n data['extraDepth'] = self.config.monitors[extraWindow].currentCalib['distance']\n driveFrames = condition['driveFrames']\n # run the proceedure\n #print(direction, self.responses[direction])\n itr = 0\n resp1 = False\n primeValue = True\n while itr < primeIter or resp1 != primeValue:\n text, primeValue = self.genLogicPrimer() # set the text and store the value for the primer\n prime.text = text\n self.present(prime)\n self.stimuliTime[0] = self.clock.getTime()\n self.waitTime(.5)\n resp1 = self.waitForResponse(self.joy.getAllButtons,[0,1],true=[[True,False]],false=[[False,True]])\n itr += 1\n self.clear(prime)\n data['primeIter'] = itr\n data['primeTime'] = self.clock.getTime() - self.stimuliTime[0]\n if driveFrames > 0:\n if self.concurrent:\n self.present(main,False)\n self.present(extra)\n self.stimuliTime[2] = self.clock.getTime()\n self.waitTime(driveFrames*SPF)\n self.clear(extra)\n data['extraLatency'] = self.clock.getTime() - self.stimuliTime[2]\n else:\n data['extraLatency'] = 0\n self.present(main)\n self.stimuliTime[1] = self.clock.getTime()\n self.waitTime(frames*SPF)\n self.present(post)\n self.clear(main)\n data['mainLatency'] = self.clock.getTime() - self.stimuliTime[1]\n data['driveFrames'] = driveFrames\n data['totalLatency'] = data['extraLatency'] + data['mainLatency'] \n self.stimuliTime[0] = self.clock.getTime()\n resp2 = None\n while resp2 is None:\n resp2 = self.waitForResponse(self.joy.getAllHats,[0],true=[self.responses[direction]],false=[i for i in self.responses if i != self.responses[direction]])\n self.clear(post)\n data['responseTime'] = self.clock.getTime() - self.stimuliTime[0]\n self.clearStimuli()\n # record the results\n data['primeCorrect'] = resp1 == primeValue\n data['correct'] = resp2\n # extra results\n data.update({'caseLabel':condition['label'],\n 'stepCorrect': sum(self.handler.currentStaircase.data[self.handler.currentStaircase.stepChangeidx:]) + data['correct'],\n 'w': self.handler.currentStaircase.pest_w,\n 'direction': self.handler.currentStaircase.currentDirection, \n 'stepsize': self.handler.currentStaircase.stepSizes[self.handler.currentStaircase.currentStepSizeIdx], \n })\n data['caseTrial'] = len(self.handler.currentStaircase.data) + 1\n data['trialsAtStep'] = data['caseTrial'] - self.handler.currentStaircase.stepChangeidx\n data['expected'] = data['trialsAtStep'] * self.handler.currentStaircase.targetProb\n data['stepChange'] = int(self.handler.currentStaircase.currentLevelTrialCount / self.handler.currentStaircase.findlay_m)\n if data['primeCorrect']: # prime was correct - this one counted\n self.handler.addResponse(data['correct'])\n for k, v in data.items():\n self.handler.addOtherData(k,v)\n # add an inital rule for vPest\n if data['correct'] and len(self.handler.currentStaircase.reversalIntensities) == 0 and self.handler.currentStaircase.currentDirection in ['down', 'start']:\n self.handler.currentStaircase.stimuliLevelTrialCounts.append(self.handler.currentStaircase.currentLevelTrialCount)\n self.handler.currentStaircase._intensityDec()\n self.handler.currentStaircase.stepChangeidx = len(self.handler.currentStaircase.data)\n else:\n self.handler.currentStaircase.intensities.pop()\n if self.storeData:\n self.dataFile.write('%s\\n'%','.join(['%s'%data[i] for i in self.dataKeys]))\n # TODO print update on number of trials completed - out of how many? Does the handler know that? probably not\n self.count += 1\n print('Trial # %s:\\tFrames = %s\\tExpr = %s'%(self.count,frames,condition['label']))\n logging.flush()\n\n # Do some checking to make sure we aren't only running random Experiments or not running any?\n #if set(self.handler.runningStaircases).issubset(self.dummies):\n if all(i in self.dummies for i in self.handler.runningStaircases):\n print('All running staircases are dummies. Ending run.')\n for stair in self.dummies:\n stair.finished = True\n #if not set(self.handler.runningStaircases).intersection(self.dummies):\n if not [i for i in self.handler.runningStaircases if i in self.dummies]:\n print('No running staircases are dummies. Restarting all dummies.')\n for stair in self.dummies:\n stair.finished = False\n stair.reversalIntensities = []\n stair.intensities = []\n stair.currentStepSizeIdx = 0\n stair.currentDirectionStepCount = 0\n stair.correctCounter = 0\n #stair._nextIntensity = stair.startVal\n self.handler.runningStaircases.append(stair)\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n userInfo = Experiment.loadUser(os.path.join(config.dataPath,'od',config.userFile), int(sys.argv[1]))\n print('Running with user %s'%userInfo['Name'])\n config.userInfo = userInfo\n #config.storeData = False\n alignExp = AlignExperiment(config)\n alignExp.run()\n alignExp.close(False)\n config.windows = alignExp.windows\n config.joy = alignExp.joy\n else:\n #config.storeData = False\n alignExp = AlignExperiment(config)\n alignExp.run()\n alignExp.close(False)\n config.ipd = alignExp.ipd\n config.windows = alignExp.windows\n config.joy = alignExp.joy\n acuityExp = AcuityExperiment(config)\n acuityExp.run()\n acuityExp.close(False)\n config.acuity = acuityExp.acuity\n config.nearacuity = acuityExp.nearAcuity\n #'''\n #config.storeData = True\n experiment = CODExperiment(config)\n experiment.run()\n experiment.close()","sub_path":"code/odExperimentC.py","file_name":"odExperimentC.py","file_ext":"py","file_size_in_byte":12676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"229865452","text":"\"\"\"\nCopyright 2017 Google Inc.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n-------------------------------------------------------------------------------\n\nWikipedia Revisions Ingester\n\nRead in Wikipedia raw revisions output them to stdout in json format.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport subprocess\nimport xml.sax\nfrom . import xml_path\nimport argparse\n\n\n\nTALK_PAGE_NAMESPACE = ['1', '3', '5', '7', '9', '11', '13', '15'] \n\nclass ParserContentHandler(xml.sax.ContentHandler):\n \"\"\"Content handler using a minimal incremental combinator parser.\"\"\"\n\n def __init__(self, data_reset_path, data_paths, revision_reset_path):\n xml.sax.ContentHandler.__init__(self)\n # The path through the XML to get to where we currently are.\n self.xml_path = xml_path.XmlPath()\n self.data = {}\n self.data_reset_path = data_reset_path\n self.data_paths = data_paths\n self.revision_reset_path = revision_reset_path\n self.page_data = {}\n\n def startElement(self, name, attrs):\n self.xml_path.enter(name)\n\n def endElement(self, name):\n # TODO(nthain): Wrap the inside of the top ifs in a try-catch\n # to determine when things go wrong.\n if self.xml_path.element_path_eq(self.revision_reset_path):\n if 'user_ip' in self.data:\n self.data['user_id'] = -1\n self.data['user_text'] = self.data['user_ip']\n self.data['page_id'] = self.page_data['page_id']\n self.data['page_namespace'] = self.page_data['page_namespace']\n self.data['page_title'] = self.page_data['page_title']\n if not('text' in self.data):\n self.data['text'] = \"\"\n if not('user_id' in self.data):\n self.data['user_id'] = None\n self.data['user_text'] = None\n if self.data['page_namespace'] in TALK_PAGE_NAMESPACE:\n print(json.dumps(self.data))\n self.data = {} \n \n if self.xml_path.element_path_eq(self.data_reset_path):\n self.page_data = {}\n\n self.xml_path.exit()\n\n def characters(self, content_text):\n self.xml_path.add_line_of_content()\n for data_name, data_path in self.data_paths:\n if self.xml_path.element_path_eq(data_path):\n if 'page' in data_name:\n if data_name not in self.page_data:\n self.page_data[data_name] = \"\"\n self.page_data[data_name] += content_text\n else:\n if data_name not in self.data:\n self.data[data_name] = \"\"\n self.data[data_name] += content_text\n\ndef _get_paths():\n data_reset_path = xml_path.XmlPath().enter_many(['mediawiki', 'page'])\n revision_reset_path = xml_path.XmlPath().enter_many(['mediawiki', 'page', 'revision']) \n data_paths = [\n ('comment', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'comment'])),\n ('format', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'format'])),\n ('model', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'model'])),\n ('page_id', xml_path.XmlPath().enter_many(['mediawiki', 'page', 'id'])),\n ('page_namespace',\n xml_path.XmlPath().enter_many(['mediawiki', 'page', 'ns'])),\n ('page_title',\n xml_path.XmlPath().enter_many(['mediawiki', 'page', 'title'])),\n ('rev_id',\n xml_path.XmlPath().enter_many(['mediawiki', 'page', 'revision', 'id'])),\n ('timestamp', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'timestamp'])),\n ('sha1', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'sha1'])),\n ('text', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'text'])),\n ('user_id', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'contributor', 'id'])),\n ('user_text', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'contributor', 'username'])),\n ('user_ip', xml_path.XmlPath().enter_many(\n ['mediawiki', 'page', 'revision', 'contributor', 'ip'])),\n\n ]\n return data_reset_path, revision_reset_path, data_paths\n\ndef parse_stream(input_file):\n data_reset_path, revision_reset_path, data_paths = _get_paths()\n content_handler = ParserContentHandler(\n data_reset_path=data_reset_path, \n data_paths=data_paths, \n revision_reset_path=revision_reset_path)\n\n cmd = (['7z', 'x', input_file, '-so']\n if input_file.endswith('.7z') else ['cat', input_file])\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n xml.sax.parse(p.stdout, content_handler)\n","sub_path":"dataflow_pipeline/ingest_revisions/ingest_utils/wikipedia_revisions_ingester.py","file_name":"wikipedia_revisions_ingester.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"524876197","text":"# -*-coding:utf-8-*-\nimport io\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.install import install\n\n\nclass InstallWrapper(install):\n\n def run(self):\n raise Exception(\"using internal PyPi to install sage-sdk, 请使用内网 PyPi 安装。\")\n\n\nwith io.open(\"README.md\", \"r\", encoding=\"UTF-8\") as fh:\n long_description = fh.read()\n\nsetup(\n name='sage-sdk',\n version='0.0.5',\n description=\"sage sdk\",\n long_description=long_description,\n packages=find_packages(),\n install_requires=[\n 'requests',\n 'future',\n 'python-dateutil',\n 'wrapt',\n 'pandas>=0.22.0',\n 'numpy>=1.14.2',\n 'enum34',\n 'tzlocal',\n 'Flask',\n ],\n cmdclass={\n 'install': InstallWrapper\n },\n python_requires='>=3.7',\n)\n","sub_path":"pypi_install_script/sage-sdk-0.0.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"96723586","text":"from concurrent.futures import thread\nimport threading\nimport torch\nimport time\nimport torch.nn as nn\nxxx = threading.Condition()\nclass Serving():\n def __init__(self, model):\n self.data_queue = []\n self.cv = []\n self.result_queue = []\n self.start = []\n self.end = []\n self.duration = []\n self.queue_cv = threading.Condition()\n self.device = \"cuda:0\"\n self.finished = []\n self.model = model.to(self.device)\n print('server have been started!')\n \n def __call__(self):\n while(True):\n for i, cv in enumerate(self.cv):\n if(self.data_queue[i] == None or self.finished[i] == True):\n continue\n\n time.sleep(0.005)\n self.cv[i].acquire()\n #print('start %d query' %(i))\n input_data = []\n input_index = []\n self.model.set_start_end(self.start[i], self.end[i])\n max_query = 3\n for num, q_start in enumerate(self.start):\n if(len(input_data) >= max_query):\n break\n if(self.data_queue[num] == None):\n continue\n if(q_start == self.start[i]):\n input_data.append(self.data_queue[num])\n input_index.append(num)\n if(num != i):\n self.cv[num].acquire()\n start = time.time() \n input_data = torch.cat(input_data, 0)\n input_data = input_data.to(self.device)\n with torch.no_grad():\n out = self.model(input_data)\n out = out.cpu()\n end = time.time() - start\n #self.data_queue[i] = self.data_queue[i].to(self.device)\n #with torch.no_grad():\n # self.result_queue[i] = self.model(self.data_queue[i])\n #print(\"result %d return\" %(i))\n #self.result_queue[i] = self.result_queue[i].cpu()\n for item in input_index:\n self.result_queue[item] = torch.tensor([1])\n if(item != i):\n self.data_queue[item] = None\n self.finished[item] = True\n self.duration[item] = end\n self.cv[item].notify()\n self.cv[item].release()\n \n self.data_queue[i] = None\n self.finished[i] = True\n self.duration[i] = end\n self.cv[i].notify()\n self.cv[i].release()\n break\n \n \n def push_index(self, data, start, end, index1):\n self.queue_cv.acquire()\n index = len(self.data_queue)\n self.data_queue.append(nn.Module.query_input[index1 - 1])\n self.result_queue.append(None)\n self.start.append(start)\n self.end.append(end)\n self.duration.append(-1)\n self.finished.append(False)\n self.cv.append(threading.Condition())\n self.queue_cv.notify()\n self.queue_cv.release()\n return index\n \n def get_result(self, index):\n self.cv[index].acquire()\n while(not isinstance(self.result_queue[index], torch.Tensor)):\n self.cv[index].wait()\n self.cv[index].notify()\n self.cv[index].release()\n self.cv[index] = None\n self.result_queue[index] = None\n self.start[index] = -1\n self.end[index] = -1\n self.data_queue[index] = None\n result = self.result_queue[index]\n duration = self.duration[index]\n return result, duration\n\n","sub_path":"breakdown/without_batching/edge_serving_yolo/serving.py","file_name":"serving.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"474828647","text":"#!/usr/bin/env python3\n\n\"\"\"\nPENMAN graph library for AMR, DMRS, etc.\n\nPenman is a module to assist in working with graphs encoded in PENMAN\nnotation, such as those for Abstract Meaning Representation (AMR) or\nDependency Minimal Recursion Semantics (DMRS). It allows for conversion\nbetween PENMAN and triples, inspection of the graphs, and\nreserialization (e.g. for selecting a new top node). Some features,\nsuch as conversion or reserialization, can be done by calling the\nmodule as a script.\n\"\"\"\n\nfrom __future__ import print_function\n\nUSAGE = '''\nPenman\n\nAn API and utility for working with graphs in PENMAN notation.\n\nUsage: penman.py [-h|--help] [-V|--version] [options]\n\nArguments:\n FILE the input file\n\nOptions:\n -h, --help display this help and exit\n -V, --version display the version and exit\n -v, --verbose verbose mode (may be repeated: -vv, -vvv)\n -i FILE, --input FILE read graphs from FILE instanced of stdin\n -o FILE, --output FILE write output to FILE instead of stdout\n -t, --triples print graphs as triple conjunctions\n'''\n\n# API overview:\n#\n# Classes:\n# * PENMANCodec(indent=True)\n# - PENMANCodec.decode(s)\n# - PENMANCodec.iterdecode(s)\n# - PENMANCodec.encode(g, top=None)\n# - PENMANCodec.is_relation_inverted(relation)\n# - PENMANCodec.invert_relation(relation)\n# - PENMANCodec.handle_triple(source, relation, target)\n# - PENMANCodec.triples_to_graph(triples, top=None)\n# * Triple(source, relation, target)\n# * Graph(data=None, top=None)\n# - Graph.top\n# - Graph.variables()\n# - Graph.triples(source=None, relation=None, target=None)\n# - Graph.edges(source=None, relation=None, target=None)\n# - Graph.attributes(source=None, relation=None, target=None)\n#\n# Module Functions:\n# * decode(s, cls=PENMANCodec, **kwargs)\n# * encode(g, cls=PENMANCodec, **kwargs)\n# * load(source, triples=False, cls=PENMANCodec, **kwargs)\n# * loads(string, triples=False, cls=PENMANCodec, **kwargs)\n# * dump(graphs, file, triples=False, cls=PENMANCodec, **kwargs)\n# * dumps(graphs, triples=False, cls=PENMANCodec, **kwargs)\n\nimport re\nfrom collections import namedtuple, defaultdict\ntry:\n basestring\nexcept NameError:\n basestring = str\n\n__version__ = '0.5.0'\n__version_info__ = __version__.replace('.', ' ').replace('-', ' ').split()\n\nclass PENMANCodec(object):\n \"\"\"\n A parameterized encoder/decoder for graphs in PENMAN notation.\n \"\"\"\n\n TYPE_REL = 'instance'\n TOP_VAR = None\n TOP_REL = 'top'\n NODE_ENTER_RE = re.compile(r'\\s*(\\()\\s*([^\\s()\\/,]+)\\s*')\n NODE_EXIT_RE = re.compile(r'\\s*(\\))\\s*')\n RELATION_RE = re.compile(r'(:[^\\s(),]*)\\s*')\n ATOM_RE = re.compile(r'\\s*([^\\s()\\/,]+)\\s*')\n STRING_RE = re.compile(r'(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")\\s*')\n COMMA_RE = re.compile(r'\\s*,\\s*')\n\n def __init__(self, indent=True):\n \"\"\"\n Initialize a new codec.\n\n Args:\n indent: if True, adaptively indent; if False or None, don't\n indent; if a non-negative integer, indent that many\n spaces per nesting level\n \"\"\"\n self.indent = indent\n\n def decode(self, s, triples=False):\n \"\"\"\n Deserialize PENMAN-notation string *s* into its Graph object.\n\n Args:\n s: a string containing a single PENMAN-serialized graph\n triples: if True, treat *s* as a conjunction of logical triples\n Returns:\n the Graph object described by *s*\n Example:\n\n >>> PENMANCodec.decode('(b / bark :ARG1 (d / dog))')\n \n >>> PENMANCodec.decode(\n ... 'instance(b, bark) ^ instance(d, dog) ^ ARG1(b, d)'\n ... )\n \n \"\"\"\n try:\n if triples:\n span, data = self._decode_triple_conjunction(s)\n else:\n span, data = self._decode_penman_node(s)\n except IndexError:\n raise DecodeError(\n 'Unexpected end of string.', string=s, pos=len(s)\n )\n top, nodes, edges = data\n return self.triples_to_graph(nodes + edges, top=top)\n\n def iterdecode(self, s, triples=False):\n \"\"\"\n Deserialize PENMAN-notation string *s* into its Graph objects.\n\n Args:\n s: a string containing zero or more PENMAN-serialized graphs\n triples: if True, treat *s* as a conjunction of logical triples\n Yields:\n valid Graph objects described by *s*\n Example:\n\n >>> list(PENMANCodec.iterdecode('(h / hello)(g / goodbye)'))\n [, ]\n >>> list(PENMANCodec.iterdecode(\n ... 'instance(h, hello)\\n'\n ... 'instance(g, goodbye)'\n ... ))\n [, ]\n \"\"\"\n pos, strlen = 0, len(s)\n while pos < strlen:\n if s[pos] == '#':\n while pos < strlen and s[pos] != '\\n':\n pos += 1\n elif triples or s[pos] == '(':\n try:\n if triples:\n span, data = self._decode_triple_conjunction(\n s, pos=pos\n )\n else:\n span, data = self._decode_penman_node(s, pos=pos)\n except (IndexError, DecodeError):\n # don't re-raise below for more robust parsing, but\n # for now, raising helps with debugging bad input\n raise\n pos += 1\n else:\n top, nodes, edges = data\n yield self.triples_to_graph(nodes + edges, top=top)\n pos = span[1]\n else:\n pos += 1\n\n def encode(self, g, top=None, triples=False):\n \"\"\"\n Serialize the graph *g* from *top* to PENMAN notation.\n\n Args:\n g: the Graph object\n top: the node identifier for the top of the serialized\n graph; if unset, the original top of *g* is used\n triples: if True, serialize as a conjunction of logical triples\n Returns:\n the PENMAN-serialized string of the Graph *g*\n Example:\n\n >>> PENMANCodec.encode(Graph([('h', 'instance', 'hi')]))\n (h / hi)\n >>> PENMANCodec.encode(Graph([('h', 'instance', 'hi')]),\n ... triples=True)\n instance(h, hi)\n \"\"\"\n if triples:\n return self._encode_triple_conjunction(g, top=top)\n else:\n return self._encode_penman(g, top=top)\n\n def is_relation_inverted(self, relation):\n \"\"\"\n Return True if *relation* is inverted.\n \"\"\"\n return relation and relation.endswith('-of')\n\n def invert_relation(self, relation):\n \"\"\"\n Invert or deinvert *relation*.\n \"\"\"\n if self.is_relation_inverted(relation):\n return relation[:-3] or None\n else:\n return (relation or '') + '-of'\n\n def handle_triple(self, lhs, relation, rhs):\n \"\"\"\n Process triples before they are added to the graph.\n\n Note that *lhs* and *rhs* are as they originally appeared, and\n may be inverted. Inversions are detected by\n is_relation_inverted() and de-inverted by invert_relation().\n\n By default, this function:\n * removes initial colons on relations\n * de-inverts all inverted relations\n * sets empty relations to `None`\n * casts numeric string targets (post-de-inversion) to their\n numeric types (e.g. float, int)\n\n Args:\n lhs: the left hand side of an observed triple\n relation: the triple relation (possibly inverted)\n rhs: the right hand side of an observed triple\n Returns:\n The processed (source, relation, target) triple. By default,\n it is returned as a Triple object.\n \"\"\"\n relation = relation.replace(':', '', 1) # remove leading :\n\n if self.is_relation_inverted(relation): # deinvert\n source, target = rhs, lhs\n relation = self.invert_relation(relation)\n else:\n source, target = lhs, rhs\n\n if isinstance(target, basestring):\n if target.startswith('\"'):\n target = target # strip quotes?\n elif re.match(\n r'-?(0|[1-9]\\d*)(\\.\\d+[eE][-+]?|\\.|[eE][-+]?)\\d+', target):\n target = float(target)\n elif re.match(r'-?\\d+', target):\n target = int(target)\n\n if relation == '': # set empty relations to None\n relation = None\n\n return Triple(source, relation, target)\n\n def triples_to_graph(self, triples, top=None):\n \"\"\"\n Create a Graph from *triples* considering codec configuration.\n\n The Graph class does not know about information in the codec,\n so if Graph instantiation depends on special `TYPE_REL` or\n `TOP_VAR` values, use this function instead of instantiating\n a Graph object directly. This is also where edge\n normalization (de-inversion) and value type conversion occur.\n\n Args:\n triples: an iterable of (lhs, relation, rhs) triples\n top: node identifier of the top node\n Returns:\n a Graph object\n \"\"\"\n inferred_top = triples[0][0] if triples else None\n ts = []\n for triple in triples:\n if triple[0] == self.TOP_VAR and triple[1] == self.TOP_REL:\n inferred_top = triple[2]\n else:\n ts.append(self.handle_triple(*triple))\n return Graph(ts, top=top or inferred_top)\n\n\n def _decode_triple_conjunction(self, s, pos=0):\n top, nodes, edges = None, [], []\n start = None\n while True:\n m = _regex(self.ATOM_RE, s, pos, \"a relation/predicate\")\n if start is None:\n start = m.start(1)\n pos, rel = m.end(0), m.group(1)\n m = _regex(self.NODE_ENTER_RE, s, pos, '\"(\" and a variable')\n pos, var = m.end(0), m.group(2)\n m = _regex(self.COMMA_RE, s, pos, '\",\"')\n pos = m.end(0)\n if s[pos] == '\"':\n m = _regex(self.STRING_RE, s, pos, 'a quoted string')\n else:\n m = _regex(self.ATOM_RE, s, pos, 'a float/int/atom')\n pos, tgt = m.end(0), m.group(1)\n if var == self.TOP_VAR and rel == self.TOP_REL:\n top = tgt\n elif rel == self.TYPE_REL:\n nodes.append((var, rel, tgt))\n else:\n edges.append((var, rel, tgt))\n m = _regex(self.NODE_EXIT_RE, s, pos, '\")\"')\n pos = m.end(1)\n if m.end(0) < len(s) and s[m.end(0)] == '^':\n pos = m.end(0) + 1\n else:\n break\n if top is None and nodes:\n top = nodes[0][0]\n return (start, pos), (top, nodes, edges)\n\n def _decode_penman_node(self, s, pos=0):\n nodes, edges = [], []\n\n strlen = len(s)\n m = _regex(self.NODE_ENTER_RE, s, pos, '\"(\" and a variable')\n start, pos, var = m.start(1), m.end(0), m.group(2)\n\n nodetype = None\n while pos < strlen and s[pos] != ')':\n\n # node type\n if s[pos] == '/':\n m = _regex(self.ATOM_RE, s, pos+1, 'a node type')\n pos, nodetype = m.end(0), m.group(1)\n\n # relation\n elif s[pos] == ':':\n m = _regex(self.RELATION_RE, s, pos, 'a relation')\n pos, rel = m.end(0), m.group(1)\n\n # node value\n if s[pos] == '(':\n span, data = self._decode_penman_node(s, pos=pos)\n pos = span[1]\n subtop, subnodes, subedges = data\n nodes.extend(subnodes)\n edges.append((var, rel, subtop))\n edges.extend(subedges)\n\n # string or other atom value\n else:\n if s[pos] == '\"':\n m = _regex(self.STRING_RE, s, pos, 'a quoted string')\n pos, value = m.end(0), m.group(1)\n else:\n m = _regex(self.ATOM_RE, s, pos, 'a float/int/atom')\n pos, value = m.end(0), m.group(1)\n edges.append((var, rel, value))\n\n elif s[pos].isspace():\n pos += 1\n\n # error\n else:\n raise DecodeError('Expected \":\" or \"/\"', string=s, pos=pos)\n\n m = _regex(self.NODE_EXIT_RE, s, pos, '\")\"')\n pos = m.end(1)\n\n nodes = [(var, self.TYPE_REL, nodetype)] + nodes\n\n return (start, pos), (var, nodes, edges)\n\n def _encode_penman(self, g, top=None):\n if top is None:\n top = g.top\n ts = defaultdict(list)\n remaining = set()\n variables = g.variables()\n for idx, t in enumerate(g.triples()):\n ts[t.source].append((t, t, 0.0, idx))\n if t.target in variables:\n invrel = self.invert_relation(t.relation)\n ts[t.target].append(\n (Triple(t.target, invrel, t.source), t, 1.0, idx)\n )\n remaining.add(t)\n p = _walk(ts, top, remaining)\n return _layout(p, top, self, 0, set())\n\n def _encode_triple_conjunction(self, g, top=None):\n if top is None:\n top = g.top\n if self.TOP_VAR is not None and top is not None:\n top_triple = [(self.TOP_VAR, self.TOP_REL, top)]\n else:\n top_triple = []\n return ' ^\\n'.join(\n map('{0[1]}({0[0]}, {0[2]})'.format, top_triple + g.triples())\n )\n\n\ndef _regex(x, s, pos, msg):\n m = x.match(s, pos=pos)\n if m is None:\n raise DecodeError('Expected {}'.format(msg), string=s, pos=pos)\n return m\n\n\nclass DecodeError(Exception):\n \"\"\"Raised when decoding PENMAN-notation fails.\"\"\"\n\n def __init__(self, *args, **kwargs):\n # Python2 doesn't allow parameters like:\n # (*args, key=val, **kwargs)\n # so do this manaully.\n string = pos = None\n if 'string' in kwargs:\n string = kwargs['string']\n del kwargs['string']\n if 'pos' in kwargs:\n pos = kwargs['pos']\n del kwargs['pos']\n super(DecodeError, self).__init__(*args, **kwargs)\n self.string = string\n self.pos = pos\n\n def __str__(self):\n if isinstance(self.pos, slice):\n loc = ' in span {}:{}'.format(self.pos.start, self.pos.stop)\n else:\n loc = ' at position {}'.format(self.pos)\n return Exception.__str__(self) + loc\n\n\ndef decode(s, cls=PENMANCodec, **kwargs):\n \"\"\"\n Deserialize PENMAN-serialized *s* into its Graph object\n\n Args:\n s: a string containing a single PENMAN-serialized graph\n cls: serialization codec class\n kwargs: keyword arguments passed to the constructor of *cls*\n Returns:\n the Graph object described by *s*\n Example:\n\n >>> decode('(b / bark :ARG1 (d / dog))')\n \n \"\"\"\n codec = cls(**kwargs)\n return codec.decode(s)\n\n\ndef encode(g, top=None, cls=PENMANCodec, **kwargs):\n \"\"\"\n Serialize the graph *g* from *top* to PENMAN notation.\n\n Args:\n g: the Graph object\n top: the node identifier for the top of the serialized graph; if\n unset, the original top of *g* is used\n cls: serialization codec class\n kwargs: keyword arguments passed to the constructor of *cls*\n Returns:\n the PENMAN-serialized string of the Graph *g*\n Example:\n\n >>> PENMANCodec.encode(Graph([('h', 'instance', 'hi')]))\n (h / hi)\n \"\"\"\n codec = cls(**kwargs)\n return codec.encode(g, top=top)\n\n\ndef load(source, triples=False, cls=PENMANCodec, **kwargs):\n \"\"\"\n Deserialize a list of PENMAN-encoded graphs from *source*.\n\n Args:\n source: a filename or file-like object to read from\n triples: if True, read graphs as triples instead of as PENMAN\n cls: serialization codec class\n kwargs: keyword arguments passed to the constructor of *cls*\n Returns:\n a list of Graph objects\n \"\"\"\n decode = cls(**kwargs).iterdecode\n if hasattr(source, 'read'):\n return list(decode(source.read()))\n else:\n with open(source) as fh:\n return list(decode(fh.read()))\n\n\ndef loads(string, triples=False, cls=PENMANCodec, **kwargs):\n \"\"\"\n Deserialize a list of PENMAN-encoded graphs from *string*.\n\n Args:\n string: a string containing graph data\n triples: if True, read graphs as triples instead of as PENMAN\n cls: serialization codec class\n kwargs: keyword arguments passed to the constructor of *cls*\n Returns:\n a list of Graph objects\n \"\"\"\n codec = cls(**kwargs)\n return list(codec.iterdecode(string, triples=triples))\n\n\ndef dump(graphs, file, triples=False, cls=PENMANCodec, **kwargs):\n \"\"\"\n Serialize each graph in *graphs* to PENMAN and write to *file*.\n\n Args:\n graphs: an iterable of Graph objects\n file: a filename or file-like object to write to\n triples: if True, write graphs as triples instead of as PENMAN\n cls: serialization codec class\n kwargs: keyword arguments passed to the constructor of *cls*\n \"\"\"\n text = dumps(graphs, triples=triples, cls=cls, **kwargs)\n\n if hasattr(file, 'write'):\n print(text, file=file)\n else:\n with open(file, 'w') as fh:\n print(text, file=fh)\n\n\ndef dumps(graphs, triples=False, cls=PENMANCodec, **kwargs):\n \"\"\"\n Serialize each graph in *graphs* to the PENMAN format.\n\n Args:\n graphs: an iterable of Graph objects\n triples: if True, write graphs as triples instead of as PENMAN\n Returns:\n the string of serialized graphs\n \"\"\"\n codec = cls(**kwargs)\n strings = [codec.encode(g, triples=triples) for g in graphs]\n return '\\n\\n'.join(strings)\n\n\nclass Triple(namedtuple('Triple', ('source', 'relation', 'target'))):\n \"\"\"Container for Graph edges and node attributes.\"\"\"\n\nclass Graph(object):\n \"\"\"\n A basic class for modeling a rooted, directed acyclic graph.\n\n A Graph is defined by a list of triples, which can be divided into\n two parts: a list of graph edges where both the source and target\n are node identifiers, and a list of node attributes where only the\n source is a node identifier and the target is a constant. These\n lists can be obtained via the Graph.triples(), Graph.edges(), and\n Graph.attributes() methods.\n \"\"\"\n\n def __init__(self, data=None, top=None):\n \"\"\"\n Create a Graph from an iterable of triples.\n\n Args:\n data: an iterable of triples (Triple objects or 3-tuples)\n top: the node identifier of the top node; if unspecified,\n the source of the first triple is used\n Example:\n\n >>> Graph([\n ... ('b', 'instance', 'bark'),\n ... ('d', 'instance', 'dog'),\n ... ('b', 'ARG1', 'd')\n ... ])\n \"\"\"\n self._triples = []\n self._top = None\n\n if data is None:\n data = []\n else:\n data = list(data) # make list (e.g., if its a generator)\n\n if data:\n self._triples.extend(Triple(*triple) for triple in data)\n # implicit top: source of first triple\n if top is None:\n top = data[0][0]\n self.top = top\n\n def __repr__(self):\n return '<{} object (top={}) at {}>'.format(\n self.__class__.__name__,\n self.top,\n id(self)\n )\n\n def __str__(self):\n return PENMANCodec.encode(self) # just use the default encoder\n\n @property\n def top(self):\n \"\"\"\n The top variable.\n \"\"\"\n return self._top\n\n @top.setter\n def top(self, top):\n if top not in self.variables():\n raise ValueError('top must be a valid node')\n self._top = top # check if top is valid variable?\n\n def variables(self):\n \"\"\"\n Return the list of variables (nonterminal node identifiers).\n \"\"\"\n return set(v for v, _, _ in self._triples)\n\n def triples(self, source=None, relation=None, target=None):\n \"\"\"\n Return triples filtered by their *source*, *relation*, or *target*.\n \"\"\"\n triplematch = lambda t: (\n (source is None or source == t.source) and\n (relation is None or relation == t.relation) and\n (target is None or target == t.target)\n )\n return list(filter(triplematch, self._triples))\n\n def edges(self, source=None, relation=None, target=None):\n \"\"\"\n Return edges filtered by their *source*, *relation*, or *target*.\n\n Edges don't include terminal triples (node types or attributes).\n \"\"\"\n edgematch = lambda e: (\n (source is None or source == e.source) and\n (relation is None or relation == e.relation) and\n (target is None or target == e.target)\n )\n variables = self.variables()\n edges = [t for t in self._triples if t.target in variables]\n return list(filter(edgematch, edges))\n\n def attributes(self, source=None, relation=None, target=None):\n \"\"\"\n Return attributes filtered by their *source*, *relation*, or *target*.\n\n Attributes don't include triples where the target is a nonterminal.\n \"\"\"\n attrmatch = lambda a: (\n (source is None or source == a.source) and\n (relation is None or relation == a.relation) and\n (target is None or target == a.target)\n )\n variables = self.variables()\n attrs = [t for t in self.triples() if t.target not in variables]\n return list(filter(attrmatch, attrs))\n\ndef _walk(graph, top, remaining):\n path = defaultdict(list)\n candidates = [\n # e, t, w, o = edge, triple, weight, original-order\n (e, t, w, o) for e, t, w, o in graph.get(top, []) if t in remaining\n ]\n candidates.sort(key=lambda c: (c[2], c[3]), reverse=True)\n while candidates:\n edge, triple, _, _ = candidates.pop()\n if triple in remaining:\n path[edge.source].append(edge)\n remaining.remove(triple)\n candidates.extend(graph.get(edge.target, []))\n candidates.sort(key=lambda c: c[2], reverse=True)\n return path\n\n\ndef _layout(g, v, codec, offset, seen):\n indent = codec.indent\n if v not in g or len(g.get(v, [])) == 0 or v in seen:\n return v\n seen.add(v)\n branches = []\n outedges = sorted(\n g[v],\n key=lambda e: ([-(e.relation == codec.TYPE_REL),\n codec.is_relation_inverted(e.relation)] +\n _relation_sort_key(e.relation))\n )\n head = '({}'.format(v)\n if indent is True:\n offset += len(head) + 1 # + 1 for space after v (added later)\n elif indent is not None and indent is not False:\n offset += indent\n for edge in outedges:\n if edge.relation == codec.TYPE_REL:\n if edge.target is None:\n continue\n rel = '/'\n else:\n rel = ':' + (edge.relation or '')\n inner_offset = (len(rel) + 1) if indent is True else 0\n branch = _layout(g, edge.target, codec, offset + inner_offset, seen)\n branches.append('{} {}'.format(rel, branch))\n if branches:\n head += ' '\n delim = ' ' if (indent is None or indent is False) else '\\n'\n tail = (delim + (' ' * offset)).join(branches) + ')'\n return head + tail\n\n\ndef _relation_sort_key(r):\n if r is not None:\n return [int(t) if t.isdigit() else t for t in re.split(r'([0-9]+)', r)]\n return []\n\n\ndef _main():\n import sys\n from docopt import docopt\n args = docopt(USAGE, version='Penman {}'.format(__version__))\n\n infile = args['--input'] or sys.stdin\n data = load(infile)\n\n outfile = args['--output'] or sys.stdout\n dump(data, outfile, triples=args['--triples'])\n\n\nif __name__ == '__main__':\n _main()\n","sub_path":"penman.py","file_name":"penman.py","file_ext":"py","file_size_in_byte":24615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"266125581","text":"bl_info = {\n\t\"name\": \"Import CivNexus6 (.cn6)\",\n\t\"author\": \"Deliverator, Sukritact\",\n\t\"version\": (1, 0),\n\t\"blender\": (2, 80, 0),\n\t\"location\": \"File > Import > CivNexus6 (.cn6)\",\n\t\"description\": \"Import CivNexus6 (.cn6)\",\n\t\"warning\": \"\",\n\t\"wiki_url\": \"\",\n\t\"category\": \"Import-Export\"}\n\nimport bpy\nimport array\nimport shlex\nfrom bpy.props import BoolProperty, IntProperty, EnumProperty, StringProperty\nfrom mathutils import Vector, Quaternion, Matrix\nfrom bpy_extras.io_utils import unpack_list, unpack_face_list, ImportHelper\nfrom math import radians\n\n# Converts ms3d euler angles to a rotation matrix\ndef RM(a):\n\tsy = sin(a[2])\n\tcy = cos(a[2])\n\tsp = sin(a[1])\n\tcp = cos(a[1])\n\tsr = sin(a[0])\n\tcr = cos(a[0])\n\treturn Matrix([cp*cy, cp*sy, -sp], [sr*sp*cy+cr*-sy, sr*sp*sy+cr*cy, sr*cp],[cr*sp*cy+-sr*-sy, cr*sp*sy+-sr*cy, cr*cp])\n\n# Converts ms3d euler angles to a quaternion\ndef RQ(a):\n\tangle = a[2] * 0.5\n\tsy = sin(angle)\n\tcy = cos(angle)\n\tangle = a[1] * 0.5\n\tsp = sin(angle)\n\tcp = cos(angle)\n\tangle = a[0] * 0.5\n\tsr = sin(angle)\n\tcr = cos(angle)\n\treturn Quaternion((cr*cp*cy+sr*sp*sy, sr*cp*cy-cr*sp*sy, cr*sp*cy+sr*cp*sy, cr*cp*sy-sr*sp*cy))\n\ndef getRotationMatrix(matrix_4x4):\n\treturn Matrix([[matrix_4x4[0][0],matrix_4x4[0][1],matrix_4x4[0][2]],\n\t\t\t\t[matrix_4x4[1][0],matrix_4x4[1][1],matrix_4x4[1][2]],\n\t\t\t\t[matrix_4x4[2][0],matrix_4x4[2][1],matrix_4x4[2][2]]])\n\t\t\t\t\ndef writeRotationMatrix(matrix_4x4, matrix_3x3):\n\tfor x in range(0, 3):\n\t\tfor y in range(0, 3):\n\t\t\tmatrix_4x4[x][y] = matrix_3x3[x][y]\n\n# returns the next non-empty, non-comment line from the file\ndef getNextLine(file):\n\tready = False\n\twhile ready==False:\n\t\tline = file.readline()\n\t\tif len(line)==0:\n\t\t\tprint (\"Warning: End of file reached.\")\n\t\t\treturn line\n\t\tready = True\n\t\tline = line.strip()\n\t\tif len(line)==0 or line.isspace():\n\t\t\tready = False\n\t\tif len(line)>=2 and line[0]=='/' and line[1]=='/':\n\t\t\tready = False\n\treturn line\n\ndef do_import(path, DELETE_TOP_BONE=True):\n\n\t# get scene\n\tscn = bpy.context.scene\n\tif scn==None:\n\t\treturn \"No scene to import to!\"\n\n\t# open the file\n\ttry:\n\t\tfile = open(path, 'r')\n\texcept IOError:\n\t\treturn \"Failed to open the file!\"\n\t\n\ttry:\n\t\tif not path.endswith(\".cn6\"):\n\t\t\traise IOError\n\texcept IOError:\n\t\treturn \"Must be an cn6 file!\"\n\n\t# Load Armature\n\ttry:\n\t\tlines = getNextLine(file).split()\n\t\tif len(lines) != 1 or lines[0] != \"skeleton\":\n\t\t\traise ValueError\n\texcept ValueError:\n\t\treturn \"File invalid!\"\n\n\t# Before adding any meshes or armatures go into Object mode.\n\tif bpy.ops.object.mode_set.poll():\n\t\tbpy.ops.object.mode_set(mode='OBJECT')\n\n\tarmature = bpy.data.armatures.new(\"Armature\")\n\tarmOb = bpy.data.objects.new(\"ArmatureObject\", armature)\n\tarmature.display_type = 'STICK'\n\tscn.collection.objects.link(armOb)\n\tbpy.context.view_layer.objects.active = armOb\n\n\t# read bones\n\tboneNames = []\n\tbpy.ops.object.editmode_toggle()\n\tbpy.types.EditBone.rot_matrix = bpy.props.FloatVectorProperty(name=\"Rot Matrix\", size=9)\n\n\tcurrentLine = \"\"\n\n\tboneCount = 0\n\tboneNameDict = []\n\tparentBoneIds = []\n\tpositions = []\n\tquaternions = []\n\n\twhile(not currentLine.startswith('meshes')):\n\t\tcurrentLine = getNextLine(file)\n\n\t\tif (not currentLine.startswith('meshes')):\n\t\t\tlines = shlex.split(currentLine)\n\t\t\tboneNameDict.append(lines[1])\n\t\t\tparentBoneIds.append(int(lines[2]))\n\t\t\tpositions.append([float(lines[3]), float(lines[4]), float(lines[5])])\n\t\t\tquaternions.append([float(lines[6]), float(lines[7]), float(lines[8]), float(lines[9])])\n\t\t\tboneCount = boneCount + 1\n\n\tprint (boneNameDict)\n\tfor i in range(boneCount):\n\t\t# read name\n\t\tfullName = boneNameDict[i]\n\t\tboneNames.append(fullName)\n\t\tbone = armature.edit_bones.new(fullName)\n\n\t\t# read parent\n\t\tif parentBoneIds[i] >= 0:\n\t\t\tparentBoneName = boneNameDict[parentBoneIds[i]] #getNextLine(file)[1:-1]\n\t\t\tbone.parent = armature.bones.data.edit_bones[parentBoneName]\n\n\t\tpos = positions[i]\n\t\tquat = quaternions[i]\n\n\t\t# Granny Rotation Quaternions are stored X,Y,Z,W but Blender uses W,X,Y,Z\n\t\tquaternion = Quaternion((quat[3], quat[0], quat[1], quat[2]))\n\t\trotMatrix = quaternion.to_matrix()\n\t\trotMatrix.transpose() # Need to transpose to get same behaviour as 2.49 script\n\n\t\tprint (\"Bone Data\")\n\t\tprint (fullName)\n\t\tprint (pos)\n\t\tprint (rotMatrix)\n\n\t\tboneLength = 3\n\t\t# set position and orientation\n\t\tif bone.parent:\n\t\t\tbone_parent_matrix = Matrix([[bone.parent.rot_matrix[0], bone.parent.rot_matrix[1], bone.parent.rot_matrix[2]],\n\t\t\t\t\t\t\t\t\t\t[bone.parent.rot_matrix[3], bone.parent.rot_matrix[4], bone.parent.rot_matrix[5]],\n\t\t\t\t\t\t\t\t\t\t[bone.parent.rot_matrix[6], bone.parent.rot_matrix[7], bone.parent.rot_matrix[8]]])\n\t\t\tbone.head = Vector(pos) @ bone_parent_matrix + bone.parent.head\n\t\t\tbone.tail = bone.head + Vector([boneLength,0,0])\n\t\t\ttempM = rotMatrix @ bone_parent_matrix\n\t\t\tbone.rot_matrix = [tempM[0][0], tempM[0][1], tempM[0][2],\n\t\t\t\t\t\t\t\ttempM[1][0], tempM[1][1], tempM[1][2],\n\t\t\t\t\t\t\t\ttempM[2][0], tempM[2][1], tempM[2][2]]\n\t\t\tbone.matrix = Matrix([[-bone.rot_matrix[3], bone.rot_matrix[0], bone.rot_matrix[6], bone.head[0]],\n\t\t\t\t\t\t\t\t [-bone.rot_matrix[4], bone.rot_matrix[1], bone.rot_matrix[7], bone.head[1]],\n\t\t\t\t\t\t\t\t [-bone.rot_matrix[5], bone.rot_matrix[2], bone.rot_matrix[8], bone.head[2]],\n\t\t\t\t\t\t\t\t [0, 0, 0, 1]])\n\t\telse:\n\t\t\tbone.head = Vector(pos)\n\t\t\tbone.tail = bone.head + Vector([boneLength,0,0])\n\t\t\tbone.rot_matrix = [rotMatrix[0][0], rotMatrix[0][1], rotMatrix[0][2],\n\t\t\t\t\t\t\t\trotMatrix[1][0], rotMatrix[1][1], rotMatrix[1][2],\n\t\t\t\t\t\t\t\trotMatrix[2][0], rotMatrix[2][1], rotMatrix[2][2]]\n\t\t\tbone.matrix = Matrix([[-bone.rot_matrix[3], bone.rot_matrix[0], bone.rot_matrix[6], bone.head[0]],\n\t\t\t\t\t\t\t\t [-bone.rot_matrix[4], bone.rot_matrix[1], bone.rot_matrix[7], bone.head[1]],\n\t\t\t\t\t\t\t\t [-bone.rot_matrix[5], bone.rot_matrix[2], bone.rot_matrix[8], bone.head[2]],\n\t\t\t\t\t\t\t\t [0, 0, 0, 1]])\n\n\t# Roll fix for all bones\n\tfor bone in armature.bones.data.edit_bones:\n\t\troll = bone.roll\n\t\tbone.roll = roll - radians(90.0)\n\n\t# read the number of meshes\n\ttry:\n\t\tlines = currentLine\n\t\tif not lines.startswith('meshes:'):\n\t\t\traise ValueError\n\t\tnumMeshes = int(lines.replace('meshes:',''))\n\t\tif numMeshes < 0:\n\t\t\traise ValueError\n\texcept ValueError:\n\t\treturn \"Number of meshes is invalid!\"\n\n\t# read meshes\n\tboneIds = [[],[],[],[],[],[],[],[]]\n\tboneWeights = [[],[],[],[],[],[],[],[]]\n\tmeshVertexGroups = {}\n\tvCount = 0\n\t\n\tmeshes = []\n\tmeshObjects = []\n\n\tprint('Num Meshes')\n\tprint(numMeshes)\n\n\tfor i in range(numMeshes):\n\n\t\twhile(not currentLine.startswith('mesh:')):\n\t\t\tcurrentLine = getNextLine(file)\n\n\t\tlines = currentLine.split(':')\n\n\t\tmeshName = lines[1][1:-1] + '#M'\n\t\tmeshes.append(bpy.data.meshes.new(meshName))\n\n\t\t# read materials\n\t\tmaterialNames = []\n\t\twhile(not currentLine.startswith('vertices')):\n\t\t\tcurrentLine = getNextLine(file)\n\t\t\tif (not currentLine.startswith('materials') and not currentLine.startswith('vertices')):\n\t\t\t\tmaterialNames.append(currentLine[1:-1])\n\n\t\tprint (\"materialNames\")\n\t\tprint (materialNames)\n\n\t\t# read vertices\n\t\tcoords = []\n\t\tnormals = []\n\t\ttangents = []\n\t\tbinormals = []\n\t\tuvs = []\n\t\tuvs2 = []\n\t\tuvs3 = []\n\t\tnumVerts = 0\n\t\tnormalsTangentsBinormals = []\n\t\toriginalTangentsBinormals = {}\n\n\t\tnonMatchingNormalTangentBinormal = True\n\n\t\twhile(not currentLine.startswith('triangles')):\n\t\t\tcurrentLine = getNextLine(file)\n\t\t\tif (not currentLine.startswith('vertices') and not currentLine.startswith('triangles')):\n\t\t\t\tlines = currentLine.split()\n\t\t\t\tif len(lines) != 34:\n\t\t\t\t\traise ValueError\n\t\t\t\tcoords.append([float(lines[0]), float(lines[1]), float(lines[2])])\n\t\t\t\tnormals.append([float(lines[3]), float(lines[4]), float(lines[5])])\n\t\t\t\ttangents.append([float(lines[6]), float(lines[7]), float(lines[8])])\n\t\t\t\tbinormals.append([float(lines[9]), float(lines[10]), float(lines[11])])\n\n\t\t\t\tif (numVerts < 10):\n\t\t\t\t\t#print(\"Normal/Tangent/Binormal Check\")\n\t\t\t\t\t#print(abs(float(lines[3]) - float(lines[6])))\n\t\t\t\t\t#print(abs(float(lines[4]) - float(lines[7])))\n\t\t\t\t\t#print(abs(float(lines[5]) - float(lines[8])))\n\t\t\t\t\tif (abs(float(lines[3]) - float(lines[6])) < 0.000001 and abs(float(lines[4]) - float(lines[7])) < 0.000001 and abs(float(lines[5]) - float(lines[8])) < 0.000001 and\n\t\t\t\t\t\tabs(float(lines[3]) - float(lines[9])) < 0.000001 and abs(float(lines[4]) - float(lines[10])) < 0.000001 and abs(float(lines[5]) - float(lines[11])) < 0.000001):\n\t\t\t\t\t\tnonMatchingNormalTangentBinormal = False\n\t\t\t\t\telse:\n\t\t\t\t\t\tnonMatchingNormalTangentBinormal = True\n\n\t\t\t\tuvs.append([float(lines[12]), 1-float(lines[13])])\n\t\t\t\tuvs2.append([float(lines[14]), 1-float(lines[15])])\n\t\t\t\tuvs3.append([float(lines[16]), 1-float(lines[17])])\n\n\t\t\t\tnormalsTangentsBinormals.append([float(lines[3]), float(lines[4]), float(lines[5]), float(lines[6]), float(lines[7]), float(lines[8]), float(lines[9]), float(lines[10]), float(lines[11])])\n\n\t\t\t\tboneIds[0].append(int(lines[18]))\n\t\t\t\tboneIds[1].append(int(lines[19]))\n\t\t\t\tboneIds[2].append(int(lines[20]))\n\t\t\t\tboneIds[3].append(int(lines[21]))\n\t\t\t\tboneIds[4].append(int(lines[22]))\n\t\t\t\tboneIds[5].append(int(lines[23]))\n\t\t\t\tboneIds[6].append(int(lines[24]))\n\t\t\t\tboneIds[7].append(int(lines[25]))\n\n\t\t\t\tboneWeights[0].append(float(lines[26]))\n\t\t\t\tboneWeights[1].append(float(lines[27]))\n\t\t\t\tboneWeights[2].append(float(lines[28]))\n\t\t\t\tboneWeights[3].append(float(lines[29]))\n\t\t\t\tboneWeights[4].append(float(lines[30]))\n\t\t\t\tboneWeights[5].append(float(lines[31]))\n\t\t\t\tboneWeights[6].append(float(lines[32]))\n\t\t\t\tboneWeights[7].append(float(lines[33]))\n\n\t\t\t\tmeshVertexGroups[vCount] = meshName # uses the long mesh name - may be > 21 chars\n\t\t\t\tnumVerts += 1\n\t\t\n\t\tmeshes[i].vertices.add(len(coords))\n\t\tmeshes[i].vertices.foreach_set(\"co\", unpack_list(coords))\n\t\tmeshOb = bpy.data.objects.new(meshName, meshes[i])\n\n\t\tfor materialName in materialNames:\n\n\t\t\tmaterial = None\n\n\t\t\tif materialName in bpy.data.materials:\n\t\t\t\tmeshOb.data.materials.append(bpy.data.materials[materialName])\n\t\t\telse:\n\t\t\t\tmaterial = bpy.data.materials.new(materialName)\n\t\t\t\tmeshOb.data.materials.append(material)\n\n\t\tif (nonMatchingNormalTangentBinormal):\n\t\t\tmeshOb.vertex_groups.new(name=\"VERTEX_KEYS\")\n\t\t\tkeyVertexGroup = meshOb.vertex_groups.get(\"VERTEX_KEYS\")\n\n\t\t\tfor v, vertex in enumerate(meshes[i].vertices):\n\t\t\t\tencoded_weight = (v / 2000000)\n\t\t\t\tkeyVertexGroup.add([v], encoded_weight, 'ADD')\n\t\t\t\t#print (\"encoded_weight {}\".format(encoded_weight))\n\t\t\t\t#print (\"vertex.bevel_weight {}\".format(vertex.groups[keyVertexGroup.index].weight))\n\t\t\t\toriginalTangentsBinormals[str(v)] = normalsTangentsBinormals[v]\n\n\t\tmeshes[i]['originalTangentsBinormals'] = originalTangentsBinormals\n\n\t\t# read triangles\n\t\tfaces = []\n\t\twhile (not currentLine.startswith('mesh:') and not currentLine.startswith('end')):\n\t\t\t# read the triangle\n\t\t\tcurrentLine = getNextLine(file)\n\t\t\tif (not currentLine.startswith('mesh:') and not currentLine.startswith('end')):\n\t\t\t\tlines = currentLine.split()\n\t\t\t\tif len(lines) != 4: # Fourth element is material index\n\t\t\t\t\traise ValueError\n\t\t\t\tv1 = int(lines[0])\n\t\t\t\tv2 = int(lines[1])\n\t\t\t\tv3 = int(lines[2])\n\t\t\t\tmi = int(lines[3])\n\n\t\t\tif v1 < numVerts and v2 < numVerts and v3 < numVerts and mi < len(materialNames):\n\t\t\t\tfaces.append([v1,v2,v3,mi])\n\n\t\t# Create Meshes and import Normals\n\t\tmesh = meshes[i]\n\t\tmesh.loops.add(len(faces) * 3)\n\t\tmesh.polygons.add(len(faces))\n\n\t\tloops_vert_idx = []\n\t\tfaces_loop_start = []\n\t\tfaces_loop_total = []\n\t\tfaces_material_index = []\n\t\tlidx = 0\n\t\tfor f in faces:\n\t\t\tvidx = [f[0],f[1],f[2]]\n\t\t\tnbr_vidx = len(vidx)\n\t\t\tloops_vert_idx.extend(vidx)\n\t\t\tfaces_loop_start.append(lidx)\n\t\t\tfaces_loop_total.append(nbr_vidx)\n\t\t\tfaces_material_index.append(f[3])\n\t\t\tlidx += nbr_vidx\n\n\t\tmesh.loops.foreach_set(\"vertex_index\", loops_vert_idx)\n\t\tmesh.polygons.foreach_set(\"loop_start\", faces_loop_start)\n\t\tmesh.polygons.foreach_set(\"loop_total\", faces_loop_total)\n\t\tmesh.polygons.foreach_set(\"material_index\", faces_material_index)\n\n\t\tmesh.create_normals_split()\n\n\t\tmesh.uv_layers.new(name='UV1')\n\t\tmesh.uv_layers.new(name='UV2')\n\t\tmesh.uv_layers.new(name='UV3')\n\n\t\tfor l in mesh.loops:\n\t\t\tl.normal[:] = normals[l.vertex_index]\n\t\t\tmesh.uv_layers[0].data[l.index].uv = uvs[l.vertex_index]\n\t\t\tmesh.uv_layers[1].data[l.index].uv = uvs2[l.vertex_index]\n\t\t\tmesh.uv_layers[2].data[l.index].uv = uvs3[l.vertex_index]\n\n\t\tmesh.validate(clean_customdata=False)\n\n\t\tclnors = array.array('f', [0.0] * (len(mesh.loops) * 3))\n\t\tmesh.loops.foreach_get(\"normal\", clnors)\n\n\t\tmesh.polygons.foreach_set(\"use_smooth\", [True] * len(mesh.polygons))\n\n\t\tmesh.normals_split_custom_set(tuple(zip(*(iter(clnors),) * 3)))\n\t\tmesh.use_auto_smooth = True\n\n\t\t#mesh.free_normals_split()\n\t\t####NORMALS - End\n\n\t\tmeshObjects.append(meshOb)\n\t\tscn.collection.objects.link(meshObjects[i])\n\t\t\t\n\tfor mesh in meshes:\n\t\tmesh.update()\n\n\t# Create Vertex Groups\n\tvi = 0\n\tfor meshOb in meshObjects:\n\t\tmesh = meshOb.data\n\t\tfor mvi, vertex in enumerate(mesh.vertices):\n\t\t\tfor bi in range(boneCount):\n\t\t\t\tfor j in range(8):\n\t\t\t\t\tif bi==boneIds[j][vi]:\n\t\t\t\t\t\tname = boneNames[bi] \n\t\t\t\t\t\tif not meshOb.vertex_groups.get(name):\n\t\t\t\t\t\t\tmeshOb.vertex_groups.new(name=name)\n\t\t\t\t\t\tgrp = meshOb.vertex_groups.get(name)\n\t\t\t\t\t\tnormalizedWeight = boneWeights[j][vi] / 255\n\t\t\t\t\t\tgrp.add([mvi], normalizedWeight, 'ADD')\n\t\t\t\t\t\t#print('Vertex: %d; Index: %d; Bone: %s; Weight: %f; ' % (mvi, j, name, normalizedWeight))\n\t\t\tvi = vi + 1\n\t\t\n\t\t# Give mesh object an armature modifier, using vertex groups but not envelopes\n\t\tmod = meshOb.modifiers.new('mod_' + mesh.name, 'ARMATURE')\n\t\tmod.object = armOb\n\t\tmod.use_bone_envelopes = False\n\t\tmod.use_vertex_groups = True\n\t\t# Parent Mesh Object to Armature Object\n\t\tmeshOb.parent = armOb\n\n\tif DELETE_TOP_BONE:\n\t\t# Adjust object names, remove top bone for Civ V\n\t\tbone = armature.bones.data.edit_bones[boneNames[0]]\n\t\twhile not bone.parent is None:\n\t\t\tbone = bone.parent\n\t\t\n\t\tprint ('Found World Bone: %s' % bone.name)\n\t\t\n\t\tname = bone.name\n\t\tarmOb.name = name\n\t\t\n\t\t# Delete top bone unless that would leave zero bones\n\t\tif (len(armature.bones.data.edit_bones) > 1):\n\t\t\tbpy.ops.object.select_pattern(pattern=name)\n\t\t\tbpy.ops.armature.delete()\n\t\t\n\tbpy.ops.object.editmode_toggle()\n\tbpy.ops.object.editmode_toggle()\n\tbpy.ops.object.editmode_toggle()\n\n\treturn \"\"\n\nclass Import_nb2(bpy.types.Operator, ImportHelper):\n\n\tbl_idname = \"import_shape.cn6\"\n\tbl_label = \"Import CN6 (.cn6)\"\n\tbl_description= \"Import a CivNexus6 .cn6 file\"\n\n\tfilename_ext = \".cn6\"\n\tfilter_glob = StringProperty(default=\"*.cn6\", options={'HIDDEN'})\n\n\tfilepath = StringProperty(name=\"File Path\",description=\"Filepath used for importing the file\",maxlen=1024,subtype='FILE_PATH',\n\t\t\t)\n\tDELETE_TOP_BONE= BoolProperty(name=\"Delete Top Bone\", description=\"Delete Top Bone\", default=True)\n\n\tdef execute(self, context):\n\t\tdo_import(self.filepath, self.DELETE_TOP_BONE)\n\t\treturn {'FINISHED'}\n\ndef menu_func(self, context):\n\tself.layout.operator(Import_nb2.bl_idname, text=\"CivNexus6 (.cn6)\")\n\ndef register():\n\tfrom bpy.utils import register_class\n\tregister_class(Import_nb2)\n\n\tbpy.types.TOPBAR_MT_file_import.append(menu_func)\n\ndef unregister():\n\tfrom bpy.utils import unregister_class\n\tunregister_class(Import_nb2)\n\n\tbpy.types.TOPBAR_MT_file_import.remove(menu_func)\n\nif __name__ == \"__main__\":\n\tregister()\n","sub_path":"Blender-2.8-Addons/io_import_cn6.py","file_name":"io_import_cn6.py","file_ext":"py","file_size_in_byte":15078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"2849304","text":"import datetime,time\n\nclass MessageHandler():\n \"\"\"\n Standardize messages to pass between systems\n \"\"\"\n def __init__(self):\n self.messages = {}\n\n def newId(self,id):\n self.messages[id] = []\n\n def serviceIncidentCreated(self, id, service, baseurl, error=None):\n \"\"\"\n initial PagerDuty Incident creation status\n \"\"\"\n if error is None:\n self.messages[id].append(\"Incident created for %s\" % (baseurl, service[\"service_url\"], service[\"name\"]))\n else:\n self.messages[id].append(\"Failed to create incident for %s with output: %s\" % (\n baseurl, \n service[\"service_url\"], \n service[\"name\"],\n error\n ))\n\n def incidentCreated(self, id, incident):\n \"\"\"\n message for new PagerDuty Incident\n \"\"\"\n self.messages[id].append(\"Incident %s created under %s\" % (\n incident[\"html_url\"],\n incident[\"id\"],\n incident[\"service\"][\"html_url\"],\n incident[\"service\"][\"name\"]\n ))\n \n def incidentAssigned(self, id, incident):\n \"\"\"\n message for new PagerDuty Incident\n \"\"\"\n self.messages[id].append(\"Incident %s Assigned to %s\" % (\n incident[\"html_url\"],\n incident[\"id\"],\n incident[\"assigned_to_user\"][\"html_url\"],\n incident[\"assigned_to_user\"][\"name\"]\n ))\n\n def incidentStatusChange(self, id, incident):\n \"\"\"\n message for PagerDuty Incident status changes\n \"\"\"\n message = \"%s: Incident %s %s by %s\" % (\n self.getUTCTime(incident[\"created_on\"]),\n incident[\"html_url\"],\n incident[\"id\"],\n incident[\"status\"], \n incident[\"last_status_change_by\"][\"html_url\"], \n incident[\"last_status_change_by\"][\"name\"]\n )\n self.messages[id].append(message)\n\n def incidentLogs(self,id,logs,baseurl):\n \"\"\"\n reformat incident log data\n \"\"\"\n for d in logs:\n created = self.getUTCTime(d[\"created_at\"])\n type = d[\"type\"]\n if type == \"annotate\":\n url = \"%s\" % (baseurl,d[\"agent\"][\"user_url\"],d[\"agent\"][\"name\"])\n self.messages[id].append(\"%s: %s Remarked: %s\" % (created,url,d['channel']['summary']))\n if type == \"notify\":\n self.messages[id].append(\"%s: Notification %s via %s to %s \" % (created,\n d[\"notification\"][\"status\"],\n d[\"notification\"][\"type\"],\n d[\"notification\"][\"address\"] ))\n elif type == \"acknowledge\":\n url = \"%s\" % (baseurl,d[\"agent\"][\"user_url\"],d[\"agent\"][\"name\"])\n self.messages[id].append(\"%s: Acknowledged by %s via %s\" % (created,\n url,\n d[\"channel\"][\"type\"]))\n elif type == \"unacknowledge\":\n self.messages[id].append(\"%s: Unacknowledged due to %s\" % (created,\n d[\"channel\"][\"type\"]))\n elif type == \"resolve\":\n url = \"%s\" % (baseurl,d[\"agent\"][\"user_url\"],d[\"agent\"][\"name\"])\n self.messages[id].append(\"%s: Resolved by %s via %s\" % (created,\n url,\n d[\"channel\"][\"type\"]))\n elif type == \"assign\":\n url = \"%s\" % (baseurl,d[\"assigned_user\"][\"user_url\"],d[\"assigned_user\"][\"name\"])\n self.messages[id].append(\"%s: Assigned to %s\" % (created,url))\n else:\n \n continue\n \n def serviceInMaintenance(self, id, action, svc, mw, baseurl):\n \"\"\"\n message with PagerDuty Maintenance Window details\n \"\"\"\n self.messages[id].append(\"%s due to %s maintenance window %s starting: %s ending: %s\" % (\n action,\n \"%s\" % (baseurl, svc[\"service_url\"], svc[\"name\"]), \n \"%s/maintenance_windows#/show/%s\" % (baseurl,mw[\"id\"]),\n mw[\"description\"],\n self.getLocalTime(mw[\"start_time\"]),\n self.getLocalTime(mw[\"end_time\"]),\n ))\n \n def serviceIsDisabled(self, id, action, svc, svcdetail, baseurl):\n \"\"\"\n message for PagerDuty Service disabled\n \"\"\"\n self.messages[id].append(\"%s because %s disabled by %s at %s\" % (\n action,\n \"%s\" % (baseurl, svc[\"service_url\"], svc[\"name\"]),\n \"%s\" % (baseurl, svcdetail[\"user\"][\"user_url\"], svcdetail[\"user\"][\"name\"]),\n self.getLocalTime(svcdetail[\"maintenance_window\"][\"time\"]),\n ))\n\n def serviceNotFound(self, id, key):\n \"\"\"\n \"\"\"\n self.messages[id].append(\"PagerDuty Service not found with KEY: %s\" % key)\n\n def getAge(self, timestring):\n time_tuple = time.strptime(timestring, \"%Y-%m-%dT%H:%M:%SZ\")\n then = time.mktime(time_tuple)\n now = time.time() + 6*60*60 # improve this to calculate local offset\n delta = now - then\n return delta\n \n def getPagerDutyTime(self,ts):\n dt = datetime.datetime.strptime(ts,'%Y-%m-%dT%H:%M:%SZ')\n dt = dt - datetime.timedelta(seconds=time.timezone)\n return time.mktime(dt.timetuple())\n \n def getUTCTime(self,ts):\n \"\"\"\n return datetime from PagerDuty UTC\n \"\"\"\n dt = datetime.datetime.strptime(ts,'%Y-%m-%dT%H:%M:%SZ') - datetime.timedelta(seconds=time.timezone)\n return dt\n\n def getLocalTime(self,ts):\n sub = ts[:-6]\n return datetime.datetime.strptime(sub,'%Y-%m-%dT%H:%M:%S')\n\n def getZenossTime(self, ts):\n sub = ts[:-4]\n dt = datetime.datetime.strptime(sub,'%Y/%m/%d %H:%M:%S')\n return dt\n #return self.getTimeStamp(dt) \n \n def getTimestamp(self,dt):\n \"\"\"\n return seconds given a datetime object\n \"\"\"\n return time.mktime(dt.timetuple())\n","sub_path":"MessageHandler.py","file_name":"MessageHandler.py","file_ext":"py","file_size_in_byte":7001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"434295737","text":"def rearrange_digits(input_list):\n \"\"\"\n Rearrange Array Elements so as to form two number such that their sum is maximum.\n\n Args:\n input_list(list): Input List\n Returns:\n (int),(int): Two maximum sums\n \"\"\"\n if len(input_list) == 0:\n return []\n elif len(input_list) == 1:\n return [input_list[0]]\n\n item1 = \"\"\n item2 = \"\"\n max_index = max(input_list)\n min_index = min(input_list)\n for i in range(max_index, min_index - 1, -1):\n if i in input_list:\n if len(item1) == 0 and len(item2) == 0:\n item1 += str(i)\n else:\n if len(item2) < len(item1):\n item2 += str(i)\n else:\n item1 += str(i)\n return [int(item1), int(item2)]\n\n\ndef test_function(test_case):\n output = rearrange_digits(test_case[0])\n solution = test_case[1]\n if sum(output) == sum(solution):\n print(\"Pass\")\n else:\n print(\"Fail\")\n\n\ntest_function([[1, 2, 3, 4, 5], [542, 31]])\ntest_function([[4, 6, 2, 5, 9, 8], [964, 852]])\ntest_function([[], []])\ntest_function([[0], [0]])\ntest_function([[0, 6, 2, 5, 9, 8], [962, 850]])\n","sub_path":"P2/problem_3.py","file_name":"problem_3.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"326166896","text":"\n\n#calss header\nclass _INDEMNIFY():\n\tdef __init__(self,): \n\t\tself.name = \"INDEMNIFY\"\n\t\tself.definitions = [u'to protect someone or something against possible damage or loss by paying an indemnity to cover the costs: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_indemnify.py","file_name":"_indemnify.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"642337766","text":"import nltk\r\nimport json\r\nimport os\r\nfrom transformers import BertTokenizer\r\n\r\n\r\nclass Vocab():\r\n def __init__(self, tokenizer=None, tokenize_func=nltk.word_tokenize):\r\n self.word2id = {\r\n '': 0, \r\n '': 1, \r\n '': 2, \r\n '': 3, \r\n }\r\n self.id2word = {\r\n 0: '', \r\n 1: '', \r\n 2: '', \r\n 3: '', \r\n }\r\n self.builtin_words = set(self.word2id.keys())\r\n self.word_count = {}\r\n self.size = len(self.word2id)\r\n self.tokenizer = tokenizer\r\n self.tokenize_func = tokenize_func\r\n\r\n\r\n def load(self, path='./vocab.json'):\r\n with open(path, 'r', encoding='utf-8') as f:\r\n self.word2id, self.id2word = json.load(f)\r\n self.size = len(self.word2id)\r\n\r\n\r\n def dump(self, path='./vocab.json'):\r\n with open(path, 'w', encoding='utf-8') as f:\r\n json.dump([self.word2id, self.id2word], f)\r\n\r\n\r\n def add_word(self, word):\r\n \"\"\"add a word to the word pool. will NOT build the dict\"\"\"\r\n word = word.strip().lower()\r\n if word in self.builtin_words:\r\n return\r\n if word not in self.word_count:\r\n self.word_count[word] = 1\r\n else:\r\n self.word_count[word] += 1\r\n \r\n\r\n def _add_word_to_dict(self, word):\r\n word = word.strip().lower()\r\n if word not in self.word2id:\r\n self.word2id[word] = self.size\r\n self.id2word[self.size] = word\r\n self.size += 1\r\n\r\n\r\n def build_dict(self, min_word_cnt_filter=5):\r\n word_count_pairs = sorted(self.word_count.items(), key=lambda x: x[1], reverse=True)\r\n print('total read:', len(word_count_pairs))\r\n for word, cnt in word_count_pairs:\r\n if cnt < min_word_cnt_filter:\r\n break\r\n self._add_word_to_dict(word)\r\n \r\n\r\n\r\n def add_word_from_sentence(self, sentence):\r\n for word in self.tokenize_func(sentence):\r\n self.add_word(word)\r\n\r\n\r\n def convert_word_to_id(self, word):\r\n if word not in self.word2id:\r\n word = ''\r\n return self.word2id[word]\r\n\r\n def convert_id_to_word(self, id):\r\n if type(id) != str:\r\n id = str(id)\r\n return self.id2word[id]\r\n\r\n def convert_sentence_to_ids(self, sentence):\r\n return [self.convert_word_to_id(word) for word in self.tokenize_func(sentence)]\r\n\r\n def convert_ids_to_sentence(self, ids, convert_all=False):\r\n if type(ids).__name__ == 'Tensor':\r\n assert len(ids.shape) == 1\r\n ids = ids.tolist()\r\n tokens = [self.convert_id_to_word(id) for id in ids]\r\n\r\n if '' in tokens and not convert_all:\r\n return ' '.join(tokens[:tokens.index('')])\r\n return ' '.join(tokens)\r\n\r\n \r\n\r\n\r\ndef preprocess(data_dir='./data/yelp/', task='yelp', lang='en'):\r\n \r\n \r\n if task == 'task1':\r\n lang = 'zh'\r\n data_dir='./data/task1/'\r\n elif task == 'task2':\r\n lang = 'zh'\r\n data_dir='./data/task2/'\r\n # elif task == 'task3':\r\n # lang = 'zh'\r\n # data_dir='./data/task3/'\r\n \r\n \r\n if lang == 'en':\r\n vocab = Vocab()\r\n elif lang == 'zh':\r\n tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')\r\n tokenize_func = tokenizer.tokenize\r\n vocab = Vocab(tokenizer=tokenizer, tokenize_func=tokenize_func) \r\n \r\n \r\n data = [] # store converted sentence ids\r\n label = [0, 1, 0, 1, 0, 1]\r\n\r\n # load preprocessed data if available\r\n if os.path.exists(f'{data_dir}/vocab.json') and os.path.exists(f'{data_dir}/data.json'):\r\n print('loading preprocessed data...', end='')\r\n vocab.load(path=f'{data_dir}/vocab.json')\r\n\r\n with open(f'{data_dir}/data.json', 'r', encoding='utf-8') as f:\r\n data, label = json.load(f)\r\n \r\n if data != [] and vocab.size > 4:\r\n print('done.')\r\n print('vocab size:', vocab.size)\r\n return data, label, vocab\r\n print('failed.')\r\n \r\n \r\n print('preprocessing data...')\r\n # read data\r\n filename_list = [\r\n 'train.0', 'train.1',\r\n 'dev.0', 'dev.1',\r\n 'test.0', 'test.1'\r\n ]\r\n\r\n # build word pool\r\n print('collecting words...')\r\n for i in range(3):\r\n with open(data_dir + filename_list[i*2], 'r', encoding='utf-8') as f:\r\n for line in f:\r\n line = line.strip().lower()\r\n if line == '':\r\n continue\r\n vocab.add_word_from_sentence(line)\r\n\r\n with open(data_dir + filename_list[i*2+1], 'r', encoding='utf-8') as f:\r\n for line in f:\r\n line = line.strip().lower()\r\n if line == '':\r\n continue\r\n vocab.add_word_from_sentence(line)\r\n\r\n # build word dict\r\n print('building word dict...')\r\n vocab.build_dict()\r\n print('vocab size:', vocab.size)\r\n vocab.dump(path=f'{data_dir}/vocab.json')\r\n\r\n # convert word to ids\r\n print('converting sentences...')\r\n vocab.load(path=f'{data_dir}/vocab.json')\r\n for i in range(3):\r\n with open(data_dir + filename_list[i*2], 'r', encoding='utf-8') as f:\r\n ids_list = []\r\n for line in f:\r\n line = line.strip().lower()\r\n if line == '':\r\n continue\r\n ids_list.append(vocab.convert_sentence_to_ids(line))\r\n \r\n data.append(ids_list)\r\n\r\n with open(data_dir + filename_list[i*2+1], 'r', encoding='utf-8') as f:\r\n ids_list = []\r\n for line in f:\r\n line = line.strip().lower()\r\n if line == '':\r\n continue\r\n ids_list.append(vocab.convert_sentence_to_ids(line))\r\n \r\n data.append(ids_list)\r\n\r\n with open(f'{data_dir}/data.json', 'w') as f:\r\n json.dump([data, label], f)\r\n\r\n return data, label, vocab\r\n\r\n\r\nif __name__ == \"__main__\":\r\n preprocess()","sub_path":"implement_original/src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"234861613","text":"import os\nfrom setuptools import setup\nREADME = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()\nsetup(name='django-oneall',\n version='0.1.4',\n packages=['django_oneall'],\n requires=['Django (>=1.4)',],\n install_requires=['pyoneall == 0.1'],\n license='MIT License, see LICENSE file',\n description='Django Authentication support for OneAll. Provides unified authentication for 20+ social networks',\n long_description=README,\n url='http://www.leandigo.com/',\n author='Michael Greenberg / Leandigo',\n author_email='michael@leandigo.com'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"346787640","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport gzip\r\nimport os\r\nimport re\r\nimport sys\r\nimport tarfile\r\n\r\nfrom six.moves import urllib\r\nimport tensorflow as tf\r\n\r\n\r\nBATCH_SIZE = 128\r\n\r\nclass MyFCN:\r\n def __init__(self):\r\n pass\r\n\r\n def _activation_summary(x):\r\n tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)\r\n tf.histogram_summary(tensor_name + '/activations', x)\r\n tf.scalar_summary(tensor_name + '/sparsity', tf.nn.zero_fraction(x))\r\n def _variable_with_weight_decay(name, shape, stddev, wd):\r\n \"\"\"\r\n stddev: standard deviation of a truncated Gaussian\r\n wd: add L2Loss weight decay multiplied by this float. If None, weight\r\n decay is not added for this Variable.\r\n \"\"\" \r\n initializer = tf.truncated_normal_initializer(stddev=stddev)\r\n var = tf.get_variable(name, shape, initializer=initializer)\r\n if wd is not None:\r\n weight_decay = tf.mul(tf.nn.l2_loss(var), wd, name='weight_loss')\r\n tf.add_to_collection('losses', weight_decay)\r\n return var\r\n\r\n def inference(images):\r\n \"\"\"Build the fcn model.\r\n Args:\r\n images: 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3]\r\n labels: may be added in future.\r\n Returns:\r\n Logits.\r\n \"\"\"\r\n # conv1\r\n with tf.variable_scope('conv1') as scope:\r\n kernel = _variable_with_weight_decay('weights', shape=[11, 11, 3, 96],\r\n stddev=1e-4, wd=0.0)\r\n conv = tf.nn.conv2d(images, kernel, strides=[1, 4, 4, 1], padding='VALID')\r\n biases = tf.get_variable('biases',[96], initializer=tf.constant_initializer(0.0))\r\n conv1 = tf.nn.relu(tf.nn.bias_add(conv, biases), name=scope.name)\r\n _activation_summary(conv1)\r\n # pool1\r\n pool1 = tf.nn.max_pool(conv1, ksize=[1,3,3,1], strides=[1,2,2,1],\r\n padding='VALID', name='pool1')\r\n #-------------------------------------------\r\n # conv2\r\n with tf.variable_scope('conv2') as scope:\r\n kernel = _variable_with_weight_decay('weights',shape=[5,5,96,256],\r\n stddev=1e-4, wd=0.0)\r\n conv = tf.nn.conv2d(pool1, kernel, strides=[1,2,2,1], padding='SAME')\r\n biases = tf.get_variable('biases',[256],initializer=tf.constant_initializer(0.1))\r\n conv2 = tf.nn.relu(tf.nn.bias_add(conv, biases), name=scope.name)\r\n # pool2\r\n pool2 = tf.nn.max_pool(conv2, ksize=[1, 3, 3, 1],\r\n strides=[1, 2, 2, 1], padding='VALID', name='pool2')\r\n #-------------------------------------------\r\n # conv3\r\n with tf.variable_scope('conv3') as scope:\r\n kernel = _variable_with_weight_decay('weights',shape=[3,3,256,384],\r\n stddev=1e-4, wd=0.0)\r\n conv = tf.nn.conv2d(pool2, kernel, strides=[1,1,1,1], padding='SAME')\r\n biases = tf.get_variable('biases',[384],initializer=tf.constant_initializer(0,1))\r\n conv3 = tf.nn.relu(tf.nn.bias_add(conv, biases), name=scope.name)\r\n #-------------------------------------------\r\n # conv4\r\n with tf.variable_scope('conv4') as scope:\r\n kernel = _variable_with_weight_decay('weights', shape=[3,3,384,384],\r\n stddev=1e-4, wd=0.0)\r\n conv = tf.nn.conv2d(conv3, kernel, strides=[1,1,1,1],padding='SAME')\r\n biases = tf.get_variable('biases',[384],initializer=tf.constant_initializer(0.1))\r\n conv4 = tf.nn.relu(tf.nn.bias_add(conv, biases), name=scope.name)\r\n #-------------------------------------------\r\n # conv5\r\n with tf.variable_scope('conv5') as scope:\r\n kernel = _variable_with_weight_decay('weights', shape=[3,3,384,256],\r\n stddev=1e-4, wd=0.0)\r\n conv = tf.nn.conv2d(conv4, kernel, strides=[1,1,1,1],padding='SAME')\r\n biases = tf.get_variable('biases',[256],initializer=tf.constant_initializer(0.1))\r\n conv5 = tf.nn.relu(tf.nn.bias_add(conv, biases), name=scope.name)\r\n # pool5\r\n pool5 = tf.nn.max_pool(conv5, ksize=[1, 3, 3, 1],\r\n strides=[1, 2, 2, 1], padding='VALID', name='pool5')\r\n\r\n #-------------------------------------------\r\n #fc6\r\n with tf.variable_scope('fc6') as scope:\r\n reshape = tf.reshape(pool5, [BATCH_SIZE, -1])\r\n dim = reshape.get_shape()[1].value\r\n weights = _variable_with_weight_decay('weights',\r\n shape=[dim,4096],stddev=0.04,wd=0.004)\r\n biases = tf.get_variable('biases',[4096],\r\n initializer=tf.constant_initializer(0.1))\r\n fc6 = tf.nn.relu(tf.matmul(reshape, weights)+biases, name=scope.name)\r\n _activation_summary(fc6)\r\n # drop layer may be need\r\n #----------------------------------------------\r\n # fc7\r\n with tf.variable_scope('fc7') as scope:\r\n weights = _variable_with_weight_decay('weights', \r\n shape=[4096, 4096], stddev=0.04, wd=0.004)\r\n biases = tf.get_variable('biases',[4096],initializer=tf.constant_initializer(0.1))\r\n fc7 = tf.nn.relu(tf.matmul(fc6,weights)+biases, name=scope.name)\r\n _activation_summary(fc7)\r\n \r\n # upsample image\r\n with tf.variable_scope('upsample') as scope:\r\n im_size = image.get_shape().as_list()\r\n conv7 = tf.reshape(fc7,[BATCH_SIZE,1,1,4096],'conv7')\r\n kernel = _variable_with_weight_decay('weights', shape=[im_size[0],im_size[1],4,4096],\r\n stddev=1e-4, wd=0.0)\r\n output_shape = tf.pack([BATCH_SIZE,im_size[0],im_size[1],4])\r\n deconv = tf.nn.conv2d_transpose(conv7, kernel, output_shape, strides=[1,1,1,1],padding='SAME')\r\ndef loss(prediction_image, depth_image):\r\n \"\"\"Add L2Loss to all the trainable variables.\r\n Args:\r\n logits: fcn_image from inference. [batch_size, w , h , c]\r\n depth_image: the depth label from grey_image, which size is same as logits\r\n [batch_size, w, h, c]\r\n Returns:\r\n Loss tensor of type float\r\n \"\"\"\r\n predict = tf.reshape(prediction_image, [-1])\r\n labels = tf.reshape(depth_image, [-1])\r\n cost = tf.nn.l2_loss(predict - labels, name='l2loss')/BATCH_SIZE\r\n tf.add_to_collection('losses', cost)\r\n return tf.add_n(tf.get_collection('losses'), name='total_less')\r\n \r\n","sub_path":"MyFCN.py","file_name":"MyFCN.py","file_ext":"py","file_size_in_byte":6572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"70395317","text":"import matplotlib\nmatplotlib.use('Agg') # this suppresses the console for plotting\nimport matplotlib.pyplot as plt\nimport bz2\nimport numpy as np\nfrom numpy import random\nimport pandas as pd\nimport os\nimport pylab\nfrom importlib import reload\nfrom sklearn.preprocessing import normalize\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras.callbacks import History, TensorBoard\nfrom keras import backend as K\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import roc_curve, auc, accuracy_score, f1_score, precision_score, recall_score\nfrom sklearn.metrics import precision_recall_curve\nimport itertools\nfrom itertools import cycle, product\nfrom sklearn.model_selection import StratifiedKFold\n\nimport config_file_local as config_file\n\ndata_directory = config_file.data_directory\nanalysis_directory = config_file.analysis_directory \nscripts_directory = config_file.scripts_directory \n\n\ndef format_plotting_string(data_set, kmer_size, norm_input, encoding_dim, encoded_activation, input_dropout_pct, dropout_pct, num_epochs, batch_size, n_splits, n_repeats):\n\n\n TF_dictionary={True:'T',False:'F'}\n\n plotting_string=''\n plotting_string+=data_set + '_'\n plotting_string+=str(kmer_size) +'_'\n plotting_string+='N:'+TF_dictionary[norm_input] +'_'\n plotting_string+='ED:'+ str(encoding_dim) +'_'\n plotting_string+='EA:'+ encoded_activation +'_'\n plotting_string+='IDP:' +str(input_dropout_pct) +'_'\n plotting_string+='DP:' + str(dropout_pct)\n\n return plotting_string\n\n\ndef format_plotting_string_2layers(data_set, kmer_size, norm_input, encoding_dim_1, encoding_dim_2, encoded_activation, input_dropout_pct, dropout_pct, num_epochs, batch_size, n_splits, n_repeats):\n\n\n TF_dictionary={True:'T',False:'F'}\n\n plotting_string=''\n plotting_string+=data_set + '_'\n plotting_string+=str(kmer_size) +'_'\n plotting_string+='N:'+TF_dictionary[norm_input] +'_'\n plotting_string+='ED1:'+ str(encoding_dim_1) +'_'\n plotting_string+='ED2:'+ str(encoding_dim_2) +'_'\n plotting_string+='EA:'+ encoded_activation +'_'\n plotting_string+='IDP:' +str(input_dropout_pct) +'_'\n plotting_string+='DP:' + str(dropout_pct)\n\n return plotting_string\n\n\n\ndef format_plotting_string_3layers(data_set, kmer_size, norm_input, encoding_dim_1, encoding_dim_2, encoding_dim_3, encoded_activation, input_dropout_pct, dropout_pct, num_epochs, batch_size, n_splits, n_repeats):\n\n\n TF_dictionary={True:'T',False:'F'}\n\n plotting_string=''\n plotting_string+=data_set + '_'\n plotting_string+=str(kmer_size) +'_'\n plotting_string+='N:'+TF_dictionary[norm_input] +'_'\n plotting_string+='ED1:'+ str(encoding_dim_1) +'_'\n plotting_string+='ED2:'+ str(encoding_dim_2) +'_'\n plotting_string+='ED3:'+ str(encoding_dim_3) +'_'\n plotting_string+='EA:'+ encoded_activation +'_'\n plotting_string+='IDP:' +str(input_dropout_pct) +'_'\n plotting_string+='DP:' + str(dropout_pct)\n\n return plotting_string\n\n\n\ndef plot_confusion_matrix(cm, classes, file_name):\n \n cmap=pylab.cm.Reds\n \"\"\"\n This function plots the confusion matrix.\n http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\n \"\"\"\n pylab.figure()\n im = pylab.imshow(cm, interpolation='nearest', cmap=cmap)\n pylab.title('confusion_matrix')\n pylab.colorbar()\n\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n pylab.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n pylab.xlabel('Predicted label')\n pylab.ylabel('True label')\n pylab.gca().set_position((.1, 10, 0.8, .8))\n\n pylab.savefig(file_name , bbox_inches='tight')\n\n\n\n\n\n\ndef plot_roc_aucs(fpr, tpr, auc, acc, graph_dir):\n title='ROC Curves, auc=%s, acc=%s' %(auc,acc)\n pylab.figure()\n\n pylab.plot([0, 1], [0, 1], 'k--')\n pylab.plot(fpr, tpr)\n pylab.xlim([0.0, 1.0])\n pylab.ylim([0.0, 1.05])\n pylab.xlabel('False Positive Rate')\n pylab.ylabel('True Positive Rate')\n pylab.title(title)\n #pylab.gca().set_position((.1, .7, .8, .8))\n\n\n pylab.savefig(os.path.expanduser(graph_dir + '/roc.pdf'))\n\n\n\ndef plot_loss_vs_epoch(history, graph_dir, plotting_str=''):\n\n pylab.figure()\n pylab.plot(history.history['loss'])\n pylab.plot(history.history['val_loss'])\n pylab.legend(['training','test'], loc='upper right')\n pylab.ylim((0, 1))\n \n pylab.title('Model loss by epochs')\n pylab.ylabel('Loss')\n pylab.xlabel('Epoch')\n\n pylab.savefig(os.path.expanduser(graph_dir + '/%sLoss.pdf' %plotting_str) , bbox_inches='tight')\n pylab.close()\n\n\ndef plot_accuracy_vs_epoch(history, graph_dir, plotting_str=''):\n pylab.figure()\n pylab.plot(history.history['acc'])\n pylab.plot(history.history['val_acc'])\n pylab.legend(['training','test'], loc='upper right')\n pylab.ylim((0, 1))\n\n pylab.title('Model accuracy by epochs')\n pylab.ylabel('Accuracy')\n pylab.xlabel('Epoch')\n \n pylab.savefig(os.path.expanduser(graph_dir + '/%saccuracy.pdf' %plotting_str) , bbox_inches='tight')\n pylab.close()\n\n\ndef plot_precision_recall(precision, recall, f1_score, plotting_string):\n pylab.figure()\n\n pylab.step(recall, precision, color='b', alpha=0.2, where='post')\n pylab.fill_between(recall, precision, step='post', alpha=0.2, color='b')\n\n pylab.xlabel('Recall')\n pylab.ylabel('Precision')\n pylab.ylim([0.0, 1.05])\n\n pylab.xlim([0.0, 1.0])\n\n print('Saving figure %sprecision_recall_%s.pdf' %(analysis_directory,plotting_string) )\n \n pylab.savefig(os.path.expanduser('%sprecision_recall_%s.pdf' %(analysis_directory, plotting_string)) , bbox_inches='tight')\n\n\n\ndef plot_all_for_iteration(aggregated_statistics, n_repeat, history, y_test, y_pred):\n\n graph_dir=os.path.expanduser('~/deep_learning_microbiome/analysis')\n\n fpr=aggregated_statistics[n_repeat]['fpr']\n tpr=aggregated_statistics[n_repeat]['tpr']\n auc=aggregated_statistics[n_repeat]['auc']\n accuracy=aggregated_statistics[n_repeat]['accuracy']\n f1=aggregated_statistics[n_repeat]['f1']\n conf_mat=aggregated_statistics[n_repeat]['conf_mat']\n\n # plot roc: \n plot_roc_aucs(fpr, tpr, auc, accuracy, graph_dir)\n\n # Plot accuracy vs epoch \n plot_accuracy_vs_epoch(history, graph_dir) \n\n # plot loss vs epoch \n plot_loss_vs_epoch(history, graph_dir)\n\n # Plot a confusion matrix \n file_name=os.path.expanduser(graph_dir + 'confusion_matrix.pdf')\n classes=['0','1']\n plot_confusion_matrix(conf_mat, classes,file_name)\n\n # Plot precision_recall \n precision_graph, recall_graph, _ = precision_recall_curve(y_test, y_pred)\n plot_precision_recall(precision_graph, recall_graph, f1, graph_dir)\n\n","sub_path":"annamarie_plots/plotting_utils.py","file_name":"plotting_utils.py","file_ext":"py","file_size_in_byte":7051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"398001267","text":"# Python program to convert\n# JSON file to CSV\n\nimport argparse\nimport csv\nimport json\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description=\"MiniConf Portal Command Line\")\n parser.add_argument(\"input\", default=\"data.json\", help=\"paper file\")\n\n parser.add_argument(\"out\", default=\"data.csv\", help=\"embeddings file to shrink\")\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n\n # Opening JSON file and loading the data\n # into the variable data\n with open(args.input) as json_file:\n data = json.load(json_file)\n\n # now we will open a file for writing\n data_file = open(args.out, \"w\")\n\n # create the csv writer object\n csv_writer = csv.writer(data_file)\n\n # Counter variable used for writing\n # headers to the CSV file\n count = 0\n\n for emp in data:\n if count == 0:\n\n # Writing headers of CSV file\n header = emp.keys()\n csv_writer.writerow(header)\n count += 1\n\n # Writing data of CSV file\n csv_writer.writerow(emp.values())\n\n data_file.close()\n","sub_path":"scripts/json_to_csv.py","file_name":"json_to_csv.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"101833","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nservers.py\n~~~~~~~~~~~~\n\nThis module implements servers HPE OneView REST API.\n\nIt has been deprecated and will be removed soon. We strongly recommend to use the OneViewClient class instead.\nSee more details at: https://github.com/HewlettPackard/python-hpOneView/tree/master/hpOneView/README.md\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom future import standard_library\n\nstandard_library.install_aliases()\n\n\n###\n# (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n###\n\nfrom hpOneView.activity import activity\nfrom hpOneView.common import get_members, uri, make_powerstate_dict, make_server_type_dict, make_ServerProfileV5, \\\n make_EnclosureGroupV200, make_ServerProfileTemplateV1\nfrom warnings import warn\n\n\ndef deprecated(func):\n def wrapper(*args, **kwargs):\n warn(\"Module servers is deprecated, use OneViewClient class instead\", DeprecationWarning)\n return func(*args, **kwargs)\n return wrapper\n\n\nclass servers(object):\n def __init__(self, con):\n self._con = con\n self._activity = activity(con)\n\n ###########################################################################\n # Connections\n ###########################################################################\n @deprecated\n def get_connections(self, filter=''):\n \"\"\" List all the active connections\n\n Args:\n filter:\n A general filter/query string that narrows the list of\n resources returned by a multi-resource GET (read) request and\n DELETE (delete) request. The default is no filter\n (all resources are returned). The filter parameter specifies\n a general filter/query string. This query string narrows the\n selection of resources returned from a GET request that\n returns a list of resources. The following example shows how to\n retrieve only the first 10 connections:\n\n Returns: all the connections, filtered or not.\n \"\"\"\n return get_members(self._con.get(uri['conn'] + filter))\n\n @deprecated\n def get_connection(self, server):\n \"\"\" List a specific connection\n\n Args:\n server:\n Connection id\n\n Returns: all the connections, filtered or not.\n \"\"\"\n body = self._con.get(server['uri'])\n return body\n\n ###########################################################################\n # Server Hardware\n ###########################################################################\n @deprecated\n def get_server_by_bay(self, baynum):\n servers = get_members(self._con.get(uri['servers']))\n for server in servers:\n if server['position'] == baynum:\n return server\n\n @deprecated\n def get_server_by_name(self, name):\n servers = get_members(self._con.get(uri['servers']))\n for server in servers:\n if server['name'] == name:\n return server\n\n @deprecated\n def get_available_servers(self, server_hardware_type=None,\n enclosure_group=None, server_profile=None):\n filters = []\n if server_hardware_type:\n filters.append('serverHardwareTypeUri=' + server_hardware_type['uri'])\n if enclosure_group:\n filters.append('enclosureGroupUri=' + enclosure_group['uri'])\n if server_profile:\n filters.append('serverProfileUri=' + server_profile['uri'])\n\n query_string = ''\n if filters:\n query_string = '?' + '&'.join(filters)\n\n return self._con.get(uri['profile-available-targets'] + query_string)\n\n @deprecated\n def get_servers(self):\n return get_members(self._con.get(uri['servers']))\n\n @deprecated\n def get_utilization(self, server):\n \"\"\"Retrieves historical utilization data for the specified resource, metrics, and time span. \"\"\"\n body = self._con.get(server['uri'] + '/utilization')\n return body\n\n @deprecated\n def get_env_conf(self, server):\n \"\"\"Gets the settings that describe the environmental configuration of the server hardware resource. \"\"\"\n body = self._con.get(server['uri'] + '/environmentalConfiguration')\n return body\n\n @deprecated\n def set_server_powerstate(self, server, state, force=False, blocking=True,\n verbose=False):\n if state == 'Off' and force is True:\n powerRequest = make_powerstate_dict('Off', 'PressAndHold')\n elif state == 'Off' and force is False:\n powerRequest = make_powerstate_dict('Off', 'MomentaryPress')\n elif state == 'On':\n powerRequest = make_powerstate_dict('On', 'MomentaryPress')\n elif state == 'Reset':\n powerRequest = make_powerstate_dict('On', 'Reset')\n task, body = self._con.put(server['uri'] + '/powerState', powerRequest)\n if blocking is True:\n task = self._activity.wait4task(task, tout=60, verbose=verbose)\n return task\n\n @deprecated\n def delete_server(self, server, force=False, blocking=True, verbose=False):\n if force:\n task, body = self._con.delete(server['uri'] + '?force=True')\n else:\n task, body = self._con.delete(server['uri'])\n if blocking is True:\n task = self._activity.wait4task(task, tout=600, verbose=verbose)\n return task\n\n @deprecated\n def update_server(self, server):\n task, body = self._con.put(server['uri'], server)\n return body\n\n @deprecated\n def add_server(self, server, blocking=True, verbose=False):\n task, body = self._con.post(uri['servers'], server)\n if blocking is True:\n task = self._activity.wait4task(task, tout=600, verbose=verbose)\n if 'type' in task and task['type'].startswith('Task'):\n entity = self._activity.get_task_associated_resource(task)\n server = self._con.get(entity['resourceUri'])\n return server\n return task\n\n @deprecated\n def get_server_schema(self):\n \"\"\" Gets the JSON schema of the server hardware resource.\"\"\"\n return self._con.get(uri['servers'] + '/schema')\n\n @deprecated\n def get_bios(self, server):\n \"\"\" Gets the list of BIOS/UEFI values currently set on the physical server.\"\"\"\n return self._con.get(server['uri'] + '/bios')\n\n @deprecated\n def get_ilo_sso_url(self, server):\n \"\"\" Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface.\"\"\"\n return self._con.get(server['uri'] + '/iloSsoUrl')\n\n @deprecated\n def get_java_remote_console_url(self, server):\n \"\"\" Generates a Single Sign-On (SSO) session for the iLO Java Applet console and returns\n the URL to launch it. \"\"\"\n return self._con.get(server['uri'] + '/javaRemoteConsoleUrl')\n\n @deprecated\n def get_remote_console_url(self, server):\n \"\"\" Generates a Single Sign-On (SSO) session for the iLO Integrated Remote Console Application\n (IRC) and returns the URL to launch it.\"\"\"\n return self._con.get(server['uri'] + '/remoteConsoleUrl')\n\n ###########################################################################\n # Server Hardware Types\n ###########################################################################\n @deprecated\n def get_server_hardware_types(self):\n \"\"\" Get the list of server hardware type resources defined on the appliance.\"\"\"\n body = self._con.get(uri['server-hardware-types'])\n return get_members(body)\n\n @deprecated\n def remove_server_hardware_type(self, server_hardware_type, force=False, blocking=True, verbose=False):\n \"\"\" Remove the server hardware type with the specified URI. A server hardware type cannot be deleted\n if it is associated with a server hardware or server profile resource. \"\"\"\n if force:\n task, body = self._con.delete(server_hardware_type['uri'] + '?force=True')\n else:\n task, body = self._con.delete(server_hardware_type['uri'])\n if blocking is True:\n task = self._activity.wait4task(task, tout=600, verbose=verbose)\n return task\n\n @deprecated\n def get_server_type_schema(self):\n \"\"\" Get the JSON schema of the server hardware types resource.\"\"\"\n return self._con.get(uri['server-hardware-types'] + '/schema')\n\n @deprecated\n def get_server_hardware_type(self, server_type):\n \"\"\" Get the server hardware type resource with the specified ID.\"\"\"\n return self._con.get(server_type['uri'])\n\n @deprecated\n def set_server_hardware_type(self, server_hardware_type, name, description):\n \"\"\" Updates one or more attributes for a server hardware type resource.\n\n Args:\n name:\n The localized name that describes a BIOS/UEFI setting.\n description:\n Brief description of the server hardware type.\n Maximum Length: 255\n Minimum Length: 0\n \"\"\"\n request = make_server_type_dict(name, description)\n task, body = self._con.put(server_hardware_type['uri'], request)\n return task\n\n ###########################################################################\n # Server Profiles\n ###########################################################################\n @deprecated\n def create_server_profile(self,\n affinity='Bay',\n biosSettings=None,\n bootSettings=None,\n bootModeSetting=None,\n profileConnectionV4=None,\n description=None,\n firmwareSettingsV3=None,\n hideUnusedFlexNics=True,\n localStorageSettingsV3=None,\n macType='Virtual',\n name=None,\n sanStorageV3=None,\n serialNumber=None,\n serialNumberType='Physical',\n serverHardwareTypeUri=None,\n serverHardwareUri=None,\n serverProfileTemplateUri=None,\n uuid=None,\n wwnType='Virtual',\n blocking=True, verbose=False):\n \"\"\" Create a ServerProfileV5 profile for use with the V200 API\n\n Args:\n affinity:\n This identifies the behavior of the server profile when the server\n hardware is removed or replaced. This can be set to 'Bay' or\n 'BayAndServer'.\n biosSettings:\n Dictionary that describes Server BIOS settings\n bootSettings:\n Dictionary that indicates that the server will attempt to boot from\n this connection. This object can only be specified if\n \"boot.manageBoot\" is set to 'true'\n bootModeSetting:\n Dictionary that describes the boot mode settings to be configured on\n Gen9 and newer servers.\n profileConnectionV4:\n Array of ProfileConnectionV3\n description:\n Description of the Server Profile\n firmwareSettingsV3:\n FirmwareSettingsV3 dictionary that defines the firmware baseline\n and management\n hideUnusedFlexNics:\n This setting controls the enumeration of physical functions that do\n not correspond to connections in a profile.\n localStorageSettingsV3:\n Dictionary that describes the local storage settings.\n macType:\n Specifies the type of MAC address to be programmed into the IO\n devices. The value can be 'Virtual', 'Physical' or 'UserDefined'.\n name:\n Unique name of the Server Profile\n sanStorageV3:\n Dictionary that describes the SAN storage settings.\n serialNumber:\n A 10-byte value that is exposed to the Operating System as the\n server hardware's Serial Number. The value can be a virtual serial\n number, user defined serial number or physical serial number read\n from the server's ROM. It cannot be modified after the profile is\n created.\n serialNumberType:\n Specifies the type of Serial Number and UUID to be programmed into\n the server ROM. The value can be 'Virtual', 'UserDefined', or\n 'Physical'. The serialNumberType defaults to 'Virtual' when\n serialNumber or uuid are not specified. It cannot be modified\n after the profile is created.\n serverHardwareTypeUri:\n Identifies the server hardware type for which the Server Profile\n was designed. The serverHardwareTypeUri is determined when the\n profile is created.\n serverHardwareUri:\n Identifies the server hardware to which the server profile is\n currently assigned, if applicable\n serverProfileTemplateUri:\n Identifies the Server profile template the Server Profile is based\n on.\n uuid:\n A 36-byte value that is exposed to the Operating System as the\n server hardware's UUID. The value can be a virtual uuid, user\n defined uuid or physical uuid read from the server's ROM. It\n cannot be modified after the profile is created.\n wwnType:\n Specifies the type of WWN address to be programmed into the IO\n devices. The value can be 'Virtual', 'Physical' or 'UserDefined'.\n It cannot be modified after the profile is created.\n\n Returns: server profile or task\n \"\"\"\n\n # Creating a profile returns a task with no resource uri\n profile = make_ServerProfileV5(affinity, biosSettings, bootSettings,\n bootModeSetting, profileConnectionV4,\n description, firmwareSettingsV3,\n hideUnusedFlexNics,\n localStorageSettingsV3, macType, name,\n sanStorageV3, serialNumber,\n serialNumberType, serverHardwareTypeUri,\n serverHardwareUri,\n serverProfileTemplateUri, uuid, wwnType)\n\n # missing required field: enclousure group\n # E.g.: profile['enclosureGroupUri'] = \"/rest/enclosure-groups/a0f1c07b-f811-4c85-8e38-ac5ec34ea2f4\"\n return self.create_server_profile_from_dict(profile, blocking, verbose)\n\n @deprecated\n def create_server_profile_from_dict(self, profile, blocking=True, verbose=False):\n # Creating a profile returns a task with no resource uri\n task, body = self._con.post(uri['profiles'], profile)\n if profile['firmware'] is None:\n tout = 600\n else:\n tout = 3600\n if blocking is True:\n task = self._activity.wait4task(task, tout, verbose=verbose)\n if 'type' in task and task['type'].startswith('Task'):\n entity = self._activity.get_task_associated_resource(task)\n profile = self._con.get(entity['resourceUri'])\n return profile\n return task\n\n @deprecated\n def get_server_profile_compliance(self, server_profile):\n compliance_preview = self._con.get(server_profile['uri'] + '/compliance-preview')\n return compliance_preview\n\n @deprecated\n def post_server_profile(self, profile, blocking=True, verbose=False):\n \"\"\" POST a ServerProfileV5 profile for use with the V200 API\n\n Args:\n profile:\n ServerProfileV5\n\n Returns: server profile or task\n \"\"\"\n\n task, body = self._con.post(uri['profiles'], profile)\n if profile['firmware'] is None:\n tout = 600\n else:\n tout = 3600\n if blocking is True:\n task = self._activity.wait4task(task, tout, verbose=verbose)\n if 'type' in task and task['type'].startswith('Task'):\n entity = self._activity.get_task_associated_resource(task)\n profile = self._con.get(entity['resourceUri'])\n return profile\n return task\n\n @deprecated\n def remove_server_profile(self, profile, force=False, blocking=True, verbose=False):\n if force:\n task, body = self._con.delete(profile['uri'] + '?force=True')\n else:\n task, body = self._con.delete(profile['uri'])\n if blocking is True:\n task = self._activity.wait4task(task, tout=600, verbose=verbose)\n return task\n\n @deprecated\n def get_server_profiles(self):\n body = self._con.get(uri['profiles'])\n return get_members(body)\n\n @deprecated\n def update_server_profile(self, profile, blocking=True, verbose=False):\n task, body = self._con.put(profile['uri'], profile)\n try:\n if profile['firmware']['firmwareBaselineUri'] is None:\n tout = 600\n else:\n tout = 3600\n except Exception:\n tout = 600\n # Update the task to get the associated resource uri\n if blocking is True:\n task = self._activity.wait4task(task, tout=tout, verbose=verbose)\n profileResource = self._activity.get_task_associated_resource(task)\n profile = self._con.get(profileResource['resourceUri'])\n return profile\n\n @deprecated\n def update_server_profile_from_template(self, profile, blocking=True, verbose=False):\n patch_request = [{'op': 'replace', 'path': '/templateCompliance', 'value': 'Compliant'}]\n task, body = self._con.patch(profile['uri'], patch_request)\n try:\n if profile['firmware']['firmwareBaselineUri'] is None:\n tout = 600\n else:\n tout = 3600\n except Exception:\n tout = 600\n # Update the task to get the associated resource uri\n if blocking is True:\n task = self._activity.wait4task(task, tout=tout, verbose=verbose)\n profileResource = self._activity.get_task_associated_resource(task)\n profile = self._con.get(profileResource['resourceUri'])\n return profile\n\n @deprecated\n def get_server_profile_by_name(self, name):\n body = self._con.get_entity_byfield(uri['profiles'], 'name', name)\n return body\n\n @deprecated\n def get_profile_message(self, profile):\n \"\"\" Retrieve the error or status messages associated with the specified profile. \"\"\"\n message = self._con.get(profile['uri'] + '/messages')\n return message\n\n @deprecated\n def get_profile_compliance_preview(self, profile):\n \"\"\" Gets the preview of manual and automatic updates required to make the\n server profile consistent with its template. \"\"\"\n return self._con.get(profile['uri'] + '/compliance-preview')\n\n ###########################################################################\n # Server Profile Templates\n ###########################################################################\n @deprecated\n def create_server_profile_template(self, name=None, description=None,\n serverProfileDescription=None, serverHardwareTypeUri=None,\n enclosureGroupUri=None, affinity=None, hideUnusedFlexNics=None,\n profileConnectionV4=None, firmwareSettingsV3=None, bootSettings=None,\n bootModeSetting=None, sanStorageV3=None, blocking=True, verbose=False):\n \"\"\"\n Create a ServerProfileTemplateV1 dictionary for use with the V200 API\n Args:\n name:\n Unique name of the Server Profile Template\n description:\n Description of the Server Profile Template\n serverProfileDescription:\n The description of the server profiles created from this template.\n serverHardwareTypeUri:\n Identifies the server hardware type for which the Server Profile\n was designed. The serverHardwareTypeUri is determined when the\n profile is created.\n enclosureGroupUri:\n Identifies the enclosure group for which the Server Profile Template\n was designed. The enclosureGroupUri is determined when the profile\n template is created and cannot be modified.\n affinity:\n This identifies the behavior of the server profile when the server\n hardware is removed or replaced. This can be set to 'Bay' or\n 'BayAndServer'.\n hideUnusedFlexNics:\n This setting controls the enumeration of physical functions that do\n not correspond to connections in a profile.\n profileConnectionV4:\n An array of profileConnectionV4\n firmwareSettingsV3:\n FirmwareSettingsV3 dictionary that defines the firmware baseline\n and management.\n bootSettings:\n Dictionary that indicates that the server will attempt to boot from\n this connection. This object can only be specified if\n \"boot.manageBoot\" is set to 'true'\n bootModeSetting:\n Dictionary that describes the boot mode settings to be configured on\n Gen9 and newer servers.\n sanStorageV3:\n Dictionary that describes the SAN storage settings.\n\n Returns: dict\n \"\"\"\n profile_template = make_ServerProfileTemplateV1(name,\n description,\n serverProfileDescription,\n serverHardwareTypeUri,\n enclosureGroupUri,\n affinity,\n hideUnusedFlexNics,\n profileConnectionV4,\n firmwareSettingsV3,\n bootSettings,\n bootModeSetting,\n sanStorageV3)\n\n task, body = self._con.post(uri['profile-templates'], profile_template)\n tout = 600\n if blocking is True:\n task = self._activity.wait4task(task, tout, verbose=verbose)\n if 'type' in task and task['type'].startswith('Task'):\n entity = self._activity.get_task_associated_resource(task)\n profile_template = self._con.get(entity['resourceUri'])\n return profile_template\n return task\n\n @deprecated\n def remove_server_profile_template(self, profile_template, blocking=True, verbose=False):\n task, body = self._con.delete(profile_template['uri'])\n if blocking is True:\n task = self._activity.wait4task(task, tout=600, verbose=verbose)\n return task\n return body\n\n @deprecated\n def get_server_profile_templates(self):\n body = self._con.get(uri['profile-templates'])\n return get_members(body)\n\n @deprecated\n def get_server_profile_template_by_name(self, name):\n body = self._con.get_entity_byfield(uri['profile-templates'], 'name', name)\n return body\n\n @deprecated\n def update_server_profile_template(self, profile_template, blocking=True, verbose=False):\n task, body = self._con.put(profile_template['uri'], profile_template)\n tout = 600\n # Update the task to get the associated resource uri\n if blocking is True:\n task = self._activity.wait4task(task, tout=tout, verbose=verbose)\n profileTemplateResource = self._activity.get_task_associated_resource(task)\n self._con.get(profileTemplateResource['resourceUri'])\n return profile_template\n\n @deprecated\n def get_server_profile_from_template(self, profile_template):\n profile = self._con.get(profile_template['uri'] + '/new-profile')\n return profile\n\n ###########################################################################\n # Enclosures\n ###########################################################################\n @deprecated\n def get_enclosures(self):\n body = self._con.get(uri['enclosures'])\n return get_members(body)\n\n @deprecated\n def add_enclosure(self, enclosure, blocking=True, verbose=False):\n task, body = self._con.post(uri['enclosures'], enclosure)\n if enclosure['state'] is 'Monitored':\n tout = 600\n elif enclosure['firmwareBaselineUri'] is None:\n tout = 600\n else:\n tout = 3600\n\n if blocking is True:\n task = self._activity.wait4task(task, tout, verbose=verbose)\n if 'type' in task and task['type'].startswith('Task'):\n entity = self._activity.get_task_associated_resource(task)\n enclosure = self._con.get(entity['resourceUri'])\n return enclosure\n return task\n\n @deprecated\n def remove_enclosure(self, enclosure, force=False, blocking=True,\n verbose=False):\n if force:\n task, body = self._con.delete(enclosure['uri'] + '?force=True')\n else:\n task, body = self._con.delete(enclosure['uri'])\n if blocking is True:\n task = self._activity.wait4task(task, tout=600, verbose=verbose)\n return task\n\n ###########################################################################\n # Enclosure Groups\n ###########################################################################\n @deprecated\n def create_enclosure_group(self, associatedLIGs, name,\n powerMode='RedundantPowerSupply'):\n \"\"\" Create an EnclosureGroupV200 dictionary\n\n Args:\n associatedLIGs:\n A sorted list of logical interconnect group URIs associated with\n the enclosure group.\n name:\n The name of the enclosure group.\n powerMode:\n Power mode of the enclosure group. Values are 'RedundantPowerFeed'\n or 'RedundantPowerSupply'.\n\n Returns: enclosure group\n \"\"\"\n egroup = make_EnclosureGroupV200(associatedLIGs, name, powerMode)\n # Creating an Enclosure Group returns the group, NOT a task\n task, body = self._con.post(uri['enclosureGroups'], egroup)\n return body\n\n @deprecated\n def delete_enclosure_group(self, egroup):\n self._con.delete(egroup['uri'])\n\n @deprecated\n def get_enclosure_groups(self):\n return get_members(self._con.get(uri['enclosureGroups']))\n\n @deprecated\n def update_enclosure_group(self, enclosuregroup):\n task, body = self._con.put(enclosuregroup['uri'], enclosuregroup)\n return body\n\n ###########################################################################\n # ID Pools\n ###########################################################################\n @deprecated\n def get_pool(self, pooltype):\n body = self._con.get(uri['idpool'] + '/' + pooltype)\n return body\n\n @deprecated\n def get_vmac_pool(self):\n body = self._con.get(uri['vmac-pool'])\n return body\n\n @deprecated\n def get_vwwn_pool(self):\n body = self._con.get(uri['vwwn-pool'])\n return body\n\n @deprecated\n def get_vsn_pool(self):\n body = self._con.get(uri['vsn-pool'])\n return body\n\n @deprecated\n def get_profile_networks(self):\n body = self._con.get(uri['profile-networks'])\n return body\n\n @deprecated\n def get_profile_schema(self):\n return self._con.get(uri['profile-networks-schema'])\n\n @deprecated\n def get_profile_available_servers(self):\n body = self._con.get(uri['profile-available-servers'])\n return body\n\n @deprecated\n def get_profile_available_storage_systems(self):\n body = self._con.get(uri['profile-available-storage-systems'])\n return body\n\n @deprecated\n def get_profile_ports(self):\n body = self._con.get(uri['profile-ports'])\n return body\n\n # TODO put pool\n @deprecated\n def allocate_pool_ids(self, url, count):\n allocatorUrl = '%s/allocator' % url\n allocatorBody = {'count': count}\n task, body = self._con.put(allocatorUrl, allocatorBody)\n return body\n\n @deprecated\n def release_pool_ids(self, url, idList):\n collectorUrl = '%s/collector' % url\n collectorBody = {'idList': idList}\n task, body = self._con.put(collectorUrl, collectorBody)\n return body\n\n @deprecated\n def allocate_range_ids(self, allocatorUrl, count):\n task, body = self._con.put(allocatorUrl, {'count': count})\n return body\n\n @deprecated\n def release_range_ids(self, collectorUrl, idList):\n task, body = self._con.put(collectorUrl, {'idList': idList})\n return body\n\n # TODO POST Range\n @deprecated\n def enable_range(self, url):\n prange = self._con.get(url)\n prange['enabled'] = True\n task, body = self._con.put(url, prange)\n return body\n\n @deprecated\n def disable_range(self, url):\n prange = self._con.get(url)\n prange['enabled'] = False\n task, body = self._con.put(url, prange)\n return body\n\n# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:\n","sub_path":"hpOneView/servers.py","file_name":"servers.py","file_ext":"py","file_size_in_byte":31645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"353808108","text":"#!/usr/bin/env python\n# -*- encoding: UTF-8 -*-\n\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'oc.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^$', 'www.views.index', name='index'),\n url(r'^www/', include('www.urls', namespace='www')),\n url(r'^bills/', include('bills.urls', namespace='bills')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'),\n \turl(r'^accounts/logout/$', 'django.contrib.auth.views.logout', name='logout'),\n)\n","sub_path":"oc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"215366674","text":"import json\n\n\ndef save2json(data, path):\n with open(path, 'w', encoding='utf-8') as f:\n json.dump(data, f)\n\n\ndef json2dict(path):\n with open(path, encoding='utf-8') as f:\n d = json.load(f)\n return d\n\n\ndef pretty_print_dict(data):\n data = json.dumps(data, indent=4, ensure_ascii=False,\n sort_keys=False, separators=(',', ': '))\n print(data)\n\n\nif __name__ == '__main__':\n filename = './files/test.json'\n savepath = './files/test_1.json'\n jsondata = json2dict(filename)\n pretty_print_dict(jsondata)\n save2json(jsondata, savepath) \n","sub_path":"jsonUtils.py","file_name":"jsonUtils.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"59699496","text":"from django.urls import path\r\nfrom apps.cart.views import CartAddView, CartInfoView, CartUpdateView, CartDeleteView\r\n\r\napp_name = 'cart'\r\nurlpatterns = [\r\n path('add', CartAddView.as_view(), name='add'), # 添加购物车\r\n path('info', CartInfoView.as_view(), name='info'), # 购物车详情\r\n path('update', CartUpdateView.as_view(), name='update'), # 购物车记录更新\r\n path('delete', CartDeleteView.as_view(), name='delete') # 购物车记录删除\r\n]\r\n\r\n","sub_path":"apps/cart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"608542071","text":"######################################\n#\n# Name: Intro to OpenCV Part 2\n#\n# Created by: John Ocker\n#\n# Assisted by: Documentation on Canvas\n#\n# Purpose: Reads in a saved picture and\n# resizes the picture in half.\n#\n######################################\n\nimport cv2\nimport numpy as np\n\nimg = cv2.imread('image.jpg')\n\ncv2.imshow('Image',img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nres = cv2.resize(img,None,fx=.5,fy=.5,interpolation = cv2.INTER_CUBIC)\n\ncv2.imshow('Image',res)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"opencv/take_picture_2.py","file_name":"take_picture_2.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"142718576","text":"from django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render\nfrom django.utils.decorators import method_decorator\n\nfrom accountapp.decorators import account_ownership_required\nfrom accountapp.forms import AccountUpdateForm\nfrom boardapp.models import Board\n\nhas_ownership = [account_ownership_required, login_required]\n\n# Create your views here.\nfrom django.urls import reverse_lazy\nfrom django.views.generic import CreateView, DetailView, UpdateView, DeleteView, ListView\n\n\ndef index(request):\n return render(request, 'accountapp/index.html')\n\nclass AccountIndexView(ListView):\n model = Board\n context_object_name = 'post_list'\n template_name = 'accountapp/index.html'\n\n def get_context_data(self):\n max = 9\n notice_list = Board.objects.filter(type='notice').order_by('-id')[:max]\n dsum_list = Board.objects.filter(type='dsum').order_by('-id')[:max]\n kquestion_list = Board.objects.filter(type='kquestion').order_by('-id')[:max]\n contest_list = Board.objects.filter(type='contest').order_by('-id')[:max]\n tutoring_list = Board.objects.filter(type='tutoring').order_by('-id')[:max]\n\n return super().get_context_data(notice_list=notice_list, dsum_list=dsum_list, kquestion_list=kquestion_list, contest_list=contest_list, tutoring_list=tutoring_list)\n\nclass AccountCreateView(CreateView):\n model = User\n form_class = UserCreationForm\n success_url = reverse_lazy('accountapp:login')\n template_name = 'accountapp/create.html'\n\n\nclass AccountDetailView(DetailView):\n model = User\n context_object_name = 'target_user'\n template_name = 'accountapp/detail.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\n@method_decorator(has_ownership, 'get')\n@method_decorator(has_ownership, 'post')\nclass AccountUpdateView(UpdateView):\n model = User\n form_class = AccountUpdateForm\n context_object_name = 'target_user'\n success_url = reverse_lazy('accountapp:hello_world')\n template_name = 'accountapp/update.html'\n\n\n@method_decorator(has_ownership, 'get')\n@method_decorator(has_ownership, 'post')\nclass AccountDeleteView(DeleteView):\n model = User\n context_object_name = 'target_user'\n success_url = reverse_lazy('accountapp:login')\n template_name = 'accountapp/delete.html'\n\n","sub_path":"accountapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"300180347","text":"\"\"\"\nPlot confusion matrix\n=====================\n\"\"\"\n\nfrom arus.models.muss import MUSSModel\nimport matplotlib.pyplot as plt\nmuss = MUSSModel()\ninput_class = ['Sit', 'Stand', 'Stand', 'Walk']\npredict_class = ['Sit', 'Walk', 'Stand', 'Stand']\nfig = muss.get_confusion_matrix(input_class, predict_class, labels=[\n 'Sit', 'Stand', 'Walk'], graph=True)\n\ndf = muss.get_confusion_matrix(input_class, predict_class, labels=[\n 'Sit', 'Stand', 'Walk'], graph=False)\n\nprint(df)\n","sub_path":"examples/models/plot_muss_confusion_matrix.py","file_name":"plot_muss_confusion_matrix.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"438220758","text":"# TODO: by wybrac wykonywane cwiczenie zmodyfikuj funkcje main (na dole pliku)\n\n# importujemy przydatne skladowe biblioteki pomagajacej w uczeniu sieci neuronowych (niezbedna do dalszych cwiczen)\n\nimport keras.applications.mobilenet_v2 as k_mobilenet_v2\nimport keras.backend as k\nimport keras.datasets.mnist as k_mnist\nimport keras.layers as k_layers\nimport keras.losses as k_losses\nimport keras.models as k_models\nimport keras.optimizers as k_optimizers\nimport keras.preprocessing.image as k_image\nimport keras.utils as k_utils\n\n# importujemy biblioteke pomagajaca w rysowaniu wykresow i wizualizacji\nimport matplotlib.pyplot as plt\n\n# importujemy biblioteke pomagajaca w obliczeniach numerycznych\nimport numpy as np\n\n# importujemy biblioteke pomagajaca nam w operacjach tensorowych (niezbedna do poczatkowych cwiczen)\nimport tensorflow as tf\n\nimport cv2\n\n\n# ladujemy przykladowe dane wejsciowe (klasyczny juz zbior danych z recznie pisanymi cyframi)\ndata = k_mnist.load_data()\n# korzystamy z gotowego podziału na czesc treningowa i testowa\n(train_images, train_labels), (test_images, test_labels) = data\n# ustalamy rozmiar jednej paczki danych uczacych na 100 przykladow - pozwala to efektywniej uzywac CPU/GPU\nbatch_size = 100\n\n\n# funkcja pomocnicza inicjujaca i zwracajaca sesje obliczeniowa TensorFlow\ndef _init_session():\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n session = tf.Session(config=config)\n init = tf.global_variables_initializer()\n session.run(init)\n return session\n\n\n# funkcja pomocnicza odpowiedzialna za uczenie (optymalizacje) z uzyciem spadku po gradiencie\ndef _optimise(session, x, correct_y, loss):\n # przygotowujemy silnik optymalizujacy (w tym przypadku oparty o wspomniany spadek po gradiencie)\n optimizer = tf.train.GradientDescentOptimizer(0.5)\n # 0.5 to stala regulujaca szybkosc spadku, a wiec tez uczenia, zazwyczaj nazywana learning rate\n train_step = optimizer.minimize(loss) # informujemy, ze tym co chcemy zredukowac jest wlasnie L (loss)\n\n # porcjujemy nasze dane treningowe na paczki do rownoczesnego wykorzystania - to przyspieszy proces uczenia\n for i in range(train_images.shape[0] // batch_size):\n batch_train_images = train_images[i * batch_size:(i + 1) * batch_size, :, :]\n batch_train_labels = train_labels[i * batch_size:(i + 1) * batch_size]\n # elementy podane do feed_dict zapelniaja stworzone wczesniej placeholdery na dane\n session.run(train_step, feed_dict={x: batch_train_images, correct_y: batch_train_labels})\n\n\n# funkcja pomocnicza odpowiedzialna za weryfikacje skutecznosci wytrenowanej sieci\ndef _test_accuracy(session, x, correct_y, y, y_):\n # definiujemy praiwdlowy wynik: wtedy gdy najwieksze prawdopodobienstwo ma wlasciwa klasa\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n # definiujemy skutecznosc jako srednia ilosc prawidlowych wynikow\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n # uruchamiamy obliczenia, tym razem sprawdzajac, nie uczac (zwroc uwage na inny argument session.run\n test_outcome = session.run(accuracy, feed_dict={x: test_images, correct_y: test_labels})\n print(\"Final accuracy result: {0} %\".format(test_outcome*100.0))\n\n\ndef intro():\n # obejrzyjmy przykladowy element zbioru - cyfre 3\n example_image = train_images[44]\n # upewnijmy sie, ze to co widzimy jest zgodne z przyporzadkowana klasa\n example_label = train_labels[44]\n print(\"Correct label for this element: {0}\".format(example_label))\n # wyplotujmy zawartosc obrazu\n plt.imshow(example_image)\n plt.show()\n # TODO: sprawdz co zawiera kilka innych elementow; czy sa latwe do rozpoznania dla czlowieka?\n\n\ndef exercise_one():\n # tworzymy nasza pierwsza, minimalna siec\n\n # tf.placeholder to miejsce na tensor, ktory zostanie zawsze podany przed startem obliczen i nigdy sie nie zmieni\n # z jego uzyciem najpierw przygotowujemy miejsca na wejsciowy obraz...\n # w tym przypadku nie zastepujemy None - oznaczaja one dowolny rozmiar\n x = tf.placeholder(tf.float32, [None, 28, 28]) # miejsce na obraz cyfry (28px na 28px)\n x_ = tf.reshape(x, [-1, 784]) # reshape do liniowego ksztaltu (28x28=784), -1 to automatyczne dopasowanie reszty\n x_ /= 255.0 # podzielenie przez 255.0 normalizuje wartosci do zakresu od 0.0 do 1.0\n # ...oraz etykiete oznaczajaca cyfre, jaka przedstawia\n correct_y = tf.placeholder(tf.uint8, [None]) # miejsce na klase cyfry (mozliwe 10 roznych klas)\n y_ = tf.one_hot(correct_y, 10) # zamienia cyfrę na wektor o 10 pozycjach, tylko jedna z nich jest inna niz 0 (hot)\n\n # potem przygotowujemy zmienne - tensory ktorych wartosci beda ewoluowac w czasie\n # inicjujemy je zerami o wlasciwym ksztalcie - tu wlasnie znajda sie poszukiwane przez nas optymalne wagi\n w = tf.Variable(tf.zeros([784, 10])) # wagi funkcji liniowej (10 neuronow, kazdy ma 784 wejscia)\n b = tf.Variable(tf.zeros([10])) # bias funkcji liniowej (dla kazdego z 10 neuronow)\n\n # TODO: zastap None, zaimplementuj funkcje f\n # wykorzystaj przygotowane wyzej zmienne oraz tf.matmul i tf.nn.softmax\n y = tf.nn.softmax(tf.matmul(x_,w)+b)\n\n # TODO: zastap None, dokoncz implementacje funkcji L (entropii krzyzowej)\n # wykorzystaj przygotowane wyzej zmienne oraz tf.log; zastanow sie jak zsumowac tylko wlasciwe elementy wyjscia!\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n\n # uruchamiamy graf obliczen tensor flow\n session = _init_session() # startujemy sesje\n _optimise(session, x, correct_y, cross_entropy) # optymalizujemy entropie krzyzowa\n _test_accuracy(session, x, correct_y, y, y_) # i weryfikujemy skutki na danych testowych\n # TODO: jaki wynik udalo sie uzyskac?\n\n\ndef exercise_two():\n # dodajemy do naszej sieci dodatkowa warstwe, w celu zwiekszenia jej pojemnosci i sily wyrazu\n\n # ta sekcja jest powtorka z poprzedniego cwiczenia - rozstawia warstwe wejsciowa\n x = tf.placeholder(tf.float32, [None, 28, 28])\n x_ = tf.reshape(x, [-1, 784]) / 255.0\n correct_y = tf.placeholder(tf.uint8, [None])\n y_ = tf.one_hot(correct_y, 10)\n\n # kolejne dwie sekcje nieco sie juz roznia - dodalismy dodatkowa warstwe wewnetrzna\n w1 = tf.Variable(tf.zeros([784, 100]))\n b1 = tf.Variable(tf.zeros([100]))\n h1 = tf.nn.relu(tf.matmul(x_,w1)+b1)\n\n w2 = tf.Variable(tf.zeros([100, 10]))\n b2 = tf.Variable(tf.zeros([10]))\n y = tf.nn.softmax(tf.matmul(h1,w2)+b2)\n # TODO: zastap None, zaimplementuj aktywacje obu warstw wzorujac sie na exercise_one\n # dla pierwszej warstwy skorzystaj z tf.nn.relu, dla drugiej (wyjsciowej) nadal z tf.nn.softmax\n\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n # TODO: wykorzystaj powyzej implementacje z exercise_one (jest nadal aktualna)\n\n # ta sekcja rowniez jest powtorka z poprzedniego cwiczenia\n session = _init_session()\n _optimise(session, x, correct_y, cross_entropy)\n _test_accuracy(session, x, correct_y, y, y_)\n # TODO: jaki wynik udalo sie tym razem uzyskac? czy zaskoczyl cie?\n\n\ndef exercise_three():\n # TODO: rozwiaz problem z poczatkowymi aktywacjami funkcji ReLU\n # zmien poczatkowe wartosci wag na losowe z odchyleniem standardowym od -0.1 do 0.1, a biasy na po prostu 0.1\n # skorzystaj z funkcji tf.truncated_normal (dla wag) i tf.constant (dla biasow)\n # TODO: pozostale elementy uzupelnij jak w cwiczeniu drugim\n\n x = tf.placeholder(tf.float32, [None, 28, 28])\n x_ = tf.reshape(x, [-1, 784]) / 255.0\n correct_y = tf.placeholder(tf.uint8, [None])\n y_ = tf.one_hot(correct_y, 10)\n\n w1 = tf.Variable(tf.truncated_normal([784, 100], 0.0, 0.1))\n b1 = tf.Variable(tf.constant(0.1, shape=[100]))\n\n y = tf.matmul(x_, w1) + b1\n\n h1 = tf.nn.relu(y)\n\n\n w2 = tf.Variable(tf.truncated_normal([100, 10], 0.0, 0.1))\n b2 = tf.Variable(tf.constant(0.1, shape=[10]))\n y = tf.nn.softmax(tf.matmul(h1, w2) + b2)\n\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n\n session = _init_session()\n _optimise(session, x, correct_y, cross_entropy)\n _test_accuracy(session, x, correct_y, y, y_)\n # TODO: raz jeszcze sprawdz jaka wartosc przyjmie accuracy\n\n\ndef exercise_four():\n print(type(train_images[0]))\n print('')\n print(train_images[0])\n print('')\n print(type(train_labels[0]))\n print('')\n print(train_labels[0])\n\n # TODO: (OPCJONALNIE) przeskocz do cwiczenia piatego w przypadku duzego zmeczenia na zajeciach - jest duzo \"lzejsze\"\n # tym razem tworzymy siec identyczna jak poprzednia, ale wykorzystujac wysokopoziomowa biblioteke Keras\n model = k_models.Sequential() # nasza siec bedzie skladac sie z sekwencji warstw (wymienionych ponizej)\n\n # klasa k_layers.X to w rzeczywistosci keras.layers.X (patrz importy u gory pliku) - analogicznie dla innych modulow\n model.add(k_layers.Reshape((784,), input_shape=(28,28))) # zmienia ksztalt wejscia z (28, 28) na (784, )\n # TODO: zastap None wykorzystujac odpowiednio skonstruowana instacje klasy k_layers.Reshape\n model.add(k_layers.Lambda(lambda x: x/255.0)) # normalizuje wejscie z 0.0 do 255.0 na 0.0 do 1.0\n # TODO: zastap None uzywajac k_layers.Lambda i wykonujac z jej uzyciem odpowiednie dzielenie\n model.add(k_layers.Dense(100,activation=k_layers.Activation('relu'), input_dim=(784,))) # pierwsza prawdziwa warstwa neuronow\n # TODO: zastap None uzywajac k_layers.Dense, pamietaj o odpowiednim rozmiarze wejsciowym (parametr input_dim),\n # TODO: (c.d.) wyjsciowym (parametr units) i aktywacji (parametr activation) - w tym przypadku relu\n model.add(k_layers.Dense(10,activation=k_layers.Activation('softmax'),input_dim=(100,))) # wyjsciowa warstwa neuronow\n # TODO: zastap None uzywajac k_layers.Dense (analogicznie), pamietaj o wlasciwych rozmiarach i aktywacji softmax\\\n\n # teraz kompilujemy nasz zdefiniowany wczesniej model\n model.compile(\n loss='categorical_crossentropy', # tu podajemy czym jest funkcja loss\n # TODO: zastap None wybierajac wlasciwy wariant z k_losses (entropia krzyzowa dla danych kategorycznych)\n optimizer=k_optimizers.SGD(lr=0.03), # a tu podajemy jak ja optymalizowac\n # TODO: zastac None instancja wlasciwego silnika z k_optimizers (SGD = Stochastic Gradient Descent),\n # TODO: (c.d.) pamietaj o ustaleniu wartosci parametra learning rate (lr)\n metrics=['accuracy'] # tu informujemy, by w trakcie pracy zbierac informacje o uzyskanej skutecznosci\n )\n # trenujemy nasz skompilowany model (k_utils.to_categorical jest odpowiednikiem tf.one_hot)\n model.fit(train_images, k_utils.to_categorical(train_labels), epochs=1, batch_size=batch_size)\n # oraz ewaluujemy jego skutecznosc\n loss_and_metrics = model.evaluate(test_images, k_utils.to_categorical(test_labels))\n print(\"Final accuracy result: {0} %\".format(loss_and_metrics[1]*100.0))\n # TODO: czy udalo sie uzyskac wynik podobny do tego z cwiczenia trzeciego?\n\ndef exercise_five():\n # na koniec skorzystamy z gotowej, wytrenowanej juz sieci glebokiej\n # TODO: uruchom przyklad pobierajacy gotowa siec, wytrenowana na zbiorze ImageNet\n\n\n\n # pobranie gotowego modelu zlozonej sieci konwolucyjnej z odpowiednimi wagami\n # include_top=True oznacza ze pobieramy wszystkie warstwy - niektore zastosowania korzystaja tylko z dolnych\n model = k_mobilenet_v2.MobileNetV2(weights='imagenet', include_top=True)\n # podejrzenie tego z ilu i jakich warstw sie sklada\n layers = dict([(layer.name, layer.output) for layer in model.layers])\n print(\"Network containts following layers:\")\n for i, (name, layer) in enumerate(layers.items()):\n print(\"Layer {0} : {1}\".format(i, (name, layer)))\n # oraz ile parametrow musialo zostac wytrenowanych\n print(\"Together: {0} parameters\\n\".format(model.count_params()))\n # TODO: odpowiedz, o ile wieksza jest ta siec od wytrenowanej przez nas?\n # powyzsza siec jest i tak wyjatkowo mala - sluzy do zastosowan mobilnych, wiec jest silnie miniaturyzowana\n\n # otworzmy przykladowe zdjecie i dostosujemy jego rozmiar i zakres wartosci do wejscia sieci\n image_path = 'nosacz.jpg'\n image = k_image.load_img(image_path, target_size=(224, 224))\n # TODO: zastap None powyzej zmieniajac rozmiar na taki, jaki przyjmuje wejscie sieci (skorzystaj z wypisanego info)\n x = k_image.img_to_array(image) # kolejne linie dodatkowo dostosowuja obraz pod dana siec\n x = np.expand_dims(x, axis=0)\n x = k_mobilenet_v2.preprocess_input(x)\n\n # sprawdzmy jaki wynik przewidzi siec\n predictions = model.predict(x)\n # i przetlumaczmy uzywajac etykiet zrozumialych dla czlowieka (5 najbardziej prawdopodobnych klas zdaniem sieci)\n print('Predicted class:', k_mobilenet_v2.decode_predictions(predictions, top=5)[0])\n # TODO: czy skonczylo sie sukcesem?\n\n # TODO: pobaw sie z innymi zdjeciami z Internetu - jak radzi sobie siec? kiedy sie myli? w jaki sposob?\n # TODO: (c.d.) pamietaj, ze siec rozumie tylko wymienione w ponizszym JSONIE klasy:\n # https://github.com/raghakot/keras-vis/blob/master/resources/imagenet_class_index.json\n\n # finalnie podgladamy aktywacje jakie wysylaja neurony sieci w trakcie dzialania\n # w wypisanych wczesniej informacjach mozna latwo spradzic ile kanalow ma warstwa o danym numerze (i ktora to)\n # layer_to_preview = 4 # numer warstwy, ktorej aktywacje podgladamy\n\n layer_to_preview = 65 # numer warstwy, ktorej aktywacje podgladamy\n # channel_to_preview = 16 # numer kanalu w tejze warstwie\n channel_to_preview = 0 # numer kanalu w tejze warstwie\n get_activations = k.function([model.layers[0].input], [model.layers[layer_to_preview].output])\n activations = get_activations([x])\n plt.imshow(activations[0][0, :, :, channel_to_preview], cmap=\"viridis\")\n plt.show()\n\n\n # TODO: podejrzyj aktywacje w kolejnych warstwach; czym roznia sie te w poczatkowych od tych w koncowych?\n # o. ..0000.00 0.0 o.0\n # colory znikajo, i rozdzielozcosc znika\n\n\n return model\n\n\n\ndef home_one_playground(model,image_path):\n\n test = [[1.0,1.0,1.0],[0.5,0.5,0.5],[0.,0.,0.]]\n testNA = np.array(test)\n plt.imshow(testNA,cmap=\"hot\")\n plt.show()\n plt.imshow(home_one_add_horizontal(testNA,testNA),cmap='hot')\n plt.show()\n plt.imshow(home_one_add_horizontal_list([testNA, testNA]), cmap='hot')\n plt.show()\n\n\ndef home_one_add_horizontal(img1,img2): #assumes same size\n out = np.copy(img1)\n out = np.append(out,img2,axis=1)\n return out\n\ndef home_one_add_horizontal_list(img_list): #assumes same size\n out = np.copy(img_list[0])\n skip_first=True\n for img in img_list:\n if skip_first:\n skip_first=False\n continue\n out=np.append(out,img,axis=1)\n return out\n\ndef home_one_add_vertical(img1,img2): #assumes same size\n out = np.copy(img1)\n out = np.append(out,img2,axis=0)\n return out\n\n\ndef home_one_add_vertical_list(img_list): #assumes same size\n out = np.copy(img_list[0])\n skip_first=True\n for img in img_list:\n if skip_first:\n skip_first=False\n continue\n out=np.append(out,img,axis=0)\n return out\n\n\n\ndef home_one_conc_and_show_im(out_image_list):\n print(\"\")\n print(\"\")\n print(len(out_image_list))\n res_image_list=[]\n single_size=28\n # for img in out_image_list:\n # res_image_list.append(cv2.resize(img, dsize=(single_size,single_size), interpolation=cv2.INTER_CUBIC))\n res_image_list= list(map(lambda img: cv2.resize(img, dsize=(single_size,single_size), interpolation=cv2.INTER_CUBIC),out_image_list))\n print(len(res_image_list))\n number_of_pics_in_row=30\n black_one = np.zeros((single_size, single_size))\n k = len(res_image_list) % number_of_pics_in_row\n if not k == 0:\n for i in range(number_of_pics_in_row - k):\n res_image_list.append(black_one)\n\n print(len(res_image_list))\n res_image_list_list=[res_image_list[number_of_pics_in_row*i:number_of_pics_in_row*(i+1)] for i in range(len(res_image_list)//number_of_pics_in_row)]\n print(len(res_image_list_list))\n print(len(res_image_list_list[0]))\n # for img in res_image_list:\n # plt.imshow(img, cmap=\"hot\")\n # plt.show()\n # # if i<=0: # TODO REMOVE\n # # break\n horizontal_img=[]\n for img_list in res_image_list_list:\n horizontal_img.append(home_one_add_horizontal_list(img_list))\n print(len(horizontal_img))\n print(horizontal_img[0].shape)\n out=None\n out=home_one_add_vertical_list(horizontal_img)\n plt.imshow(out, cmap=\"hot\")\n plt.show()\n print(out)\n print(out.shape)\n pass\n\n\ndef home_one_get_image_from_activation_and_channel(activations,channel_to_preview):\n # print(activations[0])\n # pic=plt.imshow(activations[0][0, :, :, channel_to_preview], cmap=\"viridis\")\n # print(type(pic))\n # print(pic)\n # print(\"\\n\\n\\n\\n\\n\\n\")\n # array=np.array(pic)\n # print(type(array))\n # print(array)\n return activations[0][0,:,:,channel_to_preview]\n\n\ndef home_one_print(model,image_path):\n layers = dict([(layer.name, layer.output) for layer in model.layers])\n\n # image_path = 'nosacz.jpg'\n image = k_image.load_img(image_path, target_size=(224, 224))\n x = k_image.img_to_array(image) # kolejne linie dodatkowo dostosowuja obraz pod dana siec\n x = np.expand_dims(x, axis=0)\n x = k_mobilenet_v2.preprocess_input(x)\n\n # sprawdzmy jaki wynik przewidzi siec\n predictions = model.predict(x)\n print('Predicted class:', k_mobilenet_v2.decode_predictions(predictions, top=5)[0])\n layer_to_preview = 1 # numer warstwy, ktorej aktywacje podgladamy\n # channel_to_preview = 16 # numer kanalu w tejze warstwie\n channel_to_preview = 0 # numer kanalu w tejze warstwie\n get_activations = k.function([model.layers[0].input], [model.layers[layer_to_preview].output])\n activations = get_activations([x])\n # plt.imshow(activations[0][0, :, :, channel_to_preview], cmap=\"viridis\")\n # plt.show()\n\n out_image_list=[]\n # print(\"'''\")\n # for l in model.layers:\n # print(type(l.output))\n # print(l.output)\n # print(l.output.shape)\n # break\n # print(\"'''\")\n\n for i, (name, layer) in enumerate(layers.items()):\n print(\"Layer {0} : {1}\".format(i, (name, layer)))\n if len(layer.shape) < 3 :\n continue\n if i<1:\n continue\n if i<65:# TODO remove\n continue#\n layer_to_preview = i # numer warstwy, ktorej aktywacje podgladamy\n get_activations = k.function([model.layers[0].input], [model.layers[layer_to_preview].output])\n activations = get_activations([x])\n for n in range(layer.shape[3]):\n channel_to_preview = n # numer kanalu w tejze warstwie\n out_image_list.append(home_one_get_image_from_activation_and_channel(activations, channel_to_preview))\n break # TODO remove\n print(len(out_image_list))\n home_one_conc_and_show_im(out_image_list)\n\n\n\n\n\n\n\ndef home_one():\n model = k_mobilenet_v2.MobileNetV2(weights='imagenet', include_top=True)\n # home_one_playground(model,'nosacz.jpg')\n home_one_print(model,'nosacz.jpg')\n # image_path = 'nosacz.jpg'\n # image = k_image.load_img(image_path, target_size=(10, 10))\n # print(image)\n # image_matrix=k_image.img_to_array(image)\n # print(image_matrix)\n\n\n\n\ndef home_two_run_single(model,class_name,x):\n pass\n\n\ndef add_dark_square(img_array,posx,posy,size):\n for i in range(posx,posx+size):\n for k in range(posy,posy+size):\n img_array[0][i][k][0]=0\n img_array[0][i][k][1]=0\n img_array[0][i][k][2]=0\n\ndef add_to_all(out_table,pos_x,pos_y,size,outcome):\n for i in range(224):\n for k in range(224):\n if (i>=pos_x and i<(pos_x+size) ) or (k>=pos_y and k<(pos_y+ size)):\n continue\n out_table[i][k][0]=out_table[i][k][0]+outcome\n out_table[i][k][1]=out_table[i][k][1]+1\n\n\n\ndef home_two():\n model = k_mobilenet_v2.MobileNetV2(weights='imagenet', include_top=True)\n image_path = 'RTR6S1V.jpg'\n #224=7*2^5\n\n image = k_image.load_img(image_path, target_size=(224, 224))\n print(\"running\")\n # TODO: zastap None powyzej zmieniajac rozmiar na taki, jaki przyjmuje wejscie sieci (skorzystaj z wypisanego info)\n x = k_image.img_to_array(image) # kolejne linie dodatkowo dostosowuja obraz pod dana siec\n x = np.expand_dims(x, axis=0)\n x = k_mobilenet_v2.preprocess_input(x)\n out_array=np.zeros((224,224,2)) # first is sum of % outcomes, second is number of tries later they will be divided\n size = 7*2 # 227/size must be int\n for i1 in range(224-size):\n for k1 in range(224-size):\n x_clone=np.copy(x)\n add_dark_square(x_clone, i1, k1, size)\n predictions= model.predict([x_clone])\n add_to_all(out_array, i1 ,k1, size, k_mobilenet_v2.decode_predictions(predictions, top=5)[0][0][2]) # TODO cahange 0.5 to actual outcome\n\n\n heat_map= np.zeros((224,224))\n\n min_val=1\n max_val=0\n for i in range(224):\n for k in range(224):\n heat_map[i][k]=out_array[i][k][0]/out_array[i][k][1]\n if heat_map[i][k]max_val:\n max_val=heat_map[i][k]\n\n plt.imshow(heat_map, cmap=\"hot\",vmin=min_val,vmax=max_val)\n plt.show()\n\n print(heat_map)\n print(max_val)\n print(min_val)\n print(\"\\n\\n\\n\\n\")\n\n print(type(x))\n print(x)\n print(x.shape)\n predictions = model.predict(x)\n print('Predicted class:', k_mobilenet_v2.decode_predictions(predictions, top=5)[0])\n print('Predicted class:', k_mobilenet_v2.decode_predictions(predictions, top=5)[0][0][1])\n\n\n\n\ndef main():\n # TODO: tu wybieraj wykonywane cwiczenie (wykonuj je zgodnie z kolejnoscia)\n #intro()\n #exercise_one()\n #exercise_two()\n #exercise_three()\n # exercise_four()\n # exercise_five()\n # home_one()\n home_two()\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"nn/neurolab.py","file_name":"neurolab.py","file_ext":"py","file_size_in_byte":22217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"169235551","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nRANDOM_VARIABLE_COLLECTION = \"_random_variable_collection_\"\n\n\nclass RandomVariable(object):\n \"\"\"Base class for random variables.\n\n A random variable is an object parameterized by tensors. It is\n equipped with methods such as the log-density, mean, and sample.\n\n It also wraps a tensor, where the tensor corresponds to a sample\n from the random variable. This enables operations on the TensorFlow\n graph, allowing random variables to be used in conjunction with\n other TensorFlow ops.\n\n Examples\n --------\n >>> p = tf.constant([0.5])\n >>> x = Bernoulli(p=p)\n >>>\n >>> z1 = tf.constant([[2.0, 8.0]])\n >>> z2 = tf.constant([[1.0, 2.0]])\n >>> x = Bernoulli(p=tf.matmul(z1, z2))\n >>>\n >>> mu = Normal(mu=tf.constant(0.0), sigma=tf.constant(1.0)])\n >>> x = Normal(mu=mu, sigma=tf.constant([1.0]))\n\n Notes\n -----\n RandomVariable assumes use in a multiple inheritance setting. The\n child class must first inherit RandomVariable, then second inherit a\n class in tf.contrib.distributions. With Python's method resolution\n order, this implies the following during initialization (using\n distributions.Bernoulli as an example):\n\n 1. Start the __init__() of the child class, which passes all *args,\n **kwargs to RandomVariable.\n 2. This in turn passes all *args, **kwargs to\n distributions.Bernoulli, completing the __init__() of\n distributions.Bernoulli.\n 3. Complete the __init__() of RandomVariable, which calls\n self.sample(), relying on the method from distributions.Bernoulli.\n 4. Complete the __init__() of the child class.\n\n Methods from both RandomVariable and distributions.Bernoulli\n populate the namespace of the child class. Methods from\n RandomVariable will take higher priority if there are conflicts.\n \"\"\"\n def __init__(self, *args, **kwargs):\n # storing args, kwargs for easy graph copying\n self._args = args\n self._kwargs = kwargs\n\n # need to temporarily pop value before __init__\n value = kwargs.pop('value', None)\n super(RandomVariable, self).__init__(*args, **kwargs)\n self._kwargs['value'] = value # reinsert (needed for copying)\n\n tf.add_to_collection(RANDOM_VARIABLE_COLLECTION, self)\n\n if value is not None:\n t_value = tf.convert_to_tensor(value, self.dtype)\n expected_shape = (self.get_batch_shape().as_list() +\n self.get_event_shape().as_list())\n value_shape = t_value.get_shape().as_list()\n if value_shape != expected_shape:\n raise ValueError(\n \"incompatible shape for initialization argument 'value'.\"\n \"expected '%s', got '%s'\" % (expected_shape, value_shape))\n else:\n self._value = t_value\n else:\n self._value = self.sample()\n\n def __str__(self):\n return ''\n\n def __repr__(self):\n return self.__str__()\n\n def value(self):\n \"\"\"Get tensor that the random variable corresponds to.\"\"\"\n return self._value\n\n def get_ancestors(self, collection=None):\n \"\"\"Get ancestor random variables.\"\"\"\n from edward.util.random_variables import get_ancestors\n return get_ancestors(self, collection)\n\n def get_children(self, collection=None):\n \"\"\"Get child random variables.\"\"\"\n from edward.util.random_variables import get_children\n return get_children(self, collection)\n\n def get_descendants(self, collection=None):\n \"\"\"Get descendant random variables.\"\"\"\n from edward.util.random_variables import get_descendants\n return get_descendants(self, collection)\n\n def get_parents(self, collection=None):\n \"\"\"Get parent random variables.\"\"\"\n from edward.util.random_variables import get_parents\n return get_parents(self, collection)\n\n def get_siblings(self, collection=None):\n \"\"\"Get sibling random variables.\"\"\"\n from edward.util.random_variables import get_siblings\n return get_siblings(self, collection)\n\n def get_variables(self, collection=None):\n \"\"\"Get TensorFlow variables that the random variable depends on.\"\"\"\n from edward.util.random_variables import get_variables\n return get_variables(self, collection)\n\n def _tensor_conversion_function(v, dtype=None, name=None, as_ref=False):\n _ = name\n if dtype and not dtype.is_compatible_with(v.dtype):\n raise ValueError(\n \"Incompatible type conversion requested to type '%s' for variable \"\n \"of type '%s'\" % (dtype.name, v.dtype.name))\n if as_ref:\n raise ValueError(\"%s: Ref type is not supported.\" % v)\n return v.value()\n\n\ntf.register_tensor_conversion_function(\n RandomVariable, RandomVariable._tensor_conversion_function)\n","sub_path":"edward/models/random_variable.py","file_name":"random_variable.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"439692056","text":"\"\"\"\nInterface for the SPGroup api\n- SPGroup api delivers producing data\n- delivers production from the past hour\n- constructor takes the site_id as parameter\n- !!! Access by hardcoded api key !!!\n\"\"\"\nimport time\nimport sched\nimport requests\nimport datetime\nfrom datetime import tzinfo, timedelta\n\nfrom core.abstract.input import EnergyData, Device, EnergyDataSource\n\n\n# producing asset\nclass SPGroupAPI(EnergyDataSource):\n\n def __init__(self, site_id: str, api_url: str, api_key: str):\n\n self.site = site_id\n self.api_url = api_url\n self.api_key = api_key\n self.schedule = sched.scheduler(time.time, time.sleep)\n\n def read_state(self) -> EnergyData:\n raw = self._get_daily_data()\n '''\n {\n \"sites\": [\n {\n \"site_id\": \"b1\",\n \"start_time\": \"2018-03-26T08:21:20Z\",\n \"end_time\": \"2018-03-26T09:21:20Z\",\n \"energy\": {\n \"unit\": \"wh\",\n \"data\": 875.4090909090909\n }\n },\n ...\n ]\n }\n '''\n # get the object with the right site_id\n state = {}\n\n for specific_site in raw[\"sites\"]:\n if specific_site[\"site_id\"] == self.site:\n state = specific_site\n break\n\n # build the device object\n device_meta = {\n 'manufacturer': 'Unknown',\n 'model': 'Unknown',\n 'serial_number': 'Unknown',\n 'geolocation': (0, 0)\n }\n device = Device(**device_meta)\n\n # get produced energy from filtered object\n # accumulated_power = specific_site['energy']['data']\n accumulated_power = specific_site['energy']['data']\n\n # instance of mini utc class (tzinfo)\n utc = UTC()\n\n # build access_timestamp\n now = datetime.datetime.now().astimezone()\n access_timestamp = now.isoformat()\n\n # build measurement_timestamp\n measurement_timestamp = datetime.datetime.strptime(specific_site['end_time'], '%Y-%m-%dT%H:%M:%SZ')\n measurement_timestamp = measurement_timestamp.replace(tzinfo=utc).isoformat()\n\n return EnergyData(device, access_timestamp, raw, accumulated_power, measurement_timestamp)\n\n def _get_daily_data(self) -> dict:\n marginal_query = {\n 'limit': 5,\n 'start': 'last_hour',\n 'end': 'now'\n }\n # sending header until we get usr pwd\n provisional_header = {\n \"Authorization\": \"Basic \" + self.api_key}\n endpoint = self.api_url + 'produced'\n\n r = requests.get(endpoint, params=marginal_query, headers=provisional_header, verify=False)\n ans = r.json()\n if len(ans['sites']) < 1:\n raise AttributeError('Empty response from api.')\n return ans\n\n\n# needs a site_id\nclass SPGroup_b1(SPGroupAPI):\n\n def __init__(self, api_url: str, api_key: str):\n super().__init__(site_id='b1', api_url=api_url, api_key=api_key)\n\n\nclass SPGroup_k1(SPGroupAPI):\n\n def __init__(self, api_url: str, api_key: str):\n super().__init__(site_id='k1', api_url=api_url, api_key=api_key)\n\n\nclass SPGroup_s1(SPGroupAPI):\n\n def __init__(self, api_url: str, api_key: str):\n super().__init__(site_id='s1', api_url=api_url, api_key=api_key)\n\n\nclass SPGroup_s2(SPGroupAPI):\n\n def __init__(self, api_url: str, api_key: str):\n super().__init__(site_id='s2', api_url=api_url, api_key=api_key)\n\n\nclass SPGroup_t1(SPGroupAPI):\n\n def __init__(self, api_url: str, api_key: str):\n super().__init__(site_id='t1', api_url=api_url, api_key=api_key)\n\n\nZERO = timedelta(0)\n\n\nclass UTC(tzinfo):\n def utcoffset(self, dt):\n return ZERO\n\n def tzname(self, dt):\n return \"UTC\"\n\n def dst(self, dt):\n return ZERO\n\n\nif __name__ == '__main__':\n sp = SPGroup_k1()\n sp.read_state()\n","sub_path":"bond/core/input/sp_group.py","file_name":"sp_group.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"494024066","text":"#-*- coding: utf-8 -*-\r\n#游戏的配置数据\r\n\r\nbasic={\r\n\t\"window_width\"\t:800,\r\n\t\"window_height\"\t:600,\r\n}\r\n\r\ngame={\r\n\t\"玩家移动速度\"\t\t:5*32,\r\n\t\"玩家跳跃高度\"\t\t:3*32,\r\n\t\"玩家跳至最高点时长\":1.5,\r\n\t\"普通子弹飞行速度\"\t:3*32,\r\n\t\"普通子弹飞行距离\"\t:800,\r\n\t\"怪物移动速度\"\t\t:2*32,\r\n\t\"弹簧踏板弹射高度\"\t:7*32,\r\n\t\"移动平台速度\"\t\t:2*32,\r\n\t\"消退平台时间\"\t\t:1,\r\n\t\"受重平台下降\"\t\t:1*32,\r\n}\r\n\r\ndef GetConfig(sKey):\r\n\treturn game[sKey]\r\n\r\n","sub_path":"script/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"209922154","text":"import pandas as pd\nimport numpy as np\n\ndelimiter='_'\n\ndef get_DTI_dict_from_adjmat(adjmat):\n dict_DTI=dict()\n adjmat=adjmat.T\n i=0\n for drug in adjmat.keys():\n target_list=adjmat.index[adjmat[drug]==1].tolist()\n dict_DTI[drug]=target_list\n i+=len(target_list)\n print('# of drug-target interactions: '+str(i)+'\\n')\n return dict_DTI\n\n\ndef get_pos_labels(dict_DTI):\n pos_label = set()\n\n for drug, targets in dict_DTI.items():\n for target in targets:\n pair_name = [str(drug) + delimiter + target]\n pos_label.update(pair_name)\n return pos_label\n\n\ndef construct_pos_samples(dict_DTI, matrix_drug, matrix_target, file_name=None):\n pos_label = get_pos_labels(dict_DTI)\n\n i = 0\n pos_sample=pd.DataFrame()\n for drug, targets in dict_DTI.items():\n for target in targets:\n pair_name=[str(drug) + delimiter + target]\n if i==0:\n pos_sample=pd.DataFrame(pd.concat([matrix_drug.loc[drug],matrix_target.loc[target]]),columns=pair_name)\n else:\n df_tmp=pd.DataFrame(pd.concat([matrix_drug.loc[drug],matrix_target.loc[target]]),columns=pair_name)\n pos_sample=pos_sample.join(df_tmp)\n i+=1\n\n pos_sample = pos_sample.T\n print('New positive samples file are written as \\'%s\\'' %(file_name))\n print('# of constructed positive samples: ' + str(pos_sample.shape[0]))\n print('# of features in constructed positive sample: ' + str(pos_sample.shape[1]))\n if pos_sample.shape[0] != len(pos_label):\n raise ValueError(\n 'The size of positive sample in the positive sample matrix is not matched to the lenghth of positive label list.')\n\n if file_name is not None:\n pos_sample.to_csv(file_name,sep='\\t')\n\n return pos_sample\n\n\ndef construct_neg_samples(dict_DTI, matrix_drug, matrix_target, neg_to_pos_ratio=1, file_name=None):\n pos_label = get_pos_labels(dict_DTI)\n\n n_positive = len(pos_label)\n n_negative = int(n_positive * neg_to_pos_ratio)\n neg_sample = pd.DataFrame()\n\n neg_label_total = set()\n for ind1 in matrix_target.index:\n for ind2 in matrix_drug.index:\n neg_label_total.update([str(ind2) + delimiter + str(ind1)])\n n_tmp1=len(neg_label_total)\n neg_label_total = neg_label_total.difference(pos_label)\n neg_label = np.random.choice(list(neg_label_total), size=n_negative, replace=False)\n n_tmp2=len(neg_label_total)\n if n_tmp1 != n_tmp2 + n_positive:\n raise ValueError(\n 'wrong difference between the positive samples and total negative samples')\n\n j = 0\n for neg in neg_label:\n drug, target = neg.split(delimiter, 1)\n if j == 0:\n neg_sample = pd.DataFrame(pd.concat([matrix_drug.loc[drug], matrix_target.loc[target]]),\n columns=[neg])\n else:\n df_tmp = pd.DataFrame(pd.concat([matrix_drug.loc[drug], matrix_target.loc[target]]), columns=[neg])\n neg_sample = neg_sample.join(df_tmp)\n j += 1\n neg_sample = neg_sample.T\n print('New negative samples file are written as \\'%s\\'' % (file_name))\n print('# of constructed negative samples: ' + str(neg_sample.shape[0]))\n print('# of features in constructed negative sample: ' + str(neg_sample.shape[1]))\n if neg_sample.shape[0] != len(neg_label):\n raise ValueError(\n 'The size of negative sample in the negative sample matrix is not matched to the lenghth of negative label list.')\n\n if file_name is not None:\n neg_sample.to_csv(file_name, sep='\\t')\n return neg_sample\n\n","sub_path":"0_MS_research/module_DTI/handle_sample.py","file_name":"handle_sample.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"78077332","text":"import sys\nsys.path.append(\n '/Users/rileylittlefield/Desktop/notes/readingnotes/python-ml/data-science-from-scratch/05-exercises'\n)\nsys.path.append(\n '/Users/rileylittlefield/Desktop/notes/readingnotes/python-ml/data-science-from-scratch/09-exercises'\n)\nsys.path.append(\n '/Users/rileylittlefield/Desktop/notes/readingnotes/python-ml/data-science-from-scratch/12-exercises'\n)\nsys.path.append(\n '/Users/rileylittlefield/Desktop/notes/readingnotes/python-ml/data-science-from-scratch/15-exercises'\n)\nfrom matplotlib import pyplot\nfrom my_list_vectors import dot_product\nfrom stochastic_gradient_descent_two import maximize_stochastic\nfrom maximize_utils import maximize_batch\nfrom data_split_for_model_training import test_train_split\nfrom trainer_data import trainer_stats, beat_game_stats, trainer_avg_levels, trainer_team_counts, beat_game_trainers, not_beat_game_trainers\nfrom functools import partial\nfrom logistic_function import logistic, logistic_log_likelihood, logistic_log_likelihood_i, logistic_log_gradient, logistic_log_gradient_i\nimport pdb\nimport random\n\n# random.seed(0)\nx_train, x_test, y_train, y_test = test_train_split(\n trainer_stats, \n beat_game_stats, \n 0.33\n)\n\n# Want to maximize log likelihood on the training data\nbeta_0 = [ random.random() for _ in range(3) ]\n\nbeta_hat = maximize_stochastic(\n logistic_log_likelihood_i,\n logistic_log_gradient_i,\n x_train, \n y_train,\n beta_0,\n 0.0001\n)\n\nprint('beta_hat = %s' % beta_hat)\n\n# TEST GOODNESS OF FIT\n# true_positives = true_negatives = false_positives = false_negatives = 0\n# for x_i, y_i in zip(x_test, y_test):\n\n# dot_beta_x_i = dot_product(beta_hat, x_i)\n# prediction = logistic(dot_beta_x_i)\n\n# # print('dot(beta_hat, x_i) = %s' % dot_beta_x_i)\n# # print('logistic(dot_beta_x_i) = %s' % prediction)\n\n# if y_i == 1 and prediction > 0.6:\n# true_positives += 1\n# elif y_i == 1:\n# false_negatives += 1\n# elif y_i == 0 and prediction > 0.6:\n# false_positives += 1\n# else:\n# true_negatives += 1\n\n# precision = true_positives / (true_positives + false_positives)\n# recall = true_positives / (true_positives + false_negatives)\n# print('precision = %s' % precision)\n# print('recall = %s' % recall)\n\n# A + beta_level * avg_level + beta_team_count * team_count = 0\n# avg_level = -(a + beta_team_count * team_count) / beta_level\ndef classification_line_avg_level(beta_hat, team_count):\n beta_a = beta_hat[0]\n beta_level = beta_hat[1]\n beta_team_count = beta_hat[2]\n return -(beta_a + beta_team_count * team_count) / beta_level\n\nclassification_ys = [ 1, 2, 3, 4, 5, 6 ]\nclassification_xs = [\n classification_line_avg_level(beta_hat, team_count)\n for team_count\n in classification_ys\n]\n\n\n# VISUALIZE\nbeat_game_trainer_average_level = [\n trainer['party_average_level']\n for trainer\n in beat_game_trainers\n]\n\nbeat_game_trainer_team_count = [\n trainer['team_count']\n for trainer\n in beat_game_trainers\n]\n\nnot_beat_game_trainer_average_level = [\n trainer['party_average_level']\n for trainer\n in not_beat_game_trainers\n]\n\nnot_beat_game_trainer_team_count = [\n trainer['team_count']\n for trainer\n in not_beat_game_trainers\n]\n\npyplot.scatter(beat_game_trainer_average_level, beat_game_trainer_team_count, marker='^', label=\"beat game\")\npyplot.scatter(not_beat_game_trainer_average_level, not_beat_game_trainer_team_count, marker='*', label=\"not beat game\")\npyplot.scatter(classification_xs, classification_ys, marker='.', label=\"not beat game\")\npyplot.xlabel('average level')\npyplot.ylabel('team count')\npyplot.legend()\npyplot.xlim(xmin=0, xmax=100)\npyplot.show()","sub_path":"17-exercises/applying_the_model.py","file_name":"applying_the_model.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"261478284","text":"\"\"\"\n:class:`.GeoCoder` base object from which other geocoders are templated.\n\"\"\"\n\nfrom ssl import SSLError\nfrom socket import timeout as SocketTimeout\nimport json\n\nfrom geopy.compat import string_compare, HTTPError, py3k, \\\n urlopen as urllib_urlopen, build_opener, ProxyHandler, URLError, \\\n install_opener\nfrom geopy.point import Point\nfrom geopy.exc import (GeocoderServiceError, ConfigurationError,\n GeocoderTimedOut, GeocoderAuthenticationFailure, GeocoderQuotaExceeded,\n GeocoderQueryError, GeocoderInsufficientPrivileges)\nfrom geopy.util import decode_page\n\nDEFAULT_FORMAT_STRING = '%s'\nDEFAULT_SCHEME = 'https'\nDEFAULT_TIMEOUT = 1\nDEFAULT_WKID = 4326\n\n\nclass Geocoder(object): # pylint: disable=R0921\n \"\"\"\n Template object for geocoders.\n \"\"\"\n\n def __init__(self, format_string=DEFAULT_FORMAT_STRING, scheme=DEFAULT_SCHEME,\n timeout=DEFAULT_TIMEOUT, proxies=None):\n \"\"\"\n Mostly-common geocoder validation, proxies, &c. Not all geocoders\n specify format_string and such.\n \"\"\"\n self.format_string = format_string\n self.scheme = scheme\n if self.scheme not in ('http', 'https'): # pragma: no cover\n raise ConfigurationError('Supported schemes are `http` and `https`.')\n self.proxies = proxies\n self.timeout = timeout\n\n if self.proxies:\n install_opener(\n build_opener(\n ProxyHandler(self.proxies)\n )\n )\n self.urlopen = urllib_urlopen\n\n @staticmethod\n def _coerce_point_to_string(point):\n \"\"\"\n Do the right thing on \"point\" input. For geocoders with reverse\n methods.\n \"\"\"\n if isinstance(point, Point):\n return \",\".join((str(point.latitude), str(point.longitude)))\n elif isinstance(point, (list, tuple)):\n return \",\".join((str(point[0]), str(point[1]))) # -altitude\n elif isinstance(point, string_compare):\n return point\n else: # pragma: no cover\n raise ValueError(\"Invalid point\")\n\n def _parse_json(self, page, exactly_one): # pragma: no cover\n \"\"\"\n Template for subclasses\n \"\"\"\n raise NotImplementedError()\n\n def _call_geocoder(self, url, timeout=None, raw=False):\n \"\"\"\n For a generated query URL, get the results.\n \"\"\"\n try:\n page = self.urlopen(url, timeout=timeout or self.timeout)\n except Exception as error: # pylint: disable=W0703\n message = str(error) if not py3k else \\\n (str(error.args[0] if len(error.args) else str(error)))\n if hasattr(self, '_geocoder_exception_handler'):\n self._geocoder_exception_handler(error, message) # pylint: disable=E1101\n if isinstance(error, HTTPError):\n code = error.getcode()\n error_code_map = {\n 400: GeocoderQueryError,\n 401: GeocoderAuthenticationFailure,\n 402: GeocoderQuotaExceeded,\n 403: GeocoderInsufficientPrivileges,\n 407: GeocoderAuthenticationFailure,\n 412: GeocoderQueryError,\n 413: GeocoderQueryError,\n 414: GeocoderQueryError,\n 502: GeocoderServiceError,\n 503: GeocoderTimedOut,\n 504: GeocoderTimedOut\n }\n try:\n raise error_code_map[code](message)\n except KeyError:\n raise GeocoderServiceError(message)\n elif isinstance(error, URLError):\n if \"timed out\" in message:\n raise GeocoderTimedOut('Service timed out')\n elif isinstance(error, SocketTimeout):\n raise GeocoderTimedOut('Service timed out')\n elif isinstance(error, SSLError):\n if \"timed out in message\":\n raise GeocoderTimedOut('Service timed out')\n if not py3k:\n err = GeocoderServiceError(message)\n err.__traceback__ = error\n raise err\n else:\n raise GeocoderServiceError(message)\n if raw:\n return page\n return json.loads(decode_page(page))\n\n def geocode(self, query, exactly_one=True, timeout=None): # pylint: disable=R0201,W0613\n \"\"\"\n Implemented in subclasses.\n \"\"\"\n raise NotImplementedError()\n\n def reverse(self, query, exactly_one=True, timeout=None): # pragma: no cover\n \"\"\"\n Implemented in subclasses.\n \"\"\"\n raise NotImplementedError()\n","sub_path":"geopy/geocoders/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"105454628","text":"#!/usr/bin/python \n\nimport numpy as np\nimport pandas as pd\nimport sys\nimport pickle\nfrom pyspark.sql import SparkSession\nfrom pyspark import SparkContext\nimport time\nfrom pyspark.sql import Row\nfrom pyspark.sql import functions as F\nfrom MI import mutual_information \n\nsc = SparkContext('local')\nspark = SparkSession.builder.appName(\"Python df\").config(\"some-config\", \"some-value\").getOrCreate()\n\n#first dataset\ndf = spark.read.format('csv').options(header='true', inferschema='true').load(sys.argv[1])\nrdd= df.rdd.map(lambda x: Row(key= ' '.join(x['Year_Zip'].split(',')), bble=x.BBLE, b=x.B, block=x.BLOCK, lot=x.LOT, bldgcl=x.BLDGCL, taxclass=int(x.TAXCLASS[0]), ltf=x.LTFRONT, ltd=x.LTDEPTH, fullval=x.FULLVAL, avland=x.AVLAND, avtot=x.AVTOT, exland=x.EXLAND, extot=x.EXTOT, bldf=x.BLDFRONT, bldd=x.BLDDEPTH))\ndf = spark.createDataFrame(rdd)\ndf.createOrReplaceTempView(\"SQLdf\")\ndfAgg = spark.sql('SELECT key, COUNT(*) as counts, COUNT(DISTINCT(bble)) bble_ucount, SUM(IF(b=1,1,0)) AS b_1, SUM(IF(b=2,1,0)) AS b_2, SUM(IF(b=3,1,0)) AS b_3, SUM(IF(b=4,1,0)) AS b_4, SUM(IF(b=5,1,0)) AS b_5, COUNT(DISTINCT(block)) AS block_ucount, COUNT(DISTINCT(lot)) AS lot_ucount, SUM(IF(taxclass=1,1,0)) AS taxc_1, SUM(IF(taxclass=2,1,0)) AS taxc_2, SUM(IF(taxclass=3,1,0)) AS taxc_3, SUM(IF(taxclass=4,1,0)) AS taxc_4, AVG(ltf) AS ltf_avg, AVG(ltd) AS ltd_avg, AVG(fullval) AS fval_avg, MAX(fullval) AS fval_max, MIN(fullval) as fval_min, AVG(avland) AS avland_avg, MAX(avland) AS avland_max, MIN(avland) AS avland_min, AVG(avtot) AS avtot_avg, MAX(avtot) AS avtot_max, MIN(avtot) AS avtot_min, AVG(exland) as exland_avg, AVG(extot) as extot_avg, AVG(bldf) AS bldf_avg, AVG(bldd) AS bldd_avg FROM SQLdf GROUP BY key')\n\n#second data set\ndfAgg1 = pd.read_csv('data/census_preprocessed.csv', index_col='key')\nvariable = list(dfAgg.columns)\nvariable1 = list(dfAgg1.columns)\n\ndf_join = dfAgg.join(dfAgg1, how='inner')\nprint(df_join.shape)\ndf_join.to_csv('data/join_propVScensus.csv')\ncorr_p = np.zeros((len(variable), len(variable1)))\ncorr_mi = np.zeros((len(variable), len(variable1)))\nfor i,v in enumerate(variable):\n\tif np.mean(pd.isnull(df_join[v].values)) > 0.8 or np.mean(df_join[v]==0)>0.9:\n\t\tprint('Over 80% or 90% missing values or 0 in '+v)\n\t\tcontinue\n\tfor j,v1 in enumerate(variable1):\n\t\tif np.mean(pd.isnull(df_join[v1].values)) > 0.8 or np.mean(df_join[v1]==0)>0.9:\n\t\t\tprint('Over 80% or 90% missing values or 0 in '+v1)\n\t\t\tcontinue\n\t\tdf_co = df_join[[v, v1]].values\n\t\ttry:\n\t\t\tcorr_p[i, j] = np.corrcoef(df_co.T)[0, 1]\n\t\t\tcorr_mi[i ,j] = mutual_information(df_co[:,0], df_co[:,1], 1, 1, 30)\n\t\texcept:\n\t\t\tcorr_p[i,j] = 0\n\t\t\tcorr_mi[i,j] = 0\n\t\tif abs(corr_p[i, j]) > 0.5:\n\t\t\tprint(v+' VS '+v1 )\n\t\t\tprint(corr_p[i,j])\n\t\t\tprint(corr_mi[i,j])\nnp.save('data/corrP_propVScensus.npy', corr_p)\nnp.save('data/corrMI_propVScensus.npy', corr_mi)\n\n","sub_path":"CodeSpark/corr_propVScensus.py","file_name":"corr_propVScensus.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"633369924","text":"import spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport spotipy.util as util\nimport csv\n\nSTART_ARTIST = 'drake'\nEND_ITERS = 10000\n\nwith open('creds.csv', 'r') as f:\n reader = csv.reader(f)\n for line in reader:\n client_id, client_secret = line\n\nclient_credentials_manager = SpotifyClientCredentials(\n client_id=client_id,\n client_secret=client_secret)\nsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\nresult = sp.search(q='artist:' + START_ARTIST, type='artist')\nstart_node = result['artists']['items'][0]\n\nprint('Starting with ', start_node['name'])\n\nvertex_info = {}\nedge_info = {}\n\ndef save_info():\n data_loc = '../static/data/'\n print('Writting vertex and edge info.')\n with open(data_loc + 'vertices.csv', 'w') as f:\n writer = csv.writer(f, delimiter=',')\n for vertex in vertex_info:\n writer.writerow([vertex, *vertex_info[vertex]])\n\n with open(data_loc + 'edges.csv', 'w') as f:\n writer = csv.writer(f, delimiter=',')\n for from_id in edge_info:\n for to_id in edge_info[from_id]:\n writer.writerow([from_id, to_id])\n\n print('Done writting vertex and edge info')\n\nqueue = [start_node]\nshould_stop = False\nwhile not should_stop and len(queue) > 0:\n node = queue.pop(0)\n\n if len(edge_info) != 0 and len(edge_info) % END_ITERS == 0:\n should_stop = True\n\n vertex_info[node['uri']] = [node['name'], node['popularity'], node['followers']['total']]\n print('Explored %i connections' % (len(vertex_info)))\n\n nodes = sp.artist_related_artists(node['uri'])\n\n edges = []\n\n for to_explore_node in nodes['artists']:\n edges.append(to_explore_node['uri'])\n\n if to_explore_node['uri'] not in vertex_info and (to_explore_node not in queue):\n queue.append(to_explore_node)\n\n edge_info[node['uri']] = edges\n\nfor node in queue:\n vertex_info[node['uri']] = [node['name'], node['popularity'], node['followers']['total']]\n\nsave_info()\n","sub_path":"demo_programs/spotify_artists.py","file_name":"spotify_artists.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"237553611","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Mar 25 17:40:06 2021\r\n\r\n@author: brend\r\n\"\"\"\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\nfrom matplotlib.ticker import MultipleLocator,FormatStrFormatter,MaxNLocator\r\nmpl.rcParams.update(mpl.rcParamsDefault)\r\nplt.style.use('seaborn-colorblind')\r\n# plt.rcParams[\"font.family\"] = \"serif\"\r\nmpl.rcParams['axes.linewidth'] = 0.5\r\n\r\nimport glob\r\nimport pandas as pd\r\nimport re\r\n\r\nFocusWaist = 100*1e-6\r\n\r\nspot_alpha = 0.5\r\nmarkersize = 3\r\nmarkeredgewidth = 0.5\r\nlinewidth = 1\r\nelinewidth = 1\r\nlegend_fontsize = 5\r\naxis_fontsize = 10\r\nticks_fontsize = 6\r\ngraph_edge_width = 0.5\r\ngraph_tick_width = graph_edge_width\r\n\r\ncolumnwidth = 225.8775\r\nfullwidth = 469.75502\r\ninches_per_pt = 1/72.27\r\ngolden_ratio = (5**.5 - 1) / 2\r\nfig_width_in = columnwidth * inches_per_pt\r\nheight_ratio = golden_ratio\r\nfig_height_in = fig_width_in * height_ratio\r\n\r\ndef getData(data_file, NumSamples = 1, long=False):\r\n raw_data = np.asarray(pd.read_csv(data_file, delimiter = \"[\\],\\[\\t]\", engine='python',header=None))\r\n if NumSamples == 1:\r\n # print(raw_data)\r\n counts = raw_data[:,2]\r\n else:\r\n if not long:\r\n raw_counts = raw_data[:,2:2+NumSamples]\r\n TotalPulses = raw_counts.size\r\n counts = np.mean(raw_counts, 1)\r\n else:\r\n raw_counts = raw_data[:,2:2+NumSamples]\r\n counts = raw_counts.flatten()\r\n if not long:\r\n times = raw_data[:,NumSamples + 17]\r\n times -= min(times)\r\n times = FixTimeOffset(times)\r\n datas = np.vstack((times, counts)).T\r\n else:\r\n times = raw_data[:,NumSamples + 17]\r\n times -= min(times)\r\n times = np.append(times, times[-1] + 25)\r\n times = np.array([np.linspace(times[i-1], time, NumSamples) for i, time in enumerate(times) if time != 0])\r\n times = times.flatten()\r\n datas = np.vstack((times, counts)).T\r\n return datas\r\n\r\ndef FixTimeOffset(data):#Fix timing when somehow it's less than 0.1 s between successive data points\r\n data = data.astype(float)\r\n dataDiff = np.diff(data)\r\n dataDiff2 = np.concatenate((dataDiff, np.array([0])))\r\n TimeDiff = np.mean(dataDiff)\r\n # print(f'Time Difference is {TimeDiff}')\r\n for i, x in enumerate(data):\r\n if i > 0:\r\n if data[i] - data[i-1] < 1e-1:\r\n # print(f\"time: {data[i-1]}, time2: {data[i]}\")\r\n data[i:] += TimeDiff\r\n return data\r\n \r\ndef getSweepTimings(data_file, periods=3):\r\n times = []\r\n with open(data_file) as file:\r\n for line in file:\r\n linesplit = line.split(' ')\r\n time = linesplit[1]\r\n split_time = re.split(':|\\.', time)\r\n time_hour, time_minute, time_second, time_msecond = [float(time) for time in split_time]\r\n total_seconds = 60*60*time_hour + 60*time_minute + time_second + 1e-3*time_msecond\r\n times.append(total_seconds)\r\n times = np.array(times)\r\n times -= min(times)\r\n times_diff = np.insert(np.diff(times), 0, 0)\r\n times = times[times_diff > 0.2]\r\n steps_per = times.size\r\n times_expanded = np.array([times+i*max(times) for i in range(periods)]).flatten()\r\n times_expanded -= min(times_expanded)\r\n return times_expanded, steps_per\r\n\r\ndef Down_Sample(data, Num):\r\n Rem = data.size%Num\r\n if Rem != 0:\r\n data = data[:-Rem]\r\n else:\r\n data = data\r\n data = data.reshape(-1, Num).astype(float)\r\n data_DownSampled = np.mean(data, 1)\r\n data_DownSampled_std = np.std(data, 1)\r\n return data_DownSampled, data_DownSampled_std\r\n \r\ndata_filepath = r\"2020_11_04_Pitting-Conditioning\\Condition-Sacrif1\\Neutral_Conditioning_Sacrif1*\"\r\ndata_files = glob.glob(data_filepath)\r\ndata_file_BG = [s for s in data_files if \"No-Ablation\" in s][0]\r\ndata_files_BeforeCond = [s for s in data_files if \"Before\" in s]\r\ndata_files_BeforeCond.pop(0)#Only need 1 example for figure\r\ndata_files_AfterCond = [s for s in data_files if \"After\" in s]\r\ndata_file_LongTerm = data_files_AfterCond[-1]\r\ndata_files_AfterCond.pop(-1)#Last file was long-term\r\nCondition_Fluences = np.array([130, 190])*1e-6/(math.pi*FocusWaist**2)#In J/m^2\r\n\r\n\r\ndata_BG = getData(data_file_BG)\r\nBG_Ave = np.mean(data_BG[:,1])\r\n\r\n\r\nfig = plt.figure(figsize=(fig_width_in, fig_height_in), dpi=300)\r\nax2 = fig.add_subplot(111)\r\n\r\nPulsesPer = 120\r\nDownSample = 3\r\ndata = getData(data_file_LongTerm, PulsesPer, long=True)\r\ndata_y = data[:,1]\r\ndata_y = data_y[:-1]\r\ndata_yD, data_yDsdv = Down_Sample(data_y, 3)\r\ndata_x = np.arange(data_yD.size)*DownSample\r\n\r\n\r\n# ax2.plot(data_x, data_yD, label=\"Sweep\", alpha=0.3, color='grey')\r\n\r\n\r\ndata_file = r\"Neutral-Fluorescence_Natural_Pitting_48uJ_7p26x6p13_After-Condition-1_*\"\r\ndata_file = glob.glob(data_file)[0]\r\nPit1Num = 5\r\nPit1 = getData(data_file, Pit1Num)[:,1]\r\n\r\nPit2Num = 10\r\ndata_file = r\"Neutral-Fluorescence_Natural_Pitting_48uJ_7p265x6p13_After-Condition-*\"\r\ndata_file = glob.glob(data_file)[0]\r\nPit2 = getData(data_file, Pit2Num)[:,1]\r\n\r\ndata_file = r\"Neutral_Pitting_7p28x6p125_After-Condition-1_*\"\r\ndata_file = glob.glob(data_file)[0]\r\nPit3 = getData(data_file, Pit2Num)[:,1]\r\n\r\ndata_file = r\"Neutral_Pitting_7p265x6p15_After-Condition-2_*\"\r\ndata_file = glob.glob(data_file)[0]\r\nPit4 = getData(data_file, Pit2Num)[:,1]\r\n\r\nDown = 20\r\nPit1A, Pit1SD = Down_Sample(Pit1, Down)\r\nPit2A, Pit2SD = Down_Sample(Pit2, Down)\r\nPit3A, Pit3SD = Down_Sample(Pit3, Down)\r\nPit4A, Pit4SD = Down_Sample(Pit4, Down)\r\n\r\nScale1 = 0.7\r\nScale2 = 0.4\r\nScale3 = 0.8\r\nScale4 = 0.6\r\nScale1 = Scale2 = Scal3 = Scale4 = 1\r\n\r\nax2.errorbar(np.arange(0, Pit1A.size*Down*Pit1Num, Down*Pit1Num), Pit1A*Scale1, yerr=Pit1SD, fmt='^', \\\r\n label='Spot 1', alpha=spot_alpha, lw=linewidth, elinewidth=elinewidth, \\\r\n ms=markersize, mew=markeredgewidth)\r\nax2.errorbar(np.arange(0, Pit2A.size*Down*Pit2Num, Down*Pit2Num), Pit2A*Scale2, yerr=Pit2SD, fmt='s', \\\r\n label='Spot 2', alpha=spot_alpha, lw=linewidth, elinewidth=elinewidth, \\\r\n ms=markersize, mew=markeredgewidth)\r\nax2.errorbar(np.arange(0, Pit3A.size*Down*Pit2Num, Down*Pit2Num), Pit3A*Scale3, yerr=Pit3SD, fmt='d', \\\r\n label='Spot 3', alpha=spot_alpha, lw=linewidth, elinewidth=elinewidth, \\\r\n ms=markersize, mew=markeredgewidth)\r\nax2.errorbar(np.arange(0, Pit4A.size*Down*Pit2Num, Down*Pit2Num), Pit4A*Scale4, yerr=Pit4SD, fmt='o', \\\r\n label='Spot 4', alpha=spot_alpha, lw=linewidth, elinewidth=elinewidth, \\\r\n ms=markersize, mew=markeredgewidth, color='tab:purple')\r\naverage_lifetime = np.mean([Pit1A.size*Down*Pit1Num, Pit2A.size*Down*Pit2Num, Pit3A.size*Down*Pit2Num, Pit4A.size*Down*Pit2Num])\r\nax2.vlines(average_lifetime, 0, 200, label='Mean lifetime', color='k', linestyle='dotted', lw=linewidth)\r\n\r\n## Inset target map from inkscape\r\nim = plt.imread('target_inset.png') # insert local path of the image, old version: \r\nnewax = fig.add_axes([0.45,0.6,0.2,0.2], anchor='W') \r\nnewax.imshow(im)\r\nnewax.axis('off')\r\n\r\nax2.set_xlabel('Pulse number',fontsize=axis_fontsize)\r\nax2.set_ylabel('Counts (arb. units)',fontsize=axis_fontsize)\r\nax2.tick_params(axis='both', which='major', labelsize=ticks_fontsize)\r\nax2.xaxis.set_major_locator(MultipleLocator(5000))\r\nax2.xaxis.set_minor_locator(MultipleLocator(1000))\r\nax2.yaxis.set_major_locator(MultipleLocator(50))\r\nax2.yaxis.set_minor_locator(MultipleLocator(10))\r\nax2.set_xlim(0, 13000)\r\nax2.set_ylim(0, 150)\r\n\r\n# ax2.text(5200, -47, '(b)', ha='center', fontsize=8, font='Times New Roman')\r\n\r\nax2.legend(fontsize=legend_fontsize, framealpha=1)\r\n\r\n\r\n\r\nfig.savefig('Spot_Lifetimes_Final_v3.pdf', dpi=300, bbox_inches='tight', format='pdf')","sub_path":"Paper_Data/Spot-Lifetimes/Spot-Lifetimes_No-Sweep.py","file_name":"Spot-Lifetimes_No-Sweep.py","file_ext":"py","file_size_in_byte":7741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"522631428","text":"from django.shortcuts import render, redirect, render_to_response\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.views.generic import View, ListView, DetailView, CreateView, UpdateView, TemplateView\n\nfrom django.contrib.auth.models import User\n\nfrom .forms import UserForm, CommentForm, PostForm\nfrom .models import Post, Comment, Category\n\nclass Index(TemplateView):\n template_name = \"index.html\"\n\nclass Who(TemplateView):\n template_name = \"who.html\"\n\nclass postList(ListView):\n template_name = \"postList.html\"\n model = Post\n\nclass categoryList(ListView):\n template_name = \"categoryList.html\"\n model = Category\n\nclass categoryDetail(DetailView):\n template_name = 'categoryDetail.html'\n model = Category\n\n def get_context_data(self, **kwargs):\n context = super(categoryDetail, self).get_context_data(**kwargs)\n context['post'] = Post.objects.filter(category_post_id=self.kwargs['pk'])\n return context\n\n\nclass postDetail(DetailView):\n template_name = 'postDetail.html'\n model = Post\n\nclass postCreate(View):\n form_class = PostForm\n template_name = 'postCreate.html'\n\n def get(self, request, *args, **kwargs):\n form = self.form_class(None)\n return render(request, self.template_name, {'form':form})\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST, request.FILES)\n if form.is_valid():\n obj = form.save(commit=False)\n newdoc = Post(photo_post = request.FILES['photo_post'])\n obj.status_post = True\n obj.user_post = self.request.user\n obj.save()\n return redirect('/category')\n\nclass createComment(View):\n form_class = CommentForm\n template_name = \"createComment.html\"\n\n def get(self, request, *args, **kwargs):\n form = self.form_class(None)\n return render(request, self.template_name, {'form':form})\n\n def post(self, request, pk, *args, **kwargs):\n form = self.form_class(request.POST, request.FILES)\n if form.is_valid():\n obj = form.save(commit=False)\n photo_comment = Comment(photo_comment = request.FILES['photo_comment'])\n obj.user_comment = self.request.user\n obj.post_comment_id = self.kwargs['pk']\n obj.status_comment = True\n obj.save()\n return redirect('/category')\n\nclass createUser(View):\n form_class = UserForm\n template_name = 'createUser.html'\n\n def get(self, request):\n \tform = self.form_class(None)\n \treturn render(request, self.template_name, {'form':form})\n\n def post(self, request):\n user=User.objects.create_user(self.request.POST['username'],\n self.request.POST['email'],\n self.request.POST['password'])\n user.first_name = self.request.POST['first_name']\n user.last_name = self.request.POST['last_name']\n user.save()\n return redirect('/')\n\nclass LoginView(View):\n form_class = UserForm\n template_name = 'login.html'\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, self.template_name, {'form':form})\n\n def post(self, request):\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('categoryList')\n\n return render(request, \"login.html\")\n\nclass LogoutView(View):\n def get(self, request):\n logout(request)\n return redirect('login')","sub_path":"src/unamForumApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"217305970","text":"# -*- coding: utf-8 -*-\n# @Author: Orange灬Fish\n# @Date: 2019-08-09 21:34:47\n# @Last Modified by: Orange灬Fish\n# @Last Modified time: 2019-08-09 21:40:11\n\n\nclass Solution(object):\n\tdef numSquares(self, n):\n\t\tdp = [0] * (n + 1)\n\t\tfor i in range(1, n+1):\n\t\t\t# i = 1 + 1 + ... = 1 * i\n\t\t\tdp[i] = i\n\t\t\tj = 1\n\t\t\twhile j**2 <= i:\n\t\t\t\tdp[i] = min(dp[i], dp[i-j**2] + 1)\n\t\t\t\tj += 1\n\t\treturn dp[-1]","sub_path":"Leetcode/leetcode279 完全平方数.py","file_name":"leetcode279 完全平方数.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"642360873","text":"r\"\"\"\n===============================================================================\nSubmodule -- pore_surface_area\n===============================================================================\n\n\"\"\"\nimport scipy as _sp\n\n\ndef sphere(geometry, network,\n pore_diameter='pore.diameter',\n throat_area='throat.area',\n **kwargs):\n r\"\"\"\n Calculates internal surface area of pore bodies assuming they are spherical.\n then subtracts the area of the neighboring throats in a crude way, by\n simply considering the throat cross-sectional area, thus not accounting\n for the actual curvature of the intersection.\n\n Parameters\n ----------\n geometry : OpenPNM Geometry Object\n The Geometry object which this model is associated with. This controls\n the length of the calculated array, and also provides access to other\n necessary geometric properties.\n\n network : OpenPNM Network Object\n The Network object associated with the Geometry. This is needed to\n provide some topological information such as throat connections, and\n neighboring pores.\n\n pore_diameter : string\n The dictionary key to the pore diameter array.\n\n throat_area : string\n The dictioanry key to the throat area array. Throat areas are needed\n since their insection with the pore are removed from the computation.\n\n \"\"\"\n R = geometry[pore_diameter]/2\n Asurf = 4*_sp.constants.pi*R**2\n Tn = network.find_neighbor_throats(pores=geometry.Ps, flatten=False)\n Tsurf = _sp.array([_sp.sum(network[throat_area][Ts]) for Ts in Tn])\n value = Asurf - Tsurf\n return value\n\n\ndef cube(geometry, pore_diameter='pore.diameter', **kwargs):\n r\"\"\"\n Calculate internal surface area for a cubic pore\n \"\"\"\n D = geometry[pore_diameter]\n value = 6*D**2\n return value\n","sub_path":"OpenPNM/Geometry/models/pore_surface_area.py","file_name":"pore_surface_area.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"285021280","text":"def read_input():\n i, j = (int(n) for n in raw_input().split())\n maze = []\n for _ in range(i):\n maze.append([int(c) for c in raw_input().strip()])\n \n return i, j, maze\n\ndef makeKey(i, j):\n return str(i) + \"_\" + str(j)\n\ndef getConnectedMaze(current, maze):\n max_I = len(maze)\n max_J = len(maze[0])\n i, j = current\n alts = (i, j+1), (i+1, j), (i, j-1), (i-1, j)\n return [alt for alt in alts if 0 <= alt[0] < max_I and 0 <= alt[1] < max_J and maze[alt[0]][alt[1]] != 0 ]\n \n\ndef BFS(maze, start, visited) :\n result = []\n q = [start]\n visited.add(makeKey(*start))\n while len(q) > 0:\n current = q.pop(0)\n result.append(current)\n for v in getConnectedMaze(current, maze):\n i, j = v\n key = makeKey(i, j)\n if key not in visited:\n visited.add(key)\n q.append(v)\n maze[i][j] = maze[current[0]][current[1]] + 1\n print(maze)\n return result\n\ndef main():\n r, c, maze = read_input()\n visit_table = set()\n result = BFS(maze, (0, 0), visit_table)\n print(maze[r-1][c-1])\n\nif __name__ == '__main__':\n main()","sub_path":"graph_problems/maze_2178.py","file_name":"maze_2178.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"3744727","text":"# coding: utf-8\nfrom classification_utils import *\n\nprod_cats = [\"book\",\"dvd\",\"kitchen\",\"electronics\"]\nFE_all_results = {}\nfor prod_cat in prod_cats:\n repetitions = 2 # accuracy figures are averaged over this many repetitions\n NB_accuracy_tot = 0\n for i in range(repetitions): # for each sample_size we will find average accuracy over several repetitions\n test, train = get_formatted_train_test_data(prod_cat,FE_all)\n NB_accuracy_tot += run_NB_preformatted(train,test)\n FE_all_results[prod_cat] = NB_accuracy_tot/repetitions\n \npd.set_option('precision',2)\ndf = pd.DataFrame.from_dict(FE_all_results,orient='index')\ndisplay(df)\nax = df.plot.bar(title=\"Experimental Results\",legend=False)\nax.set_ylabel(\"Classifier Accuracy\")\nax.set_xlabel(\"Product Category\")\nax.set_ylim(0.5,1.0)\n","sub_path":"Workshops/Topic 3/solutions/test_FE_all.py","file_name":"test_FE_all.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"524569690","text":"from typing import List\n\nfrom credential import PublicKey, IssueRequest, BlindSignature, AnonymousCredential, Attribute, verify, \\\n DisclosureProof\nfrom petrelic.multiplicative.pairing import G1, G2, GT, Bn, G1Element\n\nfrom zkp import KnowledgeProof\n\n\nclass User:\n \"\"\"Corresponds to a user or a prover in our protocol. \n The user has a username, a total list of attributes and a list of hidden attributes. \n \"\"\"\n\n def __init__(self, username: str, attributes: List[Attribute], hidden_attributes: List[Attribute]):\n self.t = 0 # used for the signature scheme, initialized later\n\n self.username = username\n self.all_attributes = attributes\n self.hidden_attributes = hidden_attributes\n\n\n ## ISSUANCE PROTOCOL ##\n def create_issue_request(\n self,\n pk: PublicKey,\n user_attributes: List[Attribute] #TODO: changed hidden_attribute by user_attr since equal, verify funciton still consistent\n ) -> IssueRequest:\n \"\"\" Create an issuance request\n\n This corresponds to the \"user commitment\" step in the issuance protocol.\n\n *Warning:* You may need to pass state to the `obtain_credential` function.\n \"\"\"\n self.t = G1.order().random()\n\n # Compute issue request commitment\n commitment = pk.g1 ** self.t\n for i,a in enumerate(user_attributes):\n commitment *= pk.Y1[i] ** Bn.from_binary(a)\n\n # Generate the list of secrets and parse them to big numbers\n list_secrets = [Bn.from_binary(secret) for secret in user_attributes]\n list_secrets += [self.t] # t is a random value considered a secret too\n\n # Fetch the list of public generators from the public key. One per secret attribute\n list_generators = [pk.Y1[idx] for idx in list(range(len(user_attributes)))]\n list_generators += [pk.g1] # generator for t\n\n knowledge_proof = KnowledgeProof.create_commitment(\n list_secrets, \n list_generators, \n commitment\n )\n\n return knowledge_proof\n\n def obtain_credential(\n self,\n pk: PublicKey,\n response: BlindSignature\n ) -> AnonymousCredential:\n \"\"\" Derive a credential from the issuer's response\n\n This corresponds to the \"Unblinding signature\" step.\n \"\"\"\n \n # Derive the credential from the response \n s = response[0], response[1] / (response[0] ** self.t)\n\n # Verify the signature\n if not verify(pk, s, self.all_attributes):\n return None\n \n return AnonymousCredential(s, self.all_attributes)\n\n ### SHOWING PROTOCOL ##\n def create_disclosure_proof(\n self,\n pk: PublicKey,\n credential: AnonymousCredential,\n message: bytes,\n revealed_attributes: List[Attribute] # queried types for a location request, it is not the set of all subscriptions\n ) -> DisclosureProof:\n \"\"\" Create a disclosure proof \"\"\"\n\n # generation of randomized signature\n r = G1.order().random()\n t = G1.order().random()\n\n randomized_signature = (credential.credential[0] ** r, (credential.credential[1] * (credential.credential[0] ** t)) ** r)\n\n # create a commitment based on all hidden attributes\n commitment = randomized_signature[0].pair(pk.g2) ** t\n for i, attribute in enumerate(self.hidden_attributes):\n generator = randomized_signature[0].pair(pk.Y2[i])\n commitment *= generator ** Bn.from_binary(attribute)\n \n # create a non-interactive challenge over the queried types and the message to prevent tampering\n challenge = KnowledgeProof.get_challenge(None, revealed_attributes, commitment, message)\n commitment = commitment ** challenge \n\n # store all user's public subscriptions in the disclosure proof so the issuer can access them\n disclosed_attributes = [x for x in self.all_attributes if x not in self.hidden_attributes]\n\n return DisclosureProof(randomized_signature, commitment, disclosed_attributes)\n","sub_path":"project2/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"537397122","text":"import networkx as nx\n\nfrom pgmpy.utils import NodeIdGenerator\n\nclass ArithmeticCircuit():\n\n def __init__(self, ebunch=None):\n self.graph = nx.DiGraph()\n self.node_id_gen = NodeIdGenerator()\n\n def add_sink(self,value, var, var_value):\n poss_sink = [n for n, d in self.graph.nodes(True) if d[\"type\"]==\"sink\" and d[\"value\"]==value]\n \n if len(poss_sink) > 1:\n raise ValueError(\"AC sinks should have unique value.\")\n\n if len(poss_sink) > 0:\n # Record variable and var value for new usage of the same probability (if not already recorded)\n self.graph.node[poss_sink[0]][\"variable\"].append(var)\n self.graph.node[poss_sink[0]][\"var_value\"].append(var_value)\n return poss_sink[0]\n else:\n new_node_id = self.node_id_gen.get_next_id()\n self.graph.add_node(new_node_id, {\"type\": \"sink\", \"value\": value, \"label\": \"{}\".format(value), \"variable\": [var], \"var_value\": [var_value]})\n return new_node_id\n\n def add_operation(self, operation, child1, child2):\n new_node_id = self.node_id_gen.get_next_id()\n label_op = None\n if operation == \"product\":\n label_op = \"*\"\n elif operation == \"sum\":\n label_op = \"+\"\n self.graph.add_node(new_node_id, {\"type\": \"operation_node\", \"operation\": operation, \"label\": \"{}\".format(label_op)})\n self.graph.add_edge(new_node_id, child1)\n self.graph.add_edge(new_node_id, child2)\n return new_node_id\n\n\n def add_indicator(self, var, var_value):\n new_node_id = self.node_id_gen.get_next_id()\n self.graph.add_node(new_node_id, {\"type\": \"indicator\", \"variable\": var, \"var_value\": var_value, \"label\": \"{}-{}\".format(var, var_value)})\n return new_node_id\n\n def to_spn(self, file_path):\n with open(file_path, \"w\") as file:\n # Write Nodes\n file.write(\"##NODES##\\n\")\n for node, data in self.graph.nodes(True):\n if data[\"type\"] == \"sink\":\n var_value_pairs = []\n for i in range(0,len(data[\"variable\"])):\n var_value_pairs.append(data[\"variable\"][i])\n var_value_pairs.append(data[\"var_value\"][i])\n # LEAVE Sink format: node id, LEAVE, Probability, Variable, Variable Assignment\n file.write(\"{},LEAVE,{},{}\\n\".format(node, data[\"value\"], \",\".join([str(i) for i in var_value_pairs])))\n elif data[\"type\"] == \"indicator\":\n # LEAVE Indicator format: node id, LEAVE, Probability Constant 1, Variable, Variable Assignment\n file.write(\"{},LEAVE,{},{},{}\\n\".format(node, 1, data[\"variable\"], data[\"var_value\"]))\n elif data[\"type\"] == \"operation_node\":\n op_label = None\n if data[\"operation\"] == \"product\":\n op_label = \"PRD\"\n elif data[\"operation\"] == \"sum\":\n op_label = \"SUM\"\n else:\n raise ValueError(\"Operation node not recognized.\")\n # LEAVE Indicator format: node id, LEAVE, Variable, Variable Assignment, Constant 1\n file.write(\"{},{}\\n\".format(node, op_label))\n else:\n raise ValueError(\"Node type not recognized.\")\n # Write Edges\n file.write(\"##EDGES##\\n\")\n for node1, node2, data in self.graph.edges(data=True):\n if self.graph.node[node1][\"type\"] == \"operation_node\" and self.graph.node[node1][\"operation\"] == \"sum\":\n file.write(\"{},{},{}\\n\".format(node1,node2,1))\n else:\n file.write(\"{},{}\\n\".format(node1,node2))\n\n","sub_path":"pgmpy/models/ArithmeticCircuit.py","file_name":"ArithmeticCircuit.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"314245696","text":"import os\nimport argparse\nimport json\nfrom sqlalchemy.exc import IntegrityError\n\nfrom models import Flat\nfrom server import db\n\nDB_NAME = 'flats.db'\n\ndef create_db():\n if not os.path.exists(DB_NAME):\n db.create_all()\n\n\ndef get_flat_content_from_json(json_file):\n return json.load(json_file)\n\n\ndef add_flat_content_to_db(json_content):\n for flat in json_content:\n session = db.session\n flat_content = Flat(settlement=flat['settlement'],\n under_construction=flat['under_construction'],\n description=flat['description'],\n price=flat['price'],\n oblast_district=flat['oblast_district'],\n living_area=flat['living_area'],\n has_balcony=flat['has_balcony'],\n address=flat['address'],\n construction_year=flat['construction_year'],\n rooms_number=flat['rooms_number'],\n premise_area=flat['premise_area'],\n ad_id=flat['id'],\n active=True)\n session.add(flat_content)\n session.commit()\n session.close()\n\n\ndef create_parser_for_user_arguments():\n parser = argparse.ArgumentParser(description='Work with database.')\n parser.add_argument('-u', '--update', required=True,\n type=argparse.FileType(mode='r'),\n help='Update database')\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n user_argument = create_parser_for_user_arguments()\n create_db()\n try:\n json_content = get_flat_content_from_json(user_argument.update)\n active_ads = Flat.query.filter_by(active=True)\n active_ads.update(dict(active=False))\n add_flat_content_to_db(json_content)\n except json.decoder.JSONDecodeError as e:\n print('Please check that JSON file have correct structure!\\n', e)\n except IntegrityError:\n print('Error! Please check ads for unique!\\nUpdate canceled.')\n db.session.rollback()\n except KeyError as e:\n print('Error! This value is missing:', e,\n '\\nCheck JSON file for data integrity \\nUpdate canceled.')\n db.session.rollback()\n db.session.close()\n","sub_path":"db_operations.py","file_name":"db_operations.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"649495765","text":"# -*- coding: utf-8 -*-\nimport os\nimport telebot\nimport time\nimport random\nimport threading\nfrom emoji import emojize\nfrom telebot import types\nfrom pymongo import MongoClient\nimport traceback\ngamerz=[]\nyoba=[512006137]\nimperias={}\ntoken = os.environ['TELEGRAM_TOKEN']\nbot = telebot.TeleBot(token)\n@bot.message_handler(commands=['start']) \ndef start(m):\n if m.from_user.id not in gamerz:\n imperias.update({m.from_user.id:createempire(m)})\n gamerz.append(m.from_user.id) \n bot.send_message(m.from_user.id, 'Ваша империя создана, и названа в *вашу* честь!', parse_mode = 'markdown')\n nachat(m.from_user.id, m.from_user.first_name)\n else:\n bot.send_message(m.from_user.id, 'Империя *' + imperias[m.from_user.id]['name'] + '* уже существует!', parse_mode = 'markdown')\n@bot.message_handler(commands=['me']) \ndef me(m):\n if m.from_user.id in gamerz:\n id = m.from_user.id\n sfood = str(imperias[id]['food'])\n swarriors = str(imperias[id]['warriors'])\n sfarmers = str(imperias[id]['farmers'])\n smoney = str(imperias[id]['money'])\n stoday = str(imperias[id]['day'])\n \n text = '📃Доклад о империи *' + m.from_user.first_name + '* состоянием на ' + stoday + ' день:\\n'\n text += '💂🏻‍♀️Количевство воинов:' + swarriors + '\\n'\n text += '🍎Количевство еды:' + sfood + '\\n'\n text += '💰Количевство денег:' + smoney + '\\n'\n text += '👨🏻‍🌾Количевство фермеров:' + sfarmers\n bot.send_message(m.from_user.id, text, parse_mode = 'markdown')\n \n@bot.message_handler(commands=['burnempire']) \ndef burnempire(m):\n if m.from_user.id in gamerz:\n gamerz.remove(m.from_user.id)\n del imperias[m.from_user.id]\n bot.send_message(m.from_user.id, 'Вашей империи больше несуществует.', parse_mode = 'markdown')\n else:\n bot.send_message(m.from_user.id, 'Вам нечего сжигать.', parse_mode = 'markdown')\n\ndef nachat(id, name):\n if imperias[id]['food'] > 1:\n food = imperias[id]['food']\n warriors = imperias[id]['warriors']\n farmers = imperias[id]['farmers']\n money = imperias[id]['money']\n \n today = imperias[id]['day'] + 1\n imperias.update({id:{'day':today}})\n text = 'Наступил ' + str(imperias[id]['day']) + ' день существования вашей империи!\\n'\n \n todayfood = food - (warriors*5)\n imperias.update({id:{'food':todayfood}})\n text += 'Сегодня ваши воины сьели ' + str(warriors*5) + ' единиц еды.\\n'\n \n food = imperias[id]['food']\n todayweed = food+(farmers*2)\n imperias.update({id:{'food':todayweed}})\n text += 'Также, сегодня ваши фермеры произвели ' + str(farmers*2) + ' единиц еды.\\n\\n'\n \n food = imperias[id]['food']\n \n text += '📃Доклад о империи *' + name + '* состоянием на ' + str(today) + ' день:\\n'\n text += '💂🏻‍♀️Количевство воинов:' + str(warriors) + '\\n'\n text += '🍎Количевство еды:' + str(food) + '\\n'\n text += '💰Количевство денег:' + str(money) + '\\n'\n text += '👨🏻‍🌾Количевство фермеров:' + str(farmers)\n bot.send_message(id, text, parse_mode = 'markdown')\n threading.Timer(120, nachat, args=[id, name]).start()\n else:\n bot.send_message(id, 'Ваша империя мертва. Вы все сьели.', parse_mode = 'markdown')\n gamerz.remove(id)\n del imperias[id]\n \ndef createempire(m):\n return{'name':m.from_user.first_name,\n 'warriors':100,\n 'food':1000,\n 'money':10000,\n 'farmers':1000,\n 'day':0} \nfor hu in yoba:\n bot.send_message(hu, '777', parse_mode = 'markdown')\nprint('7777')\nbot.polling(none_stop=True,timeout=600)\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"296364063","text":"from nose import with_setup\nfrom nose.tools import nottest\n\n\nfrom src.ps_timeit import ps_timeit,PSC_Timer\n\n@nottest\ndef setup():\n pass\n\n\n@with_setup(setup)\ndef test_timerdecor():\n import time\n @ps_timeit\n def calc_square(x):\n time.sleep(5)# just so we elapse\n return x**2\n\n calc_square(40000)\n\n assert True\n\n@with_setup(setup)\ndef test_timerscope():\n import time\n def calc_square(x):\n return x**2\n\n with PSC_Timer() as t:\n calc_square(40000)\n time.sleep(5)# just so we elapse\n calc_square(1000000000)\n\n assert True","sub_path":"tests/test_timeit.py","file_name":"test_timeit.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"356575883","text":"import subprocess\n\n#List changes\ns = subprocess.Popen([\"git show $CI_COMMIT_SHA --name-only\"], shell=True, stdout=subprocess.PIPE).stdout\nlines = s.read().splitlines()\ncookbooksDuplicates = []\nfor line in lines:\n if line.split('/')[0] == \"cookbooks\":\n cookbooksDuplicates.append(line.split('/')[1])\n#Remove duplicates\ncookbooks = []\nfor mycookbook in cookbooksDuplicates: \n if mycookbook not in cookbooks: \n cookbooks.append(mycookbook) \n\n#upload them to chef\nfor cookbook in cookbooks:\n print(cookbook)\n res = subprocess.check_output([\"bash\", \"./ci/upload.sh\", cookbook])\n","sub_path":"ci/pushChef.py","file_name":"pushChef.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"558259392","text":"\"\"\"\n\n - Checks connectivity with other services in the backend\n\n\"\"\"\nimport logging\n\nfrom aiohttp.web import Request, RouteTableDef\nfrom models_library.api_schemas_storage import HealthCheck, S3BucketName\nfrom models_library.app_diagnostics import AppStatusCheck\nfrom servicelib.aiohttp.rest_utils import extract_and_validate\nfrom simcore_service_storage.constants import APP_CONFIG_KEY\n\nfrom ._meta import api_version, api_version_prefix, app_name\nfrom .db import get_engine_state\nfrom .db import is_service_responsive as is_pg_responsive\nfrom .exceptions import S3AccessError, S3BucketInvalidError\nfrom .s3 import get_s3_client\nfrom .settings import Settings\n\nlog = logging.getLogger(__name__)\n\nroutes = RouteTableDef()\n\n\n@routes.get(f\"/{api_version_prefix}/\", name=\"health_check\") # type: ignore\nasync def get_health(request: Request):\n \"\"\"Service health-check endpoint\n Some general information on the API and state of the service behind\n \"\"\"\n log.debug(\"CHECK HEALTH INCOMING PATH %s\", request.path)\n await extract_and_validate(request)\n\n return HealthCheck.parse_obj(\n {\"name\": app_name, \"version\": api_version, \"api_version\": api_version}\n ).dict(exclude_unset=True)\n\n\n@routes.get(f\"/{api_version_prefix}/status\", name=\"get_status\") # type: ignore\nasync def get_status(request: Request):\n # NOTE: all calls here must NOT raise\n assert request.app # nosec\n app_settings: Settings = request.app[APP_CONFIG_KEY]\n s3_state = \"disabled\"\n if app_settings.STORAGE_S3:\n try:\n await get_s3_client(request.app).check_bucket_connection(\n S3BucketName(app_settings.STORAGE_S3.S3_BUCKET_NAME)\n )\n s3_state = \"connected\"\n except S3BucketInvalidError:\n s3_state = \"no access to S3 bucket\"\n except S3AccessError:\n s3_state = \"failed\"\n\n postgres_state = \"disabled\"\n if app_settings.STORAGE_POSTGRES:\n postgres_state = (\n \"connected\" if await is_pg_responsive(request.app) else \"failed\"\n )\n\n status = AppStatusCheck.parse_obj(\n {\n \"app_name\": app_name,\n \"version\": api_version,\n \"services\": {\n \"postgres\": {\n \"healthy\": postgres_state,\n \"pool\": get_engine_state(request.app),\n },\n \"s3\": {\"healthy\": s3_state},\n },\n }\n )\n\n return status.dict(exclude_unset=True)\n","sub_path":"services/storage/src/simcore_service_storage/handlers_health.py","file_name":"handlers_health.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"440420043","text":"from constants import *\nfrom imports import *\nfrom Actor import Actor\n\nclass PacMan(Actor):\n def __init__(self,p):\n self.img = \"PacMan-0.png\"\n self.transformations = [\"PacMan-{0}.png\".format(x) for x in range(2)]\n super(PacMan, self).__init__(self.img)\n self.rotation = (0, 0) #pointing right\n self.degrees = 0 #pointing right\n self.goto(*p)","sub_path":"Project/classes/PacMan.py","file_name":"PacMan.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"416483668","text":"import json\nimport logging\nimport random\nimport re\n\nfrom collections import defaultdict\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, remove_words, \\\n html_to_markdown\n\n\nclass Sodimac(Store):\n @classmethod\n def categories(cls):\n return [\n 'WashingMachine',\n 'Refrigerator',\n 'Oven',\n 'Television',\n 'Notebook',\n 'LightProjector',\n 'AirConditioner',\n 'WaterHeater',\n 'Tablet',\n 'SpaceHeater',\n 'Cell',\n 'Headphones',\n 'StereoSystem',\n 'VideoGameConsole',\n 'Monitor',\n 'Ups',\n 'Printer',\n ]\n\n @classmethod\n def discover_entries_for_category(cls, category, extra_args=None):\n category_paths = [\n ['scat112555', ['WashingMachine'],\n 'Lavadoras y Secadoras > Lavadoras', 1],\n ['cat1590057', ['WashingMachine'],\n 'Línea Blanca > Lavadoras y Secadoras', 1],\n ['scat114994', ['WashingMachine'],\n 'Lavadoras y Secadoras > Secadoras', 1],\n ['scat112543', ['Refrigerator'],\n 'Refrigeradores > Freezer', 1],\n ['scat114992', ['Refrigerator'],\n 'Refrigeradores > Refrigeradores No Frost', 1],\n ['scat535116', ['Refrigerator'],\n 'Refrigeradores > Refrigeradores Side by Side', 1],\n ['scat114991', ['Refrigerator'],\n 'Refrigeradores > Refrigeradores Frío Directo', 1],\n ['scat112545', ['Refrigerator'],\n 'Refrigeradores > Frigobares y Cavas de Vino', 1],\n ['cat4850343', ['Oven'],\n 'Cocinas, Hornos y Campanas > Microondas y Hornos Eléctricos', 1],\n ['scat112547', ['Oven'],\n 'Microondas y Hornos Eléctricos > Microondas', 1],\n ['cat1580015', ['Oven'],\n 'Microondas y Hornos Eléctricos > Hornos Eléctricos', 1],\n ['cat3810002', ['Television'],\n 'Tv y Video > Televisores LED', 1],\n ['cat3810003', ['Monitor'],\n 'Tv y Video > Monitores LED', 1],\n ['cat3390002', ['Notebook'],\n 'Computación > Notebooks', 1],\n ['cat4780002', ['AirConditioner'],\n 'Aire Acondicionado y Ventilación > '\n 'Aires Acondicionados Split', 1],\n ['cat4780001', ['AirConditioner'],\n 'Aire Acondicionado y Ventilación > '\n 'Aires Acondicionados Portátiles', 1],\n ['scat663002/Calefont-tiro-natural', ['WaterHeater'],\n 'Sodimac.com > Calefont y Termos > Calefont tiro natural', 1],\n ['cat2080050/Calefont-tiro-forzado', ['WaterHeater'],\n 'Sodimac.com > Calefont y Termos > Calefont tiro forzado', 1],\n ['scat923316/Termos-y-Calderas', ['WaterHeater'],\n 'Sodimac.com > Calefont y Termos > Termos y Calderas', 1],\n ['scat299492', ['SpaceHeater'],\n 'Estufas > Estufas a Gas', 1],\n ['scat411008', ['SpaceHeater'],\n 'Estufas > Estufas a Parafina', 1],\n ['scat301608', ['SpaceHeater'],\n 'Estufas > Estufas a Leña', 1],\n ['scat299482', ['SpaceHeater'],\n 'Estufas > Estufas a Pellet', 1],\n ['scat963234', ['SpaceHeater'],\n 'Estufas > Estufas Eléctricas', 1],\n ['cat3870010', ['Cell'],\n 'Celulares y Telefonía > Smartphones', 1],\n ['cat8930005', ['Cell'],\n 'Celulares y Telefonía > Celulares Reacondicionados', 1],\n ['cat3870001', ['Headphones'],\n 'Tecnología Deportiva > Audífonos', 1],\n ['scat913770', ['StereoSystem'],\n 'Tecnología y TV > Equipos de Música', 1],\n # ['cat8350012', ['StereoSystem'],\n # 'Audio > Parlantes bluetooth', 1],\n ['cat3890001', ['VideoGameConsole'],\n 'Gamer > Consolas de videojuegos', 1],\n ['cat2940090', ['Ups'],\n 'Transformadores Eléctricos y UPS > Baterías de respaldo', 1],\n ['cat3550016', ['Printer'],\n 'Especiales > Tecno indispensables > Impresoras', 1],\n ]\n\n product_entries = defaultdict(lambda: [])\n session = session_with_proxy(extra_args)\n\n for e in category_paths:\n category_id, local_categories, section_name, category_weight = e\n\n if category not in local_categories:\n continue\n\n page = 1\n current_position = 1\n\n while True:\n url = 'https://www.sodimac.cl/s/search/v1/socl/category/' \\\n 'products?priceGroup=96&zone=130617¤tpage={}&' \\\n 'sortBy=_score,desc&categoryId={}'\\\n .format(page, category_id)\n\n response = session.get(url, timeout=30)\n data = json.loads(response.text)['data']\n\n products = data['results']\n\n if not products:\n if page == 1:\n logging.warning('No products for {}'.format(url))\n break\n\n for product in products:\n product_id = product['productId']\n slug = \"productos\"\n product_url = \\\n 'https://www.sodimac.cl/sodimac-cl/product/{}/{}/{}'\\\n .format(product_id, slug, product_id)\n\n product_entries[product_url].append({\n 'category_weight': category_weight,\n 'section_name': section_name,\n 'value': current_position\n })\n current_position += 1\n\n page += 1\n\n return product_entries\n\n @classmethod\n def discover_urls_for_keyword(cls, keyword, threshold, extra_args=None):\n session = session_with_proxy(extra_args)\n product_urls = []\n\n page = 0\n\n while True:\n url = 'https://www.sodimac.cl/sodimac-cl/search/?No={}&Ntt={}'\\\n .format(page, keyword)\n\n print(url)\n\n response = session.get(url, timeout=30)\n\n if '/product/' in response.url:\n product_urls.append(response.url)\n break\n\n soup = BeautifulSoup(response.text, 'html.parser')\n\n mosaic_divs = soup.findAll('section', 'jq-item')\n\n if not mosaic_divs:\n break\n\n for div in mosaic_divs:\n product_url = 'https://www.sodimac.cl/sodimac-cl/' \\\n 'product/' + div['data']\n product_urls.append(product_url)\n\n if len(product_urls) == threshold:\n return product_urls\n\n page += 16\n\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n print(url)\n session = session_with_proxy(extra_args)\n r_url = url + \"?rnd={}\".format(random.randint(0, 1000))\n print(r_url)\n response = session.get(r_url, timeout=30)\n\n if response.url != r_url or response.status_code in [404]:\n return []\n\n soup = BeautifulSoup(response.text, 'html.parser')\n\n if soup.find('p', 'sinStock-online-p-SEO'):\n return []\n\n sku_container = soup.find('input', {'id': 'currentProductId'})\n\n if sku_container:\n print('OLD')\n return cls._old_products_for_url(url, session, soup, category)\n else:\n print('NEW')\n return cls._new_products_for_url(url, session, soup, category)\n\n @classmethod\n def _old_products_for_url(cls, url, session, soup, category):\n sku = soup.find('input', {'id': 'currentProductId'})['value'].strip()\n key = soup.find('input', {'id': 'currentSkuId'})['value'].strip()\n\n pricing_container = soup.find('div', {'id': 'JsonArray'})\n\n if soup.find('div', {'id': 'JsonArray'}):\n pricing_json = json.loads(pricing_container.text)[0]\n\n if 'EVENTO' in pricing_json:\n normal_price = Decimal(pricing_json['EVENTO'])\n elif 'MASBAJO' in pricing_json:\n normal_price = Decimal(pricing_json['MASBAJO'])\n elif 'INTERNET' in pricing_json:\n normal_price = Decimal(pricing_json['INTERNET'])\n else:\n return []\n\n if 'CMR' in pricing_json:\n offer_price = Decimal(pricing_json['CMR'])\n if offer_price > normal_price:\n offer_price = normal_price\n else:\n offer_price = normal_price\n\n name = '{} {}'.format(pricing_json.get('brand', ''),\n pricing_json['name']).strip()\n\n stock_regex = r'{}=(\\d+)'.format(key)\n stock_text = re.search(stock_regex,\n pricing_json['stockLevel']).groups()[0]\n stock = int(stock_text)\n else:\n stock = 0\n normal_price = Decimal(remove_words(\n soup.find('p', 'price').text.split('\\xa0')[0]))\n offer_price = normal_price\n\n model = soup.find('h1', 'name').text\n brand = soup.find('h2', 'brand').text\n name = u'{} {}'.format(brand, model)\n\n description = '\\n\\n'.join([html_to_markdown(str(panel)) for panel in\n soup.findAll('section', 'prod-car')])\n\n # Pictures\n\n pictures_resource_url = 'https://sodimac.scene7.com/is/image/' \\\n 'SodimacCL/{}?req=set,json'.format(sku)\n pictures_json = json.loads(\n re.search(r's7jsonResponse\\((.+),\"\"\\);',\n session.get(pictures_resource_url,\n timeout=30).text).groups()[0])\n\n picture_urls = []\n\n picture_entries = pictures_json['set']['item']\n if not isinstance(picture_entries, list):\n picture_entries = [picture_entries]\n\n for picture_entry in picture_entries:\n picture_url = 'https://sodimac.scene7.com/is/image/{}?scl=1.0' \\\n ''.format(picture_entry['i']['n'])\n picture_urls.append(picture_url)\n\n if 'reacondicionado' in name.lower():\n condition = 'https://schema.org/RefurbishedCondition'\n else:\n condition = 'https://schema.org/NewCondition'\n\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n key,\n stock,\n normal_price,\n offer_price,\n 'CLP',\n sku=sku,\n description=description,\n picture_urls=picture_urls,\n condition=condition\n )\n\n return [p]\n\n @classmethod\n def _new_products_for_url(cls, url, session, soup, category):\n sku = soup.find(\n 'div', 'product-cod').text.replace('Código', '').strip()\n name = soup.find('h1', 'product-title').text.strip()\n brand = soup.find('div', 'product-brand').text.strip()\n name = \"{} {}\".format(brand, name)\n\n if not soup.find('div', 'normal'):\n return []\n\n normal_price = Decimal(\n soup.find('div', 'normal').find('div', 'price').text\n .replace('c/u', '').replace('$', '').replace('.', '')\n .replace('Normal', '').replace('pack', '').replace('caja', '')\n .strip())\n\n offer_price_container = soup.find('div', 'cmr')\n offer_price = None\n\n if offer_price_container:\n offer_price = Decimal(\n soup.find('div', 'cmr').find('div', 'price').text\n .replace('c/u', '').replace('$', '').replace('.', '')\n .strip())\n\n if not offer_price:\n data_json = json.loads(\n soup.find(\"script\", {\"id\": \"__NEXT_DATA__\"}).text)\n offer_price = Decimal(\n data_json['props']['pageProps']['productProps']['result']\n ['variants'][0]['price'][0]['price'].replace('.', ''))\n\n if not offer_price:\n offer_price = normal_price\n\n add_button = soup.find('button', {'id': 'testId-btn-add-to-cart'})\n\n if add_button:\n stock = -1\n else:\n stock = 0\n\n pictures_resource_url = 'https://sodimac.scene7.com/is/image/' \\\n 'SodimacCL/{}?req=set,json'.format(sku)\n pictures_response = session.get(pictures_resource_url).text\n pictures_json = json.loads(\n re.search(r's7jsonResponse\\((.+),\"\"\\);',\n pictures_response).groups()[0])\n\n picture_urls = []\n\n picture_entries = pictures_json['set']['item']\n if not isinstance(picture_entries, list):\n picture_entries = [picture_entries]\n\n for picture_entry in picture_entries:\n picture_url = 'https://sodimac.scene7.com/is/image/{}?' \\\n 'wid=1500&hei=1500&qlt=70'\\\n .format(picture_entry['i']['n'])\n picture_urls.append(picture_url)\n\n description = html_to_markdown(str(soup.find('div', 'product-info')))\n\n if 'reacondicionado' in name.lower():\n condition = 'https://schema.org/RefurbishedCondition'\n else:\n condition = 'https://schema.org/NewCondition'\n\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n stock,\n normal_price,\n offer_price,\n 'CLP',\n sku=sku,\n description=description,\n picture_urls=picture_urls,\n condition=condition,\n # seller=seller\n )\n\n return [p]\n","sub_path":"storescraper/stores/sodimac.py","file_name":"sodimac.py","file_ext":"py","file_size_in_byte":14138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"461048281","text":"# Import the required modules\nimport cv2, os\nimport numpy as np\nfrom PIL import Image\nimport csv\n\ndef get_images_and_labels():\n \"\"\"\n Get the images and labels from the csv to be used for the training\n :return:\n \"\"\"\n images = []\n labels = []\n f = open('./images.csv', 'rt')\n try:\n reader = csv.reader(f)\n for (path,label) in reader:\n image_pil = Image.open(path).convert('L')\n image = np.array(image_pil, 'uint8')\n nbr = int(label)\n # detect face in that image\n faces = faceCascade.detectMultiScale(image)\n # If face is detected, append the face to images and the label to labels\n for (x, y, w, h) in faces:\n images.append(image[y: y + h, x: x + w])\n labels.append(nbr)\n\n return images, labels\n finally:\n f.close()\n\n# For face detection we will use the Haar Cascade provided by OpenCV.\ncascadePath = \"haarcascade_frontalface_default.xml\"\nfaceCascade = cv2.CascadeClassifier(cascadePath)\n\n# For face recognition we will the the LBPH Face Recognizer \nrecognizer = cv2.face.createLBPHFaceRecognizer()\n# get images and labels\nimages, labels = get_images_and_labels()\n\n# Perform the training\nrecognizer.train(images, np.array(labels))\n\n# Get a handle to the Video device:\ncap = cv2.VideoCapture(0)\n\n\ndef get_image_from_subject(nbr_predicted):\n f = open('./images.csv', 'rt')\n\n try:\n reader = csv.reader(f)\n for (path, label) in reader:\n if int(label) == int(nbr_predicted):\n return path\n finally:\n f.close()\n pass\n\n\nwhile (True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n # convert BGR -> RGB - used for prediction\n cv2_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n predict_image_pil = Image.fromarray(cv2_im).convert('L')\n predict_image = np.array(predict_image_pil, 'uint8')\n # detect faces in video frame\n faces = faceCascade.detectMultiScale(frame, 1.3, 5)\n for (x, y, w, h) in faces:\n nbr_predicted, conf = recognizer.predict(predict_image[y: y + h, x: x + w])\n # draw a rectangle around the image\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n cv2.putText(frame, str(nbr_predicted), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)\n # display the image most similar with the detected face\n most_similar_path = get_image_from_subject(nbr_predicted)\n most_similar_img = cv2.imread(most_similar_path)\n cv2.imshow('Most similar',most_similar_img)\n cv2.imshow('Original', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n","sub_path":"P10/face_detect_recognition.py","file_name":"face_detect_recognition.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174025845","text":"import urllib2\nimport webbrowser\nimport os\nimport datetime\nimport dateutil.parser as dp\n\ndef take_repo():\n address = raw_input(\"\\t\\tType in repo address: \")\n return address\n\ndef take_user():\n user = raw_input(\"\\t\\tType in the user name: \")\n return user\n\ndef input_time():\n choice = raw_input(\"\\t\\tType 'u' for entering unix timestamp;\\n\\t\\tType 't' for entering ISO 8601 time;\\n\\t\\tType others for default;\\n\\t\\t\\tSpecify your command: \")\n if choice == \"u\":\n time = int(raw_input(\"\\t\\t\\tEnter unix timestamp: \"))\n elif choice == \"t\":\n time = raw_input(\"\\t\\t\\tEnter ISO 8601 time: \")\n parsed_t = dp.parse(time)\n time = int(parsed_t.strftime('%s'))\n else:\n time = 0\n return time\n\ndef main():\n repo_address = take_repo()\n user = take_user()\n time = input_time()\n\n url = \"https://api.github.com/repos/\"\n seperated_address = repo_address.split('/')\n url += (seperated_address[3]+'/'+seperated_address[4])\n url += \"/stats/contributors\"\n\n response = urllib2.urlopen(url)\n\n content = response.read()\n content = content.decode(\"utf-8\")\n\n if user not in content:\n print(\"\\t\\tNo such user exist!\")\n return\n \n format_content = content.strip('[]').split(',')\n\n start_time = int(format_content[1].split(':')[2])\n\n if time != 0:\n if int(time) < start_time:\n print(\"\\t\\tInvalid time input!\")\n return\n\n file = open(\"onecontributor.tsv\",\"w\")\n file.write(\"date\\tvalue\\n\")\n\n start_line = 0;\n end_line = 0;\n for line in format_content:\n if \"\\\"site_admin\\\"\" in line:\n start_line = end_line + 1\n if user in line:\n end_line += 1\n break;\n end_line+=1\n\n\n for i in range(start_line,end_line):\n if time == 0:\n if \"\\\"weeks\\\"\" in format_content[i]:\n commit = format_content[i+3].strip('{}[]').split(':')[1]\n print_time = datetime.datetime.fromtimestamp(int(format_content[i].split(':')[2])).strftime('%Y-%m-%d %H:%M:%S')\n file.write(print_time.split(' ')[0] + '\\t' + commit + '\\n')\n elif \"\\\"w\\\"\" in format_content[i]:\n commit = format_content[i+3].strip('{}[]').split(':')[1]\n print_time = datetime.datetime.fromtimestamp(int(format_content[i].split(':')[1])).strftime('%Y-%m-%d %H:%M:%S')\n file.write(print_time.split(' ')[0] + '\\t' + commit + '\\n')\n else:\n if \"\\\"weeks\\\"\" in format_content[i]:\n if time <= int(format_content[i].split(':')[2]):\n commit = format_content[i+3].strip('{}[]').split(':')[1]\n print_time = datetime.datetime.fromtimestamp(int(format_content[i].split(':')[2])).strftime('%Y-%m-%d %H:%M:%S')\n file.write(print_time.split(' ')[0] + '\\t' + commit + '\\n')\n elif \"\\\"w\\\"\" in format_content[i]:\n if time <= int(format_content[i].split(':')[1]):\n commit = format_content[i+3].strip('{}[]').split(':')[1]\n print_time = datetime.datetime.fromtimestamp(int(format_content[i].split(':')[1])).strftime('%Y-%m-%d %H:%M:%S')\n file.write(print_time.split(' ')[0] + '\\t' + commit + '\\n')\n\n file.close()\n\n path = os.path.abspath('onecontributor.html')\n url = 'file://' + path\n webbrowser.open(url)\n","sub_path":"onecontributor.py","file_name":"onecontributor.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"213114095","text":"\n\nfrom xai.brain.wordbase.nouns._charm import _CHARM\n\n#calss header\nclass _CHARMS(_CHARM, ):\n\tdef __init__(self,): \n\t\t_CHARM.__init__(self)\n\t\tself.name = \"CHARMS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"charm\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_charms.py","file_name":"_charms.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"253444536","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n#mish activation\nclass Mish(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n #inlining this saves 1 second per epoch (V100 GPU) vs having a temp x and then returning x(!)\n return x *( torch.tanh(F.softplus(x)))\n\n\nfrom torch.nn.parameter import Parameter\ndef gem(x, p=3, eps=1e-6):\n return F.avg_pool1d(x.clamp(min=eps).pow(p), (x.size(-1))).pow(1./p)\nclass GeM(nn.Module):\n def __init__(self, p=3, eps=1e-6):\n super(GeM,self).__init__()\n self.p = Parameter(torch.ones(1)*p)\n self.eps = eps\n def forward(self, x):\n return gem(x, p=self.p, eps=self.eps)\n def __repr__(self):\n return self.__class__.__name__ + '(' + 'p=' + '{:.4f}'.format(self.p.data.tolist()[0]) + ', ' + 'eps=' + str(self.eps) + ')'\n\n\nclass TransformerEncoderLayer(nn.Module):\n r\"\"\"TransformerEncoderLayer is made up of self-attn and feedforward network.\n This standard encoder layer is based on the paper \"Attention Is All You Need\".\n Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,\n Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in\n Neural Information Processing Systems, pages 6000-6010. Users may modify or implement\n in a different way during application.\n\n Args:\n d_model: the number of expected features in the input (required).\n nhead: the number of heads in the multiheadattention models (required).\n dim_feedforward: the dimension of the feedforward network model (default=2048).\n dropout: the dropout value (default=0.1).\n activation: the activation function of intermediate layer, relu or gelu (default=relu).\n\n Examples::\n >>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)\n >>> src = torch.rand(10, 32, 512)\n >>> out = encoder_layer(src)\n \"\"\"\n\n def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation=\"relu\"):\n super(TransformerEncoderLayer, self).__init__()\n self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\n self.linear1 = nn.Linear(d_model, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, d_model)\n\n self.norm1 = nn.LayerNorm(d_model)\n self.norm2 = nn.LayerNorm(d_model)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n\n self.activation = nn.ReLU()\n\n\n def forward(self, src , src_mask = None, src_key_padding_mask = None):\n src2,attention_weights = self.self_attn(src, src, src, attn_mask=src_mask,\n key_padding_mask=src_key_padding_mask)\n src = src + self.dropout1(src2)\n src = self.norm1(src)\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))\n src = src + self.dropout2(src2)\n src = self.norm2(src)\n return src,attention_weights\n\n\nclass LinearDecoder(nn.Module):\n def __init__(self,num_classes,ninp,dropout,pool=True,):\n super(LinearDecoder, self).__init__()\n # if pool:\n # self.pool_layer=GeM()\n if pool:\n self.classifier=nn.Linear(ninp,num_classes)\n else:\n self.classifier=nn.Linear(ninp,num_classes)\n self.pool=pool\n self.pool_layer=GeM()\n\n def forward(self,x):\n if self.pool:\n # max_x,_=torch.max(x,dim=1)\n # x=torch.cat([torch.mean(x,dim=1),max_x],dim=-1)\n #print(x.shape)\n x=self.pool_layer(x.permute(0,2,1)).permute(0,2,1).squeeze()\n #print(x.shape)\n x=self.classifier(x)\n return x\n\n\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n\n\nclass K_mer_aggregate(nn.Module):\n def __init__(self,kmers,in_dim,out_dim,dropout=0.1):\n super(K_mer_aggregate, self).__init__()\n #self.dropout=nn.Dropout(dropout)\n self.convs=[]\n for i in kmers:\n print(i)\n self.convs.append(nn.Conv1d(in_dim,out_dim,i,padding=0))\n self.convs=nn.ModuleList(self.convs)\n self.norm=nn.LayerNorm(out_dim)\n #self.activation=nn.ReLU(inplace=True)\n #self.activation=Mish()\n\n def forward(self,x):\n outputs=[]\n for conv in self.convs:\n outputs.append(conv(x))\n outputs=torch.cat(outputs,dim=2)\n return self.norm(outputs.permute(2,0,1))\n\n\nclass NucleicTransformer(nn.Module):\n\n def __init__(self, ntoken, nclass, ninp, nhead, nhid, nlayers, kmer_aggregation, kmers, dropout=0.5,return_aw=False):\n super(NucleicTransformer, self).__init__()\n self.model_type = 'Transformer'\n self.src_mask = None\n self.pos_encoder = PositionalEncoding(ninp, dropout)\n self.kmers=kmers\n #if self.ngrams!=None:\n self.kmer_aggregation=kmer_aggregation\n if self.kmer_aggregation:\n self.k_mer_aggregate=K_mer_aggregate(kmers,ninp,ninp)\n else:\n print(\"No kmer aggregation is chosen\")\n self.transformer_encoder = []\n for i in range(nlayers):\n self.transformer_encoder.append(TransformerEncoderLayer(ninp, nhead, nhid, dropout))\n self.transformer_encoder= nn.ModuleList(self.transformer_encoder)\n self.encoder = nn.Embedding(ntoken, ninp)\n #self.directional_encoder = nn.Embedding(3, ninp//8)\n self.ninp = ninp\n self.decoder = LinearDecoder(nclass,ninp,dropout)\n self.return_aw=False\n\n def _generate_square_subsequent_mask(self, sz):\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n def forward(self, src):\n src = src.permute(1,0)\n #dir = dir.permute(1,0)\n src = self.encoder(src) #* math.sqrt(self.ninp)\n #dir = self.directional_encoder(dir)\n #src = torch.cat([src,dir],dim=-1)\n src = self.pos_encoder(src)\n #if self.ngrams!=None:\n if self.kmer_aggregation:\n kmer_output = self.k_mer_aggregate(src.permute(1,2,0))\n #src = torch.cat([src,kmer_output],dim=0)\n src = kmer_output\n attention_weights=[]\n for layer in self.transformer_encoder:\n src,attention_weights_layer=layer(src)\n attention_weights.append(attention_weights_layer)\n\n encoder_output = src.permute(1,0,2)\n #print(encoder_output.shape)\n output = self.decoder(encoder_output)\n if self.return_aw:\n attention_weights=torch.stack(attention_weights).permute(1,0,2,3)\n return output, attention_weights\n else:\n return output\n","sub_path":"src/Viral_identification/Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":7491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"424504735","text":"import argparse, importlib, sys\n\nimport pyrat\nfrom pyrat import name, version, logger\n\n\n# This returns a function to be called by a subparser below\n# We assume in the tool's submodule there's a function called 'start(args)'\n# That takes over the execution of the program.\ndef tool_(tool_name):\n def f(args):\n submodule = importlib.import_module('pyrat.' + tool_name)\n getattr(submodule, 'start')(args)\n return f\n\n\nif __name__ == '__main__':\n\n # create the top-level parser\n parser = argparse.ArgumentParser(prog=name,\n description='Raw tools for raw audio.',\n epilog= name+' -h for more details.')\n parser.add_argument('--verbose', action='store_true')\n parser.add_argument('--quiet', action='store_true',\n help='takes precedence over \\'verbose\\'')\n parser.add_argument('-v', '--version', action='store_true',\n help='print version number and exit')\n\n subparsers = parser.add_subparsers(title=\"Commands\")\n\n # create the parser for the \"conv\" command\n parser_conv = subparsers.add_parser('conv',\n description='''Convolve input signal with kernel.\nNormalize the result and write it to outfile.''',\n help='Convolve input with a kernel.')\n parser_conv.add_argument('infile', type=argparse.FileType('r'))\n parser_conv.add_argument('kerfile', type=argparse.FileType('r'),\n help=\"kernel to be convolved with infile\")\n parser_conv.add_argument('outfile', type=argparse.FileType('w'))\n parser_conv.set_defaults(func=tool_('conv'))\n\n # create the parser for the \"randph\" command\n parser_randph = subparsers.add_parser('randph',\n description='''Randomize phases of Fourier coefficients.\nCalculate the FFT of the entire signal; then randomize the phases of each\nfrequency bin by multiplying the frequency coefficient by a random phase:\ne^{2pi \\phi}, where $\\phi$ is distributed uniformly on the interval [0,b). By\ndefault, b=0.1. The result is saved to outfile.''',\n help='Randomize phases of Fourier coefficients.')\n parser_randph.add_argument('infile', type=argparse.FileType('r'))\n parser_randph.add_argument('outfile', type=argparse.FileType('w'))\n parser_randph.add_argument('-b', type=float, default=0.1,\n help='phases disttibuted uniformly on [0,b)')\n parser_randph.set_defaults(func=tool_('randph'))\n\n if len(sys.argv) < 2:\n parser.print_usage()\n sys.exit(1)\n\n args = parser.parse_args()\n\n if args.version:\n print(name + '-' + version)\n sys.exit(0)\n\n if args.verbose:\n logger.setLevel('INFO')\n else:\n logger.setLevel('WARNING')\n if args.quiet:\n logger.setLevel(60) # above 'CRITICAL'\n\n args.func(args)\n\n sys.exit(0)\n","sub_path":"pyrat/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"199494038","text":"from talon import actions, speech_system, Module\n\n# keeper $: insert(text)\n# results in: \"keeper new-line\" inserting an actual new line, instead of the words \"new line\"\n\nmod = Module()\n@mod.action_class\nclass Actions:\n def keeper_insert(text: str):\n \"\"\"insert text\"\"\"\n print(text)\n actions.insert(text)\n\n \n # switch_app(name='iTerm2')\n# def fn(d):\n# if 'parsed' not in d:\n# return\n#\n# print(d['words'])\n# print(d)\n# words = d['parsed']._unmapped\n# if words[0] == 'keeper':\n# actions.insert(' '.join(words[1:]))\n# d['parsed']._sequence = []\n#\n# speech_system.register('pre:phrase', fn)\n\n\n\"\"\"\n\n\"\"\"","sub_path":"misc/keeper.py","file_name":"keeper.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"76221112","text":"# Differences between 1.0 and 1.3 implementation:\n# + Additionally to a MAIN_DISPATCHER a CONFIG_DISPATCHER has been added\n# - The CONFIG_DISPATCHER answers to SwitchFeature Requests and adds a flow to itself which is a generic table-miss flow entry in case if this\n# table-miss occurs the packet will be send to the controller\n# + Some api changes in FlowMod, now next to actions there are also instructions which can perform actions but also are capable of switches between tables e.g.\n# + Also buffer ids have been introduced which can be added to new Flow Modifications\n#\n#\n# Maximum number of rules:\n#\n# The theoretical amount of rules can be determined by having a look at the structure of flow rules in OpenFlow 1.0.\n#\n# |Switch Port | MAC src | MAC dst | Eth type | VLAN ID | IPsrc(v4) | IP dst | TCP sport | TCP dport|\n# |-------------------------|---------|---------|------------|---------|-----------|--------|-----------|----------|\n# | number of hardware ports| 2^48 | 2^48 |4 diff types| 2^16 | 2^32 | 2^32 | 65535 | 65535 |\n#\n# This configuration would be correct for the maximum number of rules configurable due to the restriction to only one flow table.\n# But we can restrict that number to useful application rules in our used topology (or any other topology depending on the structure of it).\n#\n# in the example\n# |Switch Port | MAC src | MAC dst | Eth type | VLAN ID | IPsrc(v4) | IP dst | TCP sport(in example host) | TCP dport|\n# |------------|---------|---------|------------|---------|-----------|--------|----------------------------|----------|\n# | 3 | 4 | 4 |4 diff types| 1 | 4 | 4 | 1000 | 1000 |\n#\n# So only around 3072000000 rules that can at maxmimum be defined.\n#\n# For OpenFlow 1.3 though we can extend this since we no longer have a single flow table but multiple which can interlink each other,\n# using this we not only can create theoretically as many rules as required we also can simplify them by using links from one table to another to group certain actions e.g. in multi-tenancy systems,\n# so the upper limit will always be defined by the maximum number of rules the switch can hold.\n#\n# // Used partly as source: https://blog.ipspace.net/2013/10/flow-table-explosion-with-openflow-10.html\n\n\nimport struct\nimport logging\n\nfrom ryu.base import app_manager\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.ofproto import ofproto_v1_3\nfrom ryu.lib.packet import packet\nfrom ryu.lib.packet import ethernet\nfrom ryu.lib.packet import ether_types\n\nFILTER_TABLE = 0\nFORWARD_TABLE = 15\n\n\nclass SimpleSwitch13(app_manager.RyuApp):\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n\n def __init__(self, *args, **kwargs):\n super(SimpleSwitch13, self).__init__(*args, **kwargs)\n self.mac_to_port = {}\n\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_features_handler(self, ev):\n datapath = ev.msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n # install table-miss flow entry\n #\n # We specify NO BUFFER to max_len of the output action due to\n # OVS bug. At this moment, if we specify a lesser number, e.g.,\n # 128, OVS will send Packet-In with invalid buffer_id and\n # truncated packet data. In that case, we cannot output packets\n # correctly. The bug has been fixed in OVS v2.1.0.\n match = parser.OFPMatch()\n actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,\n ofproto.OFPCML_NO_BUFFER)]\n self.add_flow(datapath, 0, match, actions)\n\n # To set defaults which should be checked by the switch first\n self.add_filter_table(datapath)\n\n\n # Add flow to filter table which links to forward table\n def add_filter_table(self, datapath):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n inst = [parser.OFPInstructionActions(ofproto.OFPIT_CLEAR_ACTIONS, [])]\n mod = parser.OFPFlowMod(datapath=datapath, table_id=FILTER_TABLE,\n priority=1, instructions=inst)\n datapath.send_msg(mod)\n\n\n # Rules for filter table\n def apply_filter_table_rules(self, datapath, match):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n inst = [parser.OFPInstructionGotoTable(FORWARD_TABLE)]\n mod = parser.OFPFlowMod(datapath=datapath, table_id=FILTER_TABLE,\n priority=ofproto.OFP_DEFAULT_PRIORITY, match=match, instructions=inst)\n datapath.send_msg(mod)\n\n\n def add_flow(self, datapath, priority, match, actions, buffer_id=None):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,\n actions)]\n if buffer_id:\n mod = datapath.ofproto_parser.OFPFlowMod(\n datapath=datapath, match=match, cookie=0,\n command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0,\n priority=ofproto.OFP_DEFAULT_PRIORITY,\n flags=ofproto.OFPFF_SEND_FLOW_REM, instructions=inst, buffer_id=buffer_id)\n else:\n mod = datapath.ofproto_parser.OFPFlowMod(\n datapath=datapath, match=match, cookie=0,\n command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0,\n priority=ofproto.OFP_DEFAULT_PRIORITY,\n flags=ofproto.OFPFF_SEND_FLOW_REM, instructions=inst)\n datapath.send_msg(mod)\n\n\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\n def _packet_in_handler(self, ev):\n # If you hit this you might want to increase\n # the \"miss_send_length\" of your switch\n if ev.msg.msg_len < ev.msg.total_len:\n self.logger.debug(\"packet truncated: only %s of %s bytes\",\n ev.msg.msg_len, ev.msg.total_len)\n msg = ev.msg\n datapath = msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n in_port = msg.match['in_port']\n\n pkt = packet.Packet(msg.data)\n eth = pkt.get_protocols(ethernet.ethernet)[0]\n\n if eth.ethertype == ether_types.ETH_TYPE_LLDP:\n # ignore lldp packet\n return\n dst = eth.dst\n src = eth.src\n\n dpid = datapath.id\n self.mac_to_port.setdefault(dpid, {})\n\n self.logger.info(\"packet in %s %s %s %s\", dpid, src, dst, in_port)\n\n # learn a mac address to avoid FLOOD next time and enforce the one mac\n # address per port rule\n print(\"s%s: in_port=%s known ports=%s\" % (dpid, in_port, self.mac_to_port[dpid].values()))\n if in_port >= 3:\n match = parser.OFPMatch(in_port=in_port, eth_src=eth.src)\n self.logger.info(\"add >=3 packet on s%s src=%s dst=%s in_port=%s\", dpid, src, dst, in_port)\n self.mac_to_port[dpid][src] = in_port\n self.apply_filter_table_rules(datapath, match)\n elif src in self.mac_to_port[dpid] or in_port not in self.mac_to_port[dpid].values():\n match = parser.OFPMatch(in_port=in_port, eth_src=eth.src)\n self.logger.info(\"add < 3 packet on s%s src=%s dst=%s in_port=%s\", dpid, src, dst, in_port)\n self.mac_to_port[dpid][src] = in_port\n self.apply_filter_table_rules(datapath, match)\n else:\n self.logger.info(\"spoof\")\n return\n\n\n if dst in self.mac_to_port[dpid]:\n out_port = self.mac_to_port[dpid][dst]\n else:\n out_port = ofproto.OFPP_FLOOD\n\n actions = [parser.OFPActionOutput(out_port)]\n\n # install a flow to avoid packet_in next time\n if out_port != ofproto.OFPP_FLOOD:\n if in_port > 3:\n match = parser.OFPMatch(in_port=in_port, eth_src=src, eth_dst=dst)\n else:\n match = parser.OFPMatch(in_port=in_port, eth_dst=dst)\n # verify if we have a valid buffer_id, if yes avoid to send both\n # flow_mod & packet_out\n if msg.buffer_id != ofproto.OFP_NO_BUFFER:\n self.add_flow(datapath, 1, match, actions, msg.buffer_id)\n return\n else:\n self.add_flow(datapath, 1, match, actions)\n data = None\n if msg.buffer_id == ofproto.OFP_NO_BUFFER:\n data = msg.data\n\n out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,\n in_port=in_port, actions=actions, data=data)\n datapath.send_msg(out)\n\n\n @set_ev_cls(ofp_event.EventOFPPortStatus, MAIN_DISPATCHER)\n def _port_status_handler(self, ev):\n msg = ev.msg\n reason = msg.reason\n port_no = msg.desc.port_no\n\n ofproto = msg.datapath.ofproto\n if reason == ofproto.OFPPR_ADD:\n self.logger.info(\"port added %s\", port_no)\n elif reason == ofproto.OFPPR_DELETE:\n self.logger.info(\"port deleted %s\", port_no)\n elif reason == ofproto.OFPPR_MODIFY:\n self.logger.info(\"port modified %s\", port_no)\n else:\n self.logger.info(\"Illeagal port state %s %s\", port_no, reason)\n\n","sub_path":"Lab3/filter13.py","file_name":"filter13.py","file_ext":"py","file_size_in_byte":9438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"225106475","text":"from unittest import TestCase\n\n\nclass TUS(TestCase):\n # BDD\n ID = 'Sin definir'\n YO = 'Usuario sin definir'\n REQUIERO = 'Sin definir'\n TAL_QUE = 'Sin definir'\n CRITERIOS_ACEPTACION = ''' Sin definir'''\n development = ''\n\n DOMAIN = ''\n\n # Dependencies\n thu_dependencies = []\n model_dependencies = []\n\n def run_test(self, browser, dependencies=False, recursive=False):\n if dependencies is True:\n self.execute_dependency_processes(browser, recursive)\n self.main_process(browser)\n\n def execute_dependency_processes(self, browser, recursive):\n for dependency in self.thu_dependencies:\n dependency.DOMAIN = self.DOMAIN\n if recursive is True:\n dependency.run_test(browser, dependencies=True, recursive=recursive)\n else:\n dependency.run_test(browser)\n\n def print_bdd(self):\n print(\"*\" * 70)\n print(f'ID: {self.ID}')\n print(f'Yo como: {self.YO}')\n print(f'Requiero: {self.REQUIERO}')\n print(f'Tal que: {self.TAL_QUE}')\n print(f'Criterios aceptacion: {self.CRITERIOS_ACEPTACION}')\n print(f'Desarrollador: {self.development}')\n print(\"*\" * 70)\n\n def main_process(self, browser):\n pass\n","sub_path":"test_user_story/core_tus/tus.py","file_name":"tus.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"31939364","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport time\nfrom utils import label_map_util\nfrom utils import visualization_utils as vis_util\nfrom FifaEnv import FifaEnv\nfrom Keys import Keys\nfrom PIL import Image\n\nclass CNN_V2_With_Barrier(object):\n \"\"\"\n This class acts as the intermediate \"API\" to the actual game. Double quotes API because we are not touching the\n game's actual code. It interacts with the game simply using screen-grab (input) and keypress simulation (output)\n using some clever python libraries.\n \"\"\"\n # What model to download.\n MODEL_NAME = 'fifa_graph_chintan_v2_with_barrier'\n\n # Path to frozen detection graph. This is the actual model that is used for the object detection.\n PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n # List of the strings that is used to add correct label for each box.\n PATH_TO_LABELS = MODEL_NAME + '/object-detection.pbtxt'\n\n NUM_CLASSES = 4\n\n detection_graph = tf.Graph()\n\n def __init__(self):\n with self.detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(self.PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)\n print(label_map)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=self.NUM_CLASSES,\n use_display_name=True)\n self.category_index = label_map_util.create_category_index(categories)\n\n ## Run the model for the given image\n def run_inference_for_single_image(self, image):\n with self.detection_graph.as_default():\n with tf.Session(graph=self.detection_graph) as sess:\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in [\n 'num_detections', 'detection_boxes', 'detection_scores',\n 'detection_classes', 'detection_masks'\n ]:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)\n if 'detection_masks' in tensor_dict:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image.shape[0], image.shape[1])\n detection_masks_reframed = tf.cast(\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict['detection_masks'] = tf.expand_dims(\n detection_masks_reframed, 0)\n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n # Run inference\n output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)})\n\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict[\n 'detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\n return output_dict\n\n ## Saves a labeled image (generating the bounding boxes) from the given image\n def generate_labeled_image(self, image, number):\n\n def load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)\n\n # Size, in inches, of the output images.\n IMAGE_SIZE = (30, 22)\n\n image_path = 'image' + str(number) + '.png'\n\n ## Saving and loading image\n cv2.imwrite(image_path, image)\n image = Image.open(image_path)\n\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image_np = load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n output_dict = self.run_inference_for_single_image(image_np)\n\n print(output_dict)\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n self.category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=8)\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(image_np)\n plt.savefig(\"image_labeled\" + str(number))\n\n ## Extracts a 128 vector corresponding to the object desired to detection from the given image\n def get_image_feature_map(self, image):\n start = time.time()\n image = image[40:850,0:1400]\n with self.detection_graph.as_default():\n with tf.Session(graph=self.detection_graph) as sess:\n # Definite input and output Tensors for detection_graph\n image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')\n feature_vector = self.detection_graph.get_tensor_by_name(\n \"FeatureExtractor/MobilenetV2/layer_19_2_Conv2d_5_3x3_s2_128/Relu6:0\")\n\n image_np = cv2.resize(image, (900, 400))\n image_np_expanded = np.expand_dims(image_np, axis=0)\n rep = sess.run([feature_vector], feed_dict={image_tensor: image_np_expanded})\n return np.array(rep).reshape(-1, 128), image\n\n ## Validates the object detection (check if the images labeled are correct)\n def test_object_detection(self):\n\n game_env = FifaEnv()\n keys = Keys()\n paused = True\n cont=0\n\n while True:\n \n if not paused:\n \n # get the current state\n x_t = game_env.observe_state()[40:850,0:1400]\n\n self.generate_labeled_image(x_t, cont)\n\n cont+=1\n paused = True\n print('Pausing!')\n \n keys_pressed = keys.KeyCheck()\n \n if 'Q' in keys_pressed:\n if paused:\n paused = False\n print('unpaused!')\n time.sleep(1)\n\nif __name__ == '__main__':\n print('aa')\n od_model = CNN_V2_With_Barrier()\n od_model.test_object_detection()\n","sub_path":"CNN_Chintan_V2_With_Barrier.py","file_name":"CNN_Chintan_V2_With_Barrier.py","file_ext":"py","file_size_in_byte":8121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"257949396","text":"import requests\n\nfrom flask import current_app\n\n\nclass Playlist():\n playlist = None\n\n payload = {\n 'key': None,\n 'part': 'contentDetails',\n 'maxResults': 50,\n 'playlistId': None,\n }\n\n def __init__(self, playlist_id):\n self.playlists_base_url = current_app.config['PLAYLISTS_BASE_URL']\n self.payload['key'] = current_app.config['API_KEY']\n self.payload['playlistId'] = playlist_id\n\n self.get_playlist()\n\n def get_playlist(self, next_page=None):\n\n if next_page is not None:\n print('Getting next page: %s' % (next_page))\n self.payload['pageToken'] = next_page\n\n response = self.make_request()\n\n if self.playlist is None:\n self.playlist = response\n else:\n self.playlist['items'] = self.playlist['items'] + response['items']\n\n if 'nextPageToken' in response:\n self.get_playlist(response['nextPageToken'])\n else:\n return response\n\n def make_request(self):\n response = requests.get(self.playlists_base_url, params=self.payload)\n\n json = response.json()\n\n if 'error' in json:\n raise Exception('There was a problem getting the playlist')\n\n return json\n\n @property\n def playlist_items(self):\n return [item['contentDetails']['videoId'] for item in self.playlist['items']]\n","sub_path":"tuber/playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"448683930","text":"import matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nmpl.use('Agg')\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport os\nimport ns_sampling_modules as sm\nfrom ns_password import LOCAL_DIRECTORY\nimport ns_data_modules as dm\nfrom input_deck import names\nfn=names()\n\ndef violin_saved_dataset(c,loops_2_show,y_lim=None):\n '''\n\n :param c: inputs() object\n :param loops_2_show: Nx1 ndarray array of loops to show in violin plot\n :param y_lim: 2x1 list . Max and min of y limits\n :return: makes violin plot of the loops specified in loops2show\n\n\n '''\n 'nb strings is the number of strings in the violin plot'\n # first make the directory and get all the pkl files\n if y_lim is None:\n y_lim = [-1.5, 3]\n df_pp = pd.read_pickle(path=dm.make_file_name(c=c,file_description=fn.pp_fn))\n pp = sm.convert2numpy(df=df_pp, field=fn.pp_fn)\n df_min_yield =pd.read_pickle(path=dm.make_file_name(c=c,file_description=fn.min_yield_fn))\n min_yield=sm.convert2numpy(df=df_min_yield,field=fn.min_yield_fn)\n\n # make the figure\n fig,ax=plt.subplots(1, 1, figsize=[5, 3], dpi=300)\n\n labels=[]\n for k in np.arange(len(loops_2_show)):\n # read parralel file\n # s=strings[k]\n # n=numbers[k]\n\n n=loops_2_show[k]\n\n df=dm.read_pickle(c=c,file_description='sequences_loop_'+str(loops_2_show[k]))\n dev=sm.convert2numpy(df=df,field=c.yield2optimize)\n violin_parts =ax.violinplot([dev], positions=[k], showmedians=False,\n showextrema=False, points=100,\n widths=.9)\n # violin_parts['cmedians'].set_color('r')\n # violin_parts['cmedians']=min_yield[n-1]\n for pc in violin_parts['bodies']:\n pc.set_color('k')\n #TODO: figure out why min yield and pp are off by 2 idexes ,look to nested_sampling\n labels.append('Loop: %i'%n)\n\n nb_strings=loops_2_show.shape[0]\n ax.set_xticks(np.arange(nb_strings))\n ax.set_ylim(y_lim)\n ax.set_xticklabels(labels)\n # ax.set_xlabel('Loop',fontsize=6)\n ax.set_ylabel('Yield', fontsize=6)\n ax.tick_params(axis='both', which='major', labelsize=6)\n ax.set_title('Nested Sampling Loops: %i, Random Walk Steps: %i ' % (np.max(loops_2_show),c.nb_steps))\n start=-0.5\n for k in loops_2_show:\n x=[start,start+1]\n y=[min_yield[k-1],min_yield[k-1]]\n ax.plot(x,y,'-r',linewidth=0.5,label='Threshold')\n ax.text(np.average(x),np.average(y)-0.02,'%0.2f'%min_yield[k-1],fontsize=6,color='grey',horizontalalignment='center',\n verticalalignment='top')\n start=start+1\n ax.legend(['Threshold'])\n fig.tight_layout()\n print('saving ' +dm.make_file_name(c=c,file_description='violin_plot_nb_strings_%i'%nb_strings,fileformat='png'))\n fig.savefig(dm.make_file_name(c=c,file_description='violin_plot_nb_strings_%i'%nb_strings,fileformat='png'))\n plt.close(fig)\n\n\n\n\ndef make_min_yield_plot(c, min_yield_lst):\n '''\n\n :param c: inputs() object\n :param min_yield_lst: min yield list\n :return: makes a min yield plot saves to inputs() directory\n\n '''\n 'this makes the min yield plot'\n plt.plot(np.arange(c.nb_loops + 1).tolist(), min_yield_lst)\n plt.title('min yield vs. nb of loops')\n plt.ylabel('min yield')\n plt.xlabel('nb of loops')\n plt.savefig(dm.make_file_name(c=c,\n file_description='min_yield',fileformat='png'))\n plt.close()\n\ndef make_percent_positive_plot(c,percent_pos):\n '''\n\n :param c: inputs() object\n :param percent_pos: percent positive list\n :return: makes a percent positive plot saves to inputs() directory\n\n '''\n 'makes the percent positive plot '\n # pp = []\n # for i in np.arange(c.nb_loops):\n # pp.append(sum(percent_pos[i])/ c.nb_steps) # Right now percent postive is just the average ...\n plt.plot(np.arange(c.nb_loops).tolist(), percent_pos)\n plt.title('percent accepted vs. for each loop')\n plt.ylabel('percent accepted')\n plt.xlabel('# of loops')\n plt.savefig(dm.make_file_name(c=c,file_description='percent_pos',fileformat='png'))\n plt.close()\n\n\ndef plot_hist(c, i, j, seq,bins=50):\n '''\n\n :param c: inputs() object\n :param i: step number\n :param j: loop number\n :param seq: dataframe containing developability column\n :param bins: # of bins to have in histogram\n :return: saves a histogram to folder specified by c\n '''\n # future version\n print('Plotting histogram Step:%i,Loop%i' % (i, j))\n dev=seq['Developability'].to_numpy()\n plt.hist(dev, bins=bins)\n plt.title('Step: %i Loop: %i threshold yield: %0.2f'\n % (i, j, np.min(dev)))\n plt.ylabel('frequency')\n plt.xlabel('yield')\n plt.savefig(dm.make_file_name(c=c,file_description='hist_loop_%i_step%i'%(j,i),fileformat='png'))\n plt.close()\n\n\n\n\n\n\ndef make_heat_map(df,c,loop_nb):\n '''\n\n :param df: dataframe with ordinal field\n :param c: inputs() object\n :param loop_nb: the loop number in the run\n :return: makes a heat map saves to inputs() directory\n\n '''\n ord=sm.convert2numpy(df=df,field='Ordinal')\n nb_AA=21\n nb_positions=16\n heat_map=np.zeros((nb_positions,nb_AA))\n for k in np.arange(nb_AA):\n # number of amino acids\n heat_map[:,k]=np.sum(ord==k,axis=0)\n\n frequency=(heat_map.T/np.sum(heat_map,axis=1)).T.copy()\n\n heat_map_plot(frequency=frequency,c=c,loop_nb=loop_nb)\n\n\ndef heat_map_plot(frequency,c,loop_nb):\n 'function makes heat map : curtiousy of alex :)'\n frequency = pd.DataFrame(frequency)\n frequency.columns = list(\"ACDEFGHIKLMNPQRSTVWXY\")\n frequency['Gap'] = frequency['X']\n frequency = frequency[\n ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y', 'Gap']]\n frequency.index = ['7', '8', '9', '9b', '9c', '10', '11', '12', '34', '35', '36', '36b', '36c', '37', '38', '39']\n for pos in ['7', '8', '9', '10', '11', '12', '34', '35', '36', '37', '38', '39']:\n frequency['Gap'][pos] = np.nan\n frequency['Aromatic (F,W,Y)'] = frequency[['F', 'W', 'Y']].mean(axis=1)\n frequency['Small (A,C,G,S)'] = frequency[['A', 'G', 'C', 'S']].mean(axis=1)\n frequency['Non-Polar Aliphatic (A,G,I,L,M,P,V)'] = frequency[['P', 'M', 'I', 'L', 'V', 'A', 'G']].mean(axis=1)\n frequency['Polar Uncharged (C,N,Q,S,T)'] = frequency[['C', 'S', 'Q', 'S', 'T']].mean(axis=1)\n frequency['Negative Charged (D,E)'] = frequency[['D', 'E']].mean(axis=1)\n frequency['Positive Charged (H,K,R)'] = frequency[['H', 'K', 'R']].mean(axis=1)\n frequency['Hydrophobic (A,F,G,I,L,M,P,V,W,Y)'] = frequency[['A', 'F', 'G', 'I', 'L', 'M', 'P', 'V', 'W', 'Y']].mean(\n axis=1)\n frequency['Hydrophilic (C,D,E,H,K,N,Q,R,S,T)'] = frequency[['C', 'D', 'E', 'H', 'K', 'N', 'Q', 'R', 'S', 'T']].mean(\n axis=1)\n frequency = frequency.transpose()\n frequency['Loop 1 (8-11)'] = frequency[['8', '9', '9b', '9c', '10', '11']].mean(axis=1)\n frequency['Loop 2 (34-39)'] = frequency[['34', '35', '36', '36b', '36c', '37', '38', '39']].mean(axis=1)\n frequency['Loop 1 & Loop 2'] = frequency[\n ['8', '9', '9b', '9c', '10', '11', '34', '35', '36', '36b', '36c', '37', '38', '39']].mean(axis=1)\n\n frequency = frequency[\n ['7', '8', '9', '9b', '9c', '10', '11', '12', '34', '35', '36', '36b', '36c', '37', '38', '39', 'Loop 1 (8-11)',\n 'Loop 2 (34-39)', 'Loop 1 & Loop 2']]\n\n fig, ax = plt.subplots(1, 1, figsize=[5, 3], dpi=300)\n cmap = mpl.cm.Reds\n cmap.set_bad('black')\n\n heat_map = sns.heatmap(frequency.transpose(), square=True, vmin=0, vmax=1, cmap=cmap,\n cbar_kws={\"shrink\": 0.6, \"extend\": 'min', \"ticks\": [0, 0.5, 1]})\n heat_map.figure.axes[-1].set_ylabel('Frequency', size=6)\n heat_map.figure.axes[-1].tick_params(labelsize=6)\n ax.set_yticks([x + 0.5 for x in list(range(19))])\n ax.set_yticklabels(\n ['7', '8', '9', '9b', '9c', '10', '11', '12', '34', '35', '36', '36b', '36c', '37', '38', '39', 'Loop 1 (8-11)',\n 'Loop 2 (34-39)', 'Loop 1 & Loop 2'])\n ax.set_ylim([19.5, -0.5])\n\n ax.set_xticks([x + 0.5 for x in list(range(29))])\n pooled_AA = ['Aromatic', 'Small', 'Non-Polar Aliphatic', 'Polar Uncharged', 'Negative Charged', 'Positive Charged',\n 'Hydrophobic', 'Hydrophilic']\n ax.set_xticklabels(\n ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y',\n 'Gap'] + pooled_AA)\n ax.set_xlim([-0.5, 29.5])\n ax.tick_params(labelsize=6)\n ax.set_title('Heat map , loop %i'%(loop_nb+1))\n\n plt.tight_layout()\n print('saving heatmap .. '+dm.make_file_name(c=c,file_description='heatmap_loop_%i'% loop_nb,fileformat='png'))\n fig.savefig(dm.make_file_name(c=c,file_description='heatmap_loop_%i'% (loop_nb+1),fileformat='png'))\n plt.close(fig)\n\n\ndef showFieldvsLoops(c, field2Show):\n '''\n\n :param c: inputs() object\n :param field2Show: what thing to show ?\n :return: shows a plot of specified field reading from parralel files in inputs() object\n\n '''\n\n df = pd.read_pickle(path=dm.make_file_name(c=c, file_description=field2Show))\n stat = sm.convert2numpy(df=df, field=field2Show)\n\n if c.mutation_type == 'dynamic':\n nm = ''\n else:\n nm = ' ,# mutations: %i' % c.nb_mutations\n plt.plot(np.arange(stat.shape[0]).tolist(), stat, label=c.mutation_type + ' ' + nm, )\n plt.title('%s vs nested sample loop' % field2Show)\n plt.ylabel(field2Show)\n plt.xlabel('loop number')\n plt.legend()\n plt.savefig(dm.make_file_name(c=c, file_description='%s_plot'%field2Show, fileformat='png'))\n plt.close()\n\n\ndef twinAxisvsLoops(c,fields2show):\n '''\n\n\n :param c: inputs() object\n :param fields2show: 2x1 List of two fields to show [default: percent positive and nb mutations]\n :return: makes twin axis plot of the two fields that are specified\n\n '''\n\n df_pp = dm.read_pickle(c=c, file_description=fields2show[0])\n pp = sm.convert2numpy(df=df_pp, field=fields2show[0])\n\n df_nb = dm.read_pickle(c=c, file_description=fields2show[1])\n nb = sm.convert2numpy(df=df_nb, field=fields2show[1])\n\n\n\n # nb = nb[0:-2].copy()\n # if nb.shape[0] != pp.shape[0]:\n # raise IndexError('number mutations and percent positive lengths are different?')\n\n loop_range = np.arange(pp.shape[0]).tolist()\n fig, ax1 = plt.subplots(1, 1, figsize=[5, 3], dpi=300)\n color = 'tab:red'\n ax1.set_xlabel('loop nb')\n ax1.set_ylabel(fields2show[1], color=color)\n ax1.plot(loop_range, nb[0:-1], color=color)\n ax1.tick_params(axis='y', labelcolor=color)\n\n ax2 = ax1.twinx()\n color = 'tab:blue'\n ax2.set_ylabel(fields2show[0], color=color) # we already handled the x-label with ax1\n ax2.plot(loop_range, pp, color=color)\n ax2.tick_params(axis='y', labelcolor=color)\n\n fig.tight_layout() # otherwise the right y-label is slightly clipped\n plt.savefig(dm.make_file_name(c=c, file_description='%s_vs_%s_plot'%(fields2show[0],fields2show[1]), fileformat='png'))\n plt.close(fig)\n\n\ndef compare(C,field2Show):\n '''\n compare fields across runs\n make sure c.Nb_sequences and c.nb_loops is the same for all runs.\n :param C: list of runs\n :param field2Show: what thing to show ?\n :return: None\n '''\n\n\n for c in C:\n if C[0].Nb_sequences!=c.Nb_sequences or C[0].nb_loops !=c.nb_loops:\n raise SystemError('Your sequences and loops are not the same for comparing models.')\n df=pd.read_pickle(path=dm.make_file_name(c=c,file_description=field2Show))\n stat=sm.convert2numpy(df=df,field=field2Show)\n\n if c.mutation_type=='dynamic':\n nm=''\n else :\n nm=' ,# mutations: %i'%c.nb_mutations\n plt.plot(np.arange(stat.shape[0]).tolist(),stat,label=c.mutation_type+' '+nm,)\n plt.title('%s vs nested sample loop :%i'%(field2Show,C[0].Nb_sequences))\n plt.ylabel(field2Show)\n plt.xlabel('loop number')\n plt.legend()\n os.system('mkdir ./sampling_data/comparisons')\n print('saving ./sampling_data/comparisons/%s_nb_loops_%i_nb_sequences_%i'% (field2Show,C[0].nb_loops,C[0].Nb_sequences))\n plt.savefig('./sampling_data/comparisons/%s_nb_loops_%i_nb_sequences_%i'% (field2Show,C[0].nb_loops,C[0].Nb_sequences))\n plt.close()\n\n\n\n\n# unit test for making the heat map... all seemed to go well.\n# seed_parent = int.from_bytes(os.urandom(4), sys.byteorder)\n# g_parent = tf.random.experimental.Generator.from_seed(seed_parent)\n# original_seq=pd.DataFrame()\n# original_seq['Ordinal']= sm.make_sampling_data(generator=g_parent,Nb_sequences=1000,Nb_positions=16)\n# os.system('mkdir ./sampling_data/test_heat_map')\n# make_heat_map(df=original_seq,dir_name='test_heat_map',loop_nb=0)\n\n\n# def init_violin_plots(self,loops_2_show):\n# 'initilize the violin plots'\n# nb_violinplots = len(loops_2_show)\n# for k in np.arange(nb_violinplots):\n# self.vp.append(plt.subplots(1, 1, figsize=[5, 3], dpi=300))\n# return self.vp\n#\n#\n# def plot_violin(self, i, j, seq, steps_2_show, loops_2_show):\n# # i is the step number\n# # j is the Loop number\n# idx_loop = np.argmax(loops_2_show == j)\n# idx_step = np.argmax(steps_2_show == i)\n# dev = seq['Developability'].to_numpy() # yield\n# violin_parts = self.vp[idx_loop][1].violinplot([dev], positions=[idx_step], showmedians=False,\n# showextrema=False, points=100,\n# widths=.9)\n# for pc in violin_parts['bodies']:\n# pc.set_color('k')\n#\n#\n# def close_violin(self, j, steps_2_show, loops_2_show, Nb_steps, Nb_loops, y_lim=None):\n# 'close a violin plot and save it as a png file'\n# if y_lim is None:\n# y_lim = [-1, 1.5]\n# v = self.vp[np.argmax(loops_2_show == j)]\n# str_steps_2_show = []\n# for i in steps_2_show:\n# if i == 0:\n# str_steps_2_show.append('Init')\n# else:\n# str_steps_2_show.append('step:%i,percent:%0.2f' % (i,sum(self.percent_pos[j])/Nb_steps))\n# fig = v[0]\n# ax = v[1]\n# ax.set_xticks(np.arange(len(steps_2_show)))\n# ax.set_ylim(y_lim)\n# ax.set_xticklabels(str_steps_2_show)\n# ax.set_ylabel('Yield', fontsize=6)\n# ax.tick_params(axis='both', which='major', labelsize=6)\n# ax.set_title('Loop %i of %i' % (j + 1, Nb_loops))\n# ax.axhline(self.min_yield[j]).set_color('r')\n# fig.tight_layout()\n# print('saving'+make_file_name(dir_name=self.dir_name,file_description='loop_%i'%(j+1),fileformat='png'))\n# fig.savefig(make_file_name(dir_name=self.dir_name,file_description='loop_%i'%(j+1),fileformat='png'))\n# plt.close(fig)\n\n","sub_path":"ns_plot_modules.py","file_name":"ns_plot_modules.py","file_ext":"py","file_size_in_byte":14846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"104321681","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport autoencoder as ae\nimport sys\nsys.setrecursionlimit(100000)\npath = 'D:/Richard/ICP artifact rejection using representation/Artifact labeled ABP/int/'\n\nif __name__=='__main__':\n \"\"\"\n files = os.listdir(path)\n for f in files:\n sig, lab = ae.load_one_data(path + f)\n if not os.path.exists('img/ori/'+f.split('_'[0])):\n os.mkdir('img/ori/'+f.split('_')[0])\n if not os.path.exists('img/rep/'+f.split('_'[0])):\n os.mkdir('img/rep/'+f.split('_')[0])\n for i in range(len(lab)):\n cur_img = ae.signal_to_img(sig[i])\n \"\"\"\n signals, filenames = ae.load_data(path)\n total_image = []\n total_signal = []\n file_len_map = {}\n \n bef_cnt = 0\n for i in range(len(filenames)):\n filename = filenames[i].split('_')[0]\n imgs = ae.signal_to_img(signals[i])\n total_image.extend(imgs)\n total_signal.extend(signals[i])\n file_len_map[filename] = [bef_cnt, bef_cnt + len(imgs)]\n bef_cnt += len(imgs)\n #total_rep_imgs = ae.autoencoding_cnn(total_image, total_image, img_dim=64, encoding_dim=16)\n \n for k, v in file_len_map.items():\n npy_arr = []\n for i in range(v[0], v[1]):\n plt.figure(1)\n plt.imshow(total_image[i].reshape(64, 64))\n plt.savefig('img/ori_b/'+k+'_'+str(i-v[0])+'.png')\n plt.cla(); plt.clf()\n \n #plt.figure(1)\n #plt.imshow(total_rep_imgs[i].reshape(64, 64))\n #plt.savefig('img/rep_a/'+k+'_'+str(i-v[0])+'.png')\n \n #npy_arr.append(total_rep_imgs[i])\n #np.save('npy/'+k+'.abp.t.npy', npy_arr)\n","sub_path":"ICPAR/GenImg.py","file_name":"GenImg.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"330898957","text":"# -*- coding: UTF-8 -*-\n\n# Filename : 1001S02E04_control_flow_2.py\n# author by : @shen-huang\n# reference : [Python:文件的读取、创建、追加、删除、清空]\n# (https://blog.csdn.net/u010281626/article/details/53908099)\n# [Python print 输出到文件]\n# (https://blog.csdn.net/yageeart/article/details/38386121)\n# [Python 读取文件的三种方式]\n# (https://zhuanlan.zhihu.com/p/42784651)\n# [Python 指定编码格式创建、打开文件]\n# (https://blog.csdn.net/damys/article/details/79352410)\n\n# 使用 while 循环打印九九乘法表并用条件判断把偶数行去掉\n\nimport os\n\n# 原始输出会出现空行,故新建一个文件,重定向输出,再去掉多余的空行\n\n# 新建一个文件\n\nf = open('f_temp.txt', 'w', encoding='utf-8')\n\n# 会出现空行的输出,将其重定向,存入文件\n\ni = 1\nwhile (i < 10):\n if i % 2 != 0:\n j = 1\n while j <= i:\n print(j, '×', i, '=', i*j, sep='', end='\\t', file=f)\n j += 1\n i += 1\n print(file=f)\nprint(file=f)\n\n# 关闭文件\n\nf.close()\n\n# 打开文件,去掉多余的空行并输出,关闭文件\n\nf = open('f_temp.txt', encoding='utf-8')\n\nprint(f.read().replace('\\n\\n', '\\n'))\n\nf.close()\n\n# 删除文件\n\nos.remove('f_temp.txt')\n","sub_path":"exercises/1901100244/1001S02E04_control_flow_2.py","file_name":"1001S02E04_control_flow_2.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"593042084","text":"class Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n hash_map = dict()\n for idx, val in enumerate(nums):\n tmp = target - val\n if tmp in hash_map:\n return [hash_map[tmp], idx]\n hash_map[val] = idx\n","sub_path":"python/001 Two Sum.py","file_name":"001 Two Sum.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"278650941","text":"#!/usr/bin/env python\n\nimport rospy\nimport numpy as np\nfrom geometry_msgs.msg import Wrench\nfrom geometry_msgs.msg import Vector3\nfrom sensor_msgs.msg import Joy\n\n\ndef VectProduct(a,b):\n return Vector3((a.y * b.z) - (a.z * b.y),\n (a.z * b.x) - (a.x * b.z),\n (a.x * b.y) - (a.y * b.x)) \n\n# def VectScaling3(a,b,c):\n# x=a.x*b*c\n# y=a.y*b*c\n# z=a.z*b*c\n# return Vector3(x,y,z)\n\ndef VectScaling(a,b):\n x=a.x*b\n y=a.y*b\n z=a.z*b\n return Vector3(x,y,z)\n\ndef VectSum6(a,b,c,d,e,f):\n return Vector3(a.x+ b.x+ c.x+ d.x+ e.x+ f.x, \n a.y+ b.y+ c.y+ d.y+ e.y+ f.y,\n a.z+ b.z+ c.z+ d.z+ e.z+ f.z)\n\n# def VectSum3(a,b,c):\n# return Vector3(a.x+ b.x + c.x, \n# a.y+ b.y + c.y,\n# a.z+ b.z + c.z)\n\ndef VectSum2(a,b):\n return Vector3(a.x+ b.x , \n a.y+ b.y ,\n a.z+ b.z )\n\ndef SumForce(msg1):\n\n \n b=msg1.axes\n\n # initialize node\n rospy.init_node('PFD', anonymous = True)\n #### Setup MouseToJoy Publisher \n PFDPublisher = rospy.Publisher(\"PFD\", Wrench, queue_size = 1)\n rate = rospy.Rate(25) # 25hz\n msg = Wrench()\n\n dt=1/float(25)\n angle=30 * np.pi/180\n\n # Definition des vecteurs locaux comme sous Unity\n Vback = Vector3( 0, 0,-1)\n Vforward = Vector3( 0, 0, 1)\n Vdown = Vector3( 0,-1, 0)\n Vup = Vector3( 0, 1, 0)\n Vright = Vector3( 1, 0, 0)\n Vleft = Vector3(-1, 0, 0)\n\n ###Position CG###\n M1 = Vector3(-0.6, 0, -0.0925 )\n M2 = Vector3(-0.6, 0.08, 0.04625)\n M3 = Vector3(-0.6,-0.08, 0.04625)\n M4 = Vector3(-0.5, 0.08, -0.04625)\n M5 = Vector3(-0.5, 0, 0.04625)\n M6 = Vector3(-0.5,-0.08, -0.04625)\n \n #Moteur 1\n Fmot1 = Vector3(25,0,0)\n force1 = VectScaling(Fmot1, b[3]) \n torque1 = VectProduct(M1, force1)\n \n #Moteur 2\n Fmot2 = Vector3(25,0,0)\n force2 = VectScaling(Fmot2, b[3])\n torque2 = VectProduct(M2, force2)\n\n #Moteur 3\n Fmot3 = Vector3(25,0,0)\n force3 = VectScaling(Fmot3, b[3]);\n torque3 = VectProduct(M3, force3)\n\n #Moteur 4\n Fmot4 = VectScaling(Vector3( 0, -np.cos(angle), np.sin(angle)),0)\n force4 = VectScaling(Fmot4, b[2]) \n torque4 = VectProduct(M4, force4)\n\n #Moteur 5\n Fmot5 = Vector3(0,0,-10)\n force5 = VectScaling(Fmot5,b[1])\n torque5 = VectProduct(M5, force5)\n\n Fmot6 = VectScaling(Vector3( 0, np.cos(angle), np.sin(angle)),0)\n force6 = VectScaling(Fmot6, b[2]) \n torque6 = VectProduct(M6, force6)\n \n if(b[2]<0):\n #Moteur 4\n Fmot4 = VectScaling(Vector3( 0, -np.cos(angle), np.sin(angle)),10)\n force4 = VectScaling(Fmot4, -b[2]) \n torque4 = VectProduct(M4, force4)\n\n Fmot5 = Vector3(0,0,-5)\n force5 = VectScaling(Fmot5,-b[2])\n torque5 = VectProduct(M5, force5)\n\n if (b[2]>0):\n #Moteur 6\n Fmot6 = VectScaling(Vector3( 0, np.cos(angle), np.sin(angle)),10)\n force6 = VectScaling(Fmot6, b[2]) \n torque6 = VectProduct(M6, force6)\n\n Fmot5 = Vector3(0,0,-5)\n force5 = VectScaling(Fmot5,b[2])\n torque5 = VectProduct(M5, force5)\n\n if(b[1]<0):\n #Moteur 4\n Fmot4 = VectScaling(Vector3( 0, -np.cos(angle), np.sin(angle)),10)\n force4 = VectScaling(Fmot4, -b[1]) \n torque4 = VectProduct(M4, force4)\n\n Fmot6 = VectScaling(Vector3( 0, np.cos(angle), np.sin(angle)),10)\n force6 = VectScaling(Fmot6, -b[1]) \n torque6 = VectProduct(M6, force6)\n\n\n \n msg.force=VectSum6(force1,force2,force3,force4,force5,force6)\n msg.torque=VectSum6(torque1,torque2,torque3,torque4,torque5,torque6) \n \n #msg.force=VectSum3(force1,force2,force3)\n #msg.torque=VectSum3(torque1,torque2,torque3)\n '''\n rospy.loginfo(\"F1\")\n rospy.loginfo(force1)\n rospy.loginfo(\"M1\")\n rospy.loginfo(torque1)\n rospy.loginfo(\"F2\")\n rospy.loginfo(force2)\n rospy.loginfo(\"M2\")\n rospy.loginfo(torque2)\n rospy.loginfo(\"F3\")\n rospy.loginfo(force3)\n rospy.loginfo(\"M3\")\n rospy.loginfo(torque3)\n\n rospy.loginfo(\"F4\")\n rospy.loginfo(force4)\n rospy.loginfo(\"M4\")\n rospy.loginfo(torque4)\n \n rospy.loginfo(\"F5\")\n rospy.loginfo(force5)\n rospy.loginfo(\"M5\")\n rospy.loginfo(torque5)\n rospy.loginfo(\"F6\")\n rospy.loginfo(force6)\n rospy.loginfo(\"M6\")\n rospy.loginfo(torque6)\n '''\n rospy.loginfo(\"Force\")\n rospy.loginfo(msg.force)\n rospy.loginfo(\"Moment\")\n rospy.loginfo(msg.torque)\n \n PFDPublisher.publish(msg)\n rate.sleep()\n\ndef callback(msg):\n SumForce(msg)\n\n\n \ndef listener():\n\n # In ROS, nodes are uniquely named. If two nodes with the same\n # node are launched, the previous one is kicked off. The\n # anonymous=True flag means that rospy will choose a unique\n # name for our 'listener' node so that multiple listeners can\n # run simultaneously.\n rospy.init_node('PFD', anonymous=True)\n\n rospy.Subscriber(\"joy\", Joy, callback)\n\n # spin() simply keeps python from exiting until this node is stopped\n rospy.spin()\n\nif __name__ == '__main__':\n listener()","sub_path":"scripts/archive/joy_sub_ensta.py","file_name":"joy_sub_ensta.py","file_ext":"py","file_size_in_byte":5207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"238260351","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 ('ocpuser', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='NIFTIHeader',\n fields=[\n ('channel', models.ForeignKey(primary_key=True, serialize=False, to='ocpuser.Channel')),\n ('header', models.BinaryField(max_length=1024)),\n ('affine', models.BinaryField(max_length=1024)),\n ],\n options={\n 'db_table': 'nifti_header',\n 'managed': True,\n },\n ),\n migrations.AddField(\n model_name='channel',\n name='header',\n field=models.CharField(default=b'', max_length=8192, blank=True),\n ),\n ]\n","sub_path":"django/ocpuser/migrations/0002_auto_20150923_1526.py","file_name":"0002_auto_20150923_1526.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"539586676","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django .http import HttpResponse\nfrom django.shortcuts import redirect, render\nimport pandas as pd\nfrom .models import *\nfrom .thread import *\ndef excel_import(request):\n if request.method == \"POST\":\n excel_file = request.FILES['excel_file']\n \n handle_file = HandleExcel.objects.create(excel_file = excel_file)\n print(handle_file)\n\n stud_objs=list(Student.objects.all())\n df=pd.DataFrame(stud_objs)\n datas = df.to_excel('media/output/excel.xlsx')\n print(datas)\n return redirect('/home/excel-upload/')\n return render(request , 'excel-import.html')\n\nfrom django.http import HttpResponse\nfrom .admin import StudentResource\nfrom django.core.files.base import ContentFile\n\ndef export_data(request):\n if request.method == 'POST':\n # Get selected option from form\n file_format = request.POST['file-format']\n stu_resource = StudentResource()\n dataset = stu_resource.export()\n \n \n if file_format == 'XLS (Excel)':\n response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')\n response['Content-Disposition'] = 'attachment; filename=\"exported_data.xls\"'\n return response \n\n return render(request, 'excel.html')\n\n\ndef send_attachment(request):\n\n if request.method == 'POST':\n email = request.POST.get('email')\n name = request.POST.get('name')\n user_obj = Email(\n email = email, \n name = name,\n )\n user_obj.save()\n print(email)\n thread_obj = EmailAttchment(email,'Gopal')\n thread_obj.start()\n return HttpResponse('mail send please check your mail box')\n return render(request, 'sendmail.html')\n\ndef sendemail_toall(request):\n user_objs=Email.objects.all()\n for user_obj in user_objs:\n thread_obj = EmailAttchment(user_obj.email,'Gopal')\n thread_obj.start()\n return HttpResponse('mail send please check your mail box')\n return render(request, 'sendall.html')\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"69288783","text":"# exercise 6.2.1\n\nfrom pylab import *\nfrom import_data import *\nfrom scipy.io import loadmat\nimport sklearn.linear_model as lm\nfrom sklearn import cross_validation, tree\nfrom scipy import stats\nfrom import_data import *\nfrom pybrain.datasets import ClassificationDataSet\nfrom pybrain.tools.shortcuts import buildNetwork\nfrom pybrain.supervised.trainers import BackpropTrainer\nfrom pybrain.structure.modules import SoftmaxLayer\nfrom linear_regression import *\nimport neurolab as nl\n\ndata = Data()\ndata.normalize_data()\n\ny = np.matrix(data.remove_and_get_y('gdp_per_cap')).T\nX = np.matrix(data.X)\n\n#classNames = data.cont_classes\nattributeNames = data.attribute_names\n\nN, M = X.shape\n\n## Crossvalidation\n# Create crossvalidation partition for evaluation\nK = 10\nCV = cross_validation.KFold(N, K, shuffle=True)\n# CV = cross_validation.StratifiedKFold(y.A.ravel(),k=K)\n\n# Initialize variables\nError_ann = np.empty((K, 1))\nError_lin_reg = np.empty((K, 1))\nn_tested = 0\n\nk = 0\nfor train_index, test_index in CV:\n # extract training and test set for current CV fold\n X_train = X[train_index, :]\n y_train = y[train_index, :]\n X_test = X[test_index, :]\n y_test = y[test_index, :]\n\n ann = nl.net.newff([[-3, 3]] * M, [10, 1], [nl.trans.TanSig(), nl.trans.PureLin()])\n\n # train network\n train_error = ann.train(X_train, y_train, goal=0.5, epochs=10, show=200)\n y_est = ann.sim(X_test)\n Error_ann[k] = np.square(y_est - y_test).sum().astype(float) / y_test.shape[0]\n\n # train lin reg\n m = lm.LinearRegression().fit(X_train[:, best_selected_features], y_train)\n # Error_train_fs[k] = np.square(y_train - m.predict(X_train[:, best_selected_features])).sum() / y_train.shape[0]\n Error_lin_reg[k] = np.square(y_test - m.predict(X_test[:, best_selected_features])).sum() / y_test.shape[0]\n\n k += 1\n\n# Use T-test to check if classifiers are significantly different\n[tstatistic, pvalue] = stats.ttest_ind(Error_ann, Error_lin_reg)\nif pvalue <= 0.05:\n print('Classifiers are significantly different. (p={0})'.format(pvalue[0]))\nelse:\n print('Classifiers are not significantly different (p={0})'.format(pvalue[0]))\n\n# Boxplot to compare classifier error distributions\nfigure()\nsuptitle('ANN vs. Linear Regression', fontweight='bold')\nboxplot(np.bmat('Error_ann, Error_lin_reg'))\nxlabel('ANN vs. Linear Regression')\nylabel('Mean squared error')\nsavefig('img/t_test_regression.pdf')\nshow()\n","sub_path":"assignment_2/src/t_test_regression.py","file_name":"t_test_regression.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"467036394","text":" # -*- coding:utf-8 -*-\n\nimport os\nimport json\nimport cv2\nfrom subprocess import Popen,PIPE\napi_key=\"PxcWNl91AtsF51DiaeUhNYZXS18vu6_3\"\napi_secret=\"HHWh27sBEcjzm4Nta4ZEIMisjLhRX5vA\"\nouter_id=\"0x024\"\npath='./data/log'\n\ndef detect(image_file):\n result=Popen('curl -X POST \"https://api-cn.faceplusplus.com/humanbodypp/beta/detect\" -F \\\n \"api_key={api_key}\" -F \\\n \"api_secret={api_secret}\" -F \\\n \"image_file=@{image_file}\" -F \\\n \"return_attributes=gender,cloth_color\" '\n .format(api_key=api_key,api_secret=api_secret,image_file=image_file),shell=True,stdout=PIPE)\n wait=\"\"\n result=(result.stdout.read())\n with open(\"{path}/detect.json\".format(path=path),\"w+\") as f:\n f.write(result)\n with open(\"{path}/detect.json\".format(path=path)) as f:\n result=json.load(f)\n os.remove('{path}/detect.json'.format(path=path))\n return result\n\n# if __name__ == '__main__':\n # img=cv2.imread(\"20170720226458.jpg\")\n # result=detect(image_file=\"20170720226458.jpg\")\n # print result[\"humanbodies\"]\n # ft=cv2.freetype.createFreeType2()\n # ft.loadFontData(fontFileName='../data/font/simhei.ttf',id =0)\n # for i in range(0,len(result[\"humanbodies\"])):\n # humanbody_rectangle=result[\"humanbodies\"][i][\"humanbody_rectangle\"]\n # x=humanbody_rectangle[\"left\"]\n # y=humanbody_rectangle[\"top\"]\n # w=humanbody_rectangle[\"width\"]\n # h=humanbody_rectangle[\"height\"]\n # z=str(i)\n # img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,225,225),2)\n # cv2.putText(img, z, (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 100)\n\n # cv2.imwrite(\"1.png\",img)\n # gender=result[\"humanbodies\"][i][\"attributes\"][\"gender\"][\"value\"]\n # print gender","sub_path":"Ubuntu/facepp/BodyAPI.py","file_name":"BodyAPI.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"68328507","text":"from CvPythonExtensions import *\nfrom Locations import *\nfrom Events import events, handler\n\n\n@handler(\"kbdEvent\")\ndef checkUnitArt(eventType, key):\n\tkey = int(key)\n\n\tif eventType == events.EventKeyDown and key == int(InputTypes.KB_V) and events.bCtrl and events.bShift:\n\t\tfor iPlayer in players.all().barbarian():\n\t\t\tpPlayer = player(iPlayer)\n\t\t\t\n\t\t\tlEras = [iAncient, iMedieval, iIndustrial]\n\t\t\tfor iEra in lEras:\n\t\t\t\tpPlayer.setCurrentEra(iEra)\n\t\t\t\tfor iUnit in range(iNumUnits):\n\t\t\t\t\tunit = makeUnit(iPlayer, iUnit, tThebes)\n\t\t\t\t\tunit.kill(False, -1)","sub_path":"Assets/Python/Shortcuts.py","file_name":"Shortcuts.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"407959946","text":"\n\"\"\"\nThis spider is a Jobs2WebXML spider created on top of the CeviuXML Spider\nscrapy crawl jobs2web_xml -a extract=1 -a url=\"http://feeds.jobs2web.com/feeds/view?siteId=246&feedId=1729\"\nsample url:\n http://feeds.jobs2web.com/feeds/view?siteId=246&feedId=1729\n http://feeds.jobs2web.com/feeds/view?siteId=296&feedId=203\n\"\"\"\n\nimport ujson as json\nfrom brightcorp.spiders.ceviu_xml import CeviuXML\nfrom brightcorp.processors import ConvertDateString, Replace\n\n\nclass Jobs2WebXML(CeviuXML):\n\n follow_job_url = False\n name = 'jobs2web_xml'\n tag = 'job'\n\n load_functions = True\n load_exp_level = True\n load_industries = True\n load_jobtypes = True\n\n field_xpaths = {\n 'title': '//title/text()',\n 'url': '//url/text()',\n 'company': '//company/text()',\n 'description': '//description/node()',\n 'zip_code': '//postalcode/text()',\n }\n\n location_xpaths = ['//city/text()', '//state/text()', '//country/text()']\n refnum_xpath = ['//JobID/text()']\n date_xpath = {\n 'xpath': '//date/text()',\n 'processors': [ConvertDateString('%a, %d %m %Y %H:%M:%S GMT')]\n }\n loc_other_xpaths = ['//location/text()']\n function_xpath = '//JobFunctions/text() | //JobFunction/text()'\n exp_level_xpath = '//Experience_Level/text()'\n industry_xpath = '//Industries/text()'\n jobtype_xpath = '//Type/text()'\n\n # Here some of the job functions are empty.\n # These job functions obtained from seed urls.\n # Empty job functions specifies that those are present in seed url, but we dont have appropriate code for that right now.\n # If new job functions found, update this dict with appropriate code.\n functions_map = {\n \"Accounting\": 'ACCT',\n \"Administrative\": 'ADMN',\n \"Arts and Design\": 'CRE',\n \"Business Development\": 'BD',\n \"Community & Social Services\": 'CSS',\n \"Consulting\": 'CNSL',\n \"Education\": 'EDU',\n \"Engineering\": 'ENG',\n \"Engineering/Technology\": 'ENG',\n \"Entrepreneurship\": 'ENT',\n \"Finance\": 'FIN',\n \"Healthcare Services\": 'MED',\n \"Human Resources\": 'HR',\n \"Information Technology\": 'IT',\n \"Legal\": 'LGL',\n \"Logistics\": '', # empty\n \"Manufacturing\": 'MNFC',\n \"Marketing\": 'MKTG',\n \"Media & Communications\": 'PR',\n \"Military & Protective Services\": 'MPS',\n \"None\": '',\n \"Operations\": 'OPS',\n \"othr\": 'OTHR',\n \"Product Management\": 'PROD',\n \"Program & Product Management\": 'PPM',\n \"Purchasing\": 'BUY',\n \"Quality Assurance\": 'QA',\n \"Real Estate\": 'RE',\n \"Research\": 'RSCH',\n \"Risk Management\": '', # empty\n \"Sales\": 'SALE',\n \"Services\": '', # empty\n \"Support\": 'SUPP'\n }\n industry_map = {\n 'Financial Services': 43,\n 'Oil & Energy': 57,\n 'Pharmaceuticals': 15,\n }\n\n def load_functions_string(self, loader, func):\n if func:\n loader.add_value('functions', json.dumps([self.functions_map[func[0]]]))\n\n def load_exp_level_string(self, loader, exp_level):\n if exp_level:\n loader.add_value('experience_level', exp_level[0].upper(), Replace(' ', '_'))\n\n def load_ingested_industry_codes(self, loader, indus):\n if indus:\n industry_code = []\n for x in indus[0].split(',')[:self.max_industry_codes]:\n try:\n industry_code.append(int(x))\n except:\n industry_code.append(self.industry_map[x.strip()])\n loader.add_value(\n 'ingested_industry_codes', json.dumps(industry_code)\n )\n\n def load_jobtypes_string(self, loader, jobtype):\n if jobtype:\n loader.add_value('jobtype', jobtype[0].upper(), Replace(' ', '_'))\n","sub_path":"brightcorp/brightcorp/spiders/jobs2web_xml.py","file_name":"jobs2web_xml.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"648486254","text":"# encoding: utf-8\n# encoding: iso-8859-1\n# encoding: win-1252\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nimport sys\nimport os\nimport subprocess\nimport time\nimport socket\nfrom netaddr import *\nfrom pysnmp.entity.rfc3413.oneliner import cmdgen\nfrom pysnmp.hlapi import getCmd\n\napp = QApplication(sys.argv)\n\n\n#tread que lista as maquinas da rede é chamado por self.thread na linha 294\nclass RedesThread(QThread):\n def __init__(self, redes , parent=app):\n\n self.lista_de_redes = redes # passa a lista de ips\n\n QThread.__init__(self, parent)\n\n\n\n self.signal = SIGNAL(\"status\")\n self.start()\n\n def run(self):\n\n for host_ip in self.lista_de_redes:\n\n try:\n\n resposta = ()\n\n if os.name == 'nt': # ser for uma maquina windows (sistema nt) este trecho será executado\n\n resposta = subprocess.getstatusoutput('ping -n 1 %s' % host_ip)\n\n\n else: # ser for uma maquina sistema posix linux,mac etc.. este trecho será executado\n\n resposta = subprocess.getstatusoutput('ping -c 1 %s' % host_ip)\n\n texto = resposta[1] # retirando resposta da tupla no index 1\n ltexto = texto.lower() # todo texto transformado em letras minusculas para facilitar no codigo\n\n # Resposta para Destino inacessivel\n posi_inacessivel = ltexto.find('inacess')\n\n\n # Resposta para tempo esgotado\n posi_tempo_esgotado = ltexto.find('esgotado')\n inacessivel = ltexto[posi_inacessivel:posi_inacessivel + 7]\n\n tempo_esgotado = ltexto[posi_tempo_esgotado:posi_tempo_esgotado + 8]\n\n\n # testa se host inacessivel ou tempo esgotado\n if (inacessivel == 'inacess' or tempo_esgotado == 'esgotado'):\n\n # enviara comando para linha 300 a ser processado na linha 309\n self.emit(self.signal, 'INATIVO', host_ip, \"0\")\n\n else:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n porta = 22\n estado_porta = \"\"\n try:\n\n s.connect((host_ip, porta))\n estado_porta = 'Porta {} Aberta'.format(porta)\n except:\n estado_porta = 'Porta {} Fechada'.format(porta)\n\n s.close()\n self.emit(self.signal, 'ATIVO', host_ip, estado_porta)\n\n\n\n except subprocess.CalledProcessError:\n\n self.emit(self.signal, \"Erro de Procssamento\")\n\nclass JanelaMae(QMainWindow):\n count = 0\n\n def __init__(self, parent=None):\n super(JanelaMae, self).__init__(parent)\n self.mdi = QMdiArea()\n self.setCentralWidget(self.mdi)\n bar = self.menuBar()\n\n subWindBlackNight = QMdiSubWindow()\n subWindBlackNight.setWidget(BlackNight())\n self.mdi.addSubWindow(subWindBlackNight)\n\n arquivo = bar.addMenu(\"Arquivo\")\n arquivo.addAction(\"Nova Janela\")\n arquivo.addAction(\"Cascata\")\n arquivo.addAction(\"Encaixado\")\n arquivo.triggered[QAction].connect(self.windowaction)\n self.setWindowTitle(\"BlackNight v0.0.1\")\n subWindBlackNight.show()\n\n def windowaction(self, q):\n print(\"disparou\")\n\n\n if q.text() == \"Nova Janela\":\n JanelaMae.count = JanelaMae.count + 1\n sub = QMdiSubWindow()\n\n sub.setWidget(BlackNight())\n sub.setWindowTitle(\"Sub Janela\" + str(JanelaMae.count))\n self.mdi.addSubWindow(sub)\n sub.show()\n\n if q.text() == \"Cascata\":\n self.mdi.cascadeSubWindows()\n\n if q.text() == \"Encaixado\":\n self.mdi.tileSubWindows()\n\n\n\n\nclass BlackNight(QWidget):\n def __init__(self, pai=None):\n QWidget.__init__(self, pai)\n\n self.STATUS_FORMATO_ATIVO = \"      ® ATIVO \"\n self.STATUS_FORMATO_INATIVO = \"       INATIVO \"\n\n redes_global = []\n # Definindo a Janela\n\n\n self.setWindowTitle(\"BlackNight UNIRN - BSI Turma 2014\")\n self.setGeometry(200, 200, 820, 620)\n self.setFixedWidth(850)\n\n # Entrada de Dados\n self.inputIP = QLineEdit()\n self.inputMask = QLineEdit()\n self.inputIPAlvo = QLineEdit()\n\n self.le = QLabel(\"Hello\")\n\n # Comandos\n self.bntSRede = QPushButton(\"Calcular Rede\")\n self.connect(self.bntSRede, SIGNAL(\"clicked()\"), self.obterRedes)\n\n self.bntAlvo = QPushButton(\"Obter Info\")\n self.connect(self.bntAlvo, SIGNAL(\"clicked()\"),self.getDescHost)\n\n self.bntConect = QPushButton(\"Conectar no Alvo\")\n self.connect(self.bntConect, SIGNAL(\"clicked()\"), self.conectarAoHost)\n\n self.bntArq = QPushButton(\"Arquivo de Senhas\")\n self.connect(self.bntArq, SIGNAL(\"clicked()\"), self.lerSenhas)\n\n self.bntSRede.setFixedWidth(150)\n self.bntAlvo.setFixedWidth(150)\n\n # Saida de dados\n self.txtDisplay = QTextEdit()\n self.txtDisplay.setFixedHeight(600)\n self.txtDisplay.setFixedWidth(800)\n self.txtDisplay.setStyleSheet(\"QTextEdit {background-color:black;color:white}\")\n\n # Formatando e Organizando layout\n\n hbox = QHBoxLayout()\n vbox1 = QVBoxLayout()\n vbox2 = QVBoxLayout()\n\n vbox1.addWidget(QLabel(\"Infome o IP de Rede:\"))\n vbox1.addWidget(self.inputIP)\n vbox1.addWidget(QLabel(\"Mascara de Rede:\"))\n vbox1.addWidget(self.inputMask)\n\n vbox1.addWidget(self.bntSRede)\n vbox1.addWidget(self.inputIPAlvo)\n vbox1.addWidget(self.bntAlvo)\n vbox1.addWidget(self.bntArq)\n vbox1.addWidget(self.bntConect)\n vbox1.addStretch()\n\n # Saida\n vbox2.addWidget(QLabel(\"Saida do Processamento:\"))\n\n vbox2.addWidget(self.txtDisplay)\n vbox2.addStretch()\n\n hbox.addLayout(vbox1)\n hbox.addLayout(vbox2)\n\n self.setLayout(hbox)\n\n def conectarAoHost(self):\n\n alvoTexto = self.inputIPAlvo.text()\n alvo = alvoTexto[:15]\n\n ssh = subprocess.Popen([\"ssh\", \"%s\" % alvo,\"uname -a\"],\n shell=False,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n resposta = ssh.stdout.readlines()\n if resposta == []:\n erro = ssh.stderr.readlines()\n self.txtDisplay.setText(str(erro))\n else:\n self.txtDisplay.setText(str(resposta))\n\n\n\n\n\n def lerSenhas(self):\n arquivo = QFileDialog.getOpenFileName(self, 'Arquivo de Senhas', os.path.dirname(os.path.abspath(__file__)),\n \"Arquivos de Texto (*.txt)\")\n\n self.senhas = []\n\n print(os.path.dirname(os.path.abspath(__file__)) + 'arquivos/senhas.txt', 'r')\n\n try:\n\n\n if arquivo != None:\n\n with open(arquivo, 'r') as linhas:\n for line in linhas:\n self.senhas.append(line)\n linhas.close()\n\n else:\n\n\n\n with open(os.path.dirname(os.path.abspath(__file__)) + '\\arquivos\\senhas.txt', 'r')as linhas:\n for line in linhas:\n self.senhas.append(line)\n linhas.close()\n\n\n except IOError:\n print(\"Não Foi Possivel Abrir Arquivo para leitura\")\n print(\"Arquivo Não Encontrado\")\n\n\n def escrever(self, redes):\n self.txtDisplay.clear()\n\n TAMANHO = redes.size\n\n self.txtDisplay.append(\"Informações\")\n self.txtDisplay.append(\"===============\")\n self.txtDisplay.append(\n \"Mascara da Rede: %s\" % redes.netmask)\n self.txtDisplay.append(\n \"Numero de Hosts: %s\" % TAMANHO)\n self.txtDisplay.append(\n \"Faixa de IP: %s até %s \" % (\n redes[1], redes[redes.__len__() - 2]))\n self.txtDisplay.append(\n \"Broadcast: %s \" % redes[\n redes.__len__() - 1])\n\n self.txtDisplay.append(\":: Maquinas Online ::\")\n self.txtDisplay.append(\n \"=========================================================================\")\n\n def getDescHost(self):\n self.txtDisplay.clear()\n\n self.txtDisplay.append(\"Informação do Host\")\n\n alvoTexto = self.inputIPAlvo.text()\n alvo = alvoTexto[:15]\n cmdGen = cmdgen.CommandGenerator()\n\n errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(\n cmdgen.CommunityData('public', mpModel=0),\n cmdgen.UdpTransportTarget((alvo, 161)),\n cmdgen.MibVariable('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0'),\n cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0)\n )\n\n # Check for errors and print out results\n if errorIndication:\n self.txtDisplay.append(str(errorIndication))\n\n else:\n if errorStatus:\n\n self.txtDisplay.append(\n '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1] or '?'))\n\n\n else:\n for nome, val in varBinds:\n self.txtDisplay.append('%s = %s' % (nome.prettyPrint(), val.prettyPrint()))\n\n def calcularRedes(self, ipRede=\"127.0.0.1\", maskRede=\"30\"):\n netaddr = ipRede[:15] # endereço IP de rede\n netmask = maskRede.strip('/')[:15] # máscara /24 ou 255.255.255.0\n\n redes = IPNetwork(netaddr + '/' + netmask)\n\n self.escrever(redes)\n\n self.thread = RedesThread(redes)\n self.connect(self.thread, self.thread.signal, self.check_online)\n self.thread.start()\n\n\n def obterRedes(self):\n self.calcularRedes(self.inputIP.text(), self.inputMask.text())\n\n\n #chamado na linha 300 pela thread\n def check_online(self, status, ip, estado_porta):\n\n if status == 'INATIVO':\n self.txtDisplay.append(\"HOST %s %s\" % (ip, self.STATUS_FORMATO_INATIVO,))\n else:\n self.txtDisplay.append(\n \"HOST %s %s       %s \" % (\n ip, self.STATUS_FORMATO_ATIVO, estado_porta))\n\n\n\n\ndef main():\n\n ex = JanelaMae()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"480699817","text":"import asyncio\nimport traceback\nimport datetime\nimport re\nimport uuid\n\nSTATUS_CODES = {\n 200:\"OK\",\n 303:\"See Other\",\n 400:\"Bad Request\",\n 403:\"Forbidden\",\n 404:\"Not Found\",\n 500:\"Internal Server Error\",\n}\n\nSESSION = { # セッションを管理するグローバル変数\n\n}\n\nclass Article(object):\n def __init__(self, article_id, title, body, user):\n self.article_id = article_id\n self.title = title\n self.body = body\n self.date = datetime.datetime.now()\n self.user = user\n\nclass User(object):\n def __init__(self, name):\n self.name = name\n\nclass DBM(object):\n def __init__(self):\n self.articles = [\n Article(1, \"あああ\", \"いいい\", \"sato\"),\n Article(2, \"ううう\", \"えええ\", \"takahashi\")\n ]\n self.article_id_max = 2\n\n self.users = [\n User(\"sato\"),\n User(\"takahashi\")\n ]\n\n def add_article(self, title, body, user_name):\n self.article_id_max = self.article_id_max + 1\n article = Article(self.article_id_max, title, body, user_name)\n self.articles.append(article)\n return article\n\n def delete_article(self, article_id):\n target_idx = None\n for i, article in enumerate(self.articles):\n if article.article_id == article_id:\n target_idx = i\n break\n if target_idx is None:\n return False\n else:\n del self.articles[target_idx]\n return True\n\n def get_article(self, article_id):\n for article in self.articles:\n if article.article_id == article_id:\n return article\n return None\n\n def get_articles(self):\n return self.articles\n\n def get_user(self, user_name):\n for user in self.users:\n if user_name == user.name:\n return user\n return None\n\nclass NaiveHttpResponse(object):\n dbm = DBM()\n\n @classmethod\n def header_lines(cls, request, data=None):\n header = ['Content-Type: text/html']\n if request[\"cookie\"] is None:\n now = datetime.datetime.now()\n now - datetime.timedelta(hours=9) + datetime.timedelta(minutes=1)\n cstr = 'Set-Cookie: SESSION_ID={}; expires={}; path=/;'.format(\n str(uuid.uuid4()), now.strftime(\"%a, %d-%h-%Y %H:%M:%S GMT\"))\n header.append(cstr)\n if data:\n for k, v in data.items():\n header.append(\"{}: {}\".format(k,v))\n return header\n\n @classmethod\n def status_line(cls, status_code):\n return \"HTTP/1.1 {} {}\".format(\n str(status_code), STATUS_CODES[status_code]\n )\n\n @classmethod\n def get_request_user(cls, request):\n user = None\n if request[\"cookie\"]:\n session_id = request[\"cookie\"][\"key_values\"].get(\"SESSION_ID\")\n if session_id and SESSION.get(session_id):\n user = cls.dbm.get_user(SESSION[session_id])\n return user\n\n @classmethod\n def start_session(cls, request, user):\n if user and request[\"cookie\"] and request[\"cookie\"][\"key_values\"].get(\"SESSION_ID\"):\n SESSION[request[\"cookie\"][\"key_values\"][\"SESSION_ID\"]] = user.name\n return True\n return False\n\n @classmethod\n def delete_session(cls, request):\n if request[\"cookie\"]:\n session_id = request[\"cookie\"][\"key_values\"].get(\"SESSION_ID\")\n if session_id and SESSION.get(session_id):\n del SESSION[session_id]\n return True\n return False\n\n @classmethod\n def http500(cls):\n result = '\\r\\n'.join([\n 'HTTP/1.1 500 Internal Server Error',\n 'Content-Type: text/html',\n '',\n '',\n '',\n '',\n 'Internal Server Error',\n ''\n ])\n return result\n\n @classmethod\n def http404(cls):\n result = '\\r\\n'.join([\n 'HTTP/1.1 404 Not Found',\n '',\n '',\n '',\n '',\n '',\n '',\n 'Not Found',\n ''\n ])\n return result\n\n @classmethod\n def http400(cls):\n result = '\\r\\n'.join([\n 'HTTP/1.1 400 Bad Request',\n 'Content-Type: text/html',\n '',\n '',\n '',\n '',\n '',\n '',\n 'Bad Request',\n ''\n ])\n return result\n\n\n def create_response(self, request):\n if (request[\"path\"] == []):\n return self.redirect_index(request)\n elif (request[\"method\"] == \"POST\") and (request[\"path\"] == [\"login\"]):\n return self.login(request)\n elif (request[\"method\"] == \"POST\") and (request[\"path\"] == [\"logout\"]):\n return self.logout(request)\n elif (request[\"method\"] == \"GET\") and (request[\"path\"] == [\"articles\"]):\n return self.index(request)\n elif (request[\"method\"] == \"GET\") and (len(request[\"path\"]) == 2) and (request[\"path\"][0] == \"users\"):\n return self.user_page(request, request[\"path\"][1])\n elif (request[\"method\"] == \"POST\") and (request[\"path\"] == [\"articles\"]):\n return self.post_articles(request)\n elif (request[\"method\"] == \"POST\") and (request[\"path\"] == [\"articles\", \"delete\"]):\n article_id = int(request[\"data\"].get(\"article_id\"))\n return self.delete_article(request, article_id)\n else:\n return self.http404()\n\n def login(self, request):\n if request[\"data\"].get(\"user_name\"):\n user = self.dbm.get_user(request[\"data\"][\"user_name\"])\n if user:\n result = self.start_session(request, user)\n if result:\n hdata = {'Location': 'http://localhost:8000/users/{}'.format(user.name)}\n result = '\\r\\n'.join(\n [self.status_line(303)] + self.header_lines(request, hdata) + ['']\n )\n return result\n return self.http400()\n\n def logout(self, request):\n self.delete_session(request)\n return self.redirect_index(request)\n\n def redirect_index(self, request):\n hdata = {'Location': 'http://localhost:8000/articles/'}\n result = '\\r\\n'.join(\n [self.status_line(303)] + self.header_lines(request, hdata) + ['']\n )\n return result\n\n def index(self, request):\n request_user = self.get_request_user(request)\n\n table = '''\n \n \n \n \n \n \n \n \n '''\n for article in self.dbm.get_articles():\n table += '''\n \n \n \n \n \n \n \n '''.format(article.user, article.user, article.title, article.body, str(article.date), article.article_id)\n table += '
UserTitleBodyDate
{}{}{}{}\n
\n \n \n
\n
'\n\n article_form = ''\n if request_user is not None:\n article_form = '''\n
\n \n \n \n
\n '''\n\n mypage = ''\n if request_user is not None:\n mypage = 'マイページ'.format(\n request_user.name)\n\n logout_form = ''\n if request_user is not None:\n logout_form = '''\n
\n \n
\n '''\n\n login_form = ''\n if request_user is None:\n login_form = '''\n
\n \n \n
\n '''\n\n content = [\n '',\n '',\n '',\n '',\n '',\n '',\n table,\n article_form,\n mypage,\n logout_form,\n login_form,\n '',\n ''\n ]\n\n result = '\\r\\n'.join(\n [self.status_line(200)] + self.header_lines(request) + [''] + content\n )\n return result\n\n def delete_article(self, request, article_id):\n user = self.get_request_user(request)\n article = self.dbm.get_article(article_id)\n\n if article is None:\n return self.http404()\n\n elif (user is not None) and (user.name == article.user):\n result = self.dbm.delete_article(article_id)\n return self.index(request)\n return self.http400()\n\n def post_articles(self, request):\n user = self.get_request_user(request)\n if request[\"data\"].get(\"title\") and request[\"data\"].get(\"body\") and user:\n article = self.dbm.add_article(\n request[\"data\"][\"title\"], request[\"data\"][\"body\"], user.name)\n return self.index(request)\n else:\n return self.http400()\n\n\n def user_page(self, request, target_user_name):\n target_user = self.dbm.get_user(target_user_name)\n if target_user is None:\n return self.http404()\n request_user = self.get_request_user(request)\n is_mypage = False\n if (request_user is not None) and (request_user.name == target_user.name):\n is_mypage = True\n\n table = '''\n \n \n \n \n \n \n \n \n '''\n for article in self.dbm.get_articles():\n if article.user != target_user.name:\n continue\n delform = ''\n if is_mypage:\n delform = '''\n \n \n \n \n '''.format(article.article_id)\n table += '''\n \n \n \n \n \n \n \n '''.format(article.user, article.title, article.body, str(article.date), delform)\n table += '
UserTitleBodyDate
{}{}{}{}{}
'\n\n article_form = ''\n if is_mypage:\n article_form = '''\n
\n \n \n \n
\n '''\n content = [\n '',\n '',\n '',\n '',\n '',\n '',\n table,\n article_form,\n ''\n '',\n ''\n ]\n\n result = '\\r\\n'.join(\n [self.status_line(200)] + self.header_lines(request) + [''] + content\n )\n return result\n\nclass NaiveHttpParser(object):\n @classmethod\n def unquote(cls, inputstr):\n s = bytes()\n i = 0\n while i < len(inputstr):\n if inputstr[i] == \"%\":\n s += int(inputstr[i+1:i+3], base=16).to_bytes(1, \"little\")\n i += 3\n else:\n s += inputstr[i].encode(\"ascii\")\n i += 1\n return s.decode(\"utf-8\")\n\n @classmethod\n def parse_path(cls, path_str):\n return [unit for unit in path_str.split(\"/\") if bool(unit)]\n\n @classmethod\n def parse_query(cls, query):\n result = {}\n for kv_str in query.split(\"&\"):\n kv = kv_str.split(\"=\")\n if len(kv) != 2:\n raise cls.ParseError()\n result[cls.unquote(kv[0])] = cls.unquote(kv[1])\n return result\n\n @classmethod\n def _set_header_data(cls, result, key, value):\n if key == \"Cookie\":\n result[\"cookie\"] = cls.parse_cookie(value)\n\n @classmethod\n def parse_cookie(cls, cookie_str):\n key_values = {}\n metadata = {\"expires\": None, \"domain\": None, \"path\":None, \"secure\":None}\n\n for cookie_content in cookie_str.split(\"; \"):\n if cookie_content == \"secure\":\n metadata[\"secure\"] = True\n else:\n ckv = cookie_content.split(\"=\")\n if len(ckv) != 2:\n raise cls.ParseError()\n elif ckv[0] in metadata:\n metadata[ckv[0]] = ckv[1]\n else:\n key_values[ckv[0]] = ckv[1]\n if not key_values:\n raise cls.ParseError()\n return {\"key_values\": key_values, \"metadata\": metadata}\n\n @classmethod\n def add_dict(cls, d_target, d_source):\n for k,v in d_source.items():\n d_target[k] = v\n\n @classmethod\n def parse_request(cls, message):\n result = {\n \"method\": None,\n \"path\": [],\n \"query\": {},\n \"data\": {},\n \"cookie\": None,\n \"header\": {},\n }\n\n lines = list(message.splitlines())\n req = lines[0].split(\" \")\n try:\n if len(req) != 3:\n raise cls.ParseError()\n\n if req[0] not in [\"get\", \"post\", \"GET\", \"POST\"]:\n raise cls.ParseError()\n result[\"method\"] = req[0].upper()\n\n url = req[1].split(\"?\")\n if len(url) == 1:\n result[\"path\"] = cls.parse_path(url[0])\n elif len(url) == 2:\n result[\"path\"] = cls.parse_path(url[0])\n result[\"query\"] = cls.parse_query(url[1])\n else:\n raise cls.ParseError()\n\n is_header = True\n for line in lines[1:]:\n if not line:\n is_header = False\n elif is_header:\n match = re.match(\"[^:]+:\", line)\n if match:\n hkey = line[:match.end()-1]\n vstart = match.end()\n while line[vstart] == \" \":\n vstart += 1\n hvalue = line[vstart:]\n result[\"header\"][hkey] = hvalue\n cls._set_header_data(result, hkey, hvalue)\n else:\n cls.add_dict(result[\"data\"], cls.parse_query(line))\n\n except (cls.ParseError, ValueError):\n return None\n return result\n class ParseError(Exception):\n pass\n\nclass NaiveHttpServerProtocol(asyncio.Protocol):\n nhr = NaiveHttpResponse()\n def connection_made(self, transport):\n peername = transport.get_extra_info('peername')\n print('Connection from {}'.format(peername))\n self.transport = transport\n\n def data_received(self, data):\n try:\n message = data.decode()\n request = NaiveHttpParser.parse_request(message)\n if request is None:\n response = self.nhr.http500()\n else:\n response = self.nhr.create_response(request)\n except Exception as e:\n print(traceback.format_exc())\n response = self.nhr.http500()\n else:\n print('RECEIVE--------------------------')\n for mline in message.splitlines():\n print(mline)\n print('---------------------------------')\n print('RESPONSE-------------------------')\n for line in response.splitlines():\n if not line:\n break\n print(line)\n print('---------------------------------')\n\n self.transport.write(response.encode(\"utf-8\"))\n self.transport.close()\n\nloop = asyncio.get_event_loop()\n# Each client connection will create a new protocol instance\n#coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8000)\ncoro = loop.create_server(NaiveHttpServerProtocol, '0.0.0.0', 8000)\nserver = loop.run_until_complete(coro)\n\n# Serve requests until Ctrl+C is pressed\nprint('Serving on {}'.format(server.sockets[0].getsockname()))\ntry:\n loop.run_forever()\nexcept KeyboardInterrupt:\n pass\n\n# Close the server\nserver.close()\nloop.run_until_complete(server.wait_closed())\nloop.close()\n","sub_path":"naive_http_server.py","file_name":"naive_http_server.py","file_ext":"py","file_size_in_byte":17356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"448758971","text":"import random\n\nsuits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\nranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven',\n 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\nvalues = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7,\n 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}\n\nplaying = True\n\nclass Card:\n\n def __init__(self, suit, rank):\n self.suit = suit\n self.rank = rank\n\n def __str__(self):\n return f'{self.rank} of {self.suit}'\n\n\nclass Deck:\n\n def __init__(self):\n self.deck = []\n for suit in suits:\n for rank in ranks:\n self.deck.append(Card(suit, rank))\n\n def __str__(self):\n return f'{self.deck}'\n\n def suffle(self):\n random.shuffle(self.deck)\n\n def deal(self):\n return f'{self.deck.pop(0)}'\n\nclass Hand:\n\n def __init__(self):\n self.cards = []\n self.value = 0\n self.aces = 0\n\n def __str__(self):\n return f'{self.cards}\\nValue: {self.value}'\n\n def add_card(self, card):\n self.cards.append(card)\n\n card_string_split = card.split()\n self.value += values[card_string_split[0]]\n\n if card_string_split[0] == 'Ace':\n self.aces += 1\n\n def adjust_for_ace(self):\n if self.value > 21 & self.aces > 0:\n self.value -= (10 * self.aces)\n\n\nclass Chips:\n\n def __init__(self):\n self.total = 100.0\n self.bet = 0\n\n def __str__(self):\n return f'You have {self.total} in Chips.'\n\n def win_bet(self):\n self.total += self.bet\n \n def lose_bet(self):\n self.total -= self.bet\n\ndef place_bet(chips):\n\n while True:\n try:\n bet = float(input('Place your bet: '))\n if chips.total - bet < 0:\n print(f'Insufficent chips available.\\nBet: {bet}\\nAvailable chips: {chips.total}')\n continue\n else:\n chips.bet = bet\n print(f'You bet {bet}.')\n break\n except TypeError:\n print(f'{bet} is not a valid bet.')\n except:\n print(f'An unknown error occured. Please try again.')\n\ndef hit(deck,hand):\n card_to_add = deck.deal()\n hand.add_card(card_to_add)\n hand.adjust_for_ace\n print(f'\\nDealt {card_to_add}')\n\ndef hit_or_stand(deck,hand):\n global playing\n\n while True:\n try:\n action = input('\\nWould you like to Hit or Stand? ').capitalize()\n except:\n print(f'An error occured. Please try again.')\n else:\n if action in ('Hit', 'Stand'):\n break\n else:\n print(f'Invalid input. Please try again.')\n \n if action == 'Hit':\n hit(deck,hand)\n else:\n print(f'\\nPlayer stands with {hand.value}.\\nDealer plays...')\n playing = False\n\n \ndef show_some_cards(player,dealer):\n\n print(f\"\\nDealer's hand:\\n, {dealer.cards[1]}\")\n print(\"\\nPlayer's hand:\")\n print(*player.cards, sep=', ')\n print(f\"Player's Value: {player.value}\")\n\ndef show_all_cards(player,dealer):\n\n print(\"\\nDealer's hand:\")\n print(*dealer.cards, sep=', ')\n print(f\"Dealer's Value: {dealer.value}\")\n print(\"\\nPlayer's hand:\")\n print(*player.cards, sep=', ')\n print(f\"Player's Value: {player.value}\")\n\ndef player_busts(chips):\n chips.lose_bet() \n print(f'\\nPlayer is bust! Player lost {chips.bet}')\n\ndef player_wins(chips):\n chips.win_bet()\n print(f'\\nPlayer wins! Player wins {chips.bet}')\n \ndef dealer_busts(chips):\n chips.win_bet()\n print(f'\\nDealer bust! Player wins {chips.bet}')\n\ndef dealer_wins(chips):\n chips.lose_bet()\n print(f'\\nDealer Wins! Player lost {chips.bet}')\n\ndef push():\n print(f'\\nPush! No winning bet.')\n\ndef blackjack(chips):\n chips.bet = chips.bet * 1.5 # Blackjack wins one and one-half times the bet\n chips.win_bet()\n print(f'Player has Blackjack! Player wins {chips.bet}')\n\n\n'''\nInitialize game outside of the while loop to:\n 1. Only show the welcome message once.\n 2. Initialize the Player's chips object once.\n'''\n# Print an opening statement\nprint(f'\\nWelcome to Blackjack!')\ninput('\\nPlease any key to begin.')\n\n# Set up the Player's chips\nplayer_chips = Chips()\n\nwhile True:\n \n # Create & shuffle the deck, deal two cards to each player\n playing_deck = Deck()\n playing_deck.suffle()\n\n player_hand = Hand()\n dealer_hand = Hand()\n\n player_hand.add_card(playing_deck.deal())\n dealer_hand.add_card(playing_deck.deal())\n player_hand.add_card(playing_deck.deal())\n dealer_hand.add_card(playing_deck.deal())\n \n # Prompt the Player for their bet\n print(player_chips)\n place_bet(player_chips)\n \n # Show cards (but keep one dealer card hidden)\n show_some_cards(player_hand,dealer_hand)\n \n # Check for player Blackjack (can only occur on the two original dealt cards)\n if player_hand.value == 21:\n playing = False\n if dealer_hand.value == 21:\n show_all_cards(player_hand,dealer_hand) # Show that the dealer has blackjack too!\n push()\n else:\n blackjack(player_chips)\n\n while playing:\n\n # Prompt for Player to Hit or Stand\n hit_or_stand(playing_deck,player_hand)\n \n # Show cards (but keep one dealer card hidden)\n show_some_cards(player_hand,dealer_hand)\n \n # If player's hand exceeds 21, run player_busts() and break out of loop\n if player_hand.value > 21:\n player_busts(player_chips)\n break\n\n # If Player hasn't busted, play Dealer's hand until Dealer reaches 17\n if player_hand.value < 21: \n while dealer_hand.value < 17:\n hit(playing_deck,dealer_hand)\n\n # Show all cards\n show_all_cards(player_hand,dealer_hand)\n\n # Run different winning scenarios\n if dealer_hand.value > 21:\n dealer_busts(player_chips)\n\n elif dealer_hand.value > player_hand.value:\n dealer_wins(player_chips)\n\n elif dealer_hand.value < player_hand.value:\n player_wins(player_chips)\n else:\n push()\n\n # Inform Player of their chips total \n print(player_chips)\n\n # Ask to play again\n while True:\n try:\n play_again = input(\"Do you wish to play again? Y/N: \").capitalize()\n except:\n f'Invalid input. Please try again.'\n else:\n if play_again in ('Y', 'N'):\n break\n else:\n continue\n if play_again == 'Y':\n playing = True\n continue\n else:\n print('Thanks for playing!')\n break\n\n\n\n\n\n\n\n\n","sub_path":"08-Milestone Project - 2/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":6760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"329203938","text":"class Email_gen():\n def __init__(self, fname, lname):\n self.fname = fname\n self.lname = lname\n\n def get_email(self):\n print(self.fname.lower() + \".\" + self.lname.lower() + \"@gmail.com\")\n\n\nfirst_name = input(\"Enter first name: \")\nlast_name = input(\"Enter last name: \")\nobj = Email_gen(first_name, last_name)\nprint(obj.get_email())","sub_path":"genemail.py","file_name":"genemail.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"436055514","text":"from PIL import ImageGrab,ImageOps\r\nimport pyautogui,time\r\nfrom numpy import *\r\ntime.sleep(1)\r\nclass cord:\r\n replay=(530,257)\r\n dino=(231,264)\r\n\r\n\r\ndef restart():\r\n pyautogui.click(cord.replay)\r\ndef space():\r\n pyautogui.keyDown('space')\r\n time.sleep(0.01)\r\n print('jump')\r\n pyautogui.keyDown('space')\r\n\r\n\r\ndef imagegrab():\r\n box=(cord.dino[0]+60,cord.dino[1],cord.dino[0]+100,cord.dino[1]+30)\r\n image=ImageGrab.grab(box)\r\n grayImage=ImageOps.grayscale(image)\r\n a=array(grayImage.getcolors())\r\n print(a.sum())\r\n return a.sum()\r\ndef main():\r\n restart()\r\n while True:\r\n if imagegrab()!=1455:\r\n space()\r\n time.sleep(0.1)\r\nmain()\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"540635080","text":"from deepface import DeepFace\nfrom keras.models import load_model\nfrom keras.preprocessing.image import img_to_array\nimport cv2\nimport numpy as np\n\n\ndef deep_face(image, actions):\n # os.chdir('..')\n try:\n res = DeepFace.analyze(image, actions)\n except Exception as e:\n print('Exception reading the image', e)\n exit()\n # print('deep_face->', res)\n output = {}\n if 'emotion' in actions:\n output['Emotion'] = res['dominant_emotion']\n if 'age' in actions:\n output['Age'] = res['age']\n if 'gender' in actions:\n output['Gender'] = res['gender']\n if 'race' in actions:\n output['Race'] = res['dominant_race']\n\n return output\n\n\ndef pre_train(raw_image):\n face_classifier = cv2.CascadeClassifier('./docs/haarcascade_frontalface_default.xml')\n classifier = load_model('./models/take2_model_E25.h5')\n # BGR\n RED = (0, 0, 255)\n GREEN = (30, 238, 30)\n BLUE = (242, 184, 48)\n PURPLE = (211, 0, 148)\n GRAY = (128, 128, 128)\n WHITE = (255, 255, 255)\n\n class_labels = ['Angry', 'Happy', 'Neutral', 'Sad', 'Surprise']\n emotion_color_map = {'Angry': RED, 'Happy': GREEN, 'Surprise': BLUE, 'Neutral': PURPLE, 'Sad': GRAY}\n\n image = cv2.imread(raw_image, 1)\n gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n faces = face_classifier.detectMultiScale(gray_image, 1.3, 5)\n\n for (x, y, w, h) in faces:\n roi_gray = gray_image[y:y + h, x:x + w]\n roi_gray = cv2.resize(roi_gray, (48, 48), interpolation=cv2.INTER_AREA)\n\n if np.sum([roi_gray]) != 0:\n roi = roi_gray.astype('float') / 255.0\n roi = img_to_array(roi)\n roi = np.expand_dims(roi, axis=0)\n prediction = classifier.predict(roi)[0]\n # print(\"prediction = \", prediction)\n label = class_labels[prediction.argmax()]\n # print(\"prediction max = \", prediction.argmax())\n cv2.rectangle(image, (x, y), (x + w, y + h), emotion_color_map[label], 2)\n print(\"Emotion = \", label, \"\\n\")\n label_position = (x, y)\n cv2.rectangle(image, (x, y), (x + int(w / 2.5), y - int(h / 12)), emotion_color_map[label], -1)\n cv2.putText(image, label, label_position,\n cv2.FONT_HERSHEY_SIMPLEX, 1, WHITE, 2)\n\n else:\n print('No face found')\n cv2.putText(image, 'No Face Found', (20, 60),\n cv2.FONT_HERSHEY_SIMPLEX, 1, WHITE, 3)\n return None\n cv2.imshow(\"Emotion Detector - Press 'q' to quit\", image)\n while cv2.waitKey(0) != ord('q'):\n pass\n cv2.destroyAllWindows()\n\n\n# print(pre_train('/Users/apple/PycharmProjects/major1/static/uploads/Scarlett_Johanssen_Meme_Banner.jpg'))\n","sub_path":"logic/imageAnalyzer.py","file_name":"imageAnalyzer.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"618258885","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nA WSGI application entry.\n'''\n\nimport logging; logging.basicConfig(level=logging.INFO)\nimport os, time\nfrom datetime import datetime\n\nfrom transwarp import db\nfrom transwarp.web import WSGIApplication, Jinja2TemplateEngine\n\nfrom config import configs\n\ndef datetime_filter(t):\n\tdelta = int(time.time()-t)\n\tif delta < 60:\n\t\treturn u'1 minute ago'\n\tif delta < 3600:\n\t\treturn u'%s minutes ago' % (delta//60)\n\tif delta < 86400:\n\t\treturn u'%s %s ago' % (delta//3600, 'hours' if delta//3600>1 else 'hour')\n\tif delta < 604800:\n\t\treturn u'%s %s ago' % (delta//86400, 'days' if delta//86400>1 else 'day')\n\tdt = datetime.fromtimestamp(t)\n\treturn u'%s-%s-%s' % (dt.year, dt.month, dt.day)\n\n# init db:\ndb.create_engine(**configs.db)\n\n# init wsgi app:\nwsgi = WSGIApplication(os.path.dirname(os.path.abspath(__file__)))\n# init Jinja2 template engine\ntemplate_engine = Jinja2TemplateEngine(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'))\ntemplate_engine.add_filter('datetime', datetime_filter)\n\nwsgi.template_engine = template_engine\n\n# load url func with @get and @post\nimport urls\nwsgi.add_module(urls)\n\n# start the server at port 9000\nif __name__ == '__main__':\n\twsgi.run(9000, host='0.0.0.0')\nelse:\n\tapplication = wsgi.get_wsgi_application()","sub_path":"www/wsgiapp.py","file_name":"wsgiapp.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"210894505","text":"\n\n#calss header\nclass _FUMIGATOR():\n\tdef __init__(self,): \n\t\tself.name = \"FUMIGATOR\"\n\t\tself.definitions = [u'a person who uses chemicals to remove harmful insects or bacteria from buildings']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_fumigator.py","file_name":"_fumigator.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"648543234","text":"import argparse\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport hmmlearn.hmm as hmm\nimport scipy as sp\n\n\ndef get_posterior(inference_result, num_states):\n unnormalized_log_weights = inference_result[:, 0]\n normalized_log_weights = unnormalized_log_weights - \\\n sp.misc.logsumexp(unnormalized_log_weights)\n normalized_weights = np.exp(normalized_log_weights)\n\n particle_values = inference_result[:, 1:]\n\n num_timesteps = np.shape(particle_values)[1]\n\n normalized_weights_duplicated = np.tile(\n np.reshape(normalized_weights, (-1, 1)), reps=(1, num_timesteps)\n )\n\n posterior = np.zeros((num_states, num_timesteps))\n for state in range(num_states):\n posterior[state] = np.sum(\n normalized_weights_duplicated * (particle_values == state), axis=0\n )\n\n return posterior\n\n\ndef get_sum_kl(posterior_1, posterior_2, epsilon=1e-10):\n return np.sum(\n posterior_1 * (\n np.log(posterior_1 + epsilon) - np.log(posterior_2 + epsilon)\n )\n )\n\n\ndef get_sum_l2(posterior_1, posterior_2):\n return np.sum(np.sqrt(np.sum((posterior_1 - posterior_2)**2, axis=0)))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset-num-list', nargs='+', type=int,\n help='space separated list of dataset numbers')\n parser.add_argument('--num-particles-list', nargs='+', type=int,\n help='space separated list of number of particles')\n parser.add_argument('--algorithms', nargs='+', type=str,\n help='space separated list of algorithms')\n args = parser.parse_args()\n\n model = np.genfromtxt('model.csv', delimiter=',')\n num_states = np.shape(model)[1]\n my_hmm = hmm.GaussianHMM(n_components=num_states, covariance_type='full')\n my_hmm.startprob_ = model[0]\n my_hmm.transmat_ = model[1:(num_states + 1)]\n my_hmm.means_ = np.reshape(model[num_states + 1], (-1, 1))\n my_hmm.covars_ = np.reshape(model[num_states + 2], (-1, 1, 1))\n\n true_posteriors = {}\n posteriors = {}\n data = {}\n for dataset_num in args.dataset_num_list:\n data[dataset_num] = np.genfromtxt(\n 'data_{}.csv'.format(dataset_num), delimiter=','\n )\n true_posteriors[dataset_num] = np.transpose(\n my_hmm.predict_proba(np.reshape(data[dataset_num], (-1, 1)))\n )\n posteriors[dataset_num] = {}\n\n for num_particles in args.num_particles_list:\n posteriors[dataset_num][num_particles] = {}\n\n for algorithm in args.algorithms:\n inference_result = np.genfromtxt('{}_{}_{}.csv'.format(\n algorithm, dataset_num, num_particles\n ), delimiter=',')\n if len(np.shape(inference_result)) == 1:\n inference_result = np.reshape(inference_result, (1, -1))\n\n posteriors[dataset_num][num_particles][algorithm] = \\\n get_posterior(inference_result, num_states)\n\n # Plot inference_{dataset_num}_{num_particles}.pdf\n for dataset_num in args.dataset_num_list:\n for num_particles in args.num_particles_list:\n fig = plt.figure()\n fig.suptitle('{} particle{}'.format(\n num_particles, '' if num_particles == 1 else 's'\n ), fontsize=14, x=0.4, horizontalalignment='center')\n\n gs = matplotlib.gridspec.GridSpec(len(args.algorithms) + 1, 2)\n axs = [plt.subplot(gs[i, :-1])\n for i in range(len(args.algorithms) + 1)]\n colorbar_ax = plt.subplot(gs[:, -1], aspect=50)\n\n temp = axs[0].imshow(\n true_posteriors[dataset_num], clim=[0, 1]\n )\n axs[0].grid(False)\n axs[0].set_ylabel('State')\n axs[0].set_title('Ground Truth', fontsize=12)\n axs[0].set_xticks([])\n axs[0].set_yticks(range(num_states))\n\n for ax, algorithm in zip(axs[1:], args.algorithms):\n temp = ax.imshow(\n posteriors[dataset_num][num_particles][algorithm],\n clim=[0, 1]\n )\n ax.grid(False)\n ax.set_ylabel('State')\n ax.set_title(algorithm.upper(), fontsize=12)\n ax.set_xticks([])\n ax.set_yticks(range(num_states))\n\n axs[-1].set_xticks(np.arange(len(data[dataset_num])))\n axs[-1].set_xlabel('Time')\n fig.colorbar(\n temp, cax=colorbar_ax, orientation='vertical', ticks=[0, 1]\n )\n\n fig.tight_layout()\n gs.tight_layout(fig, rect=[0, 0, 1, 0.95])\n\n filename = 'inference_{0}_{1}.pdf'.format(\n dataset_num, num_particles\n )\n fig.savefig(filename, bbox_inches='tight')\n print('\\nPlot saved to {}'.format(filename))\n\n # Plot kl_{dataset_num}.pdf\n for dataset_num in args.dataset_num_list:\n fig, ax = plt.subplots(1, 1)\n fig.suptitle('Sum of KL divergences', fontsize=14)\n kls = {}\n for algorithm in args.algorithms:\n kls[algorithm] = []\n for num_particles in args.num_particles_list:\n kls[algorithm].append(get_sum_kl(\n true_posteriors[dataset_num],\n posteriors[dataset_num][num_particles][algorithm]\n ))\n\n ax.plot(args.num_particles_list, kls[algorithm], label=algorithm)\n\n ax.legend()\n ax.set_xlabel('Number of particles')\n ax.set_ylabel(\n '$\\sum_{t = 1}^T KL(p(x_t | y_{1:T}) || \\hat p(x_t | y_{1:T}))$'\n )\n\n filename = 'kl_{}.pdf'.format(dataset_num)\n fig.savefig(filename, bbox_inches='tight')\n print('\\nPlot saved to {}'.format(filename))\n\n # Plot l2_{dataset_num}.pdf\n for dataset_num in args.dataset_num_list:\n fig, ax = plt.subplots(1, 1)\n fig.suptitle('Sum of L2 norms', fontsize=14)\n l2s = {}\n for algorithm in args.algorithms:\n l2s[algorithm] = []\n for num_particles in args.num_particles_list:\n l2s[algorithm].append(get_sum_l2(\n true_posteriors[dataset_num],\n posteriors[dataset_num][num_particles][algorithm]\n ))\n\n ax.plot(args.num_particles_list, l2s[algorithm], label=algorithm)\n\n ax.legend()\n ax.set_xlabel('Number of particles')\n ax.set_ylabel(\n '$\\sum_{t = 1}^T L_2(p(x_t | y_{1:T}), \\hat p(x_t | y_{1:T}))$'\n )\n\n filename = 'l2_{}.pdf'.format(dataset_num)\n fig.savefig(filename, bbox_inches='tight')\n print('\\nPlot saved to {}'.format(filename))\n\n # Plot log_kl_{dataset_num}.pdf\n for dataset_num in args.dataset_num_list:\n fig, ax = plt.subplots(1, 1)\n fig.suptitle('Sum of KL divergences', fontsize=14)\n kls = {}\n for algorithm in args.algorithms:\n kls[algorithm] = []\n for num_particles in args.num_particles_list:\n kls[algorithm].append(get_sum_kl(\n true_posteriors[dataset_num],\n posteriors[dataset_num][num_particles][algorithm]\n ))\n\n ax.loglog(args.num_particles_list, kls[algorithm], label=algorithm)\n\n ax.legend()\n ax.set_xlabel('Number of particles')\n ax.set_ylabel(\n '$\\sum_{t = 1}^T KL(p(x_t | y_{1:T}) || \\hat p(x_t | y_{1:T}))$'\n )\n\n filename = 'log_kl_{}.pdf'.format(dataset_num)\n fig.savefig(filename, bbox_inches='tight')\n print('\\nPlot saved to {}'.format(filename))\n\n # Plot log_l2_{dataset_num}.pdf\n for dataset_num in args.dataset_num_list:\n fig, ax = plt.subplots(1, 1)\n fig.suptitle('Sum of L2 norms', fontsize=14)\n l2s = {}\n for algorithm in args.algorithms:\n l2s[algorithm] = []\n for num_particles in args.num_particles_list:\n l2s[algorithm].append(get_sum_l2(\n true_posteriors[dataset_num],\n posteriors[dataset_num][num_particles][algorithm]\n ))\n\n ax.loglog(args.num_particles_list, l2s[algorithm], label=algorithm)\n\n ax.legend()\n ax.set_xlabel('Number of particles')\n ax.set_ylabel(\n '$\\sum_{t = 1}^T L_2(p(x_t | y_{1:T}), \\hat p(x_t | y_{1:T}))$'\n )\n\n filename = 'log_l2_{}.pdf'.format(dataset_num)\n fig.savefig(filename, bbox_inches='tight')\n print('\\nPlot saved to {}'.format(filename))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"plots/hmm/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":8667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"236909536","text":"# 빙산\nimport sys\n# sys.stdin = open(\"/Users/jewerlykim/Desktop/python_Algorithm/jungleweek03/jewelrykim/9.txt\",'r')\n# import numpy as np\nsys.setrecursionlimit(10**9)\nN, M = map(int, sys.stdin.readline().split())\ngraph = []\ndays = 0\n\nfor _ in range(N):\n graph.append(list(map(int, sys.stdin.readline().split())))\n\n# graph = np.array(graph)\n# print(graph)\ndef dfs(graph, x, y):\n # 주어진 범위를 벗어나느 경우에는 즉시 종료\n if x <= -1 or x >= N or y <= -1 or y >= M:\n return False\n # 현재노드를 아직 방문하지 않았다면\n if graph[x][y] != 0:\n # 해당 노드 방문 처리\n graph[x][y] = 0\n # 상, 하, 좌, 우의 위치도 모두 재귀적으로 호출\n dfs(graph, x-1, y)\n dfs(graph, x, y-1)\n dfs(graph, x+1, y)\n dfs(graph, x, y+1)\n return True\n return False\n\ndef melt(graph, x, y):\n count = 0\n if 1<=x:\n if graph[x-1][y]==0:\n count += 1\n if x<=N-2:\n if graph[x+1][y]==0:\n count += 1\n if 1<=y:\n if graph[x][y-1]==0:\n count += 1\n if y<=M-2:\n if graph[x][y+1]==0:\n count += 1\n return count\n\n\ndef check(graph):\n count = 0\n for i in range(N):\n for j in range(M):\n if graph[i][j]!=0 and dfs(graph, i, j):\n count += 1\n return count\n\nwhile True:\n melt_graph = [[0 for _ in range(M)] for _ in range(N)]\n check_graph = [[0 for _ in range(M)] for _ in range(N)]\n days += 1\n\n for i in range(N):\n for j in range(M):\n if graph[i][j]!=0:\n melt_graph[i][j] = melt(graph, i, j)\n\n for i in range(N):\n for j in range(M):\n if graph[i][j]!=0:\n graph[i][j] -= melt_graph[i][j]\n if graph[i][j]<0:\n graph[i][j]=0\n check_graph[i][j] = graph[i][j]\n\n if check(check_graph)>=2:\n print(days)\n break\n sums = 0\n for i in graph:\n sums+=sum(i)\n if sums==0:\n print(0)\n break\n\n\n\n","sub_path":"jewelrykim/week03-09.py","file_name":"week03-09.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"619983807","text":"user = 'undefined'\nterminate = 0\nusernames = [\"CSH2206\", \"Guest\"]\nnames = [\"Caleb Howard\", \"Guest User\"]\nclearance = [\"F\", \"A\"]\n\ndef clear():\n a = 50\n while a > 0:\n print(\"\")\n a = a-1\n \ndef gendisp(a):\n print(\"CSHoward Industries\")\n print(\"\")\n print(\"Operating System\")\n print(\"Version 1.1\")\n while a > 0:\n print(\"\")\n a=a-1\n\n \n\ngendisp(21)\nprint(\"IDENTIFICATION IS REQURIED\")\nuser = input(\"IDENTIFICATION CODE> \")\ncode = input(\"PASSCODE> \")\n\nclear()\n\ngendisp(21)\nprint(\"Welcome,\", user)\nprint(\"\")\n\nwhile terminate == 0:\n command = input(\"COMMAND> \")\n if command == 'help':\n print(\"Available commands:\")\n print(\"help - opens the help menu\")\n else:\n terminate = 1\n command = 'undefined'\n","sub_path":"CSHIOS.py","file_name":"CSHIOS.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"200768499","text":"# imported from https://github.com/merose/diff_drive\n\nfrom __future__ import division, print_function\nimport math\nfrom db_planning.chassis_state import ChassisState\nimport rospy\n\nclass GoalController:\n \"\"\"Finds linear and angular velocities necessary to drive toward\n a goal pose.\n \"\"\"\n\n def __init__(self):\n self.kP = 3.0\n self.kA = 8.0\n self.kB = -1.5\n\n self.max_linear_speed = 1E9\n self.min_linear_speed = 0.0\n self.max_angular_speed = 1E9\n self.min_angular_speed = 0.0\n self.max_linear_acceleration = 1E9\n self.max_angular_acceleration = 1E9\n self.linear_tolerance = 0.025 # 2.5cm\n self.angular_tolerance = math.radians(3.0) # 3 degrees\n self.forward_movement_only = False\n self.reverse_direction = False\n\n self.dist_timeout_tolerance = 0.0005\n self.angle_timeout_tolerance = 0.0025\n self.prev_dist_error = 0.0\n self.prev_angle_error = 0.0\n self.dist_error = 0.0\n self.angle_error = 0.0\n self.dist_timeout_timer = None\n self.angle_timeout_timer = None\n self.move_timeout = rospy.Duration(10.0)\n\n def set_constants(self, kP, kA, kB):\n self.kP = kP\n self.kA = kA\n self.kB = kB\n\n def get_goal_distance(self, cur, goal):\n if goal is None:\n return 0\n diffX = cur.x - goal.x\n diffY = cur.y - goal.y\n return math.sqrt(diffX * diffX + diffY * diffY)\n\n def at_goal(self, cur, goal):\n if goal is None:\n return True\n\n self.dist_error = self.get_goal_distance(cur, goal)\n if goal.t is None:\n is_at_goal = self.dist_error < self.linear_tolerance\n else:\n self.angle_error = abs(self.normalize_pi(cur.t - goal.t))\n is_at_goal = self.dist_error < self.linear_tolerance and self.angle_error < self.angular_tolerance\n\n if is_at_goal:\n self.dist_timeout_timer = None\n return is_at_goal\n\n def is_stuck(self):\n now = rospy.Time.now()\n if self.dist_timeout_timer is None:\n self.dist_timeout_timer = now\n if abs(self.dist_error - self.prev_dist_error) < self.dist_timeout_tolerance:\n if now - self.dist_timeout_timer > self.move_timeout:\n return True\n else:\n self.dist_timeout_timer = now\n\n # if self.angle_timeout_timer is None:\n # self.angle_timeout_timer = now\n # if abs(self.angle_error - self.prev_angle_error) < self.angle_timeout_tolerance:\n # if now - self.angle_timeout_timer > self.move_timeout:\n # return True\n # else:\n # self.angle_timeout_timer = now\n\n self.prev_dist_error = self.dist_error\n # self.prev_angle_error = self.angle_error\n\n def get_velocity(self, cur, goal, dT):\n \"\"\"\n cur: ChassisState\n goal: ChassisState\n dT: float\n \"\"\"\n desired = ChassisState()\n\n goal_heading = math.atan2(goal.y - cur.y, goal.x - cur.x)\n if self.reverse_direction:\n goal_heading = self.normalize_pi(goal_heading + math.pi)\n a = -cur.t + goal_heading\n\n if goal.t is None:\n goal_t = goal_heading\n else:\n goal_t = goal.t\n\n # In Automomous Mobile Robots, they assume theta_G=0. So for\n # the error in heading, we have to adjust theta based on the\n # (possibly non-zero) goal theta.\n theta = self.normalize_pi(cur.t - goal_t)\n b = -theta - a\n\n # rospy.loginfo('cur=%f goal=%f a=%f b=%f', cur.theta, goal_heading,\n # a, b)\n\n d = self.get_goal_distance(cur, goal)\n if self.forward_movement_only:\n direction = 1.0\n a = self.normalize_pi(a)\n b = self.normalize_pi(b)\n else:\n direction = math.copysign(1.0, math.cos(a))\n a = self.normalize_half_pi(a)\n b = self.normalize_half_pi(b)\n\n if self.reverse_direction:\n direction *= -1.0\n\n # rospy.loginfo('After normalization, a=%f b=%f', a, b)\n\n if abs(d) < self.linear_tolerance:\n desired.vx = 0.0\n desired.vt = self.kB * theta\n else:\n desired.vx = self.kP * d * direction\n desired.vt = self.kA * a + self.kB * b\n\n # TBD: Adjust velocities if linear or angular acceleration\n # too high.\n\n # Adjust velocities if X velocity is too high.\n if abs(desired.vx) > self.max_linear_speed:\n ratio = self.max_linear_speed / abs(desired.vx)\n desired.vx *= ratio\n desired.vt *= ratio\n\n # Adjust velocities if turning velocity too high.\n if abs(desired.vt) > self.max_angular_speed:\n ratio = self.max_angular_speed / abs(desired.vt)\n desired.vx *= ratio\n desired.vt *= ratio\n\n # Adjust velocities if too low, so robot does not stall.\n if abs(desired.vx) > 0 and abs(desired.vx) < self.min_linear_speed:\n ratio = self.min_linear_speed / abs(desired.vx)\n desired.vx *= ratio\n desired.vt *= ratio\n elif desired.vx == 0.0 and desired.vt != 0.0 and abs(desired.vt) < self.min_angular_speed:\n ratio = self.min_angular_speed / abs(desired.vt)\n desired.vx *= ratio\n desired.vt *= ratio\n\n return desired\n\n def normalize_half_pi(self, alpha):\n alpha = self.normalize_pi(alpha)\n if alpha > math.pi / 2:\n return alpha - math.pi\n elif alpha < -math.pi / 2:\n return alpha + math.pi\n else:\n return alpha\n\n def normalize_pi(self, alpha):\n alpha %= 2.0 * math.pi\n\n if alpha >= math.pi:\n alpha -= 2.0 * math.pi\n\n return alpha\n","sub_path":"src/db_planning/src/db_planning/goal_controller.py","file_name":"goal_controller.py","file_ext":"py","file_size_in_byte":5853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"57080417","text":"def answer():\n n, m = map(int, input().split())\n ans = [-1] * n\n for i in range(m):\n s, c = map(int, input().split())\n if ans[s-1] != -1 and ans[s-1] != c:\n return -1\n ans[s-1] = c\n if n == 1 and (ans[0] == 0 or ans[0] == -1):\n return 0\n if ans[0] == 0:\n return -1\n if ans[0] == -1:\n result = 1\n else:\n result = ans[0]\n for i in range(1, n):\n if ans[i] == -1:\n result = result * 10\n else:\n result = result * 10 + ans[i]\n return result\n\nprint(answer())\n","sub_path":"atcoder/abc157/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"214734631","text":"import pytest\nimport trio\n\nfrom .mock_serf import stdtest\n\n# from .run import run\n# from functools import partial\n\nfrom distkv.auth import loader\nfrom distkv.client import ServerError\nfrom distkv.util import PathLongener\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nasync def collect(i, path=()):\n res = []\n pl = PathLongener(path)\n async for r in i:\n r.pop(\"tock\", 0)\n r.pop(\"seq\", 0)\n pl(r)\n res.append(r)\n return res\n\n\n@pytest.mark.trio\nasync def test_81_basic(autojump_clock):\n async with stdtest(args={\"init\": 123}) as st:\n s, = st.s\n async with st.client() as c:\n await c._request(\"set_internal\", path=(\"acl\", \"foo\", \"one\"), value=\"rxnc\")\n await c._request(\n \"set_internal\", path=(\"acl\", \"foo\", \"one\", \"two\"), value=\"rc\"\n )\n\n um = loader(\"_test\", \"user\", make=True, server=False)\n u = um.build({\"name\": \"std\"})\n await u.send(c)\n u = um.build({\"name\": \"aclix\", \"aux\": {\"acl\": \"foo\"}})\n await u.send(c)\n await c._request(\"set_auth_typ\", typ=\"_test\")\n\n recv = []\n um = loader(\"_test\", \"user\", make=False, server=False)\n\n async with st.client(auth=um.build({\"name\": \"aclix\"})) as c:\n await c.set(\"one\", value=10)\n await c.set(\"one\", \"two\", value=11)\n with pytest.raises(ServerError):\n await c.set(\"one\", \"two\", \"three\", value=12)\n with pytest.raises(ServerError):\n await c.set(\"foo\", value=22)\n","sub_path":"tests/test_feature_acl.py","file_name":"test_feature_acl.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"576284302","text":"import numpy as np\nimport cv2\n\nimg = cv2.imread('./inputs/faces.jpg', cv2.IMREAD_COLOR)\n\ncv2.line(img, (0, 0), (300, 400), color=(0, 0, 255), thickness=3, lineType=cv2.LINE_AA)\ncv2.rectangle(img, (100,100), (400,400), color=(255,255,255), thickness= 5, lineType=cv2.LINE_AA)\ncv2.circle(img, center=(200,150), radius=50, color=(255,0,0), thickness= 10, lineType=cv2.LINE_AA)\n\npts = np.array([[200,300], [150,330], [200,160], [400,500], [453,456], [450,140]], np.int32)\npts = pts.reshape((-1, 1, 2))\ncv2.polylines(img, [pts], isClosed=True, color=(0,255,0), thickness=5, lineType=cv2.LINE_AA)\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\ncv2.putText(img, text='Manchester United', org=(400,70), fontFace=font, fontScale=0.5, color=(255,255,255), thickness=2, lineType=cv2.LINE_AA)\n\n\ncv2.imshow('image', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"opencv_drawing.py","file_name":"opencv_drawing.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"203640293","text":"import helpers\nimport random\n\nINIT_REWARD = 5\nstill_playing = None\ngame_tokens = None\ngame_username = None\n\n\ndef init():\n global still_playing\n still_playing = True\n\n\ndef play(username, tokens):\n init()\n\n global game_tokens, game_username\n game_tokens = tokens\n game_username = username\n while still_playing:\n r = random.randint(1, 100)\n guess = int(input(\"Guess the number (1-100): \"))\n distance = abs(r - guess)\n reward = INIT_REWARD - distance\n if reward > 0:\n game_tokens += reward\n helpers.update_tokens(game_username, game_tokens)\n else:\n reward = 0\n print(f\"You earned {reward} token(s).\")\n choice = input(\"Would you like to play again? (y/n) \")\n if choice.lower() == \"n\":\n return game_tokens\n\n\nif __name__ == '__main__':\n play()\n","sub_path":"games/freeplay/freeplay.py","file_name":"freeplay.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"123883090","text":"from django import forms\n\n\nclass ArticleForm(forms.Form):\n name = forms.CharField(label='Вставьте url',\n widget=forms.URLInput(attrs={'class': 'form-control',\n 'placeholder': 'link to page'}),\n required=False)\n picture = forms.ImageField(label='Или выберите картинку',\n required=False)\n\n def clean(self):\n name = self.cleaned_data.get('name')\n image = self.cleaned_data.get('picture')\n\n if name and image:\n raise forms.ValidationError('Заполненным может ��ыть только 1 поле')\n\n if name == '' and image is None:\n raise forms.ValidationError('Нужно ввести данные хотя бы в 1 поле')\n\n\nclass ChangeParamsForm(forms.Form):\n width = forms.IntegerField(label='Ширина',\n required=False,\n widget=forms.NumberInput(attrs={'class': 'form-control'}))\n height = forms.IntegerField(label='Высота',\n required=False,\n widget=forms.NumberInput(attrs={'class': 'form-control'}))\n size = forms.IntegerField(label='Макс. размер в байтах',\n required=False,\n widget=forms.NumberInput(attrs={'class': 'form-control'}))\n\n def clean(self):\n error_string = ''\n\n width = self.data.get('width', False)\n height = self.data.get('height', False)\n size = self.data.get('size', False)\n\n if any([width, height, size]):\n try:\n res = int(width)\n except:\n if width != '':\n error_string += '\"Ширина\" должна быть числовым значением. '\n\n try:\n res = int(height)\n except:\n if height != '':\n error_string += '\"Высота\" должна быть числовым значением. '\n\n try:\n res = int(size)\n except:\n if size != '':\n error_string += 'Размер в байтах должен быть числовым значением.'\n\n if error_string != '':\n raise forms.ValidationError(error_string)","sub_path":"UploadImage/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"580842679","text":"\nimport matplotlib.pyplot as plt\nfrom pandas import Series, DataFrame\nimport pandas as pd\nimport acequia as aq\n\n\ndef message(message):\n \"\"\" function for printing message to screen \"\"\"\n print()\n print(\"-\"*len(message))\n print(message)\n print(\"-\"*len(message))\n print()\n\n\nif 1:\n\n srcdir = r'.\\testdata\\json\\\\'\n plotsdir = r'.\\output\\plots\\\\'\n\n # read four time series of one well location\n\n sourcefile = srcdir+'B29A0850_1.json'\n gw1 = aq.GwSeries.from_json(sourcefile)\n sr1 = gw1.heads(ref='datum')\n\n sourcefile = srcdir+'B29A0850_2.json'\n gw2 = aq.GwSeries.from_json(sourcefile)\n sr2 = gw2.heads(ref='datum')\n\n sourcefile = srcdir+'B29A0850_3.json'\n gw3 = aq.GwSeries.from_json(sourcefile)\n sr3 = gw3.heads(ref='datum')\n\n sourcefile = srcdir+'B29A0850_4.json'\n gw4 = aq.GwSeries.from_json(sourcefile)\n sr4 = gw4.heads(ref='datum')\n\n\n # read series with changes in reference height\n\n sourcefile = r'.\\testdata\\dinogws\\B29C0191001_1.csv'\n gw5 = aq.GwSeries.from_dinogws(sourcefile)\n sr5 = gw5.heads(ref='datum')\n\n gw6 = aq.GwSeries.from_dinogws(sourcefile)\n sr6 = gw6.heads(ref='surface')\n\nif 0:\n\n # --------------------------------\n # test PlotHeads() with one series\n # --------------------------------\n\n plot = aq.PlotHeads(ts=[sr3],ylim=[19.5,21.5])\n\nif 0:\n\n # -------------------------------------\n # test PlotHeads() with multiple series\n # -------------------------------------\n\n plot = aq.PlotHeads(ts=[sr1,sr2,sr3,sr4])\n outpath = f'{plotsdir}{plot.ts[0].name}.png'\n plot.save(outpath)\n\n\nif 1:\n\n # --------------------------------------------\n # test PlotHeads() with reference change graph\n # --------------------------------------------\n\n plot = aq.PlotHeads(ts=[sr5])\n\n mps = gw5.tubeprops_changes()\n plot = aq.PlotHeads(ts=[sr5],mps=mps)\n\n mps = gw5.tubeprops_changes(proptype='surfacelevel')\n plot = aq.PlotHeads(ts=[sr5],mps=mps)\n\n mps = gw5.tubeprops_changes(proptype='filbot')\n plot = aq.PlotHeads(ts=[sr5],mps=mps)\n\nif 1:\n\n # ---------------------------------------------------\n # test PlotHeads() for heads relative to surfacelevel\n # ---------------------------------------------------\n\n mps = gw5.tubeprops_changes(proptype='surfacelevel')\n plot = aq.PlotHeads(\n ts=[sr6],ref='surface', mps=mps)\n\n\nif 0:\n\n # ---------------------------------------------------\n # test PlotHeads() for all locations in testdata\n # ---------------------------------------------------\n\n srcdir = f'.\\\\testdata\\\\dinogws\\\\'\n plotdir = f'.\\\\output\\\\plots\\\\'\n locnames = ['B12A1806','B29A0848','B32E1199']\n locs = aq.GwLocs(filedir=srcdir,groups=locnames)\n for i,loc in enumerate(locs):\n\n for ts in loc:\n ts.heads().plot()\n\n locname = loc[0].locname()\n plot = aq.PlotHeads(ts=loc,ref='datum',title=locname)\n plot.save(f'{plotdir}{locname}.jpg')\n #plt.close()\n\nif 0:\n sr1 = dn1.series(units=\"cmmv\")\n desc1 = dn1.describe()\n\n # test pplotseries : twee meetreeksen\n message(\"Test plotseries with sbb ref point DRAn-B601a.2 \")\n\n plot = plotseries()\n\n plot.plotseries(ts=[sr1],description=[desc1],reference=\"cmmv\",xlim=['01-01-1997','14-11-1999'],\n ylim=[-50,200], title=\"Test: SBBRefpunt DRAn-601a.2\")\n plot.saveplot('.\\\\output\\\\test plotseries\\\\test-sbbref.png')\n plt.show()\n\n\nif 0:\n\n dn1 = dinogws()\n dn1.readfile(r\".\\testdata\\B34D0081001_1.csv\")\n\n dn2 = dinogws()\n dn2.readfile(r\".\\testdata\\B34D0081002_1.csv\")\n\n sr1 = dn1.series(units=\"cmnap\")\n sr2 = dn2.series(units=\"cmnap\")\n\n desc1 = dn1.describe()\n desc2 = dn2.describe()\n\n # test pplotseries : twee meetreeksen\n message(\"Test plotseries with two series \")\n\n #plt.rcParams['figure.figsize'] = [5, 3]\n\n myplotargs = [\n {'color':'#2347c5', 'marker':'o', 'linestyle':'dashed',\n 'linewidth':1, 'markersize':4},\n {'color':'#b41515', 'marker':'o', 'linestyle':'solid', \n 'linewidth':1, 'markersize':4}]\n\n plot = plotseries()\n plot.plotseries(ts=[sr1,sr2],description=[desc1,desc2], \n xlim=[1955,2005], ylim=[1500,1800], \n title=\"Test: Twee meetreeksen\",\n plotargs = myplotargs)\n plot.saveplot('.\\\\output\\\\test plotseries\\\\test twee meetreeksen.png')\n plt.show()\n\nif 0:\n\n # test plotseries \n\n # read data to series\n\n dn1 = dinogws()\n dn1.readfile(r\".\\testdata\\B12B0297001_1.csv\")\n sr1 = dn1.series(units=\"cmmv\")\n desc1 = dn1.describe()\n\n # test pplotseries : twee meetreeksen\n message(\"Test plotseries with sbb ref point DRAn-B601a.2 \")\n\n plot = plotseries()\n\n plot.plotseries(ts=[sr1],description=[desc1],reference=\"cmmv\",xlim=['01-01-1997','14-11-1999'],\n ylim=[-50,200], title=\"Test: SBBRefpunt DRAn-601a.2\")\n plot.saveplot('.\\\\output\\\\test plotseries\\\\test-sbbref.png')\n plt.show()\n\nif 0:\n\n # test plotseries : één reeks met referentielijn\n message(\"Test plotseries with reference line \")\n\n ref = dn1.mpref()\n plot = plotseries()\n plot.plotseries(ts=[sr1],description=[desc1], title=\"Test: Meetreeks met referentielijn\", mps=ref)\n plot.saveplot('.\\\\output\\\\test plotseries\\\\test meetreeks-met-referentie.png')\n plt.show()\n\n\nif 0: # test plotduurlijn\n if dn1.frq(): plot.plotduurlijn(dn1.frq)\n plot.saveplot('duurlijn.png')\n plt.show()\n\n\nif 0: \n if dn.frq(): \n plot.plotduurlijn(dn.frq)\n plot.saveplot('duurlijn.png')\n plt.show() \n\n\nif 0: # test functions for all files in directory with test files (with many problems)\n\n sourcedir = \".\\\\testdata\\\\\" \n filenames = [f for f in os.listdir(sourcedir) if os.path.isfile(os.path.join(sourcedir,f)) and f[11:13]==\"_1\"]\n for i,srcfile in enumerate(filenames):\n\n dn = dinogws(sourcedir+srcfile)\n plot = plotseries()\n #dn.readfile(sourcedir+srcfile)\n if len(dn.series())!=0:\n sr = dn.series(units=\"cmnap\")\n ref = dn.mpref()\n plot.plotseries(ts=[sr],mps=ref, title=srcfile)\n plot.saveplot(\".\\\\output\\\\log\\\\graph\\\\\"+srcfile.split(\".\")[0]+\".png\")\n plt.show()\n plt.close()\n\nprint (\"Script finished\")","sub_path":"old_tests/test_plots_plotheads.py","file_name":"test_plots_plotheads.py","file_ext":"py","file_size_in_byte":6315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"235405348","text":"import time\nimport datetime\nfrom Sensor import Sensor\nfrom my_libs import *\n\nsetup_logging()\nlog = logging.getLogger(\"GPSException\")\n\nclass GPS(Sensor):\n def __init__(self):\n self.device_name = \"GPS\"\n self.interval = 0\n self.verbose = False\n\n def read(self):\n ret1 = -1\n ret2 = -1\n try:\n return 50, 50\n except:\n eprint(\"ERROR in READ...PI/sensors/gps/gps.py\")\n log.exception('ERROR in READ...PI/sensors/gps.py')\n return ret1, ret2\n \n","sub_path":"EnviroSCALE_DataCollect/Dummy Producer (PC)/EnviroSCALE_pi/sensors/gps/gps.py","file_name":"gps.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"228946704","text":"import datetime\r\nimport urllib.request\r\nimport ssl\r\nimport json\r\nimport sys\r\nimport gzip\r\nimport shutil\r\nimport os\r\nimport io\r\n\r\n#verfies number of arguments\r\nprint(str(len(sys.argv)))\r\nprint(str(sys.argv))\r\n\r\nif len(sys.argv) < 3:\r\n print(\"\\nNumber of arguments must be at least 2\")\r\n sys.exit()\r\n\t\r\n#set keywords to find in URLs\r\nkeywords=[\"open data\",\"opendata\",\"ckan\",\"socrata\",\"opendatasoft\", \"arcgis\"]\r\n\t\r\nnum_lines = 0\r\nwith open('warc.paths', 'r') as f_path:\r\n for line in f_path:\r\n num_lines += 1\r\nf_path.close()\r\n\r\ntotalpaths = num_lines #get total number of paths in the \"warc.paths\" file\r\nprint(\"totalpaths: \" + str(totalpaths))\r\ntotalofsegments = int(sys.argv[1]) #get 1st argument - total of segments\r\nprint(\"totalofsegments: \" + str(totalofsegments))\r\ncurrentsegment = int(sys.argv[2]) #get 2st argument - currentsegment\r\nprint(\"currentsegment: \" + str(currentsegment))\r\ncurrentsegment_start = int((totalpaths / totalofsegments) * (currentsegment - 1) + 1)\r\nprint(\"currentsegment_start: \" + str(currentsegment_start))\r\ncurrentsegment_end = int((totalpaths / totalofsegments) * currentsegment)\r\nprint(\"currentsegment_end: \" + str(currentsegment_end))\r\nsegmentsinthisrunning = (currentsegment_end - currentsegment_start) + 1\r\nprint(\"segments_in_this_running: \" + str(segmentsinthisrunning))\r\n\r\n#verify if user wants to continue from a determined position\r\n#if so, open file in append mode instead of creating\r\nif len(sys.argv) == 4:\r\n\tif sys.argv[3] != 'continue':\r\n\t\tprint(\"\\n3rd argument is invalid. Type 'continue' to start from the last position\")\r\n\t\texit()\r\n\r\n\twith open('keyword_progress-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt', mode='r', encoding='latin-1') as f_progress:\r\n\t\tfor line in f_progress:\r\n\t\t\tlastlinepospaths = line[line.find('linepospaths') + 12:line.find('|')]\r\n\tf_progress.close()\r\n\r\n\tpospaths_continue = int(lastlinepospaths) + 1\r\n\r\n\tlineposrunning = (pospaths_continue - currentsegment_start) + 1\r\nelse:\r\n\t#write head of results file\r\n\toutput_file = open('keyword_results-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt', mode='w', encoding=\"latin-1\")\r\n\toutput_file.write('URL|WARC_SOURCE|KEYWORD_FOUND_POSITION\\n')\r\n\toutput_file.close()\r\n\t\r\n\t#write head of progres file\r\n\tprogress_file = open('keyword_progress-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt', mode='w', encoding=\"latin-1\")\r\n\tprogress_file.write('LINE_POS_PATH|WARC_FILE|WARC_PROC_START|WARC_PROC_END|ELAPSED_DOWNLOAD|ELAPSED_DECOMPRESS|ELAPSED_READING|ELAPSED_TOTAL\\n')\r\n\tprogress_file.close()\r\n\t\r\n\tpospaths_continue = 0\r\n\tlineposrunning = 1 #line position of this running depending on number of segments\r\n\r\nlinepospaths = 1 #line position of warc.paths\r\n\r\nwith open('warc.paths', 'r') as f_path:\r\n\tfor line in f_path:\r\n\t\tprint(\"linepos: \" + str(linepospaths))\r\n\t\t\r\n\t\tif pospaths_continue == 0:\r\n\t\t\tif not (linepospaths >= currentsegment_start and linepospaths <= currentsegment_end):\r\n\t\t\t\tlinepospaths += 1\r\n\t\t\t\tcontinue #skip line for next for\r\n\t\telse:\r\n\t\t\tif not (linepospaths >= pospaths_continue and linepospaths <= currentsegment_end):\r\n\t\t\t\tlinepospaths += 1\r\n\t\t\t\tcontinue #skip line for next for\r\n\r\n\t\t#register process start\r\n\t\tWARC_PROC_START = datetime.datetime.now()\r\n\r\n\t\turl = \"https://commoncrawl.s3.amazonaws.com/\" + line\r\n\t\tfile_name = line[line.rfind('/')+1:].strip()\r\n\r\n\t\t#register download start\r\n\t\tWARC_DOWNLOAD_START = datetime.datetime.now()\r\n\t\t\r\n\t\tprint(\"Downloading... \" + url)\r\n\t\tdownload_sucess = 0\r\n\t\twhile download_sucess == 0:\r\n\t\t\ttry:\r\n\t\t\t\tzip_inmemory = urllib.request.urlopen(url, timeout=60)\r\n\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tprint(\"Downloading error! Repeting download... \" + url)\r\n\t\t\t\tprint(str(e))\r\n\t\t\t\t\t\r\n\t\t\telse:\r\n\t\t\t\tdownload_sucess = 1\r\n\r\n\t\t#register download end\r\n\t\tWARC_DOWNLOAD_END = datetime.datetime.now()\r\n\r\n\t\t#register decompress start\r\n\t\tWARC_DECOMPRESS_START = datetime.datetime.now()\r\n\t\t\t\t\r\n\t\tprint(\"Decompressing... \" + url)\r\n\t\tbytestream = io.BytesIO(zip_inmemory.read())\r\n\t\tgz = gzip.open(bytestream, mode='rt', encoding='latin-1')\r\n\r\n\t\t#register decompress end\r\n\t\tWARC_DECOMPRESS_END = datetime.datetime.now()\r\n\t\t\r\n\t\t#start counting WARC file line position\r\n\t\tlineposwarc = 1\r\n\t\t\r\n\t\thasWARCTargetURI = 0\r\n\t\t\r\n\t\t#store results in a temp file\r\n\t\tTEMP_output_file = open('TEMP_keyword_results-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt', mode='w', encoding=\"latin-1\")\r\n\r\n\t\t#register reading start\r\n\t\tWARC_READING_START = datetime.datetime.now()\r\n\t\t\r\n\t\tfor linewarc in gz.readlines():\r\n\t\t\t\r\n\t\t\tif lineposwarc % 100000 == 0:\r\n\t\t\t\tcompleted = (lineposrunning / segmentsinthisrunning) * 100\r\n\t\t\t\tprint(str(lineposrunning) + '/' + str(segmentsinthisrunning) + ' (' + str(round(completed)) + '%) ' + 'Reading line ' + str(lineposwarc) + '...')\r\n\t\t\t\r\n\t\t\t#try to identify the beginning of WARC-Type: response\r\n\t\t\tif linewarc.find('WARC-Target-URI:') != -1:\r\n\t\t\t\tWARCTargetURI = linewarc[17:].strip()\r\n\t\t\t\thasWARCTargetURI = 1\r\n\r\n\t\t\tif hasWARCTargetURI == 1:\r\n\t\t\t\tif any(keyword in linewarc for keyword in keywords):\r\n\t\t\t\t\tTEMP_output_file.write(WARCTargetURI + '|' + file_name + '|' + str(lineposwarc) + '\\n')\r\n\r\n\t\t\t\t\tWARCTargetURI = ''\r\n\t\t\t\t\thasWARCTargetURI = 0\r\n\r\n\t\t\tlineposwarc += 1\r\n\t\t\r\n\t\tgz.close()\r\n\t\tTEMP_output_file.close()\r\n\r\n\t\t#register reading end\r\n\t\tWARC_READING_END = datetime.datetime.now()\r\n\t\t\r\n\t\t#register process end\r\n\t\tWARC_PROC_END = datetime.datetime.now()\r\n\t\t\r\n\t\t#get the elpased time of each step: DOWNLOAD, DECOMPRESS, READ, TOTAL\r\n\t\tELAPSED_DOWNLOAD = WARC_DOWNLOAD_END - WARC_DOWNLOAD_START\r\n\t\tELAPSED_DECOMPRESS = WARC_DECOMPRESS_END - WARC_DECOMPRESS_START\r\n\t\tELAPSED_READING = WARC_READING_END - WARC_READING_START\r\n\t\tELAPSED_TOTAL = WARC_PROC_END - WARC_PROC_START\r\n\r\n\t\t#append results from temp file to the output file\r\n\t\toutput_file = open('keyword_results-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt', mode='a+', encoding=\"latin-1\")\r\n\t\twith open('TEMP_keyword_results-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt', mode='r', encoding=\"latin-1\") as f_TEMP_output:\r\n\t\t\tfor lineTEMP in f_TEMP_output:\r\n\t\t\t\toutput_file.write(lineTEMP)\r\n\t\tf_TEMP_output.close()\r\n\t\toutput_file.close()\r\n\t\tif os.path.exists('TEMP_keyword_results-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt'):\r\n\t\t\tos.remove('TEMP_keyword_results-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt')\r\n\t\r\n\t\t#report progress in a file\r\n\t\tprogress_file = open('keyword_progress-seg' + str(currentsegment) + '-s' + str(currentsegment_start) + '-e' + str(currentsegment_end) + '.txt', mode='a+', encoding=\"latin-1\")\r\n\t\tprogress_file.write('linepospaths' + str(linepospaths) + '|' + file_name + '|' + str(WARC_PROC_START) + '|' + str(WARC_PROC_END) + '|' + str(ELAPSED_DOWNLOAD) + '|' + str(ELAPSED_DECOMPRESS) + '|' + str(ELAPSED_READING) + '|' + str(ELAPSED_TOTAL) + '\\n')\r\n\t\tprogress_file.close()\r\n\r\n\t\tlinepospaths += 1\r\n\t\t\r\n\t\tlineposrunning += 1\r\n\t\t\t\t\t\t\r\n\t\tif os.path.exists(file_name + '.txt'):\r\n\t\t\tos.remove(file_name + '.txt')\r\n\t\tif os.path.exists(file_name):\r\n\t\t\tos.remove(file_name)\r\n\r\nf_path.close()","sub_path":"algorithm/1-Keyword search/keywordsearch_inmemory.py","file_name":"keywordsearch_inmemory.py","file_ext":"py","file_size_in_byte":7420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"265823759","text":"#!/usr/bin/env python3\n\nimport pyglet\nfrom pyglet import gl\nwindow = pyglet.window.Window()\n\ngl.glClearColor(0.2, 0.4, 0.5, 1.0)\n\nvertices = []\nsize = 50\n\n@window.event\ndef on_draw():\n global vertices\n gl.glClear(gl.GL_COLOR_BUFFER_BIT)\n\n gl.glColor3f(0, 0, 0)\n\n gl.glBegin(gl.GL_TRIANGLES)\n for vertex in vertices:\n gl.glVertex2f(*vertex)\n\n gl.glEnd()\n\n@window.event\ndef on_mouse_press(x, y, button, modifiers):\n global size\n if button == pyglet.window.mouse.RIGHT:\n global vertices\n vertices = []\n size = 50\n else:\n draw_triangle(x, y, size=size)\n size /= 1.1\n\n\ndef draw_triangle(x, y, size=50):\n global vertices\n vertices.append((x, y+size))\n vertices.append((x+size, y-size))\n vertices.append((x-size, y-size))\n\n\npyglet.app.run()\n","sub_path":"python/Libraries/pyglet/opengl/opengl.py","file_name":"opengl.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"104821512","text":"import pandas as pd\nfrom mlxtend.preprocessing import TransactionEncoder\nfrom mlxtend.frequent_patterns import apriori\nfrom mlxtend.frequent_patterns import association_rules\nfrom datetime import datetime, timedelta\nimport csv\n\n\nclass AssociationRulesService : \n originalDataset = \"files/dataset.txt\"\n classifiedDataset = \"files/classifiedDataset.txt\"\n tempClassifiedDataset= \"files/tempClassifiedDataset.txt\"\n transactionalDataset = \"files/transactionalDataset.txt\"\n\n\n\n\n def categorizeDataset(self) : \n _file = open(self.originalDataset)\n filelines = list()\n\n for line in _file : \n spl = line.split(\",\")\n area = \"\"\n sunspot = \"\"\n xray = \"\"\n radio = \"\"\n\n for i in range(9) : \n spl[i] = spl[i].rstrip(\"\\n\")\n if i == 4 : \n area = self.classifyArea(spl[i])\n if i == 6 : \n sunspot = self.classifySunspot(spl[i])\n if i == 7 : \n xray = self.classifyXray(spl[i])\n if i == 8 : \n radio = self.classifyRadio(spl[i])\n\n newLine = spl[0] + \",\" + spl[1] + \",\" + spl[2] + \",\" + spl[3] + \",\" + area + \",\" + sunspot + \",\" + xray + \",\" + radio + \"\\n\"\n filelines.append(newLine)\n\n _file = open(self.classifiedDataset, 'w')\n _file.writelines(filelines)\n _file.close()\n\n\n def classifyArea(self, area) : \n if area != \"\" : \n area = int(area)\n if area < 200 : \n return \"area_pequena\"\n elif area >= 200 and area < 500 : \n return \"area_media\"\n elif area >= 500 and area < 1000 : \n return \"area_grande\" \n elif area >=1000 :\n return \"area_gigantesca\"\n else : \n return area\n\n \n def classifySunspot(self, sunspot) : \n return sunspot.lower().replace(\"-\", \"_\")\n\n \n def classifyXray(self, xray) : \n if xray != \"\" : \n return \"raiox_\" + xray[:1]\n else : \n return xray\n\n \n def classifyRadio(self, radio) : \n if radio != \"\" : \n radio = int(radio)\n if radio < 80 : \n return \"radio_baixo\"\n elif radio >= 80 and radio < 120 : \n return \"radio_medio\"\n elif radio >= 120 and radio < 160 : \n return \"radio_alto\" \n elif radio >= 160 :\n return \"radio_altissimo\"\n else : \n return radio\n\n \n\n\n def createTransactionalDataset(self) : \n _file = open(self.classifiedDataset)\n fileLines = list()\n for line in _file : \n fileLines.append(line)\n\n fileLines = self.removeDateAndRegion(fileLines)\n fileLines = self.cleanEmptyAttributes(fileLines)\n \n _file = open(self.transactionalDataset, 'w')\n _file.writelines(fileLines)\n _file.close()\n\n def createTransactionalDatasetByTemp(self) :\n _file = open(self.tempClassifiedDataset)\n fileLines = list()\n for line in _file : \n fileLines.append(line)\n\n fileLines = self.removeDateAndRegion(fileLines)\n fileLines = self.cleanEmptyAttributes(fileLines)\n \n _file = open(self.transactionalDataset, 'w')\n _file.writelines(fileLines)\n _file.close()\n\n\n def removeDateAndRegion(self, fileLines) : \n newFileLines = list()\n for line in fileLines : \n spl = line.split(\",\")\n newFileLines.append(spl[4] + \",\" + spl[5] + \",\" + spl[6] + \",\" + spl[7])\n\n return newFileLines \n\n\n def cleanEmptyAttributes(self, fileLines) : \n newLine = \"\"\n newFileLines = list()\n\n for line in fileLines : \n line = line.split(\"\\n\")\n spl = line[0].split(\",\")\n\n for i in range(4) : \n if spl[i] != \"\":\n if spl[i] != \"\\n\" : \n if newLine != \"\" : \n if newLine[:-1] != \",\" : \n newLine += \",\" + spl[i]\n else : \n newLine += spl[i]\n else : \n newLine += spl[i]\n newFileLines.append(newLine + \"\\n\")\n newLine = \"\"\n \n return newFileLines\n\n\n\n def getTransactionalDataset(self) : \n with open(self.transactionalDataset, 'r') as f:\n reader = csv.reader(f)\n dataset = list(reader)\n return dataset\n\n def getOriginalDataset(self) : \n return open(self.originalDataset, 'r' ) \n \n def saveTempClassifiedDataset(self, dataset) :\n _file = open(self.tempClassifiedDataset, \"w\")\n for line in dataset :\n l = line.split(\"\\n\")\n _file.write(l[0] + \"\\n\")\n _file.close()\n\n\n def getClassifiedDataset(self) : \n return open(self.classifiedDataset, 'r' ) \n\n\n\n def getDatasetByPeriod(self, dataset, lastDateInDataset, holeBase, startYear, startMonth, startDay, endYear, endMonth, endDay, area, sNumber, magClassification, xray, radio) : \n dataByPeriod = list()\n dataByPeriodAndAttributes = list()\n\n if not holeBase == \"True\": \n dataByPeriod = self.getPeriod(dataset, lastDateInDataset, startYear, startMonth, startDay, endYear, endMonth, endDay)\n else : \n dataByPeriod = dataset\n\n if area == \"True\" and magClassification == \"True\" and xray == \"True\" and radio == \"True\" and (sNumber == \"True\" or sNumber == \"none\"): \n dataByPeriodAndAttributes = dataByPeriod\n else : \n dataByPeriodAndAttributes = self.getAttributes(dataByPeriod, area, sNumber, magClassification, xray, radio)\n\n return dataByPeriodAndAttributes\n\n\n\n\n def getPeriod(self, dataset, lastDateInDataset, startYear, startMonth, startDay, endYear, endMonth, endDay) : \n dataByPeriod = list()\n startDate = datetime.strptime(startYear + startMonth + startDay, \"%Y%m%d\").date()\n endDate = datetime.strptime(endYear + endMonth + endDay, \"%Y%m%d\").date()\n firstdate = datetime.strptime(\"19970101\", \"%Y%m%d\").date()\n lastdate = lastDateInDataset\n\n if startDate < firstdate : \n startDate = firstdate\n if endDate > lastdate : \n endDate = lastdate\n print(\"Period: \" + str(startDate) + \" - \" + str(endDate))\n\n for line in dataset : \n l = line.split(\",\")\n date = datetime.strptime(l[0] + l[1] + l[2], \"%Y%b%d\").date()\n\n if date >= startDate : \n if date <= endDate : \n dataByPeriod.append(line)\n \n return dataByPeriod\n\n\n\n def getAttributes(self, dataset, area, sNumber, magClassification, xray, radio) : \n if sNumber == \"none\" : \n return self.getAttributesForClassifiedDataset(dataset, area, magClassification, xray, radio)\n else : \n return self.getAttributesForOriginalDataset(dataset, area, sNumber, magClassification, xray, radio)\n\n\n def getAttributesForOriginalDataset(self, dataset, area, sNumber, magClassification, xray, radio) : \n transaction = \"\"\n dataByAtributes = list()\n\n for line in dataset : \n l = line.split(\",\")\n transaction = l[0] + \",\" + l[1] + \",\" + l[2] + \",\" + l[3] + \",\"\n if area == \"True\" :\n transaction += l[4]\n transaction += \",\"\n if sNumber == \"True\" : \n transaction += l[5]\n transaction += \",\"\n if magClassification == \"True\" : \n transaction += l[6]\n transaction += \",\"\n if xray == \"True\" : \n transaction += l[7]\n transaction += \",\"\n if radio == \"True\" : \n transaction += l[8]\n transaction += \"\\n\"\n dataByAtributes.append(transaction)\n\n return dataByAtributes\n \n\n\n def getAttributesForClassifiedDataset(self, dataset, area, magClassification, xray, radio) : \n transaction = \"\"\n dataByAtributes = list()\n\n for line in dataset : \n l = line.split(\",\")\n transaction = l[0] + \",\" + l[1] + \",\" + l[2] + \",\" + l[3] + \",\"\n if area == \"True\" :\n transaction += l[4]\n transaction += \",\"\n if magClassification == \"True\" : \n transaction += l[5]\n transaction += \",\"\n if xray == \"True\" : \n transaction += l[6]\n transaction += \",\"\n if radio == \"True\" : \n transaction += l[7]\n transaction += \"\\n\"\n dataByAtributes.append(transaction)\n\n return dataByAtributes\n\n\n\n\n def generateAssociationRules(self, support, confidence) : \n dataset = self.getTransactionalDataset()\n support = float(support)\n confidence = float(confidence)\n print(support)\n print(confidence)\n\n te = TransactionEncoder()\n te_ary = te.fit(dataset).transform(dataset)\n df = pd.DataFrame(te_ary, columns=te.columns_)\n\n frequent_itemsets = apriori(df, min_support=support, use_colnames=True)\n print(frequent_itemsets)\n print(\"\\n-----------\\n\")\n rules = association_rules(frequent_itemsets, metric=\"confidence\", min_threshold=confidence)\n \n return rules\n\n","sub_path":"associationRulesService.py","file_name":"associationRulesService.py","file_ext":"py","file_size_in_byte":9526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"102876845","text":"import sys, pygame, math, numpy, random, time, copy\nfrom pygame.locals import *\n\nfrom constants import *\nfrom utils import *\nfrom core import *\nfrom mycreatepathnetwork import *\nfrom mynavigatorhelpers import *\n\n\n###############################\n### AStarNavigator\n###\n### Creates a path node network and implements the FloydWarshall all-pairs shortest-path algorithm to create a path to the given destination.\n\nclass AStarNavigator(NavMeshNavigator):\n\n\tdef __init__(self):\n\t\tNavMeshNavigator.__init__(self)\n\n\n\t### Create the pathnode network and pre-compute all shortest paths along the network.\n\t### self: the navigator object\n\t### world: the world object\n\tdef createPathNetwork(self, world):\n\t\tself.pathnodes, self.pathnetwork, self.navmesh = myCreatePathNetwork(world, self.agent)\n\t\treturn None\n\n\t### Finds the shortest path from the source to the destination using A*.\n\t### self: the navigator object\n\t### source: the place the agent is starting from (i.e., it's current location)\n\t### dest: the place the agent is told to go to\n\tdef computePath(self, source, dest):\n\t\t### Make sure the next and dist matricies exist\n\t\tif self.agent != None and self.world != None:\n\t\t\tself.source = source\n\t\t\tself.destination = dest\n\t\t\t### Step 1: If the agent has a clear path from the source to dest, then go straight there.\n\t\t\t### Determine if there are no obstacles between source and destination (hint: cast rays against world.getLines(), check for clearance).\n\t\t\t### Tell the agent to move to dest\n\t\t\t### Step 2: If there is an obstacle, create the path that will move around the obstacles.\n\t\t\t### Find the pathnodes closest to source and destination.\n\t\t\t### Create the path by traversing the self.next matrix until the pathnode closes to the destination is reached\n\t\t\t### Store the path by calling self.setPath()\n\t\t\t### Tell the agent to move to the first node in the path (and pop the first node off the path)\n\t\t\tif clearShot(source, dest, self.world.getLinesWithoutBorders(), self.world.getPoints(), self.agent):\n\t\t\t\tself.agent.moveToTarget(dest)\n\t\t\telse:\n\t\t\t\tstart = findClosestUnobstructed(source, self.pathnodes, self.world.getLinesWithoutBorders())\n\t\t\t\tend = findClosestUnobstructed(dest, self.pathnodes, self.world.getLinesWithoutBorders())\n\t\t\t\tif start != None and end != None:\n\t\t\t\t\t#print len(self.pathnetwork)\n\t\t\t\t\tnewnetwork = unobstructedNetwork(self.pathnetwork, self.world.getGates())\n\t\t\t\t\t#print len(newnetwork)\n\t\t\t\t\t#print \"ok\"\n\t\t\t\t\tclosedlist = []\n\t\t\t\t\tpath, closedlist = astar(start, end, newnetwork)\n\t\t\t\t\tif path is not None and len(path) > 0:\n\t\t\t\t\t\tpath = shortcutPath(source, dest, path, self.world, self.agent)\n\t\t\t\t\t\tself.setPath(path)\n\t\t\t\t\t\tif self.path is not None and len(self.path) > 0:\n\t\t\t\t\t\t\tfirst = self.path.pop(0)\n\t\t\t\t\t\t\tself.agent.moveToTarget(first)\n\t\treturn None\n\n\t### Called when the agent gets to a node in the path.\n\t### self: the navigator object\n\tdef checkpoint(self):\n\t\tmyCheckpoint(self)\n\t\treturn None\n\n\t### This function gets called by the agent to figure out if some shortcutes can be taken when traversing the path.\n\t### This function should update the path and return True if the path was updated.\n\tdef smooth(self):\n\t\treturn mySmooth(self)\n\n\tdef update(self, delta):\n\t\tmyUpdate(self, delta)\n\n\ndef unobstructedNetwork(network, worldLines):\n\tnewnetwork = []\n\tfor l in network:\n\t\thit = rayTraceWorld(l[0], l[1], worldLines)\n\t\tif hit == None:\n\t\t\tnewnetwork.append(l)\n\treturn newnetwork\n\n\ndef foom (OO0OOO000OO0O000O ,O0O000OOOOOOO0O0O ,func =lambda O0OO0OOO00000OO0O :O0OO0OOO00000OO0O ):#line:1\n\tfor OO00O0OOO0O0O0OO0 in xrange (len (O0O000OOOOOOO0O0O )):#line:2\n\t\tif func (OO0OOO000OO0O000O )0 :#line:23\n\t\tOOO0O0O0OO0OOO00O .add (O00OO0OOOO00000OO [0 ])#line:24\n\t\tOO00O0000OO000O00 .add (O00OO0OOOO00000OO )#line:25\n\t\tO0000OO00O0OOO0OO .pop (0 )#line:26\n\t\tO0O00O0000OOO0OOO =fooz (O00OO0OOOO00000OO ,O00000O0OOO0OOOO0 ,O0OO0OOOOOO0OO0OO )#line:28\n\t\tfor OO000O00O0000O0OO in O0O00O0000OOO0OOO :#line:30\n\t\t\tif OO000O00O0000O0OO [0 ]not in OOO0O0O0OO0OOO00O :#line:31\n\t\t\t\tfoom (OO000O00O0000O0OO ,O0000OO00O0OOO0OO ,lambda O0OO0O0O000OO00O0 :O0OO0O0O000OO00O0 [1 ]+O0OO0O0O000OO00O0 [2 ])#line:32\n\t\tif len (O0000OO00O0OOO0OO )>0 :#line:34\n\t\t\tO00OO0OOOO00000OO =O0000OO00O0OOO0OO [0 ]#line:35\n\t\telse :#line:36\n\t\t\tO00OO0OOOO00000OO =None #line:37\n\tif O00OO0OOOO00000OO is not None :#line:40\n\t\twhile O00OO0OOOO00000OO [3 ]is not None :#line:41\n\t\t\tO0OOO0OOOOO0O00OO .append (O00OO0OOOO00000OO [0 ])#line:42\n\t\t\tO00O0O000O000OOO0 =O00OO0OOOO00000OO [3 ]#line:43\n\t\t\tfor OO00O0O000O000O0O in list (OO00O0000OO000O00 ):#line:44\n\t\t\t\tif O00O0O000O000OOO0 ==OO00O0O000O000O0O [0 ]:#line:45\n\t\t\t\t\tO00OO0OOOO00000OO =OO00O0O000O000O0O #line:46\n\t\t\t\t\tbreak #line:47\n\t\tO0OOO0OOOOO0O00OO .append (O00OO0OOOO00000OO [0 ])#line:48\n\t\tO0OOO0OOOOO0O00OO .reverse ()#line:49\n\tOOO0O0O0OO0OOO00O =list (OOO0O0O0OO0OOO00O )#line:50\n\treturn O0OOO0OOOOO0O00OO ,OOO0O0O0OO0OOO00O #line:52\ndef fooz (OO0OOOOOOO00O0O0O ,OOOOOO0OOOOOOO000 ,OO00O0O000O0OOO0O ):#line:55\n\tOO0OOOO0O0O0OOOOO =[]#line:56\n\tfor OO0O00O0OO00OOO00 in OOOOOO0OOOOOOO000 :#line:57\n\t\tif OO0O00O0OO00OOO00 [0 ]==OO0OOOOOOO00O0O0O [0 ]:#line:58\n\t\t\tOO0OOOO0O0O0OOOOO .append ((OO0O00O0OO00OOO00 [1 ],OO0OOOOOOO00O0O0O [1 ]+distance (OO0O00O0OO00OOO00 [0 ],OO0O00O0OO00OOO00 [1 ]),distance (OO0O00O0OO00OOO00 [1 ],OO00O0O000O0OOO0O ),OO0OOOOOOO00O0O0O [0 ]))#line:59\n\t\telif OO0O00O0OO00OOO00 [1 ]==OO0OOOOOOO00O0O0O [0 ]:#line:60\n\t\t\tOO0OOOO0O0O0OOOOO .append ((OO0O00O0OO00OOO00 [0 ],OO0OOOOOOO00O0O0O [1 ]+distance (OO0O00O0OO00OOO00 [0 ],OO0O00O0OO00OOO00 [1 ]),distance (OO0O00O0OO00OOO00 [0 ],OO00O0O000O0OOO0O ),OO0OOOOOOO00O0O0O [0 ]))#line:61\n\treturn OO0OOOO0O0O0OOOOO #line:62\ndef myUpdate (OO0OOO00O0OO00O00 ,O0OOO0000OOOO00OO ):#line:66\n\tif OO0OOO00O0OO00O00 .getPath ()is not None :#line:68\n\t\tOOOO000O0OOO00000 =OO0OOO00O0OO00O00 .world .getGates ()#line:69\n\t\tOO0O000O000O0000O =OO0OOO00O0OO00O00 .agent .getLocation ()#line:79\n\t\tfor OO0O00OOO0000OOOO in OO0OOO00O0OO00O00 .getPath ()+[OO0OOO00O0OO00O00 .getDestination ()]:#line:80\n\t\t\tif OO0O000O000O0000O is not None :#line:81\n\t\t\t\tO00O0OO0O000000O0 =rayTraceWorld (OO0O000O000O0000O ,OO0O00OOO0000OOOO ,OOOO000O0OOO00000 )#line:82\n\t\t\t\tif O00O0OO0O000000O0 is not None :#line:83\n\t\t\t\t\tOO0OOO00O0OO00O00 .setPath (None )#line:85\n\t\t\t\t\tOO0OOO00O0OO00O00 .agent .stopMoving ()#line:86\n\t\t\t\t\treturn None #line:87\n\t\t\tOO0O000O000O0000O =OO0O00OOO0000OOOO\n\t\treturn None #line:108\ndef myCheckpoint (O0OOOOOOO0OOOO000 ):#line:113\n\t\"\"#line:128\n\treturn None #line:130\ndef clearShot(p1, p2, worldLines, worldPoints, agent):\n\t### YOUR CODE GOES BELOW HERE ###\n\tif rayTraceWorld(p1, p2, worldLines) != None:\n\t\treturn False\n\tfor p in worldPoints:\n\t\tif minimumDistance((p1, p2), p) < agent.getMaxRadius():\n\t\t\treturn False\n\treturn True\n\t### YOUR CODE GOES ABOVE HERE ###\n\treturn False\n#e9015584e6a44b14988f13e2298bcbf9\n\n\n#===============================================================#\n# Obfuscated by Oxyry Python Obfuscator (http://pyob.oxyry.com) #\n#===============================================================#\n","sub_path":"MOBA/astarnavigator.py","file_name":"astarnavigator.py","file_ext":"py","file_size_in_byte":7854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"552810919","text":"from django.urls import path\nfrom . import views\n\napp_name = 'home_app'\n\nurlpatterns = [\n path('', views.HomePageView.as_view(), name='home'),\n path('contacto/', views.ContactFormView.as_view(), name='contact'),\n path('search/', views.SearchResultView.as_view(), name='search')\n]\n","sub_path":"applications/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"248323254","text":"import os\nimport subprocess\n\ndata_dir = \"/home/lemin/1TBdisk/data/bne\"\nfile_list = [\"bytecup.corpus.train.{}.txt\".format(i) for i in range(0, 9)]\ntokenizer_dir = \"/home/lemin/1TBdisk/data/bne/tokenizer\"\n\n\ndef tokenizer_stories(data_dir, tokenizer_dir):\n print(\"Preparing to tokenize {} to {}...\".format(data_dir,\n tokenizer_dir))\n\n # make IO list file\n print(\"Making list of files to tokenize...\")\n with open(\"mapping.txt\", \"w\") as f:\n for s in file_list:\n f.write(\n \"{} \\t {}\\n\".format(\n os.path.join(data_dir, s),\n os.path.join(tokenizer_dir, s)\n )\n )\n command = ['java', 'edu.stanford.nlp.process.PTBTokenizer',\n '-ioFileList', '-preserveLines', 'mapping.txt']\n print(\"Tokenizing {} files in {} and saving in {}...\".format(\n len(file_list), data_dir, tokenizer_dir))\n subprocess.call(command)\n print(\"Stanford CoreNLP Tokenizer has finished.\")\n os.remove(\"mapping.txt\")\n\n num_orig = len(file_list)\n num_tokenized = len(os.listdir(tokenizer_dir))\n if num_orig != num_tokenized:\n raise Exception(\n \"The tokenized stories directory {} contains {} files, but it \"\n \"should contain the same number as {} (which has {} files). Was\"\n \" there an error during tokenization?\".format(\n tokenizer_dir, num_tokenized, data_dir, num_orig)\n )\n\n print(\"Successfully finished tokenizing {} to {}.\\n\".format(\n data_dir, tokenizer_dir))\n\n\ndef tokenize_single_file(file_name, tokenizer_dir):\n print(\"Preparing to tokenize {} to {}...\".format(file_name,\n tokenizer_dir))\n\n print(\"Making list of files to tokenize...\")\n with open(\"mapping.txt\", \"w\") as f:\n\n f.write(\"{} \\t {}\\n\".format(\n os.path.join(data_dir, file_name),\n os.path.join(tokenizer_dir, file_name)\n ))\n command = ['java', 'edu.stanford.nlp.process.PTBTokenizer',\n '-ioFileList', '-preserveLines', 'mapping.txt']\n print(\"Tokenizing {} files in {} and saving in {}...\".format(\n len(file_list), data_dir, tokenizer_dir))\n subprocess.call(command)\n print(\"Stanford CoreNLP Tokenizer has finished.\")\n os.remove(\"mapping.txt\")\n\n\nif __name__ == '__main__':\n tokenizer_stories(data_dir, tokenizer_dir)","sub_path":"tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"581832398","text":"\nimport numpy as np\nimport torch\n\nimport bgflow as bg\nfrom .tensor_info import BONDS, ANGLES, TORSIONS, FIXED, AUGMENTED\n\n__all__ = [\"InternalCoordinateMarginals\"]\n\n\nclass InternalCoordinateMarginals(dict):\n def __init__(\n self,\n current_dims,\n ctx,\n bond_mu=1.0,\n bond_sigma=1.0,\n bond_lower=1e-5,\n bond_upper=np.infty,\n angle_mu=0.5,\n angle_sigma=1.0,\n angle_lower=1e-5,\n angle_upper=1.0,\n torsion_lower=0.0,\n torsion_upper=1.0,\n fixed_scale=20.0,\n bonds=BONDS,\n angles=ANGLES,\n torsions=TORSIONS,\n fixed=FIXED,\n augmented=AUGMENTED,\n ):\n self.current_dims = current_dims\n self.ctx = ctx\n super().__init__()\n if bonds in current_dims:\n self[bonds] = bg.TruncatedNormalDistribution(\n mu=bond_mu*torch.ones(current_dims[bonds], **ctx),\n sigma=bond_sigma*torch.ones(current_dims[bonds], **ctx),\n lower_bound=torch.tensor(bond_lower, **ctx),\n upper_bound=torch.tensor(bond_upper, **ctx),\n )\n\n # angles\n if angles in current_dims:\n self[angles] = bg.TruncatedNormalDistribution(\n mu=angle_mu*torch.ones(current_dims[angles], **ctx),\n sigma=angle_sigma*torch.ones(current_dims[angles], **ctx),\n lower_bound=torch.tensor(angle_lower, **ctx),\n upper_bound=torch.tensor(angle_upper, **ctx),\n )\n\n # angles\n if torsions in current_dims:\n self[torsions] = bg.SloppyUniform(\n low=torsion_lower*torch.ones(current_dims[torsions], **ctx),\n high=torsion_upper*torch.ones(current_dims[torsions], **ctx)\n )\n\n # fixed\n if fixed in current_dims:\n self[fixed] = torch.distributions.Normal(\n loc=torch.zeros(current_dims[fixed], **ctx),\n scale=fixed_scale*torch.ones(current_dims[fixed], **ctx)\n )\n\n # augmented\n if augmented in current_dims:\n self[augmented] = torch.distributions.Normal(\n loc=torch.zeros(current_dims[augmented], **ctx),\n scale=torch.ones(current_dims[augmented], **ctx)\n )\n\n","sub_path":"bgflow/bgflow/factory/icmarginals.py","file_name":"icmarginals.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"570968024","text":"#!/usr/bin/env python3\n\n# OpenBACH is a generic testbed able to control/configure multiple\n# network/physical entities (under test) and collect data from them. It is\n# composed of an Auditorium (HMIs), a Controller, a Collector and multiple\n# Agents (one for each network entity that wants to be tested).\n#\n#\n# Copyright © 2016 CNES\n#\n#\n# This file is part of the OpenBACH testbed.\n#\n#\n# OpenBACH is a free software : you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free\n# Software Foundation, either version 3 of the License, or (at your option)\n# any later version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program. If not, see http://www.gnu.org/licenses/.\n\n\n\"\"\"Sources of the Job synchronization\"\"\"\n\n\n__author__ = 'Viveris Technologies'\n__credits__ = '''Contributors:\n * Adrien THIBAUD \n * Mathias ETTINGER \n'''\n\n\nimport subprocess\n\n\ndef main():\n subprocess.run(['systemctl', 'stop', 'ntp.service'], check=True)\n subprocess.run(['ntpd', '-gq'], check=True)\n subprocess.run(['systemctl', 'restart', 'ntp.service'], check=True)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/jobs/admin_jobs/synchronization/files/synchronization.py","file_name":"synchronization.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"270162276","text":"\"\"\"\n Helper functions frequently used by the module's classes\n\"\"\"\n\ndef add_tag(tags, tag):\n \"\"\"\n Add a tag to a given tag list\n \"\"\"\n\n # Format tag to e621 standards\n tag = clean_tag(tag)\n\n # Retrieve the tag 'key' if any\n key = None\n if ':' in tag:\n key = tag.split(':')[0]\n key = '%s:' % key\n cleaned_key = clean_key(key)\n\n for i, item in enumerate(tags):\n # Look for simple duplicates\n if item == tag:\n return tags\n\n\n # Look for key duplicates\n if key and (key in item or cleaned_key in item):\n tags[i] = tag\n return tags\n\n tags.append(tag)\n return tags\n\ndef clean_tag(tag):\n \"\"\"\n Format tag to match e621 format\n \"\"\"\n tag = tag.replace(' ', '_')\n return tag\n\ndef clean_key(key):\n \"\"\"\n Clean up a tag key\n \"\"\"\n key = key.replace(':', '')\n\n if len(key) >= 1 and key[0] == '-':\n key = key[1:]\n\n return key\n","sub_path":"e621apy/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"599212120","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def __init__(self):\n self.res = []\n\n def minDiffInBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n self.inorder(root)\n min_val = self.res[1] - self.res[0]\n for i in range(len(self.res) - 1):\n diff = abs(self.res[i + 1] - self.res[i])\n min_val = min(min_val, diff)\n return min_val\n\n def inorder(self, r):\n if r is None:\n return\n self.inorder(r.left)\n self.res.append(r.val)\n self.inorder(r.right)\n\n\n\n\n\n\n\n","sub_path":"LeetCode(Python)/783. Minimum Distance Between BST Nodes.py","file_name":"783. Minimum Distance Between BST Nodes.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"463707621","text":"from hello_world.formater import plain_text_upper_case\nfrom hello_world.formater import plain_text_lower_case\nfrom hello_world.formater import format_to_xml\nfrom hello_world.formater import plain_text\nfrom hello_world.formater import format_to_json\n\nimport unittest\nimport json\nimport xml.etree.cElementTree as ET\n\n\nclass TestFormater(unittest.TestCase):\n def test_plain_uppercase(self):\n r = plain_text_upper_case(\"wwww\", \"EEEMSG\")\n name = r.split(\" \")[0]\n msg = r.split(\" \")[1]\n self.assertTrue(name.isupper())\n self.assertTrue(msg.isupper())\n\n def test_plain_text_lower_case(self):\n r = plain_text_lower_case(\"wwww\", \"EEEMSG\")\n name = r.split(\" \")[0]\n msg = r.split(\" \")[1]\n self.assertTrue(name.islower())\n self.assertTrue(msg.islower())\n\n def test_format_to_xml(self):\n name = \"Krysia\"\n msg = \"Hello\"\n result = format_to_xml(msg, name)\n actual = ET.fromstring(result)\n actualName = actual.find(\"name\")\n actualMsg = actual.find(\"msg\")\n self.assertEqual(name, actualName.text)\n self.assertEqual(msg, actualMsg.text)\n\n def test_format_to_json(self):\n name = \"Kasia\"\n msg = \"How are you?\"\n actual = json.loads(format_to_json(msg, name))\n self.assertEqual(name, actual['imie'])\n self.assertEqual(msg, actual['msg'])\n\n def test_plain_text(self):\n name = \"Basia\"\n msg = \"Hi\"\n result = plain_text(msg, name)\n self.assertEqual(name, result.split(\" \")[0])\n self.assertEqual(msg, result.split(\" \")[1])\n","sub_path":"test/test_formater.py","file_name":"test_formater.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"339638833","text":"# condition : \n#1. substring len (r-l+1)(idx) r move l stay \n#2. longest(maxx) \n#3. not repeat: l,r pointer, dic store the char its idx (for renew l)\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n l = 0\n dic = {}\n maxx = 0\n for r in range(len(s)): \n if s[r] in dic and l <= dic[s[r]]: \n# s[r] in s[l:r] 只有在检查的范围内重复才更新。 比如 \"twwabcdeft\" 当r到最后一位的时候 他出现过,但是t没出现在我们检查的范围内,所以r-l+1要更新(进入else的循环)而不是不更新了\n l = dic[s[r]]+1\n else:\n maxx = max(maxx,r-l+1)\n dic[s[r]] =r\n return maxx\n#time O(n)\n#spaceO(n)\n","sub_path":"0. Sliding Window/3. Longest Substring Without Repeating Characters.py","file_name":"3. Longest Substring Without Repeating Characters.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"309911523","text":"import os\nfrom setuptools import setup, find_packages\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\nsetup(\n name = 'zetapush_python',\n version = \"0.1.5\",\n author = \"Damien Le Dantec\",\n author_email = \"damien.le-dantec@zetapush.com\",\n description = \"Zetapush Python SDK\",\n license = \"MIT\",\n packages = find_packages(),\n package_data={\n },\n entry_points={ },\n install_requires = requirements,\n include_package_data=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"104966778","text":"import random\nfrom .lib import AiNNBase\nfrom .lib.nn_lib import NetworkBase, INPUT_SIZE\nimport tensorflow as tf\nMAX_BEADS = 48\n\n\ndef oneHot(r, length=MAX_BEADS):\n \"\"\"\n Given an integer r in the range [0:48] return vector of length 48 where all\n values are zero except the vector at index r which is one.\n\n >>> oneHot(5, 10)\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]\n\n >>> oneHot(15, 10)\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n \"\"\"\n if r > length - 1:\n r = length - 1\n return [0] * (r) + [1] + [0] * (length - 1 - r)\n\n\nclass Network(NetworkBase):\n\n def initInputPlaceholder(self):\n self.input_size = INPUT_SIZE * MAX_BEADS\n # self.pre_x0 = tf.placeholder(\n # tf.float32,\n # shape=(None, MAX_BEADS, INPUT_SIZE),\n # name=\"raw_input\")\n # self.pre_x1 = tf.reshape(self.pre_x0, [-1, self.input_size, 1],\n # name=\"reshaped\")\n # self.x = tf.squeeze(self.pre_x1, [2], name=\"squeezed\")\n self.x = tf.placeholder(\n tf.float32,\n shape=(None, self.input_size),\n name=\"x\")\n\n def makeInputVector(self, state):\n vector = [oneHot(r) for r in state[:14]]\n return [item for sublist in vector for item in sublist]\n\n def __init__(self, name):\n super().__init__(name)\n with self.graph.as_default():\n self.initPlaceholders()\n self.addHiddenLayer(128)\n self.initOutputLayer()\n self.initCostFn()\n self.initSession()\n\n\nclass AI(AiNNBase):\n def __init__(self):\n super().__init__()\n self.nn = Network(__name__)\n\n def taunt(self):\n taunts = [\n 'I look at the board in a different way.',\n \"I'll win this one for sure.\",\n \"You're not as good looking as I am.\",\n ]\n return random.choice(taunts)\n","sub_path":"mancala/ai/nnx1h128.py","file_name":"nnx1h128.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"653296761","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport sys\nimport os\nimport subprocess\n\n\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\npackages_dir = os.path.join(current_dir, '..', 'resources', 'packages')\ndevnull = open('/dev/null', 'w')\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\ndef gets(prompt):\n if sys.version_info[0] < 3:\n return raw_input(prompt)\n else:\n return input(prompt)\n\n\ndef get_package_managers():\n for f in os.listdir(packages_dir):\n if f[0] != '.':\n yield f\n\n\ndef not_enough_arguments():\n eprint('usage: ./packages.py [PACKAGE LIST]')\n eprint()\n eprint(' try:')\n for m in get_package_managers():\n eprint(' ./packages.py', m)\n exit(1)\n\n\ndef invalid_package_manager(package_manager):\n eprint(package_manager, 'is not a valid package manager')\n eprint()\n eprint('valid package managers:')\n for m in get_package_managers():\n eprint('*', m)\n exit(1)\n\n\ndef package_dir(package_manager):\n return os.path.join(packages_dir, package_manager)\n\n\ndef file_path(package_manager, f):\n return os.path.join(package_dir(package_manager), f)\n\n\ndef check_package_manager_installed(package_manager):\n check_installed_bin = os.path.join(package_dir(package_manager),\n 'check_installed')\n check_installed_result = subprocess.call([check_installed_bin],\n stdout=devnull, stderr=devnull)\n if check_installed_result != 0:\n eprint(package_manager, 'does not appear to be installed')\n exit(1)\n\n\ndef first_word(s):\n return s.split()[0]\n\n\ndef packages_to_ask_about(package_manager):\n desired_txt = file_path(package_manager, 'desired')\n existing_bin = file_path(package_manager, 'existing')\n\n existing = set(subprocess.check_output([existing_bin]).split('\\n'))\n\n for desired in open(desired_txt):\n desired = desired.strip()\n if len(desired) == 0:\n continue\n desired_name = first_word(desired)\n if desired_name not in existing:\n yield desired\n\n\ndef main(argv):\n if len(argv) < 2:\n not_enough_arguments()\n\n package_manager = argv[1]\n\n if not os.path.isdir(package_dir(package_manager)):\n invalid_package_manager(package_manager)\n\n check_package_manager_installed(package_manager)\n\n packages_to_install = []\n for package in packages_to_ask_about(package_manager):\n user_says = gets('install ' + first_word(package) + ' (Y/n)? ').strip()\n if user_says.lower() in ['', 'y', 'yes', 'yas']:\n packages_to_install.append(package)\n\n print()\n\n if len(packages_to_install) == 0:\n print(\"i guess we're done here\")\n return\n\n print(\"alright, let's do this\")\n print()\n\n preamble_bin = file_path(package_manager, 'preamble')\n if os.path.isfile(preamble_bin):\n subprocess.call(file_path(package_manager, 'preamble'), shell=True)\n\n install_command_bin = file_path(package_manager, 'install_command')\n for package in packages_to_install:\n cmd = subprocess.check_output([install_command_bin, package]).strip()\n subprocess.call(cmd, shell=True)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"script/packages.py","file_name":"packages.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"430267900","text":"#############\n## Imports ##\n#############\n\nimport random\n\nimport torch\nimport torch.nn as nn\n\nimport corpus\n\n\n#######################\n## Important Globals ##\n#######################\n\nsample_length = 100\nemb_dim = 100\nhidden_dim = 500\n\n\n################################\n## Dataset-Dependent Defaults ##\n################################\n\ndataset = corpus.brown_dataset\nvocab_size = dataset.vocab_size\n\n\n##########################\n## Initialize the Rando ##\n##########################\n\nrandom.seed(777)\n\n\n#####################\n## The Model Class ##\n#####################\n\nclass ProbabilisticNeuralLM(nn.Module):\n def __init__(\n self,\n vocab_size,\n emb_dim=emb_dim,\n hidden_dim=hidden_dim,\n sample_length=sample_length\n ):\n super(ProbabilisticNeuralLM, self).__init__()\n \n self.emb = nn.Embedding(vocab_size, emb_dim)\n self.hidden = nn.Linear(sample_length * emb_dim, hidden_dim)\n self.hidden_activation = nn.ReLU()\n self.output = nn.Linear(hidden_dim, vocab_size)\n self.output_activation = nn.LogSoftmax(dim=-1)\n\n def forward(self, xs):\n batch_size = xs.size()[0]\n\n # embed and merge\n xs = self.emb(xs)\n xs = torch.reshape(xs, (batch_size, -1))\n\n # hidden layer\n hidden = self.hidden(xs)\n hidden = self.hidden_activation(hidden)\n\n # output log probabilities\n output_logits = self.output(hidden)\n output_log_probs = self.output_activation(output_logits)\n \n return output_log_probs\n\n def predict(self, xs):\n return torch.argmax(self.forward(xs))\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"279502313","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Challenges of 30 Days of Code from HackerRank.\n\nThis is a basic tutorial challenge specified by `HackerRank`_.\n\n.. _HackerRank:\n https://www.hackerrank.com/challenges/30-arrays\n\"\"\"\n\ndef main():\n \"\"\"The main routine.\"\"\"\n n = int(input().strip())\n arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]\n print(\" \".join(str(x) for x in arr[::-1]))\n\nif __name__ == '__main__':\n main()\n","sub_path":"hackerrank/practice/30_days_of_code/day07_arrays.py","file_name":"day07_arrays.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"134836165","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport math\nimport datetime\nfrom dateutil.parser import parse\n\ndef checkmylist(mylist):\n it = (np.int64(x) for x in mylist)\n first = next(it)\n return all(a == b for a, b in enumerate(it, first + 1))\n \ndef tryConvertionToType(value, default, *types):\n for t in types:\n try:\n return t(value)\n except ValueError:\n #print ('ERROR IN Value !!!')\n #print (value)\n continue\n except TypeError:\n #print ('ERROR IN Type !!!')\n #print (value)\n continue\n return default\n\n\ndef identifyCorrectDatatype(columnValues):\n from dateutil.parser import parse\n\n if all(isinstance(x, (int, np.int64)) for x in columnValues):\n# all the values in the column are identified as Integers. No conversion is required\n #print ('Is Integer')\n return ('Integer')\n elif all(isinstance(x, (float, np.float64)) for x in columnValues):\n# all the values in the column are identified as Floats. No conversion is required\n #print ('Is Float')\n return ('Float')\n else:\n# Values in the input column are not numbers. The first step is to covert these to a standard\n# String data type\n#\n# Remove all the nulls from the column values\n stripList = list(filter(None, columnValues))\n# Try to convert all values in the column to string datatype\n try:\n stripList = list(map(lambda x: tryConvertionToType(x, None, str).strip(), stripList))\n# Could not convert to string. Unexcepted error. Abort\n except ValueError:\n print ('ERROR IN STRING !!!')\n# Remove all values that contain only white spaces (blank and formating characters such as newline)\n stripList = [s for s in stripList if (s and not(s.isspace()))]\n try:\n# Covert all string values to Float datatype. The function ensures that if the coversion is not possible,\n# a null value (None) will be created as default\n stripListNew = list(map(lambda x: tryConvertionToType(x, None, float), stripList))\n# Find out the number of items that were succesfuly converted to float\n itemsNotNulls = len(list(filter(lambda x: x is not None, stripListNew)))\n# Find out total number of items\n itemsAll = len(stripList)\n #print (itemsNotNulls, itemsAll)\n\n# If the ratio of successfully coverted items to total items is less than the threshold,\n# then the values can not be coverted to float\n #print ((np.float64(itemsNotNulls) / itemsAll))\n if (np.float64(itemsNotNulls) / itemsAll) > 0.75:\n return ('Float')\n else:\n# Checking for date datatype. Covert all string values to date. If conversion is not possible,\n# then a null value (None) will be created as default\n try:\n stripListNew = list(map(lambda x: tryConvertionToType(x, None, parse), stripList))\n# Find out the number of items that were succesfuly converted to date\n itemsNotNulls = len(list(filter(lambda x: x is not None, stripListNew)))\n# Find out total number of items\n itemsAll = len(stripList)\n #print (itemsNotNulls, itemsAll)\n# If the ratio of successfully coverted items to total items is less than the threshold,\n# then the values can not be coverted to date. The values inside the input are identified as\n# String data types\n if (np.float64(itemsNotNulls) / itemsAll) > 0.8:\n return ('Date')\n else:\n return ('String')\n except ValueError:\n# Unexpected error\n print ('ERROR IN DATE !!!! ')\n# Unexpected error\n except ValueError:\n print ('ERROR IN NUMBER !!!')\n except TypeError:\n print ('ERROR IN NUMBER !!!')\n return ('String')\n return (type(columnValues))\n\ndef covertToCorrectDataTypes (dataset):\n from dateutil.parser import parse\n\n from random import randint\n try:\n num_rows, num_columns = dataset.shape\n except ValueError:\n num_columns = 1\n \n for i in range(num_columns):\n# Define number of samples to be considerd for evaluating data types of the input. \n# In case of a single instance the instance itself is chosen\n sampleLimit = min(100, len(dataset.iloc[:, i]))\n \n# Choose sample values randomly from the input. If the input size is small entire set is chosen \n selectValues = []\n for j in range(sampleLimit):\n listEntry = randint(0,len(dataset.iloc[:, i]))\n selectValues.append(list(dataset.iloc[:, i].values)[j])\n\n data_type = identifyCorrectDatatype(selectValues)\n print ('Identified Data Type is : ', data_type)\n if data_type == 'String':\n# If identified datatype is string, remove leading and trailing white spaces\n dataset.iloc[:,i] = dataset.iloc[:,i].apply(lambda x: tryConvertionToType(x, None, str).strip())\n# If identified datatype is float, covert all to float and default to null when no coversion is possible\n elif data_type == 'Float':\n dataset.iloc[:,i] = dataset.iloc[:,i].apply(lambda x: tryConvertionToType(x, None, np.float64))\n# IF identified datatype is date, covert all the date format to datetime object.\n elif data_type == 'Date':\n dataset.iloc[:,i] = dataset.iloc[:,i].apply(lambda x: tryConvertionToType(x, None, parse))\n #print (dataset.head(5))\n return (0)\n \ndef preprocess_ind (dataset, override):\n\n unique_identification_cutoff = 0.1\n drop_column_cutoff = 0.75\n\n override_ind = 0\n encoding_override_ind = 1\n dropcolumn_override_ind = 2\n normalize_override_ind = 3\n\n num_rows, num_columns = dataset.shape\n \n null_list = dataset.isnull().sum()\n encoding_override = list((override == encoding_override_ind).values)[0]\n drop_column_override = list((override == dropcolumn_override_ind).values)[0]\n normalize_column_override = list((override == normalize_override_ind).values)[0]\n\n return_list = []\n category_encoding_columns = []\n missing_value_strategy = []\n drop_strategy_columns = []\n normalize_strategy_columns = []\n\n#Inspect every columns\n for i in range(num_columns):\n# Inspect uniquenes\n\n# Make sure that the null values are not considered while finding out the count of unique values for the column\n presence_of_missing_values = False\n percentage_missing_values = 100*null_list[i]/num_rows\n column_with_notnull_values = dataset[dataset.columns[i]][dataset[dataset.columns[i]].notnull()==True]\n if null_list[i] != 0:\n presence_of_missing_values = True\n\n# Initialize indicators\n drop_ind = False\n encode_ind = False\n\n# disparate_data_index is the ratio of number of unique values in the column to the number of rows. Lower values\n# indicates potential of uniqueness. A value of 1 indicates that every value in the coulmn is different than the rest\n disparate_data_index = ((len(column_with_notnull_values.unique())) /(num_rows-null_list[i]))\n\n\n# Inspect the data type\n number_datatype = False\n #if dataset[dataset.columns[i]].dtype in ('int64', 'float64'):\n if all(isinstance(n, np.int64) for n in column_with_notnull_values) \\\n or all(isinstance(n, np.float64) for n in column_with_notnull_values): \n number_datatype = True\n\n if presence_of_missing_values:\n if percentage_missing_values > 50:\n#Set the missing value strategy to removing the column(or feature)\n missing_value_strategy.append(3)\n drop_strategy_columns.append(i)\n drop_ind = True\n elif percentage_missing_values < 1:\n#Set the missing value strategy to removing the rows with missing value\n missing_value_strategy.append(1)\n elif number_datatype:\n#Set the missing value strategy to setting the value to mean of the column values\n missing_value_strategy.append(2)\n else:\n#Set the missing value strategy to UNKNOWN. This is related to non-numeric fields\n missing_value_strategy.append(4)\n else:\n#Set the missing value strategy to not applicable as there are no missing values\n missing_value_strategy.append(0)\n\n if disparate_data_index < drop_column_cutoff \\\n or number_datatype \\\n or drop_column_override[i] \\\n or missing_value_strategy[i] == 3:\n pass\n else:\n drop_strategy_columns.append(i)\n drop_ind = True\n\n# Determine if the column is a candidate for feature encoding\n if disparate_data_index > unique_identification_cutoff \\\n or encoding_override[i] \\\n or drop_ind \\\n or missing_value_strategy[i] == 3:\n pass\n else:\n category_encoding_columns.append(i)\n encode_ind = True\n\n# Determine if the column values need to be normalized\n\n if encode_ind or \\\n missing_value_strategy [i] == 3 or \\\n drop_ind or \\\n normalize_column_override[i] or \\\n not number_datatype:\n pass\n else:\n if checkmylist(dataset[dataset.columns[i]]):\n drop_strategy_columns.append(i)\n drop_ind = True\n else:\n normalize_strategy_columns.append(i)\n\n\n\n return_list.append(category_encoding_columns)\n return_list.append(missing_value_strategy)\n return_list.append(drop_strategy_columns)\n return_list.append(normalize_strategy_columns)\n\n return (return_list)\n\ndef preprocess_ind_df (dataset, override):\n\n unique_identification_cutoff = 0.1\n drop_column_cutoff = 0.75\n\n override_ind = 0\n drop_column_enforce_ind = 1 # 0000 0001\n encoding_override_ind = 4 # 0000 0100\n dropcolumn_override_ind = 2 # 0000 0010\n normalize_override_ind = 8 # 0000 1000\n standardize_override_ind = 16 # 0001 0000\n\n num_rows, num_columns = dataset.shape\n \n null_list = dataset.isnull().sum()\n \n drop_column_enforce = list(((override & drop_column_enforce_ind)==drop_column_enforce_ind).values)[0]\n standardize_override = list(((override & standardize_override_ind)==standardize_override_ind).values)[0]\n encoding_override = list(((override & encoding_override_ind)==encoding_override_ind).values)[0]\n drop_column_override = list(((override & dropcolumn_override_ind)==dropcolumn_override_ind).values)[0]\n normalize_column_override = list(((override & normalize_override_ind)==normalize_override_ind).values)[0]\n\n return_list = []\n category_encoding_columns = []\n missing_value_mean_columns = []\n missing_value_predict_columns = []\n missing_value_text_columns = []\n no_missing_value_columns = []\n drop_strategy_columns = []\n normalize_strategy_columns = []\n date_transform_columns = []\n\n#Inspect every columns\n for i in range(num_columns):\n# If marked for drop column populate list and continue\n if drop_column_enforce[i]:\n print ('Drop enforce column is : ', i)\n drop_ind = True\n drop_strategy_columns.append(i)\n continue\n #print (dataset[dataset.columns[i]].dtype)\n if dataset[dataset.columns[i]].dtype in ['datetime64[ns]']:\n #print ('ok')\n date_transform_columns.append(i)\n continue\n\n# Make sure that the null values are not considered while finding out the count of unique values for the column\n presence_of_missing_values = False\n percentage_missing_values = 100*null_list[i]/num_rows\n column_with_notnull_values = dataset[dataset.columns[i]][dataset[dataset.columns[i]].notnull()==True]\n if null_list[i] != 0:\n presence_of_missing_values = True\n\n# Initialize indicators\n drop_ind = False\n encode_ind = False\n\n# disparate_data_index is the ratio of number of unique values in the column to the number of rows. Lower values\n# indicates potential of uniqueness. A value of 1 indicates that every value in the coulmn is different than the rest\n disparate_data_index = ((len(column_with_notnull_values.unique())) /(num_rows-null_list[i]))\n\n print ('Disparate data index : ', disparate_data_index, ' Unique cut off : ', unique_identification_cutoff)\n# Inspect the data type\n number_datatype = False\n if all(isinstance(n, np.int64) for n in column_with_notnull_values) \\\n or all(isinstance(n, np.float64) for n in column_with_notnull_values): \n number_datatype = True\n\n if presence_of_missing_values:\n if percentage_missing_values > 90:\n#Set the missing value strategy to removing the column(or feature)\n #missing_value_strategy.append(3)\n drop_strategy_columns.append(i)\n drop_ind = True\n #elif percentage_missing_values < 1:\n#Set the missing value strategy to removing the rows with missing value\n #missing_value_strategy.append(1)\n elif number_datatype:\n#Set the missing value strategy to setting the value to mean of the column values\n missing_value_mean_columns.append(i)\n else:\n#Set the missing value strategy to UNKNOWN. This is related to non-numeric fields\n missing_value_text_columns.append(i)\n else:\n#Set the missing value strategy to not applicable as there are no missing values\n no_missing_value_columns.append(i)\n\n #print ('Columns is : ', dataset.columns[i], ' index is : ', disparate_data_index, ' number type : ', number_datatype)\n \n if disparate_data_index < drop_column_cutoff \\\n or number_datatype \\\n or drop_column_override[i]: \n pass\n else:\n drop_strategy_columns.append(i)\n drop_ind = True\n\n# Determine if the column is a candidate for feature encoding\n if disparate_data_index > unique_identification_cutoff \\\n or encoding_override[i] \\\n or drop_ind:\n pass\n else:\n category_encoding_columns.append(i)\n encode_ind = True\n\n# Determine if the column values need to be normalized\n\n if encode_ind or \\\n drop_ind or \\\n normalize_column_override[i] or \\\n not number_datatype:\n pass\n else:\n if checkmylist(dataset[dataset.columns[i]]):\n drop_strategy_columns.append(i)\n drop_ind = True\n else:\n normalize_strategy_columns.append(i)\n\n return_list = { \\\n 'dataset': dataset, \\\n 'encoding_columns': category_encoding_columns, \\\n 'missing_value_mean_columns': missing_value_mean_columns, \\\n 'missing_value_text_columns': missing_value_text_columns, \\\n 'missing_value_predict_columns': missing_value_predict_columns, \\\n 'no_missing_value_columns': no_missing_value_columns, \\\n 'drop_columns': drop_strategy_columns, \\\n 'normalize_columns': normalize_strategy_columns, \\\n 'date_transform_columns': date_transform_columns\n\n }\n\n print ('Drop Columns ', drop_strategy_columns)\n print ('Normalize Columns ', normalize_strategy_columns)\n print ('Date Columns ', date_transform_columns)\n print ('Encoding Columns ', category_encoding_columns)\n\n \"\"\"\n return_list.append(category_encoding_columns)\n return_list.append(missing_value_strategy)\n return_list.append(drop_strategy_columns)\n return_list.append(normalize_strategy_columns)\n \"\"\"\n return (return_list)\n\n\ndef manage_missing_values(X,y, missing_values_strategy):\n\n# common parameters\n\n missing_values_not_applicable = 0\n missing_values_drop_rows = 1\n missing_values_fill_mean = 2\n missing_values_drop_column = 3\n missing_values_not_decided = 4\n\n # Taking care of missing data by dropping the rows\n\n missing_columns_drop_rows = list(np.where(np.array(missing_values_strategy) == missing_values_drop_rows))[0]\n\n for i in missing_columns_drop_rows:\n indices_of_empty_rows = np.where((pd.isnull(X[:,i]) == True))[0]\n\n X = np.delete(X, indices_of_empty_rows , axis=0)\n if y != None:\n y = np.delete(y, indices_of_empty_rows , axis=0)\n\n# Taking care of missing data by filling with mean values\n\n missing_columns_tobe_filled_with_mean = list(np.where(np.array(missing_values_strategy) == missing_values_fill_mean))[0]\n\n from sklearn.preprocessing import Imputer\n imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)\n\n for i in missing_columns_tobe_filled_with_mean:\n imputer = imputer.fit(X[:, i:i+1])\n X[:, i:i+1] = imputer.transform(X[:, i:i+1])\n\n return ({\"X\":X, \"y\":y})\n\ndef manage_missing_values_with_mean(x):\n\n from sklearn.preprocessing import Imputer\n imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)\n ds = x['dataset']\n\n for i in x['missing_value_mean_columns']:\n #for i in range(x.shape[1]):\n #print (i)\n imputer = imputer.fit(ds[[ds.columns[i]]])\n ds[ds.columns[i]] = imputer.transform(ds[[ds.columns[i]]])\n x['dataset'] = ds\n #print (x)\n return (x)\n\n\ndef manage_normalize_values(X, normalize_strategy_columns):\n\n from sklearn.preprocessing import StandardScaler\n sc_X = StandardScaler()\n for i in normalize_strategy_columns:\n X[:, [i]] = sc_X.fit_transform(X[:, i].reshape(-1, 1))\n\n return(X)\n\ndef manage_normalize_values_df(x):\n\n from sklearn.preprocessing import MinMaxScaler\n sc_X = MinMaxScaler(feature_range=(1, 2),copy=False)\n for i in range(x.shape[1]): \n #X[X.columns[i]].apply(lambda x: sc_X.fit_transform(x.reshape(-1, 1)))\n x[x.columns[i]] = sc_X.fit_transform(x[x.columns[i]])\n \n #for i in normalize_strategy_columns:\n # X[:, [i]] = sc_X.fit_transform(X[:, i].reshape(-1, 1))\n\n return(x)\n\ndef manage_target_values(y):\n\n unique_identification_cutoff_y = 0.01\n lc_y = None\n sc_y = None\n\n disparate_data_index_y = ((len(np.unique(y))) /len(y))\n\n \n if y.dtype in ('int64', 'float64'):\n number_datatype_y = True\n\n if number_datatype_y:\n if disparate_data_index_y > unique_identification_cutoff_y:\n from sklearn.preprocessing import StandardScaler\n sc_y = StandardScaler()\n y = sc_y.fit_transform(y.reshape(-1, 1)) \n else:\n from sklearn.preprocessing import LabelEncoder\n lc_y = LabelEncoder()\n y = lc_y.fit_transform(y)\n\n labelEncoder_y = lc_y\n standardScaler_y = sc_y\n \n y_return = {\"y\": y, \\\n \"labelEncoder_y\": labelEncoder_y, \\\n \"standardScaler_y\": standardScaler_y}\n return(y_return)\n\ndef manage_category_encoding(X, category_encoding_columns, drop_strategy_columns):\n\n# For unique string column that can be cosidered as classification, convert into classification encoding using onecode\n\n X_extract_encoded = None\n if not (not category_encoding_columns):\n from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n labelencoder_X = LabelEncoder()\n\n for i in (category_encoding_columns):\n X[:, i] = labelencoder_X.fit_transform(X[:, i])\n\n\n X_extract = X[:,category_encoding_columns]\n onehotencoder = OneHotEncoder(categorical_features = 'all')\n X_extract_encoded = onehotencoder.fit_transform(X_extract).toarray()\n\n# Remove one of the encoded columns from each encoded category\n remove_columns = [0]\n for i in range (1, len(onehotencoder.n_values_)):\n remove_columns.append(remove_columns[i-1] + \\\n onehotencoder.n_values_[i])\n\n X_extract_encoded = np.delete(X_extract_encoded, \\\n remove_columns, axis=1)\n \n# Drop all marked columns, including the ones marked for encoding \n X = np.delete(X, category_encoding_columns+drop_strategy_columns , axis=1)\n\n# Append the encoded columns\n if X_extract_encoded == None:\n pass\n else:\n X = np.c_[X_extract_encoded, X]\n\n return(X)\n\ndef manage_encoding_df(x):\n\n #print (x[x.columns[0])\n column_list = [x.columns[i] for i in range(x.shape[1])]\n #print (column_list)\n if column_list ==[]:\n x_encoded = x\n else:\n x_encoded = pd.get_dummies(x, columns=column_list, drop_first=True)\n #print(x_encoded)\n #print (x_encoded['Distributor_Buena Vista'][x_encoded['Distributor_Buena Vista'] == 1])\n\n return(x_encoded)\n\ndef manage_date_transform_df(x):\n\n epoch = datetime.datetime.utcfromtimestamp(0)\n\n def unix_time_millis(dt):\n return (dt - epoch).total_seconds() * 1000.0\n\n for i in range(x.shape[1]):\n x[x.columns[i]] = x[x.columns[i]].apply(lambda x: unix_time_millis(x))\n\n x = manage_normalize_values_df(x)\n\n return(x)\n","sub_path":"common/preprocessing/common_functions.py","file_name":"common_functions.py","file_ext":"py","file_size_in_byte":21211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"439946247","text":"\"\"\"\n.. moduleauthor:: Violeta Gonzalez-Perez \n\"\"\"\nimport os\nimport numpy as np\nimport glob\n\ndef check_files(infiles):\n '''\n Check the existance of an array of files\n\n Args:\n files: string, list with files names (with paths)\n '''\n\n for ff in infiles:\n if not os.path.isfile(ff):\n print('STOP: file not found, \\n {}'.format(ff)) ; exit()\n\n return\n\ndef jumpheader(infile):\n '''\n Given a file with a structure: header+data, \n counts the number of header lines\n\n Args:\n infile: string, input file\n\n Returns:\n ih: integer, number of lines with the header text\n '''\n ih = 0\n ff = open(infile,'r')\n for line in ff:\n if not line.strip():\n # Count any empty lines in theh header\n ih += 1\n else:\n # Check that the first character is not a digit\n char1 = line[0]\n if not char1.isdigit():\n ih += 1\n else:\n return ih\n return ih\n\n\ndef joinCVfiles(overwrite=True):\n '''\n Join all the files CV_*_#.txt from the inputdata folder \n into a single file\n\n Parameters:\n overwrite : boolean\n True to overwrite an existing file\n\n Return:\n cvnom : string\n Name of the output file\n '''\n\n inpath = 'inputdata/'\n\n # Find all the CV files\n files = glob.glob(inpath+'CV_*.txt') \n nums = np.array([int(ff.split('_')[-1].split('.txt')[0]) for ff in files])\n isort = np.argsort(nums)\n \n # Check if any CV files are missing\n inarr = nums[isort] \n narr = np.arange(inarr[0], inarr[-1]+1, 1, dtype=int)\n if (not np.array_equal(inarr,narr)):\n print('WARNING (joinCVfiles): there are missing CV files {}'.format(files))\n\n t0cv = files[isort[0]].split('CV_')[-1].split('_')[0]\n cvnom = 'CVall_'+t0cv+'.txt'\n cvfile = inpath+cvnom\n if (os.path.isfile(cvfile) and not overwrite):\n return\n \n # Write header in combined file\n with open(cvfile, 'w') as f:\n f.write(\"# Total time (s), Electrode_potential (V), Cell_Potential (V), I (A), Time (s), Cycle number \\n\")\n f.close\n \n # Add content from each CV file, following the isort order\n jj = 0 ; ndays = 0 ; tstart = 0.; first00 = True \n for i in isort:\n ff = files[i]\n\n # Read the data\n ih = jumpheader(ff)\n time, ev, ucell, ia = np.loadtxt(ff, usecols=(0,1,2,3),\n unpack=True, skiprows=ih)\n\n # Total time\n fft = ff.split('_')[1].split('_')[0]\n\n if (fft[:2] == '00' and first00):\n # Deal times passing midnight\n first00 = False\n ndays += 1\n elif (fft[:2] != '00'):\n first00 = True\n \n ffh = ndays*24 + float(fft[:2])\n ffsec = ffh*3600. + float(fft[2:4])*60. + float(fft[4:6])\n \n if (jj == 0):\n totalt = time\n tstart = ffsec\n else:\n totalt = time + ffsec - tstart\n \n # Create an array with cycle number\n jj += 1 \n cycle = np.full(shape=len(time),fill_value=jj)\n\n tofile = np.column_stack((totalt,ev,ucell,ia,time,cycle))\n with open(cvfile,'a') as outf:\n np.savetxt(outf,tofile,fmt='%.10e %.5e %.5e %.5e %.5e %i')\n\n return cvnom\n\n\ndef read_columns(infile,columns,delimiter=None):\n '''\n Read the columns in a file\n\n Args:\n infile: string, name of file (with path)\n columns: integer or list of integers, position of the columns to be read\n delimiter: string, delimiter to be used when reading the file\n '''\n \n ih = jumpheader(infile) #; print('ih={}'.format(ih))\n if delimiter:\n values = np.loadtxt(infile, usecols= (columns),\n unpack=True, skiprows=ih, delimiter=',')\n else:\n values = np.loadtxt(infile, usecols= (columns),\n unpack=True, skiprows=ih)\n\n return values\n\ndef get_col_nom(infile,columns,delimiter=None):\n '''\n Read the names of the given columns in a file\n\n Args:\n infile: string, name of file (with path)\n columns: integer or list of integers, position of the columns to be read\n delimiter: string, delimiter to be used when reading the file\n '''\n\n colnames=[' ']*len(columns)\n\n ih = jumpheader(infile)\n\n with open(infile, 'r') as ff:\n ii = 0\n for line in ff:\n ii += 1\n if (ii == ih):\n head = line.rstrip().split(delimiter)\n break\n\n for ii,icol in enumerate(columns):\n colnames[ii] = head[icol]\n \n return colnames\n\n\ndef get_Dt(files):\n '''\n Get shift times to output continuous times\n across different output files\n\n Parameters:\n files : list of strings\n Names of files\n\n Return:\n Dt : numpy array of floats\n Shift times to be applied to output\n '''\n\n Dt0, Dt = [np.zeros(len(files)) for ii in range(2)]\n\n ndays = 0 ; first00 = True\n for ii, ff in enumerate(files[:-1]):\n # Check that the name format is the expected one\n try:\n tini = ff.split('_')[1].split('.txt')[0]\n except:\n return Dt0\n\n if (len(tini) != 6): return Dt0\n\n # Total time\n if (tini[:2] == '00' and first00):\n # Deal times passing midnight\n first00 = False\n ndays += 1\n elif (tini[:2] != '00'):\n first00 = True\n \n th = ndays*24 + float(tini[:2])\n tsec = th*3600. + float(tini[2:4])*60. + float(tini[4:6])\n\n if (ii == 0):\n t0pre = tsec\n Dt[0] = 0.\n else:\n Dt[ii] = tsec - t0pre\n\n return Dt\n","sub_path":"src/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":5732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"329992636","text":"# -*- coding: utf-8 -*-\r\n# @Author: hliu.Luke\r\n# @Date: 2020-07-31 10:00:34\r\n# @Last Modified by: LH\r\n# @Last Modified time: 2020-08-07 00:11:12\r\n\r\nimport os\r\nimport time\r\nimport argparse\r\nimport numpy as np\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.utils.data as data\r\nimport torch.backends.cudnn as cudnn\r\nfrom tensorboardX import SummaryWriter\r\n\r\nimport model\r\nimport evaluation\r\nfrom dataLoader import BPRData, load_rating_data\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--lr\", \r\n type=float, \r\n default=5e-4, \r\n help=\"learning rate\")\r\nparser.add_argument(\"--lamda\", \r\n type=float, \r\n default=0.001, \r\n help=\"model regularization rate\")\r\nparser.add_argument(\"--batch_size\", \r\n type=int, \r\n default=256, \r\n help=\"batch size for training\")\r\nparser.add_argument(\"--epochs\", \r\n type=int,\r\n default=200, \r\n help=\"training epoches\")\r\nparser.add_argument(\"--top_k\", \r\n type=int, \r\n default=10, \r\n help=\"compute metrics@top_k\")\r\nparser.add_argument(\"--factor_num\", \r\n type=int,\r\n default=100, \r\n help=\"predictive factors numbers in the model\")\r\nparser.add_argument(\"--num_ng\", \r\n type=int,\r\n default=4, \r\n help=\"sample negative items for training\")\r\nparser.add_argument(\"--test_num_ng\", \r\n type=int,\r\n default=99, \r\n help=\"sample part of negative items for testing\")\r\nparser.add_argument(\"--out\", \r\n default=True,\r\n help=\"save model or not\")\r\nparser.add_argument(\"--gpu\", \r\n type=str,\r\n default=\"0\", \r\n help=\"gpu card ID\")\r\nargs = parser.parse_args()\r\n\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\r\ncudnn.benchmark = True\r\n\r\n\r\n############################## PREPARE DATASET ##########################\r\n\r\ntrain_data, test_data, \\\r\nnum_users, num_items, \\\r\nneg_user_item_matrix, \\\r\ntrain_user_item_matrix, \\\r\nunqiue, rate_max = load_rating_data(path=\"../data/ratings.dat\", test_size=0.1, sep=\"::\")\r\n\r\n\r\ntrain_datasets = BPRData(train_data, num_users, num_items, rate_max)\r\ntrain_loader = data.DataLoader(train_datasets, batch_size=1024, shuffle=True, num_workers=12)\r\n\r\ntest_datasets = BPRData(test_data, num_users, num_items, rate_max)\r\ntest_loader = data.DataLoader(test_datasets, batch_size=256, shuffle=False, num_workers=12)\r\n\r\nprint('len train loader = {} len test loader = {}'.format(len(train_loader), len(test_loader)))\r\n\r\n########################### CREATE MODEL #################################\r\nmodel = model.BPR(num_users, num_items, np.mean(list(train_data.tocoo().data)), args.factor_num)\r\nmodel.cuda()\r\n\r\n# optimizer = torch.optim.Adagrad(model.parameters(), lr=args.lr, lr_decay=0, weight_decay=0)\r\noptimizer = optim.RMSprop(\r\n model.parameters(), lr=args.lr, weight_decay=1e-5)\r\n# optimizer = torch.optim.SGD(\r\n# model.parameters(), lr=args.lr, momentum=0.9, weight_decay=1e-5)\r\n\r\nwriter = SummaryWriter() # for visualization\r\n\r\n\r\n# def loss_fn(pred, rate, rate_max):\r\n# c_ui = 1+ 0.2 * torch.abs(rate - (rate_max )/2)\r\n# mse = torch.pow((rate_max - rate) - pred, 2)\r\n# return torch.sum(c_ui * mse)\r\n\r\ndef loss_fn(pred, rate, rate_max):\r\n # c_ui = 1+ 0.2 * torch.abs(rate - (rate_max )/2)\r\n mse = torch.pow(rate - pred, 2)\r\n return torch.sum(mse)\r\n\r\n########################### TRAIN MODEL #################################\r\ncount = 0\r\nmin_val_metric = np.Inf\r\nn_epochs_stop = 5\r\nepochs_no_improve = 0\r\n\r\nmin_val_rmse = np.Inf\r\nmin_val_mse = np.Inf\r\nmin_val_mae = np.Inf\r\nfor epoch in range(args.epochs):\r\n model.train()\r\n start_time = time.time()\r\n loss_total = 0\r\n # train \r\n for i, (user, item, rate, rate_max) in enumerate(train_loader):\r\n user = user.cuda().long()\r\n item = item.cuda().long()\r\n rate = rate.cuda()\r\n rate_max = rate_max.cuda()\r\n model.zero_grad()\r\n pred = model.forward(user, item)\r\n loss = loss_fn(pred, rate, rate_max)\r\n # calculate loss function\r\n loss.backward()\r\n optimizer.step()\r\n writer.add_scalar('data/loss', loss.item(), count)\r\n count += 1\r\n loss_total += loss.item()\r\n\r\n print(\"Epoch: %03d; loss = %.4f cost time %.4f\" % (epoch, np.mean(loss.item()), time.time() - start_time))\r\n\r\n # evaluate\r\n if (epoch) % 1 == 0:\r\n model.eval()\r\n pred_list = None\r\n rate_list = None\r\n for user, item, rate, rate_max in test_loader:\r\n user = user.cuda().long()\r\n item = item.cuda().long()\r\n rate = rate.cuda()\r\n rate_max =rate_max.cuda()\r\n pred = model.forward(user, item)\r\n # calculate loss\r\n loss_eval = loss_fn(pred, rate, rate_max)\r\n\r\n if pred_list is not None:\r\n pred_list = torch.cat((pred, pred_list), dim = 0)\r\n else:\r\n pred_list = pred\r\n\r\n if rate_list is not None:\r\n rate_list = torch.cat((rate, rate_list), dim = 0)\r\n else:\r\n rate_list = rate\r\n\r\n\r\n mse, rmse, mae = evaluation.mse_rmse_mae(pred_list, rate_list)\r\n\r\n\r\n # early stop \r\n if rmse.cpu().detach().numpy() < min_val_rmse:\r\n epochs_no_improve = 0\r\n min_val_rmse = rmse.cpu().detach().numpy()\r\n min_val_mse = mse.cpu().detach().numpy()\r\n min_val_mae = mae.cpu().detach().numpy()\r\n print(\"MSE:%.4f ; RMSE:%.4f; MAE:%.4f\" %(mse.cpu().detach().numpy(), rmse.cpu().detach().numpy(), mae.cpu().detach().numpy()) )\r\n else:\r\n epochs_no_improve += 1\r\n print(\"MSE:%.4f ; RMSE:%.4f; MAE:%.4f\" %(mse.cpu().detach().numpy(), rmse.cpu().detach().numpy(), mae.cpu().detach().numpy()) )\r\n\r\n if epochs_no_improve == n_epochs_stop:\r\n print('Early stopping!' )\r\n print(\"MSE:%.4f ; RMSE:%.4f; MAE:%.4f\" %(min_val_mse, min_val_rmse, min_val_mae))\r\n break\r\n\r\n\r\n\r\n\r\n\r\nfrom predict import fastPredictionGpu\r\n\r\nresults_score, results_index = fastPredictionGpu(\r\n model.embed_user.weight.detach(),\r\n model.embed_item.weight.detach(),\r\n model.bias_user.weight.detach(),\r\n model.bias_item.weight.detach(),\r\n np.mean(list(train_data.tocoo().data)),\r\n filter_list = None,\r\n batch = 512,\r\n topk = 10)\r\n\r\nprint(results_score.shape, results_index.shape)\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"22043491","text":"from functools import reduce\nfrom pdb import set_trace as db\n\nwith open(\"input.txt\") as f:\n foods = f.read().splitlines()\n\ntest_foods = \"\"\"mxmxvkd kfcds sqjhc nhms (contains dairy, fish)\ntrh fvjkl sbzzf mxmxvkd (contains dairy)\nsqjhc fvjkl (contains soy)\nsqjhc mxmxvkd sbzzf (contains fish)\"\"\".splitlines()\n\n\ndef match_allergens(foods, is_p1=False):\n foods = [\n [set(i.split()), set(a.replace(\",\", \"\").split())]\n for i, a in [food[:-1].split(\" (contains \") for food in foods]\n ]\n\n possible = {}\n ingr_usage = []\n all_ingrs = set()\n for ingrs, allgs in foods:\n ingr_usage += ingrs\n all_ingrs |= ingrs\n\n for allg in allgs:\n if allg not in possible:\n possible[allg] = ingrs.copy()\n else:\n possible[allg] &= ingrs\n\n if is_p1:\n possible_allergens = reduce(lambda a, b: a | b, possible.values())\n not_possible_allergens = all_ingrs - possible_allergens\n return sum(ingr_usage.count(ingr) for ingr in not_possible_allergens)\n\n allg_ingr = {}\n while any(len(v) for v in possible.values()):\n for allg, ingrs in possible.items():\n if len(ingrs) == 1:\n ingr = min(ingrs)\n allg_ingr[allg] = ingr\n for rem_ingrs in possible.values():\n if ingr in rem_ingrs:\n rem_ingrs.remove(ingr)\n\n return \",\".join([allg_ingr[k] for k in sorted(allg_ingr.keys())])\n\n\nprint(match_allergens(test_foods, True)) # 5\nprint(match_allergens(foods, True)) # 2627\n\nprint(match_allergens(test_foods)) # mxmxvkd,sqjhc,fvjkl\n# mxmxvkd contains dairy.\n# sqjhc contains fish.\n# fvjkl contains soy.\n\nprint(match_allergens(foods)) # hn,dgsdtj,kpksf,sjcvsr,bstzgn,kmmqmv,vkdxfj,bsfqgb\n","sub_path":"2020/day21/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"166222509","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n#\n##############################################################################\n\nimport logging\nlogger = logging.getLogger('report_aeroo')\n\nfrom openerp.report import report_sxw\nfrom openerp.report.report_sxw import rml_parse\n\nimport time\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nDATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\nDATE_FORMAT = \"%Y-%m-%d\"\n\nclass Parser(rml_parse):\n def __init__(self, cr, uid, name, context):\n super(self.__class__, self).__init__(cr, uid, name, context)\n self.cr = cr\n self.uid = uid\n self.lead_planned_revenue = 0.0\n self.opp_planned_revenue = 0.0\n self.total_order = 0.0\n self.localcontext.update({\n 'get_vietname_date':self.get_vietname_date,\n 'get_vietname_datetime':self.get_vietname_datetime,\n })\n \n def get_vietname_date(self, date):\n if not date:\n date = time.strftime(DATE_FORMAT)\n date = datetime.strptime(date, DATE_FORMAT) \n return date.strftime('%d-%m-%Y')\n \n def get_vietname_datetime(self, date):\n if not date:\n date = time.strftime(DATETIME_FORMAT)\n date = datetime.strptime(date, DATETIME_FORMAT) \n return date.strftime('%d-%m-%Y')\n \n \n \n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"besco_mrp/general_mrp/report/operation_order.py","file_name":"operation_order.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"462249940","text":"#!/usr/bin/env python\n\n\"\"\"\nAuthor: Nasir Bilal\nEmail: nbilal@paloaltonetworks.com\n\"\"\"\n\n##############################################################\n# IMPORTS\n##############################################################\nimport xmltodict\nfrom ipaddress import ip_network, ip_address\nimport re\nfrom openpyxl import Workbook\nimport logging\nfrom copy import copy\n\n\n\n##############################################################\n# GLOBAL VARIABLES\n##############################################################\nPAN_CFG_FILE = 'panorama_config.xml'\nDEVICE_GROUP = 'DG_01'\n\n\n##############################################################\n# FUNCTIONS\n##############################################################\ndef flatten(c):\n if not isinstance(c, str):\n for i in c:\n if hasattr(i, '__iter__'):\n for j in flatten(i):\n yield j\n else:\n yield i\n else:\n yield c\n\n\ndef validate_ip(address):\n try:\n ip_network(address)\n return True\n except ValueError:\n return False\n\n\ndef findIPs(start, end):\n start = ip_address(start)\n end = ip_address(end)\n result = []\n while start <= end:\n result.append(str(start))\n start += 1\n return result\n\n\ndef resolve_address(address, pan_cfg):\n \"\"\"\n Queries address-group for object matching this string.\n :param address: address object being searched for\n :param add_tree: etree built from address section of PANOS XML\n :return: string of object's IP address\n \"\"\"\n if address in ('any', 'dynamic', 'unknown') or validate_ip(address):\n return [address]\n elif address in ('panw-highrisk-ip-list', 'panw-known-ip-list'):\n return ['dynamic']\n else:\n sh_add_tree = pan_cfg['config']['shared']['address']['entry']\n sh_ag_tree = pan_cfg['config']['shared']['address-group']['entry']\n sh_edl_tree = pan_cfg['config']['shared']['external-list']['entry']\n device_groups = pan_cfg['config']['devices']['entry']['device-group']['entry']\n dg_tree = [a for a in device_groups if a['@name'] == DEVICE_GROUP][0]\n dg_add_tree = dg_tree['address']['entry']\n dg_ag_tree = dg_tree['address-group']['entry']\n\n try:\n if dg_tree.get('external-list', {}).get('entry'):\n for edl in dg_tree['external-list']['entry']:\n if edl['@name'] == address:\n return ['dynamic']\n if pan_cfg['config']['shared']['external-list'].get('entry'):\n for edl in pan_cfg['config']['shared']['external-list']['entry']:\n if edl['@name'] == address:\n return ['dynamic']\n if dg_add_tree:\n for add in dg_add_tree:\n if add['@name'] == address:\n if add.get('ip-netmask'):\n addr = add.get('ip-netmask')\n elif add.get('ip-range'):\n addr = findIPs(*add.get('ip-range').split('-'))\n elif add.get('fqdn'):\n addr = 'dynamic'\n return [addr]\n except BaseException as e:\n logging.exception(\"Unable to search dg_add_tree due to {}\".format(e))\n try:\n if sh_add_tree:\n for add in sh_add_tree:\n if add['@name'] == address:\n if add.get('ip-netmask'):\n addr = add.get('ip-netmask')\n elif add.get('ip-range'):\n addr = 'ip-range'\n elif add.get('fqdn'):\n addr = 'dynamic'\n return [addr]\n except BaseException as e:\n logging.exception(\"Unable to search sh_add_tree due to {}\".format(e))\n\n try:\n if dg_ag_tree:\n for add in dg_ag_tree:\n if add['@name'] == address:\n return add.get('static', {}).get('member')\n except BaseException as e:\n logging.exception(\"Unable to search dg_ag_tree due to {}\".format(e))\n try:\n if sh_ag_tree:\n for add in sh_ag_tree:\n if add['@name'] == address:\n return add.get('static', {}).get('member')\n except BaseException as e:\n logging.exception(\"Unable to search sh_ag_tree due to {}\".format(e))\n\n return 'unknown'\n\n\n\ndef resolve_service(service, pan_cfg):\n \"\"\"\n Queries services and service-groups for object matching this string.\n :param service: address object being searched for\n :param pan_cfg: nested dictionary built from address section of PANOS XML\n :return: protocol_port value for given service if found, else 'unknown'\n \"\"\"\n if service == 'any' or service == 'application-default' or bool(re.search(r'(tcp|udp)_\\d+$', str(service))):\n return service\n else:\n sh_svc_tree = pan_cfg['config']['shared']['service']['entry']\n sh_sg_tree = pan_cfg['config']['shared']['service-group']['entry']\n device_groups = pan_cfg['config']['devices']['entry']['device-group']['entry']\n dg_tree = [a for a in device_groups if a['@name'] == DEVICE_GROUP][0]\n dg_svc_tree = dg_tree['service']['entry']\n dg_sg_tree = dg_tree['service-group']['entry']\n try:\n if dg_svc_tree:\n for svc in dg_svc_tree:\n if svc['@name'] == service:\n if svc.get('protocol'):\n if svc['protocol'].get('tcp'):\n s = \"tcp_{}\".format(svc['protocol']['tcp'].get('port'))\n elif svc['protocol'].get('udp'):\n s = \"udp_{}\".format(svc['protocol']['udp'].get('port'))\n return [s]\n except BaseException as e:\n logging.exception(\"Couldn't search device-group services due to {}\".format(e))\n try:\n if sh_svc_tree:\n for svc in sh_svc_tree:\n if svc['@name'] == service:\n if svc.get('protocol'):\n if svc['protocol'].get('tcp'):\n s = \"tcp_{}\".format(svc['protocol']['tcp'].get('port'))\n elif svc['protocol'].get('udp'):\n s = \"udp_{}\".format(svc['protocol']['udp'].get('port'))\n return [s]\n except BaseException as e:\n logging.exception(\"Couldn't search shared services due to {}\".format(e))\n try:\n if dg_sg_tree:\n for svc in dg_sg_tree:\n if svc['@name'] == service:\n return svc.get('members').get('member')\n except BaseException as e:\n logging.exception(\"Unable to search dg_ag_tree due to {}\".format(e))\n\n try:\n if sh_sg_tree:\n for svc in sh_sg_tree:\n if svc['@name'] == service:\n return svc.get('members').get('member')\n except BaseException as e:\n logging.exception(\"Unable to search dg_ag_tree due to {}\".format(e))\n\n return 'unknown'\n\n\n\n##############################################################\n# MAIN FUNCTION\n##############################################################\ndef main():\n\n # Initialize log file for exceptions\n logging.basicConfig(level=logging.INFO, filename='exceptions.log')\n\n with open(PAN_CFG_FILE, 'r') as f:\n pan_cfg = xmltodict.parse(f.read())\n\n device_groups = pan_cfg['config']['devices']['entry']['device-group']['entry']\n dg_tree = [a for a in device_groups if a['@name'] == DEVICE_GROUP][0]\n nat_tree = dg_tree['post-rulebase']['nat']['rules']['entry']\n sec_tree = dg_tree['post-rulebase']['security']['rules']['entry']\n\n # BUILD CSV FILE FOR SUMMARIZED RESULTS\n wb = Workbook()\n ws = wb.active\n ws.append([\n 'NAME',\n 'FROM',\n 'SOURCE',\n 'RESOLVED SRC',\n 'TO',\n 'DESTINATION',\n 'RESOLVED DST',\n 'APP',\n 'SERVICE',\n 'RESOLVED PT',\n 'CATEGORY',\n 'ACTION',\n 'PROFILE-SETTING',\n 'LOG-SETTING',\n ])\n\n for r in sec_tree:\n try:\n # If \"source\" field is a list of address(es)/address-group(s), iterate over each\n # Return a list of IPs\n add_check = lambda x: validate_ip(x) or x in ('any', 'dynamic', 'unknown')\n if add_check(r['source'].get('member')):\n src = copy(r['source'].get('member'))\n else:\n src = copy(r['source'].get('member'))\n while not add_check(src) and sum(map(add_check, src)) < len(list(src)):\n if type(src) == list:\n src_list = []\n for s in src:\n s = resolve_address(s, pan_cfg)\n src_list.append(s)\n src = list(src_list)\n # Otherwise, try to resolve single address in \"source\" field into list of one IP\n else:\n src = resolve_address(src, pan_cfg)\n src = list(flatten(src))\n\n if add_check(r['destination'].get('member')):\n dst = copy(r['destination'].get('member'))\n else:\n dst = copy(r['destination'].get('member'))\n while not add_check(dst) and sum(map(add_check, dst)) < len(list(dst)):\n if type(dst) == list:\n dst_list = []\n for d in dst:\n d = resolve_address(d, pan_cfg)\n dst_list.append(d)\n dst = list(dst_list)\n # Otherwise, try to resolve single address in \"source\" field into list of one IP\n else:\n dst = resolve_address(dst, pan_cfg)\n dst = list(flatten(dst))\n\n # Resolve services to a list of ports\n port_check = lambda x: x in ('any', 'unknown', 'application-default') or bool(re.search(r'(tcp|udp)_[\\d\\-,]+$', str(x))) or not x\n if type(r['service']) == list:\n dport = copy(r['service'][0].get('member'))\n else:\n dport = copy(r['service'].get('member'))\n if not port_check(dport):\n while not port_check(dport) and sum(map(port_check, dport)) < len(list(dport)):\n if type(dport) == list:\n dp_list = []\n for dp in dport:\n dp = resolve_service(dp, pan_cfg)\n dp_list.append(dp)\n dport = list(dp_list)\n # Otherwise, try to resolve single address in \"source\" field into list of one IP\n else:\n dport = resolve_service(dport, pan_cfg)\n dport = list(flatten(dport))\n\n rule = (\n str(r['@name']),\n str(r['from'].get('member')),\n str(r['source'].get('member')),\n str(src),\n str(r['to'].get('member')),\n str(r['destination'].get('member')),\n str(dst),\n str(r['application'].get('member')),\n str(r['service'].get('member')),\n str(dport),\n str(r['category'].get('member')),\n str(r['action']),\n str(r.get('profile-setting', {}).get('group', {}).get('member', 'none')),\n str(r['log-setting']),\n )\n ws.append(rule)\n except BaseException as e:\n logging.exception(\"UNABLE TO EXPORT RULE {} DUE TO {}\".format(r, e))\n\n wb.save('{}_rules.xlsx'.format(DEVICE_GROUP))\n\n\n##############################################################\n# RUN IT!\n##############################################################\nif __name__ == '__main__':\n main()\n\n","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":12235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"193399969","text":"# Import packages\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom keras import regularizers\nfrom keras.layers import Dense, Dropout\nfrom keras.models import Sequential\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n\nsns.set()\n\n# Import data\ndf = pd.read_csv('data/cancer.csv')\n\n# Get the feel of data\nprint(df.head())\nwait = input(\"PRESS ENTER TO CONTINUE.\")\nprint(df.info())\nwait = input(\"PRESS ENTER TO CONTINUE.\")\n\nprint(df.describe())\nwait = input(\"PRESS ENTER TO CONTINUE.\")\n\nprint(df.shape)\nwait = input(\"PRESS ENTER TO CONTINUE.\")\n\n# df.plot.scatter(x='mean radius', y='mean texture', c='target')\n# plt.show()\n\n# sns.lmplot(x='mean radius', y='mean texture', data=df)\n# plt.show()\n\n# sns.lmplot(x='mean radius', y='mean texture', hue='target', data=df)\n# plt.show()\n\n# df.plot.scatter(x='mean radius', y='mean perimeter', c='target')\n# plt.show()\n\n# Creating subset of data\ndf_sub1 = df\n\n# sns.pairplot(hue='target', data=df_sub1, height=3)\n# plt.show()\n\nX = df_sub1.drop('target', axis=1).values\nY = df_sub1['target'].values\n\nmmScaler = preprocessing.MinMaxScaler()\nX_Scale = mmScaler.fit_transform(X)\n\nX_train, X_test_val, Y_train, Y_test_val = train_test_split(X_Scale, Y, test_size=0.2, random_state=42, stratify=Y)\nX_test, X_val, Y_test, Y_val = train_test_split(X_test_val, Y_test_val, test_size=0.5)\n\n# Using Decision Tree\n# clf = tree.DecisionTreeClassifier(max_depth=2)\n# print(clf.fit(X_train, Y_train))\n# print(clf.score(X_test, Y_test))\n# print(clf.score(X_val, Y_val))\n\n# Using ANN\nmodel = Sequential()\n# model.add(Dense(32, activation='relu', input_shape=(30,), kernel_regularizer=regularizers.l2(0.01)))\n# model.add(Dropout(0.33))\n# model.add(Dense(32, activation='relu'))\n# model.add(Dropout(0.33))\n# model.add(Dense(32, activation='relu'))\n# model.add(Dropout(0.33))\n# model.add(Dense(32, activation='relu'))\n# model.add(Dropout(0.33))\n# model.add(Dense(1, activation='relu'))\nprint(X_train.shape)\nprint(Y_train.shape)\n\nmodel = Sequential([\n Dense(32, activation='relu', input_shape=(10,)),\n# Dropout(0.33),\n Dense(32, activation='relu'),\n#Dropout(0.33),\n Dense(1, activation='sigmoid'),\n])\n\nmodel.compile(optimizer='sgd',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\nhist = model.fit(X_train, Y_train, batch_size=32, epochs=100, validation_data=(X_val, Y_val))\n\nprint(model.evaluate(X_test, Y_test)[1])\n\nplt.plot(hist.history['accuracy'])\n\nplt.plot(hist.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper right')\nplt.show()\n","sub_path":"dataframe_ANN.py","file_name":"dataframe_ANN.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"53085462","text":"# Copyright 2018 The RLgraph authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\n\nfrom rlgraph.components import Component\nfrom rlgraph.utils.decorators import rlgraph_api\nfrom rlgraph.utils.ops import DataOpDict\n\n\nclass DictMerger(Component):\n \"\"\"\n Merges incoming items into one FlattenedDataOp.\n \"\"\"\n def __init__(self, *input_names, **kwargs):\n \"\"\"\n Args:\n *input_names (str): List of the names of the different inputs in the order they will\n be passed into the `merge` API-method in the returned merged Dict.\n Example:\n input_names = [\"A\", \"B\"]\n - merge(Dict(c=1, d=2), Tuple(3, 4))\n - returned value: Dict(A=Dict(c=1, d=2), B=Tuple(3, 4))\n \"\"\"\n super(DictMerger, self).__init__(scope=kwargs.pop(\"scope\", \"dict-merger\"), **kwargs)\n\n assert all(isinstance(i, str) and not re.search(r'/', i) for i in input_names), \\\n \"ERROR: Not all input names of DictMerger Component '{}' are strings or some of them have '/' \" \\\n \"characters in them, which are not allowed.\".format(self.global_scope)\n self.input_names = input_names\n\n def check_input_spaces(self, input_spaces, action_space=None):\n spaces = []\n idx = 0\n while True:\n key = \"inputs[{}]\".format(idx)\n if key not in input_spaces:\n break\n spaces.append(input_spaces[key])\n idx += 1\n\n #assert len(spaces) == len(self.input_names),\\\n # \"ERROR: Number of incoming Spaces ({}) does not match number of given `input_names` in DictMerger Component \" \\\n # \"'{}'!\".format(len(spaces), len(self.input_names), self.global_scope)\n\n # #for space in spaces:\n # # assert not isinstance(space, ContainerSpace),\\\n # # \"ERROR: Single Space ({}) going into merger '{}' must not be a Container \" \\\n # # \"Space!\".format(space, self.global_scope)\n\n @rlgraph_api\n def _graph_fn_merge(self, *inputs):\n \"\"\"\n Merges the inputs into a single FlattenedDataOp with the flat keys given in `self.input_names`.\n\n Args:\n *inputs (FlattenedDataOp): The input items to be merged into a FlattenedDataOp.\n\n Returns:\n FlattenedDataOp: The FlattenedDataOp as a merger of all api_methods.\n \"\"\"\n ret = DataOpDict()\n for i, op in enumerate(inputs):\n ret[self.input_names[i]] = op\n return ret\n\n","sub_path":"rlgraph/components/common/dict_merger.py","file_name":"dict_merger.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"516082980","text":"#Delaunay before\nimport numpy as np\nimport math\n\n\ndef tri(srcfile,filename):\n def sqdist(p1,p2):\n dist = math.sqrt((float(p1[0])-float(p2[0]))**2+(float(p1[1])-float(p2[1]))**2+(float(p1[2])-float(p2[2]))**2)\n return dist\n\n f = open(srcfile,\"r\")\n d = f.readlines()\n vdata = {}\n fdata = []\n count = 1\n for i in d:\n if i[0] == \"v\" and i[1] != \"n\":\n vdata[str(count)] = str(i[2:]).split()\n vdata[str(count)][0] = float(vdata[str(count)][0])\n vdata[str(count)][1] = float(vdata[str(count)][1])\n vdata[str(count)][2] = float(vdata[str(count)][2])\n if i[0] == \"f\":\n fdata.append(str(i[2:]).split())\n\n count += 1\n z = open(filename,\"w+\")\n dd = z.readlines()\n z.truncate()\n count = 0\n deletelist = []\n for i in fdata:\n if sqdist(np.array(vdata[i[0]]), np.array(vdata[i[1]])) > 100 or sqdist(np.array(vdata[i[0]]), np.array(vdata[i[2]])) > 100 or sqdist(np.array(vdata[i[1]]), np.array(vdata[i[2]])) > 100:\n deletelist.append(count)\n pass\n count += 1\n \n for i in reversed(deletelist):\n del fdata[i]\n\n\n count = 0\n count2 = 0\n for i in d:\n if i[0] == \"v\" and i[1] != \"n\":\n z.write(i)\n elif i[0] == \"f\" and count < len(fdata):\n z.write(\"f \"+fdata[count][0]+\" \"+fdata[count][1]+\" \"+fdata[count][2]+\"\\n\")\n count += 1\n elif i[0] == \"\\n\":\n pass\n else:\n break\n\n f.close()\n z.close()\n","sub_path":"Delaunay.py","file_name":"Delaunay.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"458244552","text":"\nimport pandas as pd\nimport scipy.io as sio\nimport numpy as np\nfrom glob import glob\nimport pickle\nfrom scipy.stats.mstats import zscore\nfrom ScanImageTiffReader import ScanImageTiffReader\n\ndef chop_file_vars(starts, lengths, skip_ends, skip_starts):\n \"\"\"for dropping elems of starts and lengths to ignore first or last acqs\n \"\"\"\n if skip_ends > 0:\n starts = starts[0:len(starts)-skip_ends]\n lengths = lengths[0:len(starts)-skip_ends]\n if skip_starts > 0:\n starts = starts[skip_starts:]\n lengths = lengths[skip_starts:]\n return starts, lengths\n\n\ndef do_pre_dfof(traces, dfof_method, do_zscore):\n \"\"\"do fluorescence calculations that should occur before chopping into PSTHS\n This occurs for percentile, rolling_percentile, and z scoring.\n \"\"\"\n if dfof_method == 'percentile':\n f0=np.nanpercentile(traces,30, axis=1)\n f0 = np.reshape(f0,(f0.shape[0],1))\n traces = (traces-f0)/f0\n if dfof_method == 'rolling_percentile':\n f0s = pd.DataFrame(np.transpose(traces)).rolling(200, min_periods=1,center=True).quantile(.20)\n f0s = np.transpose(f0s.as_matrix())\n traces = (traces-f0s)/f0s\n if do_zscore:\n traces = zscore(traces, axis=1)\n return traces\n\ndef do_dfof_cuts(cut_traces, dfof_method, do_baseline, baseline_n):\n if dfof_method == 'at start':\n for i in range(0, np.shape(cut_traces)[1]):\n for j in range(0, np.shape(cut_traces)[0]):\n f0 = np.mean(traces[i,df_range[0]:df_range[1]])\n cut_traces[j,i,:] = (cut_traces[j,i,:]-f0)/f0\n elif dfof_method == 'by trial':\n for i in range(0, np.shape(cut_traces)[1]):\n for j in range(0, np.shape(cut_traces)[0]):\n f0 = np.mean(cut_traces[j,i,df_range[0]:df_range[1]])\n cut_traces[j,i,:] = (cut_traces[j,i,:]-f0)/f0\n elif 'percentile' not in dfof_method:\n print('no dfof method selected, returning raw cut traces')\n if do_baseline:\n print('subtracting baseline!')\n cut_traces = cut_traces -np.mean(cut_traces[:,:,0:baseline_n],axis=2).reshape((cut_traces.shape[0],\n cut_traces.shape[1],\n 1))\n return cut_traces\n\ndef get_traces_segment(real_start, real_end, traces, cell=None):\n \"\"\"get a segment of fluorescent traces with nan padding\n Rteturns a segment of traces corresponding to a time period for a given cell (if cell is not None) or\n all cells if cell is None. Pads with nans if a start is before the beginning of traces or an end is after\n the end of traces, but will throw an error if real_start exceeds 2nd dim of traces or real_end is less than 0.\n\n Args:\n real_start (int): start index in frames of segment\n real_end (int): end index in frames of segment\n traces (2d np array): array of F values, cells x frames\n cell (int or array): cell or cells for which the F values should be returned. If none, returns for all cells.\n\n Returns:\n\n \"\"\"\n if cell==None:\n cell = np.linspace(0, traces.shape[0]-1, traces.shape[0]).astype('int16')\n if real_start < 0 and real_end > 0:\n try:\n cut = np.concatenate((np.tile(np.nan, (len(cell),-1*real_start)), traces[cell,0:real_end]),1)\n except:\n print('shape of traces was: ', traces.shape, ' start was ', real_start, ' end was ', real_end,\n 'padded nans were', np.tile(np.nan, (len(cell),-1*real_start)).shape,\n ' cut bit was ', traces[cell,0:real_end])\n raise Exception('unexpected error, see printed message for details')\n elif real_end < 0: #this should never happen\n raise Exception('requested a trace segment with end time exceeding length of traces')\n #if real_end longer than available data, but real start isn't\n elif real_end > traces.shape[1] and real_start < traces.shape[1]:\n try:\n cut = np.concatenate((traces[cell,real_start:],np.tile(np.nan, (len(cell),real_end-traces.shape[1]))),1)\n except:\n print('shape of traces was: ', traces.shape, ' start was ', real_start, ' end was ', real_end,\n 'padded nans were', np.tile(np.nan, (len(cell),real_end-traces.shape[1])).shape,\n 'cut bit was ', traces[cell,real_start:].shape)\n raise Exception('unexpected error, see printed message for details')\n elif real_end > traces.shape[1] and real_start >= traces.shape[1]: #this also should not happen\n raise Exception('requested a start time that exceeds the length of traces')\n else:\n cut = traces[cell, real_start:real_end]\n return cut\n","sub_path":"python/chromeStimTest/PSTH_creation_utils.py","file_name":"PSTH_creation_utils.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"138963631","text":"import RPi.GPIO as GPIO\nimport time\n\ndef SetAngle(angle):\n duty = angle/18+2\n GPIO.output(12, True)\n pwm.ChangeDutyCycle(duty)\n time.sleep(1)\n GPIO.output(12, False)\n pwm.ChangeDutyCycle(0)\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n\nGPIO.setup(12,GPIO.OUT)\n\npwm = GPIO.PWM(12, 50)\n\npwm.start(0)\nwhile True:\n angle = input(\"input angle:\")\n SetAngle(int(angle))\n\npwm.stop()\nGPIO.cleanup()\n","sub_path":"python/servo_test.py","file_name":"servo_test.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"502890172","text":"#!/usr/bin/env python3\n\nimport sys\nimport string\n\ndef canonicalize(s):\n \"\"\"Return a caseless(lowercase) version of s with surrounding punctuation removed.\"\"\"\n return s.casefold().strip(string.punctuation)\n\ndef frequencies(a):\n \"\"\"Return information on an iterable's element frequency - a dictionary mapping from an element(duplicates ignored) to the number of times that element occured in the iterable.\"\"\"\n fd = {}\n for i in a:\n if i not in fd:\n fd[i] = 1\n else:\n fd[i] += 1\n return fd\n\ndef main():\n s = sys.stdin.read()\n tokens = s.split()\n\n words = [canonicalize(w) for w in tokens]\n d = frequencies(words)\n d_alphabetically = sorted(d.keys())\n\n for i in d_alphabetically:\n print('{} : {}'.format(i, d[i]))\n\nif __name__ == '__main__':\n main()","sub_path":"year1_1718/computer_programming_2/scripts/20180722180629/2018-02-24/words_041.py","file_name":"words_041.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"27372400","text":"import pygame\nimport sys\nfrom pygame.locals import *\nimport math\npygame.init()\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nRED = (255, 0, 0)\npoints = [(200, 50), (300, 100), (300, 75), (500, 75), (500, 25), (300, 25),(300, 0)]\n\nsize = width, height = 640, 480\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption('fh-demo')\nclock = pygame.time.Clock()\nposition = size[0]//2, size[1]//2\nmoving = False\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n moving = True\n\n if event.type == MOUSEBUTTONUP:\n if event.button == 1:\n moving = False\n\n if moving == True:\n position = pygame.mouse.get_pos()\n print(position)\n\n\n screen.fill(WHITE)\n\n pygame.draw.polygon(screen, GREEN, points, 1)\n pygame.draw.circle(screen, BLUE, position, 125, 1)\n pygame.draw.ellipse(screen, BLACK, (100, 100, 400, 100), 1)\n pygame.draw.arc(screen, RED, (50, 50, 100, 100), 0, math.pi, 1)\n pygame.draw.aaline(screen,BLACK,(0, 0), (100, 300), 1)\n\n\n pygame.display.flip()\n\n clock.tick(10)\n","sub_path":"python/Code/Python Learner/pygame画图.py","file_name":"pygame画图.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"122092557","text":"#! /usr/bin/env python\n\n\"\"\"\nRuns tests for `protocol` package.\n\nRevision Info\n=============\n* $LastChangedBy: mandke $\n* $LastChangedDate: 2011-09-28 21:43:47 -0500 (Wed, 28 Sep 2011) $\n* $LastChangedRevision: 5169 $\n\n:author: Ketan Mandke \n\n:copyright:\n Copyright 2009 The University of Texas at Austin\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n__docformat__ = \"restructuredtext en\"\n\nimport unittest\n\nfrom SimPy.Simulation import *\nfrom scapy.all import *\nfrom wins import *\nfrom copy import copy, deepcopy\n\nclass Agent(Element):\n \"\"\"Simple agent to act as source and sink.\"\"\"\n name=\"agent\"\n tracename=\"AGT\"\n def __init__(self, **kwargs):\n self.nsent, self.nrcvd = 0, 0\n self.dest = None\n Element.__init__(self, **kwargs)\n def configure(self, dest=None, rate=None, duration=None, **kwargs):\n if rate is None: rate=1.0\n if dest: self.dest = dest\n self.addport(\"TX\")\n self.addport(\"RX\")\n f = self.newchild(\"txfsm\", FSM, tracename=self.tracename+\".TX\")\n g = self.newchild(\"rxfsm\", FSM, tracename=self.tracename+\".RX\")\n f.goto(self.SEND, rate, duration)\n g.goto(self.RECV)\n def connect(self, net):\n self.TX.connect(net.RXU)\n net.TXU.connect(self.RX)\n def SEND(self, fsm, rate, duration):\n delay = 0\n if rate>0: delay = 1.0/rate\n if duration is None: duration = 1.0e-3\n while fsm.active() and (delay>0):\n self.log(\"wait\", delay=delay)\n yield hold, fsm, delay\n p = Packet()/\"helloworld\"\n crcupdate(p)\n p.setanno('cif-duration', duration)\n if self.dest: p.setanno('net-dst', self.dest)\n self.log(\"snd\", p, duration=time2usec(duration) )\n yield self.TX.send(fsm, [p])\n self.nsent += 1\n yield hold, fsm, duration\n yield fsm.stop()\n def RECV(self, fsm):\n while fsm.active():\n yield self.RX.recv(fsm, \"all\")\n for p in fsm.got:\n err = CRC32.haserror(p)\n if err: self.log(\"drp\", p, crcerror=err)\n else: self.log(\"rcv\", p, crcerror=err)\n if not err: self.nrcvd += 1\n yield fsm.stop()\n\nclass MyARP(Element):\n name = \"arp\"\n tracename = \"ARP\"\n _share = {NET.broadcast:MAC.broadcast} # translate net->mac address\n def __init__(self, **kwargs):\n self.__netaddr = None\n self.__macaddr = None\n Element.__init__(self, **kwargs)\n\n netaddr = property(fget=lambda self: self.__netaddr)\n macaddr = property(fget=lambda self: self.__macaddr)\n\n def configure(self, netaddr=None, macaddr=None, **kwargs):\n if netaddr and macaddr: self.setaddr(netaddr, macaddr)\n # add ports and FSM\n self.addport(\"RXU\"), self.addport(\"TXU\")\n self.addport(\"TXD\"), self.addport(\"RXD\")\n txfsm = self.newchild(\"txfsm\",FSM,tracename=self.tracename+\".TX\")\n rxfsm = self.newchild(\"rxfsm\",FSM,tracename=self.tracename+\".RX\")\n # init states\n txfsm.goto(self.SEND)\n rxfsm.goto(self.RECV)\n\n def setaddr(self, netaddr, macaddr):\n if self.netaddr or self.macaddr: del self._share[self.netaddr]\n self.__netaddr = netaddr\n self.__macaddr = macaddr\n # register with _share\n self._share[netaddr] = macaddr\n\n def SEND(self, fsm):\n while fsm.active():\n yield self.RXU.recv(fsm, 1)\n p = fsm.got[0]\n pdst = p.dst #ANNO.supported(p) and p.getanno('net-dst')\n if p.hasanno('net-dst'): pdst = p.getanno('net-dst')\n assert (pdst in self._share) # p.dst in _share?\n src, dst, etype = self.macaddr, self._share[pdst], const.ETHERTYPE_IP\n eth = Ether(src=src,dst=dst,type=etype)/p\n self.log(\"snd\", eth, src=src, dst=dst, type=etype)\n yield self.TXD.send(fsm, [eth])\n yield fsm.stop()\n\n def RECV(self, fsm):\n while fsm.active():\n yield self.RXD.recv(fsm, \"all\")\n for p in fsm.got:\n self.log(\"rcv\", p)\n pay = p.payload\n crcremove(pay)\n yield self.TXU.send(fsm, [pay])\n yield fsm.stop()\n\nclass TestProtocol(unittest.TestCase):\n \"\"\"Test elements in `protocol` package.\"\"\"\n\n def setUp(self):\n Trace.Global.reset()\n\n def test_routing(self):\n \"\"\"Test `Routing`.\"\"\"\n class Node(Element):\n name = \"node\"\n tracename = \"NODE\"\n def __init__(self, **kwargs):\n Element.__init__(self, **kwargs)\n def configure(self, rate=None, duration=None, pos=None, **kwargs):\n agt = self.newchild('agent', Agent, rate=rate, duration=duration)\n net = self.newchild('net', Routing)\n cif = self.newchild('cif', Radio)\n mobi = self.newchild('motion', Motion, pos=pos)\n # connect ports\n agt.connect(net)\n net.TXD.connect(cif.RXU)\n cif.TXU.connect(net.RXD)\n\n # set up parameters\n initialize()\n stoptime = 10.1\n verbose = 80\n kwargs = {'verbose':verbose}\n ch = Channel(model=Propagation, **kwargs)\n n0 = Node(rate=0.5, pos=(0, 0), **kwargs)\n n1 = Node(rate=0.0, pos=(0, 50), **kwargs)\n n2 = Node(rate=0.0, pos=(0,100), **kwargs)\n # connect to channel\n ch.add_edge(n0.cif, n1.cif)\n ch.add_edge(n1.cif, n2.cif)\n # set agent destination\n d0 = n0.net.address\n d1 = n1.net.address\n d2 = n2.net.address\n n0.agent.dest = d2\n n0.net.addroute(d2, d1)\n n1.net.addroute(d2)\n\n # run simulation\n simulate(until=stoptime)\n #ch.trace.output()\n\n \"\"\"\n # check for errors\n for n in [n0, n1, n2]:\n ch.stderr(\"%s: nsent = %s\\n\"%(n, n.agent.nsent) )\n ch.stderr(\"%s nrcvd = %s\\n\"%(\" \"*len(str(n)), n.agent.nrcvd) )\n \"\"\"\n # check output\n nsent = [0, 0, 0]\n nrcvd = [0, 0, 0]\n nfwrd = [0, 0, 0]\n ndrop = [0, 0, 0]\n nid0, nid1, nid2 = n0.uid, n1.uid, n2.uid\n rtgid0 = n0.net.uid\n for e in ch.trace.events:\n if (e['event']==\"SND\") and (e['obj']==\"RTG\"):\n if (int(e['nid'])==nid0): nsent[0] += 1\n if (int(e['nid'])==nid1): nsent[1] += 1\n if (int(e['nid'])==nid2): nsent[2] += 1\n if (e['event']==\"RCV\") and (e['obj']==\"RTG\") and (e['packet']=='Packet'):\n if (int(e['nid'])==nid0): nrcvd[0] += 1\n if (int(e['nid'])==nid1): nrcvd[1] += 1\n if (int(e['nid'])==nid2): nrcvd[2] += 1\n if (e['event']==\"FWD\") and (e['obj']==\"RTG\"):\n if (int(e['nid'])==nid0): nfwrd[0] += 1\n if (int(e['nid'])==nid1): nfwrd[1] += 1\n if (int(e['nid'])==nid2): nfwrd[2] += 1\n if (e['event']==\"DRP\") and (e['obj']==\"RTG\"):\n if (int(e['uid'])==rtgid0) and (e['drop']==\"not for me\"): ndrop+=1\n self.assertEqual(n0.agent.nsent, n2.agent.nrcvd) # routing failed\n self.assertEqual(nsent[0], nrcvd[2]) # send error\n self.assertEqual(nsent[0], nfwrd[1]) # forward error\n self.assertEqual(nsent[2], 0) # send error\n self.assertEqual(nrcvd[2], n2.agent.nrcvd) # did not send upstream\n\n def test_aloha(self):\n \"\"\"Test `Aloha`.\"\"\"\n class Node(Element):\n name = \"node\"\n tracename = \"NODE\"\n def __init__(self, **kwargs):\n Element.__init__(self, **kwargs)\n def configure(self, rate=None, duration=None, pos=None, **kwargs):\n agt = self.newchild('agent', Agent, rate=rate, duration=duration)\n net = self.newchild('net', Routing)\n mac = self.newchild('mac', Aloha)\n arp = self.newchild('arp', MyARP, \\\n netaddr=net.addr, macaddr=mac.addr)\n cif = self.newchild('cif', Radio)\n mobi = self.newchild('motion', Motion, pos=pos)\n # connect ports\n agt.connect(net)\n net.TXD.connect(arp.RXU), arp.TXU.connect(net.RXD)\n arp.TXD.connect(mac.RXU), mac.TXU.connect(arp.RXD)\n mac.connect(cif)\n #arp.TXD.connect(cif.RXU), cif.TXU.connect(arp.RXD)\n\n # set up parameters\n initialize()\n stoptime = 10.1\n verbose = 80\n kwargs = {'verbose':verbose}\n ch = Channel(model=Propagation, **kwargs)\n n0 = Node(rate=0.5, pos=(0, 0), **kwargs)\n n1 = Node(rate=0.0, pos=(0, 50), **kwargs)\n n2 = Node(rate=0.0, pos=(0,100), **kwargs)\n #n3 = Node(rate=0.0, pos=(0,200), **kwargs)\n ch.add_edge(n0.cif, n1.cif)\n ch.add_edge(n1.cif, n2.cif)\n ch.add_edge(n1.cif, n0.cif)\n ch.add_edge(n0.cif, n2.cif)\n #ch.add_edge(n3.cif, n0.cif)\n # set agent destination\n d0 = n0.net.address\n d1 = n1.net.address\n d2 = n2.net.address\n n0.agent.dest = n2.net.address\n n0.net.addroute(d2, d1)\n n1.net.addroute(d2)\n\n # run simulation\n simulate(until=stoptime)\n #ch.trace.output()\n\n # check output\n nsent = [0, 0, 0]\n nrcvd = [0, 0, 0]\n ndrop = [0, 0, 0]\n nid0, nid1, nid2 = n0.uid, n1.uid, n2.uid\n aid0, aid1, aid2 = n0.mac.uid, n1.mac.uid, n2.mac.uid\n for e in ch.trace.events:\n if (e['event']==\"SND\") and (e['obj']==\"ALOHA\"):\n if (int(e['nid'])==nid0): nsent[0] += 1\n if (int(e['nid'])==nid1): nsent[1] += 1\n if (int(e['nid'])==nid2): nsent[2] += 1\n if (e['event']==\"RCV\") and (e['obj']==\"ALOHA\"):\n if (int(e['nid'])==nid0): nrcvd[0] += 1\n if (int(e['nid'])==nid1): nrcvd[1] += 1\n if (int(e['nid'])==nid2): nrcvd[2] += 1\n if (e['event']==\"DRP\") and (e['obj']==\"ALOHA\"):\n if (int(e['uid'])==aid0) and (e['drop']==\"not for me\"): ndrop[0]+=1\n if (int(e['uid'])==aid1) and (e['drop']==\"not for me\"): ndrop[1]+=1\n if (int(e['uid'])==aid2) and (e['drop']==\"not for me\"): ndrop[2]+=1\n self.assertEqual(n0.agent.nsent, n2.agent.nrcvd) # pass-upstream failed\n self.assertEqual(nsent[0], nrcvd[1]) # send error\n self.assertEqual(nsent[1], nrcvd[2]) # forward error\n self.assertEqual(ndrop[0], nsent[1]) # address match error\n self.assertEqual(nsent[0], ndrop[2]) # address match error\n\n def test_arp(self):\n \"\"\"Test `ARP` module.\"\"\"\n class Node(Element):\n name = \"node\"\n tracename = \"NODE\"\n def __init__(self, **kwargs):\n Element.__init__(self, **kwargs)\n def configure(self, rate=None, duration=None, pos=None, \\\n useshared=False, **kwargs):\n agt = self.newchild('agent', Agent, rate=rate, duration=duration)\n net = self.newchild('net', Routing)\n mac = self.newchild('mac', Aloha)\n arp = self.newchild('arp', ARP, useshared=useshared)\n cif = self.newchild('cif', Radio)\n mobi = self.newchild('motion', Motion, pos=pos)\n # connect ports\n agt.connect(net)\n arp.connect(net, mac)\n mac.connect(cif)\n # add kludge\n mac.duration = lambda *args,**kwargs: self.duration(*args,**kwargs)\n def duration(self, p):\n d = 1e-4 #const.EPSILON\n if p.hasanno('cif-duration'): d = p.getanno('cif-duration')\n p.setanno('cif-duration', d)\n return d\n\n # set up parameters\n initialize()\n stoptime = 20.1\n verbose = 80\n useshared = True\n kwargs = {'verbose':verbose, 'useshared': useshared}\n ch = Channel(model=Propagation, **kwargs)\n n0 = Node(rate=0.5, pos=(0, 0), **kwargs)\n n1 = Node(rate=0.0, pos=(0, 50), **kwargs)\n n2 = Node(rate=0.0, pos=(0,100), **kwargs)\n #n3 = Node(rate=0.0, pos=(0,200), **kwargs)\n nlist = [n0, n1, n2]\n # connect interfaces\n for n in nlist:\n for m in nlist:\n if (n is not m): ch.add_edge(n.cif, m.cif)\n # set agent destination\n d0 = n0.net.address\n d1 = n1.net.address\n d2 = n2.net.address\n n0.agent.dest = d2\n n0.net.addroute(d2, d1) # n0->n1\n n1.net.addroute(d2) # n1->n2\n\n # run simulation\n simulate(until=stoptime)\n #ch.trace.output()\n \"\"\"\n # check for errors\n for n in [n0, n1, n2]:\n ch.stderr(\"%s: nsent = %s\\n\"%(n, n.agent.nsent) )\n ch.stderr(\"%s nrcvd = %s\\n\"%(\" \"*len(str(n)), n.agent.nrcvd) )\n \"\"\"\n\n # check output\n nsent = [0,0,0]\n nrcvd = [0,0,0]\n ndrop = [0,0,0]\n nsreq, nrreq = [0,0,0], [0,0,0] # requests sent/rcvd\n nsrep, nrrep = [0,0,0], [0,0,0] # replies sent/rcvd\n ndreq, ndrep = [0,0,0], [0,0,0] # dropped requests/replies\n nid0, nid1, nid2 = n0.uid, n1.uid, n2.uid\n aid0, aid1, aid2 = n0.arp.uid, n1.arp.uid, n2.arp.uid\n reason1 = \"dst not found in IPSEND\"\n reason2 = \"ARP request not for me in ARPRECV\"\n for e in ch.trace.events:\n if (e['event']==\"SND\") and (e['obj']==\"ARP\"):\n for (id, k) in [(nid0,0), (nid1,1), (nid2,2)]:\n if (int(e['nid'])==id):\n if (e['root']==\"ARP Request\"): nsreq[k] += 1\n elif (e['root']==\"ARP Reply\"): nsrep[k] += 1\n else: nsent[k] += 1\n if (e['event']==\"RCV\") and (e['obj']==\"ARP\"):\n for (id, k) in [(nid0,0), (nid1,1), (nid2,2)]:\n if (int(e['nid'])==id):\n if (e['packet']==\"ARP Request\"): nrreq[k] += 1\n elif (e['packet']==\"ARP Reply\"): nrrep[k] += 1\n else: nrcvd[k] += 1\n if (e['event']==\"DRP\") and (e['obj']==\"ARP\"):\n for (id, k) in [(aid0,0), (aid1,1), (aid2,2)]:\n if (int(e['uid'])==id):\n if (e['packet']==\"ARP Request\"): ndreq[k] += 1\n elif (e['packet']==\"ARP Reply\"): ndrep[k] += 1\n else: ndrop[k] += 1\n if useshared:\n self.assertEqual(ndrop[0], 0) # ARP lookup failed in IPSEND\n self.assertEqual(ndrop[1], 0) # ARP lookup failed in IPSEND\n for k in [0,1,2]:\n self.assertEqual(nsreq[k], 0) # Shared ARP fail -> requests!\n self.assertEqual(nsrep[k], 0) # Shared ARP fail -> replies!\n else:\n self.assertEqual(ndrop[0], 1) # ARP lookup failed in IPSEND\n self.assertEqual(ndrop[1], 1) # ARP lookup failed in IPSEND\n self.assertEqual(nsreq[0], 1) # failed to send ARP request\n self.assertEqual(nsrep[1], 1) # failed to send ARP reply\n self.assertEqual(nrrep[0], 2) # failed to recv ARP reply\n self.assertEqual(nsreq[1], 1) # failed to send ARP request\n self.assertEqual(nsrep[2], 1) # failed to send ARP reply\n self.assertEqual(nrrep[1], 1) # failed to recv ARP reply\n self.assertEqual(ndreq[2], 1) # drop 'not for me' request failed\n self.assertEqual(ndreq[0], 1) # drop 'not for me' request failed\n for k in [0,1,2]:\n self.assertEqual(ndrep[k], 0) # dropped ARP Reply!\n tdrop = 0\n for x in ndrop: tdrop += x\n self.assertEqual(n0.agent.nsent, n2.agent.nrcvd+tdrop) # end-to-end fail\n","sub_path":"tests/qa_protocol.py","file_name":"qa_protocol.py","file_ext":"py","file_size_in_byte":16612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"296549108","text":"\"\"\"0.0.2\n\nRevision ID: 3b9497859da\nRevises: 5910f79875f\nCreate Date: 2015-02-28 16:19:15.064836\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '3b9497859da'\ndown_revision = '5910f79875f'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('supplier',\n sa.Column('id', sa.String(length=32), nullable=False),\n sa.Column('created_date', sa.DateTime(), nullable=False),\n sa.Column('last_modified_date', sa.DateTime(), nullable=False),\n sa.Column('brief', sa.String(length=50), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('brief')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('supplier')\n ### end Alembic commands ###\n","sub_path":"alembic/versions/3b9497859da_0_0_2.py","file_name":"3b9497859da_0_0_2.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"164368828","text":"#!/usr/bin/env python3\n\nimport math\nfrom itertools import combinations\nfrom itertools import permutations\nfrom collections import Counter\n\nwith open(\"./17.txt\",'r') as f: f_s=f.read().replace('\\n','')\n\nalph=\"абвгдежзийклмнопрстуфхцчшщьыэюя\"\nm=31\nmost_fr_b_lang = [\"ст\", \"но\", \"по\", \"то\", \"на\" ]\ndef egcd(a, b):\n if a == 0:\n return (b, 0, 1)\n else:\n b_div_a, b_mod_a = divmod(b, a)\n g, x, y = egcd(b_mod_a, a)\n return (g, y - b_div_a * x, x)\n\ndef obern(a, n):\n try:\n g, x, _ = egcd(a[0], n)\n except:\n g, x, _ = egcd(a, n)\n if g != 1:\n return \"-\"\n return x % n\n\ndef solve(a,b,n):\n\n #a*x=b%n\n x=[]\n if egcd(a,n)[0]==1:\n x.append((obern(a,n)*b)%n)\n else:\n d, _, _ = egcd(a,n)\n a1=a/d\n n1=n/d\n x=[]\n if b%d == 0:\n b1=b/d\n x.append(( obern(a1, n) * b1) % n1)\n for i in range(d):\n x.append(x[0]+i*n1)\n else:\n return \"-\"\n return x\n\ndef split_bigrs_wo_cross(str2):\n res = Counter(str2[idx: idx + 2] for idx in range(len(str2) - 1))\n return res\n \n\n\ndef most_fr_b_ct(str2):\n res = Counter(str2[idx: idx + 2] for idx in range(0,len(str2) - 1,2)) \n most_fr = []\n for k in sorted(res, key=res.get, reverse=True)[:5]:\n most_fr.append(k)\n return res, most_fr\n\ndef count_entr( dec):\n res = split_bigrs_wo_cross(dec)\n sum2 = 0\n sum1 = sum(res.values())\n for i in list(res.keys()):\n sum2 = sum2 + (res[i]/sum1)*math.log2(res[i]/sum1)\n return -sum2/2\n\ndef solve_sys(xz, xzz, yz, yzz):\n xz = (alph.find(xz[0])*m + alph.find(xz[1]))%(m*m)\n xzz = (alph.find(xzz[0])*m + alph.find(xzz[1]))%(m*m)\n yz = (alph.find(yz[0])*m + alph.find(yz[1]))%(m*m)\n yzz = (alph.find(yzz[0])*m + alph.find(yzz[1]))%(m*m)\n a = solve((xz-xzz)%(m*m), (yz-yzz)%(m*m),m*m)\n b=[]\n sol=[]\n if a[0]=='-':\n return \"-\",'-'\n else:\n for i in a:\n b= (yz-i*xz)%(m*m)\n sol.append((i,b))\n return sol\n\ndef decrypt(cip_t, a, b):\n decr=\"\"\n for i in range(0,len(cip_t)-1,2):\n yi= alph.index(cip_t[i])*m+alph.index(cip_t[i+1])\n if obern(a, m* m) != '-':\n try:\n xi = ( obern(a, m*m )*(yi-b )) % (m* m )\n except:\n xi = ( obern(a[0], m*m)*(yi-b )) % (m* m )\n else:\n return \"sorry\"\n xi=int(xi)\n decr+=alph[xi//31]+alph[xi%31]\n return decr\n\nprint(count_entr(f_s))\ndef main_pr():\n res, mst_fr = most_fr_b_ct( f_s)\n print(mst_fr)\n perm_y = permutations(mst_fr, 2) \n perm_x = permutations(most_fr_b_lang, 2)\n perm_x = list(perm_x)\n perm_y = list(perm_y)\n \n for i1 in perm_x[0:]:\n for i2 in perm_y[0:]:\n #comb = combinations([i1[0], i1[1], i2[0], i2[1]], 4)\n #for j123 in (list(comb)):\n sol = solve_sys(i1[0], i1[1], i2[0], i2[1])\n try:\n for a,b in sol:\n if a=='-':\n continue\n dec=decrypt(f_s, a, b)\n if dec=='sorry':\n continue\n if(count_entr( dec) >4.3):\n continue\n else:\n #pass\n #print(\"yes\")\n print(i1,i2)\n print(a,b)\n #print('entropy: ',count_entr(dec))\n print(dec[:500])\n return dec\n break\n #print(j123)\n except:\n continue\n\n\ndecrypted_text = main_pr()\n\nwith open(\"./17_dec.txt\",'w') as f2: f2.write(decrypted_text)\n\n","sub_path":"cp_3/Moroz_fb84_Yalovchuk_fb84_cp3/lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"602931305","text":"\"\"\"\nA quick task to change all leetcode codes PXXX to LCXXX\n\"\"\"\n\nimport os\nimport re\n\nfolder = \"D:\\Documents\\GitHub\\Learning_Python\\LeetCode\"\npattern = r\"(p|P)(\\d{3})\"\n\n\ndef p_to_LC(filedir: str):\n # to match find the genNode in application\n raw_pattern = r\"(p|P)(\\d{3})\"\n\n if filedir.endswith(\".py\"):\n p_phrase = re.compile(raw_pattern)\n\n with open(filedir, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n new_content = p_phrase.sub(r\"LC\\g<2>\", content)\n\n with open(filedir, \"w\", encoding=\"utf-8\") as f:\n f.write(new_content)\n\n\nif __name__ == \"__main__\":\n # single file test for regex\n first_file = \"D:\\Documents\\GitHub\\Learning_Python\\LeetCode\\LC001_two_sum.py\"\n # p_to_LC(first_file)\n\n from FileIteration.dir_search import general_modify\n general_modify(folder, p_to_LC)\n","sub_path":"QuickProjects/TextWash/leetcode_name_change_2.py","file_name":"leetcode_name_change_2.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"357491169","text":"import pybullet as p\nimport pybullet_data as pd\nimport math\nimport time\n\np.connect(p.GUI)\np.setAdditionalSearchPath(pd.getDataPath())\n# create the shape of terrain\nterrainShape = p.createCollisionShape(shapeType=p.GEOM_HEIGHTFIELD, meshScale=[1, 1, 1],\n fileName=\"data/test.txt\", heightfieldTextureScaling=128)\nterrain = p.createMultiBody(0, terrainShape)\np.resetBasePositionAndOrientation(terrain, [0, 0, 0], [0, 0, 0, 1])\np.changeVisualShape(terrain, -1, rgbaColor=[1, 1, 1, 1])\np.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 1)\np.setGravity(0, 0, -10)\np.setRealTimeSimulation(1)\n\nwhile (p.isConnected()):\n keys = p.getKeyboardEvents()\n\n time.sleep(0.01)","sub_path":"submit/terrain/terrain_try.py","file_name":"terrain_try.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"279031300","text":"import numpy as np\nimport sys\nimport os\nfrom PIL import ImageFile\nimport cv2\nimport dlib\nfrom sklearn import svm\nfrom sklearn.externals import joblib\nfrom sklearn import metrics\n# import openface\n\n# def pause():\n# programPause = input(\"Press the key to continue...\")\n\npredictor_model = \"./weight/shape_predictor_68_face_landmarks.dat\"\nface_recognition_model = './weight/dlib_face_recognition_resnet_model_v1.dat'\n\ndetector = dlib.get_frontal_face_detector()\nsp = dlib.shape_predictor(predictor_model)\nfacerec = dlib.face_recognition_model_v1(face_recognition_model)\n# face_aligner = openface.AlignDlib(predictor_model) \n\ndef dlib_to_opencv(rect):\n\tx = rect.left()\n\ty = rect.top()\n\tw = rect.right() - x\n\th = rect.bottom() - y\n \n\t# return a tuple of (x, y, w, h)\n\treturn (x, y, w, h)\n\ndef face_distance(face_encodings, labels, face_to_compare, tolerance):\n if len(face_encodings) == 0:\n return np.empty((0))\n\n preds = np.linalg.norm(face_encodings - face_to_compare, axis=1)\n sort_prob = np.argsort(preds)\n if preds[sort_prob[0]] > tolerance:\n return -1\n return labels[sort_prob[0]]\n\ndef compare_faces(known_face_encodings, labels, face_encoding_to_check, tolerance=0.45):\n label = face_distance(known_face_encodings, labels, face_encoding_to_check, tolerance)\n if label == -1:\n return 'unknown'\n else:\n return label\n\ndef load_features(src):\n print(\"[+] Load data....\")\n data = []\n label = []\n with open(src, \"r\") as file:\n for i,line in enumerate(file):\n img_path = line[:-1]\n #print(\"[+] Read image : \", img_path,\" id : \", i)\n if os.path.isfile(img_path) and img_path.find(\".jpg\") != -1: \n save_path = img_path.replace(\"images\", \"features\").replace(\".jpg\", \".npy\") \n if os.path.isfile(save_path):\n lb = save_path.split(\"/\")[1]\n # lb1 = lb.split(\".\")[1]\n # print (lb)\n # print(save_path)\n data.append(np.load(save_path))\n label.append(lb)\n print(\"[+] Load data finished\")\n return data, label\n\ndef face_recognition(image_path, features, labels):\n img = cv2.imread(image_path)\n # print(image_path)\n\n # win = dlib.image_window()\n # win.clear_overlay()\n # win.set_image(img)\n\n dets = detector(img, 1) #Xác định vị trí khuôn mặt trong bức ảnh\n # win.add_overlay(dets) #Vẽ khung hình bao quanh khuôn mặt\n\n # pause()\n # dlib.hit_enter_to_continue()\n\n for k, d in enumerate(dets):\n (x, y, w, h) = dlib_to_opencv(d)\n\n # Xác định facial landmark trên khuôn mặt\n shape = sp(img, d)\n\n # Vẽ facial landmark lên bức ảnh\n # win.add_overlay(shape)\n\n # Affine transformations using openface\n # alignedFace = face_aligner.align(534, img, d, landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)\n\n # Affine transformations using dlib\n face_chip = dlib.get_face_chip(img, shape)\n\n # win1 = dlib.image_window()\n # win1.clear_overlay()\n # win1.set_image(face_chip)\n\n # dlib.hit_enter_to_continue()\n\n # Encoding faces\n face_descriptor = facerec.compute_face_descriptor(face_chip)\n feature = np.reshape(face_descriptor, (1, -1))\n result = compare_faces(features, labels, feature)\n # feature = np.reshape(face_descriptor, (1, -1))\n\n # result = clf.predict(feature)[0]\n \n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)\n startX = x\n startY = y - 15 if y - 15 > 15 else y + 15\n cv2.putText(img, result, (startX, startY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)\n \n print(\"The face is: \" + result)\n # print(face_descriptor)\n cv2.imshow(\"Recognition\", img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nif __name__==\"__main__\":\n\n image_path = sys.argv[1] #input parameter của script\n features_path = sys.argv[2]\n features, labels = load_features(features_path)\n # db = sys.argv[2]\n\n # clf = joblib.load(db + '/model.joblib')\n\n face_recognition(image_path, features, labels)\n \n","sub_path":"face_recognition/face_recognition.py","file_name":"face_recognition.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"446469093","text":"#!/usr/bin/env python3\n\ndata = open('input.txt').read()\nlines = data.splitlines()\n\nN = 2503\n\nreindeers = []\nfor line in lines:\n parts = line.split(' ')\n speed = int(parts[3])\n duration = int(parts[6])\n sleep = int(parts[-2])\n reindeers.append((speed, duration, sleep))\n\ndef move(reindeer):\n t = 0\n distance = 0\n duration = reindeer[1]\n tosleep = 0\n d = {}\n\n while t <= N:\n if t >= 1:\n d[t] = distance\n\n if tosleep > 0:\n tosleep -= 1\n t += 1\n continue\n elif tosleep == 0:\n duration = reindeer[1]\n tosleep = -1\n\n if duration == 0:\n tosleep = reindeer[2] - 1\n else:\n distance += reindeer[0]\n duration -= 1\n t += 1\n return (distance, d)\n\nprint(reindeers)\n\ndistances = [move(r) for r in reindeers]\nmaxdist = max([d[0] for d in distances])\nprint(maxdist)\nassert maxdist == 2655\n\nscores = [d[1] for d in distances]\n\nscore_card = [0] * len(distances)\n\nfor t in range(N):\n if t == 0:\n continue\n best = 0\n besti = []\n for i, score in enumerate(scores):\n s = score[t]\n if s > best:\n best = s\n besti = [i]\n elif s == best:\n besti.append(i)\n\n for bi in besti:\n score_card[bi] += 1\n\nprint(score_card)\nprint(max(score_card))\n","sub_path":"day14/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"233553575","text":"#!/usr/bin/env python\n\"\"\"\nConsolidate TranscriptSet into bam files, allowing adding a prefix\nstring (e.g., 'mysample_HQ_') to every transcript names.\n\"\"\"\n\nimport sys\nimport os.path as op\nimport logging\nimport subprocess\n\nimport pysam\nfrom pysam import AlignmentFile # pylint: disable=no-member, no-name-in-module\n\nfrom pbcommand.utils import setup_log\nfrom pbcommand.cli import pacbio_args_runner\nfrom pbcommand.models import FileTypes, DataStore, DataStoreFile\nfrom pbcore.io import ConsensusAlignmentSet, TranscriptAlignmentSet, TranscriptSet, openDataSet\n\nfrom pbcoretools.file_utils import get_prefixes\nfrom pbcoretools.datastore_utils import dataset_to_datastore\nfrom pbcoretools.utils import get_base_parser\n\n\ndef get_parser():\n \"\"\"\n Input:\n idx - 0 SubreadSet\n idx - 1 HQ TranscriptSet\n idx - 2 LQ TranscriptSet\n Output:\n idx - 0 HQ TranscriptSet, of which read names have biosample_HQ prefix\n idx - 1 LQ TranscriptSet, of which read names have biosample_LQ prefix\n idx - 2 HQ DataStore of output TranscriptSet BAM file\n idx - 3 LQ DataStore of output TranscriptSet BAM file\n \"\"\"\n p = get_base_parser(__doc__)\n p.add_argument(\"subreads\", help=\"SubreadSet with biosample metadata.\")\n p.add_argument(\"hq_ds_in\", help=\"Gathered HQ transcripts\")\n p.add_argument(\"lq_ds_in\", help=\"Gathered LQ transcripts\")\n p.add_argument(\"hq_ds_out\", help=\"Output HQ transcripts\")\n p.add_argument(\"lq_ds_out\", help=\"Output LQ transcripts\")\n p.add_argument(\n \"hq_datastore\", help=\"Datastore containing HQ transcripts BAM\")\n p.add_argument(\n \"lq_datastore\", help=\"Datastore containing LQ transcripts BAM\")\n return p\n\n\nclass Constants:\n TOOL_ID = \"consolidate_transcripts\"\n BAI_FILE_TYPES = {\n FileTypes.BAMBAI.file_type_id,\n FileTypes.I_BAI.file_type_id\n }\n\n\ndef consolidate_transcripts(ds_in, prefix):\n \"\"\"Return a function which\n - must take (new_resource_file, numFiles, useTmp) as input,\n - should consolidate ds_in (input transcripset)\n - should add biosample prefix to transcript read names\n \"\"\"\n def _consolidate_transcripts_f(new_resource_file, numFiles, useTmp,\n perfix=prefix, ds_in=ds_in):\n external_files = ds_in.toExternalFiles()\n assert len(\n external_files) >= 1, \"{!r} must contain one or more bam files\".format(ds_in)\n header = AlignmentFile(external_files[0], 'rb', check_sq=False).header\n with AlignmentFile(new_resource_file, 'wb', header=header) as writer:\n for external_file in external_files:\n with AlignmentFile(external_file, 'rb', check_sq=False) as reader:\n for record in reader:\n record.query_name = prefix + record.query_name\n writer.write(record)\n # create pbi and bai index files for new_resource_file\n subprocess.check_call([\"pbindex\", new_resource_file])\n ds_in = TranscriptSet(new_resource_file) # override ds_in\n return _consolidate_transcripts_f\n\n\ndef bam_of_dataset(dataset_fn):\n return op.splitext(dataset_fn)[0] + \".bam\"\n\n\ndef get_reads_name(ds_in):\n if isinstance(ds_in, TranscriptAlignmentSet):\n return 'Aligned transcripts'\n if isinstance(ds_in, ConsensusAlignmentSet):\n return 'Aligned consensus reads'\n return 'Aligned reads'\n\n\ndef run_consolidate(dataset_file, output_file, datastore_file,\n consolidate, n_files,\n consolidate_f=lambda ds: ds.consolidate):\n # XXX https://github.com/pysam-developers/pysam/issues/939\n pysam.set_verbosity(0) # pylint: disable=no-member\n datastore_files = []\n with openDataSet(dataset_file) as ds_in:\n if consolidate:\n if len(ds_in.toExternalFiles()) <= 0:\n raise ValueError(\n \"DataSet {} must contain one or more files!\".format(dataset_file))\n new_resource_file = bam_of_dataset(output_file)\n consolidate_f(ds_in)(new_resource_file,\n numFiles=n_files, useTmp=False)\n # always display the BAM/BAI if consolidation is enabled\n # XXX there is no uniqueness constraint on the sourceId, but this\n # seems sloppy nonetheless - unfortunately I don't know how else to\n # make view rule whitelisting work\n reads_name = get_reads_name(ds_in)\n for ext_res in ds_in.externalResources:\n if ext_res.resourceId.endswith(\".bam\"):\n ds_file = DataStoreFile(\n ext_res.uniqueId,\n Constants.TOOL_ID + \"-out-2\",\n ext_res.metaType,\n ext_res.bam,\n name=reads_name,\n description=reads_name)\n datastore_files.append(ds_file)\n # Prevent duplicated index files being added to datastore, since consolidated\n # dataset may contain multiple indices pointing to the same physical file\n added_resources = set()\n for index in ext_res.indices:\n if (index.metaType in Constants.BAI_FILE_TYPES and\n index.resourceId not in added_resources):\n added_resources.add(index.resourceId)\n ds_file = DataStoreFile(\n index.uniqueId,\n Constants.TOOL_ID + \"-out-3\",\n index.metaType,\n index.resourceId,\n name=\"Index of {}\".format(reads_name.lower()),\n description=\"Index of {}\".format(reads_name.lower()))\n datastore_files.append(ds_file)\n ds_in.newUuid()\n ds_in.write(output_file)\n datastore = DataStore(datastore_files)\n datastore.write_json(datastore_file)\n return 0\n\n\ndef __runner(ds_items):\n for ds_in, ds_out, datastore, prefix in ds_items:\n def func(ds_in):\n return consolidate_transcripts(ds_in, prefix=prefix)\n run_consolidate(dataset_file=ds_in,\n output_file=ds_out,\n datastore_file=datastore,\n consolidate=True,\n n_files=1,\n consolidate_f=func)\n # At this piont, ds_out is the same as ds_in, override ds_out with\n # newly created, read name modified TranscriptSet\n new_resource_file = bam_of_dataset(ds_out)\n _ds_out = TranscriptSet(new_resource_file)\n _ds_out.newUuid()\n _ds_in = TranscriptSet(ds_in)\n _ds_out.tags = _ds_in.tags\n _ds_out.name = _ds_in.name\n _ds_out.write(ds_out)\n # At this piont datastore contains paths to bam/bai/pbi files, now override\n # datastore with TranscriptSet\n dataset_to_datastore(ds_out, datastore, source_id=Constants.TOOL_ID)\n return 0\n\n\ndef args_runner(args):\n hq_prefix, lq_prefix = get_prefixes(args.subreads)\n ds_items = [\n (args.hq_ds_in, args.hq_ds_out, args.hq_datastore, hq_prefix),\n (args.lq_ds_in, args.lq_ds_out, args.lq_datastore, lq_prefix)\n ]\n return __runner(ds_items)\n\n\ndef main(argv=sys.argv):\n logging.basicConfig(level=logging.DEBUG)\n log = logging.getLogger()\n return pacbio_args_runner(argv[1:],\n get_parser(),\n args_runner,\n log,\n setup_log)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"pbcoretools/tasks/isoseq/consolidate_transcripts.py","file_name":"consolidate_transcripts.py","file_ext":"py","file_size_in_byte":7745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"383147717","text":"# import the python GUI libary as tk for easier typing in the future.\n# Import StrngVar to create read only entry fields. \n# Import filedialog to use native file explorer.\n# Import messagebox to display message to the user\n# Import constraints \nimport tkinter as tk\nfrom tkinter import StringVar, filedialog, messagebox\nfrom tkinter.constants import DISABLED, RIGHT, Y\n# import the sorter function code\nimport sorter\n# Import pillows in order to handle the logo\nfrom PIL import ImageTk, Image\n# Import Path and OS in order to check the folders exist and read the file extentions\nfrom pathlib import Path\nimport os\n\n\n# Global Variables that need to be used by various functions\ndst_count = 0\nfile_exts =[]\ndst = []\nfile_type = []\n\n# Create the window on the users screen\nwindow = tk.Tk()\nwindow.geometry(\"500x500\")\nwindow.title(\"File Tidy\")\nwindow.iconbitmap(\"cs50_final_project\\\\quizy.ico\")\n\n# Create the frames for the desired layout\nframe_header = tk.Frame(master = window, pady=2, padx=2)\nframe_src = tk.Frame(master = window, pady=2, padx=2)\nframe_dst = tk.Frame(master = window, pady=2, padx=2)\nframe_button = tk.Frame(master = window, pady=2, padx=2)\nframe_header.pack()\nframe_src.pack()\nframe_dst.pack()\nframe_button.pack()\n\n# Open the image file and resize\nlogo = Image.open(\"cs50_final_project\\\\quizy_logo.png\")\nlogo = logo.resize((100, 100), Image.ANTIALIAS)\nlogo_img = ImageTk.PhotoImage(logo)\nlabel1 = tk.Label(image=logo_img, master = frame_header)\nlabel1.image = logo_img\nlabel1.grid(row=0, column=0)\n\n# A welcome message at the top of the app screen\ngreeting = tk.Label(\n master=frame_header,\n text = \"Welcome to File Tidy!\",\n font=(\"Helvetica\", 22),\n )\ngreeting.grid(row=0, column=1)\n\n# layout for the source section\nframe_src_inst = tk.Frame(frame_src)\nframe_src_entry = tk.Frame(frame_src)\nframe_src_inst.pack()\nframe_src_entry.pack()\n\n# Fucntion to create the new destination line\ndef new_dst():\n \n #referance global variables\n global dst_count\n global dst\n global file_type\n global file_exts\n # For easier use in this fucntion\n i = dst_count\n\n # Destination browse button action\n def get_dst():\n dst_loc = filedialog.askdirectory()\n dst[i].insert(0, dst_loc)\n\n # layout for the destination section\n frame_dst_inst = tk.Frame(frame_dst)\n frame_dst_entry = tk.Frame(frame_dst)\n frame_dst_inst.pack()\n frame_dst_entry.pack()\n\n # Instructional Label\n dst_label = tk.Label(frame_dst_inst, text=\"Select a destination folder for this file type!\")\n dst_label.pack()\n\n # Populate the file types in read only entry fields\n fletyp = StringVar()\n typ = tk.Entry(frame_dst_entry,\n textvariable=fletyp,\n state=DISABLED, \n width=5\n )\n file_type.append(typ)\n file_type[i].grid(row=0, column=0)\n fletyp.set(file_exts[i])\n\n # Destination Browse button\n browse_dst = tk.Button(\n master=frame_dst_entry,\n text=\"Browse\",\n width=7,\n height=1,\n bg=\"#D4D0C8\",\n fg=\"black\", \n borderwidth=5,\n relief=tk.RAISED, \n command=get_dst\n )\n browse_dst.grid(row=0, column=2)\n\n # Create a label to store the Source path in\n destination = tk.Entry(frame_dst_entry, width=50)\n dst.append(destination)\n dst[i].grid(row=0, column=1)\n\n # Keep count of the number of dsts added\n dst_count += 1\n\n# Get the user input for the source file when the button is pressed\ndef get_src():\n\n global file_exts\n global dst_count\n global file_exts\n global dst\n global file_type\n\n # Clear any previous entries and clear the dst frames & data\n source.delete(0, \"end\")\n dst_count = 0\n file_exts =[]\n dst = []\n file_type = []\n for widget in frame_dst.winfo_children():\n widget.pack_forget()\n\n # Populate the Source box\n src = filedialog.askdirectory()\n source.insert(0, src)\n\n # Identify the files in the source folder\n files = []\n for entry in os.scandir(path=src):\n files.append(entry.path) \n\n # Identify and sotre the file extentions\n for item in files: \n # Ensure no duplications in what is presented to the user\n if Path(item).suffix not in file_exts:\n file_exts.append(Path(item).suffix)\n \n # Filter to remove blanks from the list\n file_exts = list(filter(None, file_exts))\n \n # Give the user an error if the folder has no files.\n if not file_exts:\n messagebox.showerror(\"No files found at location\", \"There are no files in this folder!\")\n \n # Display the file extentions in the label\n for file_ext in file_exts:\n new_dst()\n\n# Instructional Label\nsrc_label = tk.Label(text=\"Select a folder to tidy!\", master=frame_src_inst)\nsrc_label.pack()\n\n#button for the user to choose the source file to sort. \nbrowse_src = tk.Button(\n master=frame_src_entry, \n text=\"Browse\",\n width=7,\n height=1,\n bg=\"#D4D0C8\",\n fg=\"black\", \n borderwidth=5,\n relief=tk.RAISED, \n command=get_src\n)\nbrowse_src.grid(row=0, column=1)\n\n# Create a label to store the Source path in\nsource = tk.Entry(master=frame_src_entry, width=55)\nsource.grid(row=0, column=0)\n\n# Tidy button code\ndef handle_click():\n # Display an error message if the user has not selected a sorce folder\n if not source.get():\n messagebox.showerror(\"No folder selected\", \"Please select a folder to tidy!\")\n return\n # Display an error message if the source folder cannot be located\n if not os.path.isdir(source.get()):\n messagebox.showerror(\"Error\", \"Source folder cannot be found. Please check input\")\n return\n \n # Check and process the desired destination folders\n for i in range(dst_count):\n # If the destination is blank - ignore\n if not dst[i].get():\n continue\n # Display an error message if the destination folder cannot be located\n elif not os.path.isdir(dst[i].get()):\n messagebox.showerror(\"Error\", f\"Destination folder for {file_type[i].get()} file type could not be located\")\n break\n # If all checks have been passed, execute the sort code.\n else:\n sorter.Sort(source.get(), dst[i].get(), file_type[i].get())\n # Inform the user that the sort completed without errors. Need to display different error if code errored out\n messagebox.showinfo(\"Complete\", \"All files have been moved to their destination folders\")\n return\n\n# Sort button \nsort = tk.Button(\n master=frame_button,\n text=\"Tidy!\",\n width=7,\n height=1,\n bg=\"#D4D0C8\",\n fg=\"black\", \n borderwidth=5,\n relief=tk.RAISED, \n command=handle_click \n)\nsort.pack()\n\n# necersary to get the window to display\nwindow.mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"22952071","text":"#! /usr/bin/python\n#Iterates points on the mandelbrot set\n#Peter Wolf\n\n#started 3-3-11\n#last update 9-8-17\n\n\nimport math\n\n#Returns a mandelbrot point magnitude for a given starting point and number of iterations\ndef getValue(x, y, iterations):\n\n x,y=getPoint(x,y,iterations)\n return(math.sqrt(x*x+y*y))\n \n#Returns a mandelbrot point for a given starting point and number of iterations\ndef getPoint(x, y, iterations):\n\n oldx=x\n oldy=y\n for i in range(iterations):\n nx=oldx*oldx-oldy*oldy+x\n ny=2*oldx*oldy+y\n oldx=nx\n oldy=ny\n return(nx,ny)\n","sub_path":"mandelbrot_iterator.py","file_name":"mandelbrot_iterator.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"219322857","text":"from django.utils import timezone\nfrom django.db.models import Q\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.models import AnonymousUser\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.authentication import BasicAuthentication\nfrom Arion.utils import CsrfExemptSessionAuthentication\nfrom public.models import Users,Student\nfrom internship.serializers import *\n\n\n# class InternShipStateView(APIView):\n# def get(self, request):\n# internshipstate = InternShipState\n\n\nclass RequestInternShipView(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n def get(self, request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n else:\n ###Show Student Information\n student = Student.objects.get(user = request.user)\n serializer = StudentInformationSerializer(instance=student)\n\n if student.credits < 80 :\n return Response(\n {\n 'message' : 'Credits Error',\n\n 'data' : serializer.data\n },\n status=status.HTTP_403_FORBIDDEN\n )\n\n return Response(\n {\n 'data' : serializer.data\n },\n status=status.HTTP_200_OK\n )\n\n def post(self,request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n else:\n # student = Student.objects.get(user = request.user)\n student = Student.objects.filter(user = request.user)[0]\n serializer = RequestFormInternShipSerializer(\n data=request.data,\n context={\n 'student' : student\n }\n )\n\n if serializer.is_valid():\n serializer.save()\n return Response(\n {\n 'Message' : 'Form completed',\n },\n status=status.HTTP_200_OK\n )\n else:\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n def put(self,request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n else:\n editcredit = Student.objects.get(user = request.user)\n serializer = EditCreditsSerializer(instance=editcredit,data=request.data)\n if serializer.is_valid():\n serializer.save()\n\n return Response(\n {\n 'message': 'Credits Edited successfuly',\n 'data': serializer.data\n },\n status=status.HTTP_200_OK\n )\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\nclass RequestFlowView(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n def get(self,request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n student = Student.objects.get(user = request.user)\n opinion = Opinion.objects.filter(request__student=student)\n\n serializer = RequestFlowSerializer(instance=opinion,many=True)\n\n return Response(\n {\n 'data' : serializer.data\n },\n status=status.HTTP_200_OK\n )\n\n\n\n\nclass CheckRequestView(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n\n def get(self,request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n\n opinion_serializer = OpinionGetFilterSerializer(data=request.GET) #data=request.data\n if opinion_serializer.is_valid():\n for r in request.user.roles.all():\n r=str(r)\n if r == 'FacultyTrainingStaff':\n opinion = Opinion.objects.filter(request__state=1)\n\n elif r == 'DepartmentHead':\n opinion = Opinion.objects.filter(Q(user__roles__role='DepartmentHead')&Q(request__state=2))\n print(\"**************hiiiiasdnnksjnk*********************\",opinion)\n\n elif r == 'UniversityTrainingStaff':\n opinion = Opinion.objects.filter(Q(user__roles__role='UniversityTrainingStaff')&Q(request__state=3))\n\n else:\n return Response(\n {\n 'message' : 'InAccessibility !!!'\n },\n status=status.HTTP_403_FORBIDDEN\n )\n\n\n\n if 'first_name' in opinion_serializer.data:\n opinion = opinion.filter(\n request__student__user__first_name=opinion_serializer.data['first_name']\n )\n if 'last_name' in opinion_serializer.data:\n opinion = opinion.filter(\n request__student__user__last_name=opinion_serializer.data['last_name']\n )\n if 'username' in opinion_serializer.data:\n opinion = opinion.filter(\n request__student__user__username=opinion_serializer.data['username']\n )\n if 'title' in opinion_serializer.data:\n opinion = opinion.filter(\n request__title=opinion_serializer.data['title']\n )\n serializer=OpinionSerializers(instance=opinion,many=True)\n for op in opinion:\n if op.seenDate is None:\n op.seenDate=timezone.now()\n op.save()\n\n # op.seenDate=datetime.now()\n # op.save()\n\n\n return Response(\n {\n 'data' : serializer.data\n },\n status=status.HTTP_200_OK\n )\n else:\n return Response(\n opinion_serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n def put(self, request):\n\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n else:\n\n opinion = Opinion.objects.get(Q(request = request.data['id']) & Q(user=request.user))\n serializer = OpinionEditSerializer(instance=opinion,data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(\n {\n 'message': 'Your Opinion Was Recorded Successfuly',\n # 'data': serializer.data\n },\n status=status.HTTP_200_OK\n )\n else:\n return Response(\n serializer.errors,\n status=status.HTTP_404_NOT_FOUND\n )\n\n return Response(\n {\n \"user\" : serializer.data\n },\n status=status.HTTP_200_OK\n )\n","sub_path":"internship/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"242549495","text":"\"\"\"\nPurpose: This script implements maximum intensity projections (MIP). This\nprocess involves taking 3D brain scans, chunking them into three relevant\nsections, and compressing each section's maximum values down into a 2D array.\nWhen these are recombined, we get an array with the shape (3, X, Y) — which is\nready to be fed directly into standardized Keras architecture with pretrained\nfeature detection weights from ImageNet/CIFAR10.\n\nExactly the same as overlap_mip(), but calls segment_vessels() on the array\ninstead of remove_extremes().\n\"\"\"\n\nimport logging\n\n# from matplotlib import pyplot as plt\nimport lib.cloud_management as cloud\nimport lib.transforms as transforms\n\nWHENCE = ['numpy/axial',\n 'numpy/coronal']\n\nFAILURE_ANALYSIS = ['SSQSB70QYC5L5CJJ',\n 'MTWW42SPCGLHEDKY',\n 'GKDV3FW4M56I3IKV',\n 'BMFSUHVBPJ7RY56P',\n 'NWO33W453F6ZJ4BU',\n '8TLM2DUBYEE2GDH0',\n 'J3JHPC3E15NZGX34',\n 'J3JHPC3E15NZGX35',\n '3AWM4ZZHCWJ8MREY',\n 'MHL54TPCTOQJ2I4K',\n '5H94IH9XGI83T610',\n 'UGXVSPJLHJL6AHSW',\n '2KMKXR2G1BLD0C2G',\n 'PCNMFAZL5VWWK7RP',\n 'VVGO45TQNOASBLZM',\n 'NHXCOHZ4HH53NLQ6',\n 'F8W2RDY3D6L2EOFT',\n 'KK2Y9XHUUUC5LISA',\n 'HZLBHRHYLSY9TXJ4',\n '0RB9KGMO90G1YQZD',\n 'J2JPFK8ZOICHFG34',\n 'HLXOSVDF27JWNCMJ',\n 'AEPRN5R7W2ASOGR0',\n '99YJX0CY4FHHW46S',\n 'LOZOKQFJMDLL6IL5',\n 'STCSWQHX4UN23CDK',\n 'ZC9H37RWIQ90483S',\n 'CJDXGZHXAGH7QL3C',\n '5KZSOKNYS84ZTDK6',\n 'AKZ8T688ZRU9UTY2',\n '6BMRRS9RAZUPR3IL',\n 'HXLMZWH3SFX3SPAN',\n 'GHVG2CNNRZ65UBEU',\n 'TSDXCC6X3M7PG91E',\n 'IP4X9W512RO56NQ7',\n 'LNU3P20QOML7YGMZ',\n '56GX2GI8AGT0BIHN',\n 'TSZFE43KG3NQJR69',\n 'IXRSXXZI0S6L0EJI',\n 'FCYGZ75WMW6L4PJM',\n 'KOE9CU24WK2TUQ43',\n 'KOE9CU24WK2TUQ44',\n 'TFIG39JA77W6USD3',\n 'XQBRGW3CYGNUMWHI',\n 'PB7YJZRJU74HFKTS',\n 'EUNTRXNEDB7VDVIS',\n 'JQWIIAADGKE2YMJS',\n 'NXLFQLVZRLUEK2UF',\n 'RHWTMTHC7HIWZ2YZ',\n 'RW13S0OR03CO7OP5',\n 'LYUO2OPTNYUBCHT2',\n 'CSCIKXOMNAIB3LUQ',\n 'Q8BNE59JIKQLLYJ1',\n 'K2GS9PIQ1E0DBDBE',\n 'WWEFFBIMLZ3KLQVZ']\n\n\ndef configure_logger():\n root_logger = logging.getLogger()\n root_logger.setLevel(logging.INFO)\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\n fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n root_logger.addHandler(handler)\n\n\ndef multichannel_mip():\n configure_logger()\n client = cloud.authenticate()\n bucket = client.get_bucket('elvos')\n\n # iterate through every source directory...\n for location in WHENCE:\n prefix = location + '/'\n logging.info(f\"MIPing images from {prefix}\")\n\n for in_blob in bucket.list_blobs(prefix=prefix):\n # blacklist\n if in_blob.name == prefix + 'LAUIHISOEZIM5ILF.npy':\n continue\n\n file_id = in_blob.name.split('/')[2]\n file_id = file_id.split('.')[0]\n\n # perform the normal MIPing procedure\n logging.info(f'downloading {in_blob.name}')\n input_arr = cloud.download_array(in_blob)\n logging.info(f\"blob shape: {input_arr.shape}\")\n if file_id in FAILURE_ANALYSIS:\n if location == 'numpy/axial':\n cropped_arr = \\\n transforms.crop_multichannel_axial_fa(input_arr,\n location)\n else:\n if location == 'numpy/axial':\n cropped_arr = transforms.crop_multichannel_axial(input_arr,\n location)\n else:\n cropped_arr = transforms.crop_multichannel_coronal(\n input_arr)\n not_extreme_arr = transforms.segment_vessels(cropped_arr)\n logging.info(f'removed array extremes')\n mip_arr = transforms.mip_multichannel(not_extreme_arr)\n # plt.figure(figsize=(6, 6))\n # plt.imshow(mip_arr[1], interpolation='none')\n # plt.show()\n\n # save to the numpy generator source directory\n cloud.save_segmented_npy_to_cloud(mip_arr, file_id, location,\n 'multichannel')\n\n\nif __name__ == '__main__':\n multichannel_mip()\n","sub_path":"etl/multichannel_mip_with_segmentation.py","file_name":"multichannel_mip_with_segmentation.py","file_ext":"py","file_size_in_byte":5203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84064491","text":"import numpy as np\n\n\ndef compute_convolution_output(w, h, d, f, s, k):\n\n w2 = (w-f+0.0)/s + 1\n h2 = (h-f+0.0)/s + 1\n d2 = k + 0.0\n\n return [w2, h2, d2]\n\n\ndef compute_pool_output(w, h, d, f, s):\n\n w2 = (w-f+0.0)/s + 1\n h2 = (h-f+0.0)/s + 1\n d2 = d + 0.0\n\n return [w2, h2, d2]\n\n\ndef compute_relu_output(w, h, d):\n\n return [w, h, d]\n\n\ndef compute_output(w, h, d, f, s, k, f2, s2):\n\n [w2, h2, d2] = compute_convolution_output(w, h, d, f, s, k)\n [w3, h3, d3] = compute_pool_output(w2, h2, d2, f2, s2)\n return [w3, h3, d3]\n\n\ndef is_valid(output):\n\n truth = [x.is_integer() for x in output]\n truth = truth + [x > 0 for x in output]\n return np.all(truth)\n\n\ndef generate_layer_params(w = 32,h = 32,d = 32):\n\n params = []\n\n # fill f, s, k, f, s\n fs = [1,3,5,6]\n ss = [1,2,3]\n ks = [3,12,32,64,96]\n f2s = [1,3,5,6]\n s2s = [1,2,3]\n\n for f in fs:\n for s in ss:\n for k in ks:\n for f2 in f2s:\n for s2 in s2s:\n\n [w2, h2, d2] = compute_convolution_output(w, h, d, f, s, k)\n [w3, h3, d3] = compute_pool_output(w2, h2, d2, f2, s2)\n outputs = [w2, h2, d2] + [w3, h3, d3]\n\n if is_valid(outputs):\n\n valid_outputs = [f, s, k, f2, s2]\n params.append(valid_outputs)\n\n return params\n\n\ndef generate_2_layer_combos():\n\n layer_1_params = generate_layer_params()\n\n\n w = 32\n h = 32\n d = 3\n\n new_params = []\n\n for params in layer_1_params:\n\n [f, s, k] = params[0:3]\n [f2, s2] = params[3:]\n\n [w, h, d] = compute_output(w, h, d, f, s, k, f2, s2)\n\n okay_params = generate_layer_params(w, h, d)\n\n if len(okay_params) > 0:\n okay_params = [params, okay_params]\n new_params.append(okay_params)\n\n return new_params\n","sub_path":"layergenerator.py","file_name":"layergenerator.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"569089837","text":"from model.disciplina_ofertada import Disciplina_ofertada\nfrom infra.log import Log\n\ndisciplina_ofertadas_db = []\n\nclass Disciplina_ofertadaJaExiste(Exception):\n pass\n\ndef comparar_chave_unica(left, right):\n return left['id_disciplina'] == right['id_disciplina'] and \\\n left['ano'] == right['ano'] and \\\n left['semestre'] == right['semestre'] and \\\n left['turma'] == right['turma'] and \\\n left['id_curso'] == right['id_curso']\n\ndef listar():\n return disciplina_ofertadas_db\n\ndef localizar(id):\n for x in disciplina_ofertadas_db:\n if x.id == id:\n return x\n return None\n\ndef criar(id, id_disciplina, id_professor, ano, semestre, turma, id_curso, data):\n idx = localizar(id)\n if idx != None:\n raise Disciplina_ofertadaJaExiste()\n \n for disc in disciplina_ofertadas_db:\n if comparar_chave_unica(disc, disciplina_ofertadas_db[idx]):\n raise Disciplina_ofertadaJaExiste\n \n log = Log(None)\n criado = Disciplina_ofertada(id, id_disciplina, id_professor, ano, semestre, turma, id_curso, data)\n disciplina_ofertadas_db.append(criado)\n log.finalizar(criado)\n return criado\n\ndef remover(id):\n existente = localizar(id)\n if existente == None:\n return None\n log = Log(existente)\n disciplina_ofertadas_db.remove(existente)\n log.finalizar(None)\n return existente\n\ndef atualizar(id_antigo, id_novo, id_disciplina, id_professor, ano, semestre, turma, id_curso, data):\n existente = localizar(id_antigo)\n if existente == None:\n return None\n if id_antigo != id_novo:\n colisao = localizar(id_novo)\n if colisao != None:\n raise Disciplina_ofertadaJaExiste()\n log = Log(existente)\n existente.atualizar(id_novo, id_disciplina, id_professor, ano, semestre, turma, id_curso, data)\n log.finalizar(existente)\n return existente","sub_path":"POCs/outros/matricula_python/matricula_2_0/Ac6/services/disciplina_ofertada_service.py","file_name":"disciplina_ofertada_service.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"488638167","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 1 10:26:03 2018\r\n\r\n@author: Julia Bristow\r\n\"\"\"\r\n\r\nimport numpy\r\nfrom keras.datasets import mnist\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Activation, Dropout, Flatten\r\nfrom keras.layers.convolutional import Conv2D, AveragePooling2D\r\nfrom keras.utils import np_utils\r\nfrom keras import backend as K\r\nK.set_image_dim_ordering\r\n\r\n# initialize random # generator to a constant\r\n# this ensures reproducability\r\nseed = 7\r\nnumpy.random.seed(seed)\r\n\r\n# load data\r\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\r\n\r\n# reshape the images to 28x28\r\nX_train = X_train.reshape(X_train.shape[0], 1,28,28).astype('float32')\r\nX_test = X_test.reshape(X_test.shape[0], 1,28,28).astype('float32')\r\n\r\n# normalize inputs from 0-225 to 0-1\r\nX_train = X_train/255\r\nX_test = X_test/255\r\n\r\n# turn the vector of possible outputs into a binary matrix\r\n# one hot encoding\r\ny_train = np_utils.to_categorical(y_train)\r\ny_test = np_utils.to_categorical(y_test)\r\nnum_classes = y_test.shape[1]\r\n\r\n\r\n# now we can make the neural network\r\n# define the baseline model\r\ndef baseline_model():\r\n # create model\r\n model = Sequential()\r\n model.add(Conv2D(32, (5,5), input_shape=(1,28,28)))\r\n model.add(Activation('relu'))\r\n model.add(AveragePooling2D(pool_size=(2,2)))\r\n # Dropout helps prevent overfitting\r\n model.add(Dropout(0.2))\r\n model.add(Flatten())\r\n model.add(Dense(128))\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.2))\r\n model.add(Dense(num_classes))\r\n model.add(Activation('softmax'))\r\n # compile the model\r\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n return model\r\n\r\n# build the model\r\nmodel = baseline_model()\r\n# fit the model\r\nmodel.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=20, batch_size=200, verbose=2)\r\n# save the model\r\nmodel.save('mnist_cnn.h5')\r\n# final evaluation of the model\r\nscores = model.evaluate(X_test, y_test, verbose=0)\r\nprint(\"Error: %.2f%%\" % (100-scores[1]*100))","sub_path":"keras_nn/mnist_cnn.py","file_name":"mnist_cnn.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"73986458","text":"from . import qt\nimport sip\nimport multiprocessing\n\nfrom typing import List, Set\nfrom .work_window import WorkWindow\n\n\nclass ManagerWindow(qt.QWidget):\n def __init__(self):\n super().__init__()\n\n self.start_button = qt.QPushButton()\n self.start_button.setText('Start Work')\n self.start_button.clicked.connect(self.start_work)\n self.work_started = False\n\n def pause_all(paused):\n for window in self.work_windows:\n if not sip.isdeleted(window):\n window.pause_button.setChecked(paused)\n\n self.pause_all_button = qt.QPushButton()\n self.pause_all_button.setCheckable(True)\n self.pause_all_button.setText('Pause')\n self.pause_all_button.toggled.connect(pause_all)\n\n self.rearrange_button = qt.QPushButton()\n self.rearrange_button.setText('Rearrange Windows')\n self.rearrange_button.clicked.connect(self.arrange_windows)\n\n self.mdiarea = qt.QMdiArea()\n self.mdiarea.setActivationOrder(qt.QMdiArea.CreationOrder)\n\n self.vboxlayout = qt.QVBoxLayout(self)\n self.vboxlayout.addWidget(self.start_button)\n self.vboxlayout.addWidget(self.pause_all_button)\n self.vboxlayout.addWidget(self.rearrange_button)\n self.vboxlayout.addWidget(self.mdiarea)\n\n self.input_queue = multiprocessing.Queue()\n self.output_queue = multiprocessing.Queue()\n\n self.queues: Set[multiprocessing.Queue] = set()\n self.work_windows: List[WorkWindow] = []\n # self.setFixedWidth(256)\n\n def start_work(self):\n if not self.work_started:\n self.start_button.setEnabled(False)\n self.work_started = True\n\n for window in self.work_windows:\n window.show()\n window.start_work()\n\n self.arrange_windows()\n\n def add_window(self, window: WorkWindow):\n self.work_windows.append(window)\n\n self.queues.add(window.input_queue)\n self.queues.add(window.output_queue)\n\n mdi_subwindow: qt.QMdiSubWindow = self.mdiarea.addSubWindow(window)\n mdi_subwindow.setWindowFlag(qt.constants.FramelessWindowHint)\n\n def add_process(self, process_type, input_queue=None, output_queue=None):\n if input_queue is None:\n input_queue = self.input_queue\n\n if output_queue is None:\n output_queue = self.output_queue\n\n self.add_window(\n WorkWindow(input_queue, output_queue, process_type)\n )\n\n def add_queue(self, queue: multiprocessing.Queue):\n self.queues.append(queue)\n\n def arrange_windows(self):\n self.mdiarea.tileSubWindows()\n for window in self.work_windows:\n window.stdout.verticalScrollBar().setValue(\n window.stdout.verticalScrollBar().maximum()\n )\n\n def closeEvent(self, event: qt.QCloseEvent):\n for queue in self.queues:\n queue.cancel_join_thread()\n\n for window in self.work_windows:\n if not sip.isdeleted(window):\n window.close()\n\n super().closeEvent(event)\n","sub_path":"qt_work/manager_window.py","file_name":"manager_window.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"306634417","text":"\"\"\"\nNapisz program, który na podstawie numeru karty odpowie czy ma do czynienia z Visą, MasterCard,\na może AmericanExpress.\nCo wiemy o numerach tych kart?\n- All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.\n- MasterCard numbers either start with the numbers 51 through 55 or with the numbers 2221 through 2720.\n All have 16 digits.\n- American Express card numbers start with 34 or 37 and have 15 digits.\n\"\"\"\n\n\ndef is_visa(is_card, number):\n if not is_card:\n return False\n if len(number) == 16 or len(number) == 13:\n if number[0] == '4':\n return True\n\n\ndef is_mastercard(is_card, number):\n if not is_card:\n return False\n if len(number) == 16:\n if (int(number[0:2]) in range(51, 56)) or (int(number[0:4]) in range(2221, 2721)):\n return True\n\n\ndef is_american_express(is_card, number):\n if not is_card:\n return False\n if len(number) == 15:\n if number[0:2] in ('34', '37'):\n return True\n\n\ncard_number = input(\"Put your card number here: \")\n\ncan_be_card_number = False\n\nif len(card_number) < 13 or len(card_number) > 16:\n print(\"Wrong number\")\nelse:\n if card_number.isdecimal():\n print(\"Can be card number\")\n can_be_card_number = True\n else:\n print(\"Not a number\")\n\nif is_visa(can_be_card_number, card_number):\n print(\"I'm Visa\")\nelif is_mastercard(can_be_card_number, card_number):\n print(\"I'm MasterCard\")\nelif is_american_express(can_be_card_number, card_number):\n print(\"I'm Visa\")\nelse:\n print(\"Not known card type\")\n","sub_path":"05_funkcje_cd_2019-10-23/zad_7_karty_kredytowe_funkcje.py","file_name":"zad_7_karty_kredytowe_funkcje.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"15213041","text":"import pyttsx3\nimport webbrowser\nimport speech_recognition as sr\nimport random\nimport wolframalpha\nimport wikipedia\nimport datetime\nimport os\nimport sys\nfrom VideoPlayer import playVideo\n\n\nengine=pyttsx3.init()\nclient = wolframalpha.Client('GAPU32-XTGXHHK2HH')\n\ndef speak(audio):\n print(\"CUTIE:\"+ audio)\n engine.say(audio)\n engine.runAndWait()\n\ndef greet():\n ch=int(datetime.datetime.now().hour)\n if ch>=0 and ch<12:\n s=['pleasant morning','good morning','marvelous morning']\n speak(random.choice(s)+\" my dear munnaf\")\n\n if ch>=12 and ch<18:\n speak('good afternoon my dear munnaf')\n\n if ch>=18 and ch!=0:\n speak('good evening my dear munnaf')\n\ngreet()\n\n#speak('hello munnaf! I am your digital assistant CUTIE ,lady assistant for singles ')\nspeak(\"how may I help you\")\n\ndef myCommand():\n r=sr.Recognizer()\n with sr.Microphone()as source:\n print(\"Listening...\")\n r.pause_threshold =1.0\n audio = r.listen(source)\n\n try:\n query=r.recognize_google(audio,language='en-in')\n print(\"User:\" + query +'\\n')\n except sr.UnknownValueError:\n speak('Sorry Sir! I didn\\'t get that! Try typing the command')\n query=str(input('Command:'))\n\n return query\n\n\nif __name__=='__main__':\n while True:\n query=myCommand()\n query=query.lower()\n\n if 'open youtube' in query:\n speak('okay')\n webbrowser.open('www.youtube.com')\n\n elif 'open google' in query:\n speak('okay')\n webbrowser.open('www.google.co.in')\n\n elif 'i want to search' in query or 'search' in query:\n speak('okay')\n speak(\"what would you like to search\")\n que =myCommand()\n \n webbrowser.open('www.google.com/search?q='+ que)\n\n elif 'play video' in query:\n speak('okay')\n speak('name the video to play')\n que=myCommand()\n li=que.split()\n s=\"+\"\n s1=s.join(li)\n playVideo(self.s1)\n #webbrowser.open('https://www.youtube.com/results?search_query='+s)\n \n\n elif 'open facebook' in query:\n speak('okay')\n webbrowser.open('www.facebook.com')\n\n elif 'I love you Cutie'in query or 'I love you'in query or 'be my girlfriend' in query:\n s=['sorry sir!,I am your assistant','I love you','I hate you']\n speak(random.choice(s))\n\n elif 'open gmail' in query:\n speak('okay')\n webbrowser.open('www.gmail.com')\n elif \"what\\'s up\" in query or 'how are you' in query:\n smgs=['Just doing my thing!','I am fine!','I am nice and full of energy']\n speak(random.choice(smgs))\n\n elif 'hello'in query or 'hi'in query or 'hai' in query:\n speak('Hello Sir')\n\n elif 'bye' in query:\n speak('Bye sir!,have a good day.')\n sys.exit()\n else:\n query=query\n speak('Searching...')\n try:\n try:\n res=client.query(query)\n results=next(res.results).text\n speak('WOLFRAM-ALPHA says -')\n speak('Got it.')\n speak(results)\n\n except:\n results =wikipedia.summary(query, sentences=2)\n speak('Got it.')\n speak('WIKIPEDIA says -')\n speak(results)\n except:\n webbrowser.open('www.google.com')\n\n speak(\"Next Command Sir\")\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"myCutie.py","file_name":"myCutie.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"485148149","text":"#!/usr/bin/python3\n\n# This script is used to build the AMD open source vulkan driver and make a deb package from github for tags.\n\n# Before running this script, please install dependency packages with\n# pip3 install gitpython\n# pip3 install PyGithub\n\nimport sys\nimport os\nimport string\nimport time\nimport datetime\nimport git\nimport shutil\nimport re\nfrom optparse import OptionParser\nfrom github import Github\n\nDriverVersionStub = 'DriverVersionStub'\nArchitectureStub = 'ArchitectureStub'\nControl = \"Package: amdvlk\\n\\\nVersion: \" + DriverVersionStub + \"\\n\\\nArchitecture: \" + ArchitectureStub + \"\\n\\\nMaintainer: Advanced Micro Devices (AMD) \\n\\\nDepends: libc6 (>= 2.17), libgcc1 (>= 1:3.4), libstdc++6 (>= 5.2)\\n\\\nConflicts: amdvlk\\n\\\nReplaces: amdvlk\\n\\\nSection: libs\\n\\\nPriority: optional\\n\\\nMulti-Arch: same\\n\\\nHomepage: https://github.com/GPUOpen-Drivers/AMDVLK\\n\\\nDescription: AMD Open Source Driver for Vulkan\"\n\nSPEC = \"Name: amdvlk\\n\\\nVersion: \" + DriverVersionStub + \"\\n\\\nRelease: el\\n\\\nSummary: AMD Open Source Driver for Vulkan\\n\\\nURL: https://github.com/GPUOpen-Drivers/AMDVLK\\n\\\nLicense: MIT\\n\\\nGroup: System Environment/Libraries\\n\\\nVendor: Advanced Micro Devices (AMD) \\n\\\nBuildarch: x86_64\\n\\n\\\n%description\\n\\\n%prep\\n\\\n%build\\n\\\n%pre\\n\\\n%post\\n\\\n%preun\\n\\\n%postun\\n\\\n%files\\n\\\n/usr/lib64/amdvlk64.so\\n\\\n/etc/vulkan/icd.d/amd_icd64.json\\n\\\n/usr/share/doc/amdvlk/copyright\\n\\\n/usr/share/doc/amdvlk/changelog\\n\\\n%changelog\"\n\nChangeHeader = \"vulkan-amdgpu (\" + DriverVersionStub + \") unstable; urgency=low\\n\\\n\\n\\\n * Checkout from github:\"\n\nCopyRight = \"The MIT License (MIT)\\n\\\n\\n\\\nCopyright (c) 2018 Advanced Micro Devices, Inc.\\n\\\n\\n\\\nPermission is hereby granted, free of charge, to any person obtaining a copy\\n\\\nof this software and associated documentation files (the \\\"Software\\\"), to deal\\n\\\nin the Software without restriction, including without limitation the rights\\n\\\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\\n\\\ncopies of the Software, and to permit persons to whom the Software is\\n\\\nfurnished to do so, subject to the following conditions:\\n\\\n\\n\\\nThe above copyright notice and this permission notice shall be included in all\\n\\\ncopies or substantial portions of the Software.\\n\\\n\\n\\\nTHE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\n\\\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\\n\\\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\n\\\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\\n\\\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\\n\\\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\\n\\\nSOFTWARE.\"\n\nclass Worker:\n def __init__(self):\n self.workDir = os.getcwd()\n self.srcDir = self.workDir + \"/amdvlk_src/\"\n self.pkgDir = self.workDir + \"/amdvlk_pkg/\"\n self.pkgSharedDir = os.path.join(self.workDir, 'pkgShared')\n self.branch = 'master'\n self.components = ['xgl', 'pal', 'llpc', 'spvgen', 'llvm-project', 'MetroHash', 'CWPack']\n self.tagList = []\n self.relTagList = [] # The tags already released on github\n self.commits = {'xgl':'', 'pal':'', 'llpc':'', 'spvgen':'', 'llvm-project':'', 'MetroHash':'', 'CWPack':''}\n self.descript = \"\"\n self.targetRepo = 'https://github.com/GPUOpen-Drivers/'\n self.choice = 'build'\n self.distro = self.DistributionType()\n\n def GetOpt(self):\n parser = OptionParser()\n\n parser.add_option(\"-w\", \"--workDir\", action=\"store\",\n type=\"string\",\n dest=\"workDir\",\n help=\"Specify the location of source code, or download it from github\")\n\n parser.add_option(\"-a\", \"--accessToken\", action=\"store\",\n type=\"string\",\n dest=\"accessToken\",\n help=\"Specify the accessToken to access github\")\n\n parser.add_option(\"-t\", \"--targetRepo\", action=\"store\",\n type=\"string\",\n dest=\"targetRepo\",\n help=\"Specify the target repo of github, default is \" + self.targetRepo)\n\n parser.add_option(\"-c\", \"--choice\", action=\"store\",\n type=\"string\",\n dest=\"choice\",\n help=\"Build package or release it? Default is: \" + self.choice)\n\n (options, args) = parser.parse_args()\n\n if options.workDir:\n print(\"The source code is under %s\" % (options.workDir))\n self.workDir = options.workDir\n self.srcDir = self.workDir + \"/amdvlk_src/\"\n self.pkgDir = self.workDir + \"/amdvlk_pkg/\"\n else:\n print(\"The source code is not specified, downloading from github to: \" + self.workDir)\n\n if not os.path.exists(self.srcDir):\n os.makedirs(self.srcDir)\n\n if options.accessToken:\n self.accessToken = options.accessToken\n else:\n print(\"Please specify the access token to github, exiting...\")\n sys.exit(-1)\n\n if options.targetRepo:\n self.targetRepo = options.targetRepo\n\n print(\"The target repos is \" + self.targetRepo)\n\n if options.choice:\n self.choice = options.choice\n else:\n print('Please specify choice, build or release?')\n sys.exit(-1)\n\n def ConnectGithub(self):\n foundRepo = False\n self.github = Github(self.accessToken)\n for repo in self.github.get_user().get_repos():\n if (repo.name == 'AMDVLK'):\n self.repo = repo\n foundRepo = True\n\n if (foundRepo == False):\n print(\"Fatal: AMDVLK repo is not found\")\n sys.exit(-1)\n\n def DistributionType(self):\n result = os.popen('lsb_release -is').read().strip()\n if (result == 'Ubuntu'):\n return result\n elif (result == 'RedHatEnterprise' or result == 'RedHatEnterpriseWorkstation'):\n return 'RHEL'\n else:\n print('Unknown Linux distribution: ' + result)\n sys.exit(-1)\n\n def GetReleasedTagsOnGithub(self):\n releases = self.repo.get_releases()\n\n for release in releases:\n print(release.tag_name + \" is released already\")\n self.relTagList.append(release.tag_name)\n\n def CloneAMDVLK(self):\n # Clone the AMDVLK and get the released tag list\n # The released tag name must be with format \"v-major.minor\", for example, \"v-1.0\"\n os.chdir(self.srcDir)\n # Remove it if it exists\n if os.path.exists(self.srcDir + 'AMDVLK'):\n shutil.rmtree(self.srcDir + 'AMDVLK')\n\n git.Git().clone(self.targetRepo + 'AMDVLK')\n repo = git.Repo('AMDVLK')\n tags = repo.git.tag()\n release_tag_pattern = r'(^v-)'\n for tag in tags.split('\\n'):\n if re.findall(release_tag_pattern, tag):\n self.tagList.append(tag)\n print(tag + ' is added to tag lists')\n\n def DownloadAMDVLKComponents(self):\n os.chdir(self.srcDir)\n\n for i in self.components:\n if not os.path.exists(self.srcDir + i):\n print(\"Downloading \" + i + \".....\")\n git.Git().clone(self.targetRepo + i)\n\n repo = git.Repo(i)\n repo.git.clean('-xdf')\n # Clean the submodule\n repo.git.clean('-xdff')\n if (i == 'llvm-project'):\n repo.git.checkout('remotes/origin/amd-gfx-gpuopen-' + self.branch, B='amd-gfx-gpuopen-' + self.branch)\n elif (i == 'MetroHash' or i == 'CWPack'):\n repo.git.checkout('remotes/origin/amd-master', B='amd-master')\n else:\n repo.git.checkout('remotes/origin/' + self.branch, B=self.branch)\n repo.git.pull()\n\n def GetRevisions(self, tag):\n os.chdir(self.srcDir)\n repo = git.Repo('AMDVLK')\n repo.git.checkout(tag)\n self.descript = repo.head.commit.message\n\n # Update version\n self.version = tag[2:]\n print(\"Building for \" + tag + \" with version \" + self.version)\n\n # Get the commits from default.xml\n srcFileName = 'AMDVLK/default.xml'\n srcFile = open(srcFileName, 'r')\n lines = srcFile.readlines()\n\n for line in lines:\n for i in self.commits:\n index = line.find(\"revision=\");\n if (index > -1) and (line.find(i) > -1):\n startIndex = index + len(\"revision=\\\"\")\n stopIndex = line.find(\"\\\"\", startIndex)\n self.commits[i] = line[startIndex:stopIndex]\n print(i + \":\" + self.commits[i])\n # Checkout the commits\n repo = git.Repo(i)\n repo.git.clean('-xdf')\n # Clean the submodule\n repo.git.clean('-xdff')\n repo.git.checkout(self.commits[i])\n break\n\n srcFile.close()\n def Build(self):\n if self.distro == 'Ubuntu':\n self.MakeDriver('64')\n self.MakeDriver('32')\n elif self.distro == 'RHEL':\n self.MakeDriver('64')\n\n def MakeDriver(self, arch):\n cmakeName = 'cmake '\n if (self.distro == 'RHEL'):\n cmakeName = 'source scl_source enable devtoolset-7 && cmake3 '\n\n # fetch spvgen resources\n os.chdir(self.srcDir + 'spvgen/external')\n if os.system('python fetch_external_sources.py'):\n print(\"SPVGEN: fetch external sources failed\")\n exit(-1)\n\n # build amdvlk\n buildDir = 'rbuild64' if arch == '64' else 'rbuild32'\n cmakeFlags = ' -H. -G Ninja -B' + buildDir + ' -DCMAKE_BUILD_TYPE=Release -DBUILD_WAYLAND_SUPPORT=ON'\n cFlags = '' if arch == '64' else ' -DCMAKE_C_FLAGS=\\\"-m32 -march=i686\\\" -DCMAKE_CXX_FLAGS=\\\"-m32 -march=i686\\\"'\n\n os.chdir(self.srcDir + 'xgl/')\n if os.path.exists(buildDir):\n shutil.rmtree(buildDir)\n os.makedirs(buildDir)\n\n if os.system(cmakeName + cmakeFlags + cFlags):\n print(cmakeName + cmakeFlags + cFlags + ' failed')\n exit(-1)\n\n os.chdir(buildDir);\n if os.system('ninja'):\n print(\"build amdvlk failed\")\n exit(-1);\n\n # build spvgen\n if os.system('ninja spvgen'):\n print('SPVGEN: build failed')\n exit(-1);\n\n # build amdllpc\n if os.system('ninja amdllpc'):\n print('build amdllpc failed')\n exit(-1);\n\n def PreparePkgSharedResources(self):\n if os.path.exists(self.pkgSharedDir):\n shutil.rmtree(self.pkgSharedDir)\n os.makedirs(self.pkgSharedDir)\n os.chdir(self.pkgSharedDir)\n\n change_file = open('changelog', 'w')\n pkgChangeHeader = ChangeHeader.replace(DriverVersionStub, self.version)\n change_file.write(pkgChangeHeader + '\\n')\n\n for i in self.components:\n change_file.write(\" \" + self.targetRepo + i + \": \" + self.branch + \"--\" + self.commits[i] + '\\n')\n change_file.close()\n\n os.system('cp changelog changelog.Debian')\n os.system('gzip -9 -c ' + 'changelog.Debian' + ' >| ' + 'changelog.Debian.gz')\n os.remove('changelog.Debian')\n\n copyright_file = open('copyright', 'w')\n copyright_file.write(CopyRight + '\\n')\n copyright_file.close()\n\n def MakeDebPackage(self, arch):\n if not os.path.exists(self.pkgDir):\n os.makedirs(self.pkgDir)\n os.chdir(self.pkgDir)\n\n if os.path.exists(arch):\n shutil.rmtree(arch)\n os.makedirs(arch)\n os.chdir(arch)\n\n icdInstallDir = 'usr/lib/x86_64-linux-gnu' if arch == 'amd64' else 'usr/lib/i386-linux-gnu'\n jsonInstallDir = 'etc/vulkan/icd.d'\n implicitLayerDir = 'etc/vulkan/implicit_layer.d'\n docInstallDir = 'usr/share/doc/amdvlk'\n icdName = 'amdvlk64.so' if arch == 'amd64' else 'amdvlk32.so'\n icdBuildDir = 'xgl/rbuild64/icd' if arch == 'amd64' else 'xgl/rbuild32/icd'\n jsonName = 'amd_icd64.json' if arch == 'amd64' else 'amd_icd32.json'\n\n os.makedirs(icdInstallDir)\n os.makedirs(docInstallDir)\n os.makedirs(jsonInstallDir)\n os.makedirs(implicitLayerDir)\n os.makedirs('DEBIAN')\n\n os.system('cp ' + os.path.join(self.srcDir, icdBuildDir, icdName) + ' ' + icdInstallDir)\n os.system('strip ' + os.path.join(icdInstallDir, icdName))\n os.system('cp ' + os.path.join(self.srcDir, 'AMDVLK/json/Ubuntu', jsonName) + ' ' + jsonInstallDir)\n #os.system('cp ' + os.path.join(self.srcDir, 'AMDVLK/json/Ubuntu', jsonName) + ' ' + implicitLayerDir)\n\n debControl = Control.replace(DriverVersionStub, self.version).replace(ArchitectureStub, arch)\n control_file = open(\"DEBIAN/control\",'w')\n control_file.write(debControl + '\\n')\n control_file.close()\n\n os.system('cp ' + os.path.join(self.pkgSharedDir, 'changelog.Debian.gz') + ' ' + os.path.join(docInstallDir, 'changelog.Debian.gz'))\n os.system('cp ' + os.path.join(self.pkgSharedDir, 'copyright') + ' ' + docInstallDir)\n\n pkg_content = os.path.join(icdInstallDir, icdName) + ' ' + os.path.join(jsonInstallDir, jsonName) + ' ' \\\n + os.path.join(docInstallDir,'changelog.Debian.gz') + ' ' + os.path.join(docInstallDir, 'copyright') + ' '\n os.system('md5sum ' + pkg_content + '> DEBIAN/md5sums')\n\n os.chdir(self.workDir)\n os.system('dpkg -b ' + os.path.join(self.pkgDir, arch) + ' amdvlk_' + self.version + '_' + arch + '.deb')\n\n def ArchiveAmdllpcTools(self, arch):\n toolsDir = 'amdllpc_' + arch\n\n os.chdir(self.workDir)\n if os.path.exists(toolsDir):\n shutil.rmtree(toolsDir)\n os.makedirs(toolsDir)\n\n spvgenName = 'spvgen.so'\n spvgenBuildDir = 'xgl/rbuild64/spvgen' if arch == 'amd64' else 'xgl/rbuild32/spvgen'\n amdllpcName = 'amdllpc'\n amdllpcBuildDir = 'xgl/rbuild64/compiler/llpc' if arch == 'amd64' else 'xgl/rbuild32/compiler/llpc'\n\n os.system('cp ' + os.path.join(self.srcDir, amdllpcBuildDir, amdllpcName) + ' ' + toolsDir)\n os.system('cp ' + os.path.join(self.srcDir, spvgenBuildDir, spvgenName) + ' ' + toolsDir)\n os.system('zip -r ' + toolsDir + '.zip ' + toolsDir)\n\n def MakeRpmPackage(self):\n rpmbuild_dir = os.path.join(os.getenv('HOME'), 'rpmbuild')\n rpmbuildroot_dir = 'BUILDROOT'\n rpmspec_dir = 'SPEC'\n rpmspec_file_name = 'amdvlk.spec'\n icd_install_dir = 'usr/lib64'\n doc_install_dir = 'usr/share/doc/amdvlk'\n json_install_dir = 'etc/vulkan/icd.d'\n implicit_layer_dir = 'etc/vulkan/implicit_layer.d'\n icd_name = 'amdvlk64.so'\n json_name = 'amd_icd64.json'\n\n if os.path.exists(rpmbuild_dir):\n shutil.rmtree(rpmbuild_dir)\n os.makedirs(rpmbuild_dir)\n os.chdir(rpmbuild_dir)\n os.makedirs(rpmbuildroot_dir)\n os.makedirs(rpmspec_dir)\n\n rpm_spec = SPEC.replace(DriverVersionStub, self.version)\n spec_file = open(os.path.join(rpmspec_dir, rpmspec_file_name), 'w')\n spec_file.write(rpm_spec + '\\n')\n spec_file.close()\n\n os.chdir(rpmbuildroot_dir)\n packagename = 'amdvlk-' + self.version + '-el.x86_64'\n os.makedirs(packagename)\n os.chdir(packagename)\n os.makedirs(icd_install_dir)\n os.makedirs(doc_install_dir)\n os.makedirs(json_install_dir)\n os.makedirs(implicit_layer_dir)\n\n os.system('cp ' + os.path.join(self.srcDir, 'xgl/rbuild64/icd', icd_name) + ' ' + icd_install_dir)\n os.system('strip ' + os.path.join(icd_install_dir, icd_name))\n os.system('cp ' + os.path.join(self.srcDir, 'AMDVLK/json/Redhat', json_name) + ' ' + json_install_dir)\n #os.system('cp ' + os.path.join(self.srcDir, 'AMDVLK/json/Redhat', json_name) + ' ' + implicit_layer_dir)\n\n os.system('cp ' + os.path.join(self.pkgSharedDir, 'changelog') + ' ' + doc_install_dir)\n os.system('cp ' + os.path.join(self.pkgSharedDir, 'copyright') + ' ' + doc_install_dir)\n\n os.chdir(rpmbuild_dir)\n os.chdir(rpmspec_dir)\n os.system('rpmbuild -bb ' + rpmspec_file_name)\n os.chdir(rpmbuild_dir)\n os.system('cp RPMS/x86_64/' + packagename + '.rpm ' + self.workDir)\n\n def Package(self):\n self.PreparePkgSharedResources()\n\n if (self.distro == 'Ubuntu'):\n self.MakeDebPackage('amd64')\n self.ArchiveAmdllpcTools('amd64')\n self.MakeDebPackage('i386')\n self.ArchiveAmdllpcTools('i386')\n elif (self.distro == 'RHEL'):\n self.MakeRpmPackage()\n\n def Release(self, tag):\n os.chdir(self.workDir)\n\n rpmPackageName = 'amdvlk-' + self.version + '-el.x86_64.rpm'\n debPackage64bitName = 'amdvlk_' + self.version + '_amd64.deb'\n debPackage32bitName = 'amdvlk_' + self.version + '_i386.deb'\n amdllpc64bitName = 'amdllpc_amd64.zip'\n amdllpc32bitName = 'amdllpc_i386.zip'\n\n if not os.path.isfile(rpmPackageName):\n print('Can not find package: ' + rpmPackageName)\n sys.exit(-1)\n if not os.path.isfile(debPackage64bitName):\n print('Can not find package: ' + debPackage64bitName)\n sys.exit(-1)\n if not os.path.isfile(debPackage32bitName):\n print('Can not find package: ' + debPackage32bitName)\n sys.exit(-1)\n if not os.path.isfile(amdllpc64bitName):\n print('Can not find package: ' + amdllpc64bitName)\n sys.exit(-1)\n if not os.path.isfile(amdllpc32bitName):\n print('Can not find package: ' + amdllpc32bitName)\n sys.exit(-1)\n\n\n releaseNote = '[Driver installation instruction](https://github.com/GPUOpen-Drivers/AMDVLK#install-with-pre-built-driver) \\n\\n'\n formated_str = self.descript.replace(\"New feature and improvement\", \"## New feature and improvement\")\n formated_str = formated_str.replace(\"Issue fix\", \"## Issue fix\")\n releaseNote += formated_str\n\n newRelease = self.repo.create_git_release(tag, tag, releaseNote, False, False)\n\n newRelease.upload_asset(rpmPackageName, rpmPackageName + '(RedHat 7.8 8.2)')\n newRelease.upload_asset(debPackage64bitName, debPackage64bitName + '(Ubuntu 18.04 20.04)')\n newRelease.upload_asset(debPackage32bitName, debPackage32bitName + '(Ubuntu 18.04 20.04)')\n newRelease.upload_asset(amdllpc64bitName, amdllpc64bitName)\n newRelease.upload_asset(amdllpc32bitName, amdllpc32bitName)\n\n def start(self):\n self.GetOpt()\n self.ConnectGithub()\n self.GetReleasedTagsOnGithub()\n self.CloneAMDVLK()\n # Build and package if there is any tag un-released.\n downloaded = False\n ReleaseCount = 0\n for tag in self.tagList:\n if tag not in self.relTagList:\n ReleaseCount += 1\n if not downloaded:\n self.DownloadAMDVLKComponents()\n downloaded = True\n self.GetRevisions(tag)\n if (self.choice == 'build'):\n self.Build()\n self.Package()\n print(\"The package is generated successfully for \" + tag)\n elif (self.choice == 'release'):\n self.Release(tag)\n print(\"Released \" + tag + \" successfully\")\n\n if ReleaseCount == 0:\n print(\"All of the tags are released!\")\n\nif __name__ == '__main__':\n worker = Worker()\n worker.start()\n\n","sub_path":"utils/amdvlk_release_for_tag.py","file_name":"amdvlk_release_for_tag.py","file_ext":"py","file_size_in_byte":20048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"115177731","text":"from flask import Flask,render_template,request,url_for\r\napp = Flask(__name__)\r\n\r\n@app.route('/index')\r\ndef success():\r\n return render_template(\"ma.html\")\r\n\r\n@app.route('/Medicalcollege')\r\ndef main():\r\n return render_template('college.html')\r\n\r\n@app.route('/Engineeringcollege')\r\ndef main1():\r\n return render_template('college1.html')\r\n \r\n@app.route('/login',methods = ['POST', 'GET'])\r\ndef login():\r\n if request.method == 'POST':\r\n mark=request.form['Mark of 12: ']\r\n q=int(mark)//12\r\n if 90<=q<=100:\r\n n='Your Eligible To Join The Medical College as well as Engineering college'\r\n form = request.form\r\n return render_template('pysir.html',form=form,rest=n,mark=q)\r\n elif 80<=q<=89:\r\n n='Your Eligible To Join The Engineering College'\r\n form = request.form\r\n return render_template('pysir.html',form=form,rest=n,mark=q)\r\n else:\r\n n='Your Not Eligible To Join The Medical College And Engineering College'\r\n form = request.form\r\n return render_template('pysir.html',form=form,rest=n,mark=q)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug = True)\r\n","sub_path":"hello/psir1.py","file_name":"psir1.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"17477781","text":"# -*- coding: utf-8 -*-\r\n\r\nimport os, time, shutil, zipfile\r\nfrom abc import abstractmethod, ABCMeta\r\n\r\n'''Программа для сортировки файлов/фотографий по дате создания. Даёт возможность сортировать файлы как в обычной \r\nдиректории, так и из архива. При написании использовался шаблонный метод проектирования'''\r\n\r\nSOURCE_PATH = 'сюда вносим путь до папки, где лежат файлы, требующие сортировки'\r\nZIP_SOURCE_PATH = 'путь до zip-файла, если сортировка требуется для заархивированных фалов'\r\nTARGET_PATH = 'путь до папки, где в результате появятся отсортированные файлы'\r\n\r\n\r\nclass MainFileArranger(metaclass=ABCMeta):\r\n\r\n def __init__(self, path, target_path):\r\n self.path = os.path.normpath(path)\r\n self.target_path = os.path.normpath(target_path)\r\n self.stat = {}\r\n self.pathes = []\r\n\r\n def start_all_operations(self) -> None:\r\n self._get_stat()\r\n self._create_pathes()\r\n self._copy_file()\r\n\r\n @abstractmethod\r\n def _get_stat(self) -> None:\r\n pass\r\n\r\n def _create_pathes(self):\r\n '''создаем директории, по которым будут рассортированы файлы'''\r\n for year_of_creation, month_of_creation in self.stat.items():\r\n for month in month_of_creation:\r\n new_folder_path = os.path.join(self.target_path, str(year_of_creation), str(month))\r\n if os.path.exists(new_folder_path):\r\n pass\r\n else:\r\n os.makedirs(new_folder_path)\r\n self.pathes.append(new_folder_path)\r\n\r\n def _copy_file(self):\r\n '''копируем файлы в созданные директории'''\r\n for dirpath, dirnames, filenames in os.walk(self.path):\r\n for file in filenames:\r\n path_to_file = os.path.join(dirpath, file)\r\n secs = os.path.getmtime(path_to_file)\r\n file_full_time = time.gmtime(secs)\r\n file_path = os.path.join(self.target_path, str(file_full_time[0]), str(file_full_time[1]))\r\n if file_path in self.pathes:\r\n shutil.copy2(src=path_to_file, dst=file_path)\r\n\r\n\r\nclass FileArranger(MainFileArranger):\r\n '''используем этот класс, если отсортировать нужно файлы находящиеся в одной конкретной директории'''\r\n def _get_stat(self):\r\n for dirpath, dirnames, filenames in os.walk(self.path):\r\n for file in filenames:\r\n path_to_file = os.path.join(dirpath, file)\r\n secs = os.path.getmtime(path_to_file)\r\n file_full_time = time.gmtime(secs)\r\n year_of_creation = file_full_time[0]\r\n month_of_creation = file_full_time[1]\r\n if year_of_creation in self.stat:\r\n if month_of_creation not in self.stat[year_of_creation]:\r\n self.stat[year_of_creation].append(month_of_creation)\r\n else:\r\n self.stat[year_of_creation] = []\r\n\r\n\r\nclass ZipFileArranger(MainFileArranger):\r\n '''используем этот класс, если работаем с zip-архивом с файлами'''\r\n def _get_stat(self):\r\n if zipfile.is_zipfile(self.path):\r\n zip_file = zipfile.ZipFile(self.path, 'r')\r\n for file in zip_file.namelist():\r\n file_full_time = zip_file.getinfo(file).date_time\r\n year_of_creation = file_full_time[0]\r\n month_of_creation = file_full_time[1]\r\n if year_of_creation in self.stat:\r\n if month_of_creation not in self.stat[year_of_creation]:\r\n self.stat[year_of_creation].append(month_of_creation)\r\n else:\r\n self.stat[year_of_creation] = []\r\n else:\r\n print(\"Это не zip-file!\")\r\n\r\ntest = FileArranger(path=SOURCE_PATH, target_path=TARGET_PATH)\r\ntest.start_all_operations()\r\n","sub_path":"arranger.py","file_name":"arranger.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"17989934","text":"import sys\nimport Extraction\nimport math\nimport SeoulData\nimport requests\nimport json\nfrom geopy.geocoders import Nominatim\nfrom PyQt5.QtWidgets import *\n\nclass MyWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"GASEYO\")\n self.setGeometry(200, 200, 920, 320)\n\n ################################3\n # 현재위치\n\n textLabel = QLabel(\"중심위치\", self)\n textLabel.move(20, 100)\n\n # 위도\n self.labelLatitude = QLabel(\"위도 : \", self)\n self.labelLatitude.move(20, 140)\n self.editTextLatitude = QTextEdit(self)\n self.editTextLatitude.resize(200, 30)\n self.editTextLatitude.move(80,140)\n\n # 경도\n self.labelLongitude = QLabel(\"경도 : \", self)\n self.labelLongitude.move(20, 180)\n self.editTextLongitude = QTextEdit(self)\n self.editTextLongitude.resize(200, 30)\n self.editTextLongitude.move(80, 180)\n\n # 주소\n self.labelAddress = QLabel(\"주소 : \", self)\n self.labelAddress.move(20, 220)\n self.editTextAddress = QTextEdit(self)\n self.editTextAddress.resize(200, 30)\n self.editTextAddress.move(80, 220)\n\n # 축척\n self.labelScale = QLabel(\"축척 : \", self)\n self.labelScale.move(20, 260)\n self.editTextScale = QTextEdit(self)\n self.editTextScale.resize(200,30)\n self.editTextScale.move(80, 260)\n\n ################################ 현재위치 끝\n\n ################################\n # 시작위치\n\n textLabelStart = QLabel(\"시작위치 \", self)\n textLabelStart.move(320, 100)\n\n\n # 위도\n self.labelLatitudeStart = QLabel(\"위도 : \", self)\n self.labelLatitudeStart.move(320, 140)\n self.editTextLatitudeStart = QTextEdit(self)\n self.editTextLatitudeStart.resize(200, 30)\n self.editTextLatitudeStart.move(380, 140)\n\n # 경도\n self.labelLongitudeStart = QLabel(\"경도 : \", self)\n self.labelLongitudeStart.move(320, 180)\n self.editTextLongitudeStart = QTextEdit(self)\n self.editTextLongitudeStart.resize(200, 30)\n self.editTextLongitudeStart.move(380, 180)\n\n # 주소\n self.labelAddressStart = QLabel(\"주소 : \", self)\n self.labelAddressStart.move(320, 220)\n self.editTextAddressStart = QTextEdit(self)\n self.editTextAddressStart.resize(200, 30)\n self.editTextAddressStart.move(380, 220)\n ################################ 시작위치 끝\n\n\n ################################\n # 도착위치\n\n textLabelEnd = QLabel(\"도착위치 \", self)\n textLabelEnd.move(620, 100)\n\n\n # 위도\n self.labelLatitudeEnd = QLabel(\"위도 : \", self)\n self.labelLatitudeEnd.move(620, 140)\n self.editTextLatitudeEnd = QTextEdit(self)\n self.editTextLatitudeEnd.resize(200, 30)\n self.editTextLatitudeEnd.move(680, 140)\n\n # 경도\n self.labelLongitudeEnd = QLabel(\"경도 : \", self)\n self.labelLongitudeEnd.move(620, 180)\n self.editTextLongitudeEnd = QTextEdit(self)\n self.editTextLongitudeEnd.resize(200, 30)\n self.editTextLongitudeEnd.move(680, 180)\n\n # 주소\n self.labelAddressEnd = QLabel(\"주소 : \", self)\n self.labelAddressEnd.move(620, 220)\n self.editTextAddressEnd = QTextEdit(self)\n self.editTextAddressEnd.resize(200, 30)\n self.editTextAddressEnd.move(680, 220)\n ################################ 도착위치 끝\n\n\n # 맵 그리기\n btn1 = QPushButton(\"지도 보기\", self)\n btn1.move(20, 20)\n btn1.clicked.connect(self.btn1_clicked)\n\n # 길찾기\n btn2 = QPushButton(\"길 찾기\", self)\n btn2.move(20, 60)\n btn2.clicked.connect(self.btn2_clicked)\n\n # 지도보기 - 현재위치 알려줌\n def btn1_clicked(self):\n\n try:\n\n QMessageBox.about(self, \"message\", \"Loading....\")\n print(\"중심위치\")\n print(self.editTextAddress.toPlainText())\n\n response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + self.editTextAddress.toPlainText())\n resp_json_payload = response.json()\n latitude = resp_json_payload['results'][0]['geometry']['location']['lat']\n longitude = resp_json_payload['results'][0]['geometry']['location']['lng']\n latitude = str(latitude)\n longitude = str(longitude)\n\n #position = SeoulData.Data[self.editTextAddress.toPlainText()]\n #latitude = position.split(',')[0]\n #longitude = position.split(',')[1]\n\n print(latitude + ' ' + longitude)\n\n self.editTextLatitude.setText(latitude)\n self.editTextLongitude.setText(longitude)\n\n # 미국주소로 뽑는 부분\n '''\n geolocator = Nominatim()\n if self.editTextAddress.toPlainText() != '' : # 비어있지 않으면\n\n address1 = self.editTextAddress.toPlainText()\n location = geolocator.geocode(address1)\n latitude = str(location.latitude)\n self.editTextLatitude.setText(latitude)\n longitude = str(location.longitude)\n self.editTextLongitude.setText(longitude) \n '''\n\n scale = self.editTextScale.toPlainText()\n latitude = self.editTextLatitude.toPlainText()\n longitude = self.editTextLongitude.toPlainText()\n\n ext = Extraction.extract()\n ext.printMap(scale,latitude,longitude)\n\n except:\n\n QMessageBox.about(self, \"message\", \"다시 입력하세요.\")\n\n # 길찾기\n def btn2_clicked(self):\n try:\n ##### 현재위치 파악 #####\n QMessageBox.about(self, \"message\", \"Loading....\")\n print(\"중심위치\")\n print(self.editTextAddress.toPlainText())\n #position = SeoulData.Data[self.editTextAddress.toPlainText()]\n #latitude = position.split(',')[0]\n #longitude = position.split(',')[1]\n\n response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + self.editTextAddress.toPlainText())\n resp_json_payload = response.json()\n latitude = resp_json_payload['results'][0]['geometry']['location']['lat']\n longitude = resp_json_payload['results'][0]['geometry']['location']['lng']\n latitude = str(latitude)\n longitude = str(longitude)\n print(latitude + ' ' + longitude)\n\n #보이게 하는 부분\n self.editTextLatitude.setText(latitude)\n self.editTextLongitude.setText(longitude)\n\n #scale받아오는 부분\n scale = self.editTextScale.toPlainText()\n\n ##### 시작위치 파악 #####\n print(\"시작위치\")\n print(self.editTextAddressStart.toPlainText())\n #position = SeoulData.Data[self.editTextAddressStart.toPlainText()]\n #start_latitude = position.split(',')[0]\n #start_longitude = position.split(',')[1]\n\n response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + self.editTextAddressStart.toPlainText())\n resp_json_payload = response.json()\n start_latitude = resp_json_payload['results'][0]['geometry']['location']['lat']\n start_longitude = resp_json_payload['results'][0]['geometry']['location']['lng']\n start_latitude = str(start_latitude)\n start_longitude = str(start_longitude)\n print(start_latitude + ' ' + start_longitude)\n\n #보여주는 부분\n self.editTextLatitudeStart.setText(start_latitude)\n self.editTextLongitudeStart.setText(start_longitude)\n start_point = (float(start_latitude),float(start_longitude))\n\n ##### 끝위치 파악 #####\n print(\"끝 위치\")\n print(self.editTextAddressEnd.toPlainText())\n #position = SeoulData.Data[self.editTextAddressEnd.toPlainText()]\n #end_latitude = position.split(',')[0]\n #end_longitude = position.split(',')[1]\n response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + self.editTextAddressEnd.toPlainText())\n resp_json_payload = response.json()\n end_latitude = resp_json_payload['results'][0]['geometry']['location']['lat']\n end_longitude = resp_json_payload['results'][0]['geometry']['location']['lng']\n end_latitude = str(end_latitude)\n end_longitude = str(end_longitude)\n print(end_latitude + ' ' + end_longitude)\n\n # 보여주는 부분\n self.editTextLatitudeEnd.setText(end_latitude)\n self.editTextLongitudeEnd.setText(end_longitude)\n end_point = (float(end_latitude), float(end_longitude))\n\n ## 길찾기 수행 ##\n\n #거리찾기\n a = math.pow(float(start_latitude) - float(end_latitude), 2)\n b = math.pow(float(start_longitude) - float(end_longitude), 2)\n print(a)\n print(b)\n c = round(100000 * (a + b), 1)\n print(c)\n dis = math.sqrt(float(c))\n print(dis)\n scale = int(500 * dis)\n\n print(scale)\n\n if scale < 1000 :\n scale = 1000\n\n self.editTextScale.setText(str(scale))\n scale = int(scale)\n\n\n str_latitude = str((float(start_latitude) + float(end_latitude))/2)\n str_longitude = str((float(start_longitude) + float(end_longitude))/2)\n\n ext = Extraction.extract()\n ext.printShortestMap(scale,str_latitude,str_longitude,start_point,end_point)\n\n except:\n QMessageBox.about(self, \"message\", \"다시 입력하세요.\")\n\nif __name__ == \"__main__\":\n\n app = QApplication(sys.argv)\n myWindow = MyWindow()\n myWindow.show()\n app.exec_()","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":10147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"18003043","text":"\"\"\" Sahana Eden Module Automated Tests - Test Roles\n\n @copyright: 2012 (c) Sahana Software Foundation\n @license: MIT\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport os\ntry:\n from cStringIO import StringIO # Faster, where available\nexcept:\n from StringIO import StringIO\n\nfrom lxml import etree\n\nfrom gluon import current\nfrom gluon.storage import Storage\n\ndef create_role_test_data(orgs, branches):\n\n db = current.db\n s3db = current.s3db\n auth = current.auth\n s3mgr = current.manager\n request = current.request\n\n #----------------------------------------------------------------------\n # Initialize Data & Users\n auth.override = True\n s3db.load_all_models()\n\n test_dir = os.path.join(current.request.folder, \"modules\",\n \"tests\", \"roles\",\n current.deployment_settings.base.template)\n\n org_file = open(os.path.join(test_dir, \"org_organisation.xml\"), \"rb\")\n org_template_string = org_file.read()\n data_file = open(os.path.join(test_dir, \"data.xml\"), \"rb\")\n data_template_string = data_file.read()\n org_resource = s3db.resource(\"org_organisation\")\n org_branch_file = open(os.path.join(test_dir, \"org_organisation_branch.xml\"), \"rb\")\n org_branch_template_string = org_branch_file.read()\n org_branch_resource = s3db.resource(\"org_organisation_branch\")\n\n user_file = open(os.path.join(test_dir, \"users_template.csv\"), \"rb\")\n user_template_string = user_file.read()\n\n # Ensure that the users are imported correctly\n s3db.configure(\"auth_user\",\n onaccept = lambda form: auth.s3_link_user(form.vars))\n s3db.add_component(\"auth_membership\", auth_user=\"user_id\")\n s3mgr.import_prep = auth.s3_membership_import_prep\n\n user_resource = s3db.resource(\"auth_user\")\n hr_resource = s3db.resource(\"pr_person\")\n\n user_file = StringIO()\n user_stylesheet = os.path.join(current.request.folder, \"static\", \"formats\",\n \"s3csv\", \"auth\", \"user.xsl\")\n hr_stylesheet = os.path.join(current.request.folder, \"static\", \"formats\", \"s3csv\", \"hrm\", \"person.xsl\")\n\n for org in orgs:\n for branch in branches:\n\n # Get the \"Other\" Orgs\n copy_orgs = list(orgs)\n copy_orgs.remove(org)\n orgx1 = copy_orgs[0]\n orgx2 = copy_orgs[1]\n\n if branch:\n orgx = \"%s-%s\" % (org,branch)\n else:\n orgx = org\n #print orgx\n \n # Create Org & get id\n org_string = org_template_string % dict( org = orgx )\n xmltree = etree.ElementTree( etree.fromstring(org_string) )\n success = org_resource.import_xml(xmltree)\n otable = s3db.org_organisation\n org_id = db(otable.name == orgx).select(otable.id).first().id\n auth.user = Storage(organisation_id = org_id)\n\n # Create Test Data for each Organisation\n data_string = data_template_string % dict( org = orgx,\n orgx1 = orgx1,\n orgx2 = orgx2,\n )\n xmltree = etree.ElementTree( etree.fromstring(data_string) )\n success = org_resource.import_xml(xmltree)\n\n # Create Users for each Organisation\n user_string = user_template_string % dict(org = orgx,\n org_lower = orgx.lower())\n user_file = StringIO(user_string)\n success = user_resource.import_xml(user_file,\n format=\"csv\",\n stylesheet=user_stylesheet)\n user_file = StringIO(user_string)\n hr_resource.import_xml(user_file, format=\"csv\", stylesheet=hr_stylesheet)\n \n if branch:\n # Link Branch to Org\n org_branch_string = org_branch_template_string % dict( org = org,\n branch = branch\n )\n #print org_branch_string\n xmltree = etree.ElementTree( etree.fromstring(org_branch_string) )\n success = org_branch_resource.import_xml(xmltree)\n #print success\n\n # Import Test Users\n test_user_file = open(os.path.join(test_dir, \"test_users.csv\"), \"rb\")\n success = user_resource.import_xml(test_user_file,\n format=\"csv\",\n stylesheet=user_stylesheet)\n test_user_file = open(os.path.join(test_dir, \"test_users.csv\"), \"rb\")\n hr_resource.import_xml(test_user_file, format=\"csv\", stylesheet=hr_stylesheet)\n \n db.commit()\n auth.override = False\n\n# END =========================================================================\n","sub_path":"modules/tests/roles/create_role_test_data.py","file_name":"create_role_test_data.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"43297067","text":"'''\nReturns a list that contains only the elements that are common between the lists.\n'''\nfrom random import randint\n\na = [ randint(0,30) for i in range(randint(10,15))]\nb = [ randint(0,30) for i in range(randint(10,15))]\na.sort()\nb.sort()\n\ncommon = [ i for i in a if i in b]\ncommon.sort()\ncommon = [ common[i] for i in range(len(common)) if i==0 or (i!=0 and common[i]!=common[i-1]) ]\n\nprint('First list: ', a)\nprint('Second list: ', b)\nprint('Intersection: ', common)\n\n","sub_path":"10_List-overlap-comprehensions.py","file_name":"10_List-overlap-comprehensions.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"447319784","text":"import tkinter\nfrom tkinter import *\nfrom tkinter import messagebox\n\n\nroot = tkinter.Tk()\nroot.resizable(0,0)\n\nroot.title(\"Calculator\")\n\nws = root.winfo_screenwidth()\nhs = root.winfo_screenheight()\nw = 250\nh = 400\nx = int(ws/2 - w/2)\ny = int(hs/2 - h/2)\ndata = str(w)+\"x\"+str(h)+\"+\"+str(x)+\"+\"+str(y)\nroot.geometry(data)\n\ndata = StringVar()\nA = 0\nval = \"\"\noperator = \"\"\n\ndef btn1_isclicked():\n global val\n val = val + \"1\"\n data.set(val)\ndef btn2_isclicked():\n global val\n val = val + \"2\"\n data.set(val)\ndef btn3_isclicked():\n global val\n val = val + \"3\"\n data.set(val) \ndef btn4_isclicked():\n global val\n val = val + \"4\"\n data.set(val)\n\ndef btn5_isclicked():\n global val\n val = val + \"5\"\n data.set(val)\n\ndef btn6_isclicked():\n global val\n val = val + \"6\"\n data.set(val)\n\ndef btn7_isclicked():\n global val\n val = val + \"7\"\n data.set(val)\n\ndef btn8_isclicked():\n global val\n val = val + \"8\"\n data.set(val)\n\ndef btn9_isclicked():\n global val\n val = val + \"9\"\n data.set(val)\n\ndef btn0_isclicked():\n global val\n val = val + \"0\"\n data.set(val)\n\ndef btn_plusclicked():\n global A\n global val\n global operator\n A = int(val)\n operator = \"+\"\n val = val + \"+\"\n data.set(val)\n\ndef btn_subclicked():\n global A\n global val\n global operator\n A = int(val)\n operator = \"-\"\n val = val + \"-\"\n data.set(val)\n\ndef btn_mulclicked():\n global A\n global val\n global operator\n A = int(val)\n operator = \"*\"\n val = val + \"x\"\n data.set(val)\n\ndef btn_divclicked():\n global A\n global val\n global operator\n A = int(val)\n operator = \"/\"\n val = val + \"/\"\n data.set(val)\n\ndef c_pressed():\n global val\n global A\n global operator\n val = \"\"\n A = 0\n opertor = \"\"\n data.set(val) \n\ndef result():\n global val\n global A\n global operator\n val2 = val\n if operator == \"+\":\n x = int((val2.split(\"+\")[1]))\n c = A + x\n data.set(c)\n val = str(c)\n elif operator == \"-\":\n x = int((val2.split(\"-\")[1]))\n c = A - x\n data.set(c)\n val = str(c)\n elif operator == \"*\":\n x = int((val2.split(\"x\")[1]))\n c = A * x\n data.set(c)\n val = str(c)\n elif operator == \"/\":\n x = int((val2.split(\"/\")[1]))\n if x == 0:\n messagebox.showerror(\"Error\",\"Not Allowed !! Infinity\")\n val = \"\"\n A = 0\n data.set(val)\n else:\n c = int(A / x)\n data.set(c)\n val = str(c) \n\n\n\n\nlbl = Label(\n root,\n text = \"Label\",\n font = (\"Verdana\",20),\n anchor = SE,\n textvariable = data,\n background = \"#ffffff\",\n fg = \"#000000\"\n)\nlbl.pack(expan = True, fill = \"both\")\n\n\nbutnrow1 = Frame(root,bg=\"#000000\")\nbutnrow1.pack(expand = True, fill = \"both\")\n\nbutnrow2 = Frame(root)\nbutnrow2.pack(expand = True, fill = \"both\")\n\nbutnrow3 = Frame(root)\nbutnrow3.pack(expand = True, fill = \"both\")\n\nbutnrow4 = Frame(root)\nbutnrow4.pack(expand = True, fill = \"both\")\n\nbtn1 = Button (butnrow1, text = \"1\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn1_isclicked)\nbtn1.pack(side = LEFT, expand = True, fill = \"both\")\nbtn2 = Button (butnrow1, text = \"2\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn2_isclicked)\nbtn2.pack(side = LEFT, expand = True, fill = \"both\")\nbtn3 = Button (butnrow1, text = \"3\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn3_isclicked)\nbtn3.pack(side = LEFT, expand = True, fill = \"both\")\nbtn4 = Button (butnrow1, text = \"+\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn_plusclicked)\nbtn4.pack(side = LEFT, expand = True, fill = \"both\")\n\n\nbtn5 = Button (butnrow2, text = \"4\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn4_isclicked)\nbtn5.pack(side = LEFT, expand = True, fill = \"both\")\nbtn6 = Button (butnrow2, text = \"5\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn5_isclicked)\nbtn6.pack(side = LEFT, expand = True, fill = \"both\")\nbtn7 = Button (butnrow2, text = \"6\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn6_isclicked)\nbtn7.pack(side = LEFT, expand = True, fill = \"both\")\nbtn8 = Button (butnrow2, text = \"-\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn_subclicked)\nbtn8.pack(side = LEFT, expand = True, fill = \"both\")\n\n\nbtn9 = Button (butnrow3, text = \"7\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn7_isclicked)\nbtn9.pack(side = LEFT, expand = True, fill = \"both\")\nbtn10 = Button (butnrow3, text = \"8\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn8_isclicked)\nbtn10.pack(side = LEFT, expand = True, fill = \"both\")\nbtn11 = Button (butnrow3, text = \"9\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn9_isclicked)\nbtn11.pack(side = LEFT, expand = True, fill = \"both\")\nbtn12 = Button (butnrow3, text = \"x\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn_mulclicked)\nbtn12.pack(side = LEFT, expand = True, fill = \"both\")\n\n\nbtn13 = Button (butnrow4, text = \"C\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = c_pressed)\nbtn13.pack(side = LEFT, expand = True, fill = \"both\")\nbtn14 = Button (butnrow4, text = \"0\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn0_isclicked)\nbtn14.pack(side = LEFT, expand = True, fill = \"both\")\nbtn15 = Button (butnrow4, text = \"=\", font = (\"Verdana\",22),relief = GROOVE, border = 0, command = result)\nbtn15.pack(side = LEFT, expand = True, fill = \"both\")\nbtn16 = Button (butnrow4, text = \"/\", font = (\"Verdana\",22),relief = GROOVE, border = 0,command = btn_divclicked)\nbtn16.pack(side = LEFT, expand = True, fill = \"both\")\n\n\n\n\nroot.mainloop()","sub_path":"mainframe.py","file_name":"mainframe.py","file_ext":"py","file_size_in_byte":6043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"615361015","text":"#!/usr/bin/env python\n\n\"\"\" sick, the spectroscopic inference crank \"\"\"\n\nfrom __future__ import division, print_function\n\n__author__ = \"Andy Casey \"\n\nimport argparse\nimport logging\n\nimport cPickle as pickle\nimport json\nimport os\nimport requests\nimport sys\nimport tarfile\nimport yaml\nfrom textwrap import wrap\nfrom time import time\n\nimport numpy as np\nimport pyfits\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\nfrom emcee.utils import sample_ball\n\nimport sick\n\nCACHED_MODEL_GRID_URL = \\\n \"https://raw.githubusercontent.com/andycasey/sick/master/.cached-models.json\"\n\nlogger = logging.getLogger(\"sick\")\n\ndef download_file(url):\n \"\"\" Download a file to the current working directory. \"\"\"\n\n local_filename = url.split('/')[-1]\n r = requests.get(url, stream=True)\n with open(local_filename, 'wb') as f:\n progress, total = 0, int(r.headers.get(\"content-length\"))\n for chunk in r.iter_content(chunk_size=1024):\n if chunk:\n progress += len(chunk)\n complete = int(50 * progress / total)\n sys.stdout.write(\"\\r[{0}{1}] {2:3.0f}%\".format('=' * complete,\n ' ' * (50-complete), 2*complete))\n sys.stdout.flush()\n f.write(chunk)\n f.flush()\n sys.stdout.flush()\n sys.stdout.write(\"\\nDownload of {0} complete.\\n\".format(local_filename))\n return local_filename\n\ndef resume(args):\n raise NotImplementedError\n\n\ndef cache(args):\n \"\"\" Cache a model \"\"\"\n\n if not os.path.exists(args.model):\n raise IOError(\"model filename {0} does not exist\".format(args.model))\n\n model = sick.models.Model(args.model)\n cached_configuration = model.cache(\n args.grid_points_filename, args.fluxes_filename, clobber=args.clobber)\n\n model.configuration = cached_configuration\n model.save(args.model, True)\n\n logging.info(\"Updated model filename {0} to include cached data.\".format(\n args.model))\n return (model, cached_configuration)\n \n\ndef download(args):\n \"\"\" Download requested files. \"\"\"\n\n # Get the current list of model grids\n cached_model_list = requests.get(CACHED_MODEL_GRID_URL).json()\n message = \\\n \"{0}: {1}\\n\"\\\n \"\\t{2}\\n\"\\\n \"\\tADS Reference: {3}\\n\\n\"\n\n def exit_without_download():\n sys.stdout.write(\"No model downloaded.\\n\")\n sys.exit(-1)\n\n if args.model_grid_name == \"list\":\n # Just print out all of the available ones. Follow pip-style.\n sys.stdout.write(\"Found {0} cached sick models online:\\n\\n\".format(\n len(cached_model_list)))\n for model in cached_model_list:\n sys.stdout.write(message.format(model[\"short_name\"],\n model[\"long_name\"], \"\\n\\t\".join(wrap(model[\"description\"])),\n model[\"ads_reference\"]))\n\n else:\n # Look for the specific model.\n cached_model_names = [model[\"short_name\"].lower() \\\n for model in cached_model_list]\n\n requested_model_name = args.model_grid_name.lower()\n if requested_model_name not in cached_model_names:\n sys.stdout.write(\"No cached model matching name '{0}' found. Use \" \\\n \"'sick get list' to retrieve the current list of cached models\"\\\n \" available online.\\n\".format(requested_model_name))\n sys.exit(-1)\n\n else:\n # Confirm the selection\n model = cached_model_list[cached_model_names.index(requested_model_name)]\n sys.stdout.write(\"Found {0} model:\\n\\n\".format(model[\"short_name\"]))\n sys.stdout.write(message.format(model[\"short_name\"],\n model[\"long_name\"], \"\\n\\t\".join(wrap(model[\"description\"])),\n model[\"ads_reference\"]))\n sys.stdout.write(\"Download {0} model? [y/N]\".format(model[\"short_name\"]))\n confirm = raw_input().lower().strip()\n if len(confirm) > 0 and confirm[0] == \"y\":\n\n # Check that we won't overwrite anything.\n filename = model[\"download_link\"].split(\"/\")[-1]\n if os.path.exists(filename):\n sys.stdout.write(\"Clobber existing file {0}? [y/N]\".format(\n filename))\n confirm = raw_input().lower().strip()\n if 1 > len(confirm) or confirm[0] != \"y\":\n exit_without_download()\n\n # Once downloaded, it could overwrite files in a directory:\n if os.path.exists(model[\"short_name\"]):\n sys.stdout.write(\"This may overwrite files in pre-existing\"\\\n \" folder {0}/ -- is that OK? [y/N]\".format(model[\"short_name\"]))\n confirm = raw_input().lower().strip()\n if 1 > len(confirm) or confirm[0] != \"y\":\n exit_without_download()\n\n # OK, download it.\n sys.stdout.write(\"Downloading {0} model...\\n\".format(\n model[\"short_name\"]))\n filename = download_file(model[\"download_link\"])\n\n # Now untar it to a new directory.\n with tarfile.open(filename, \"r\") as tarball:\n tarball.extractall(path=model[\"short_name\"])\n sys.stdout.write(\"Extracted files to {0}/\\n\".format(model[\"short_name\"]))\n\n # Remove the tarball\n os.remove(filename)\n\n else:\n exit_without_download()\n\n\ndef _check_analysis_args(args):\n \"\"\" Perform some analysis checks \"\"\"\n\n if not os.path.exists(args.model):\n raise IOError(\"model filename {0} does not exist.\".format(args.model))\n\n if args.plotting:\n fig = plt.figure()\n available = fig.canvas.get_supported_filetypes().keys()\n plt.close(fig)\n\n if args.plot_format.lower() not in available:\n raise ValueError(\"plotting format {0} not available: Options are: \"\\\n \"{1}\".format(args.plot_format.lower(), \", \".join(available)))\n return None\n\n\ndef _parse_and_load_spectra(args):\n \"\"\" Parse and load the spectra from the arguments provided. \"\"\"\n\n if args.read_from_filename:\n logger.debug(\"Reading sources from input filename {}\".format(\n args.spectrum_filenames[0]))\n\n with open(args.spectrum_filenames[0], \"r\") as fp:\n source_spectrum_filenames = map(str.strip, fp.readlines())\n\n all_spectra = []\n for row in source_spectrum_filenames:\n all_spectra.append(map(sick.specutils.Spectrum1D.load, row.split(\" \")))\n\n return all_spectra\n\n all_spectra = map(sick.specutils.Spectrum1D.load, args.spectrum_filenames)\n\n # Possibilities:\n # (1) Many spectra for single star [default behaviour]\n # (2) Single spectrum for many stars [indicated by --multi-sources]\n # (3) Many spectra for many stars [indicated by --multi-plexing]\n\n # Possibility (3): Are the input FITS files multiplexed spectra?\n if args.multiplexing:\n\n # This implies multiple sources.\n if len(set(map(len, all_spectra))) > 1:\n raise IOError(\"input filenames contain different number of spectra\")\n\n sources = []\n num_channels, num_sources = len(all_spectra), len(all_spectra[0])\n for i in xrange(num_sources):\n sources.append([all_spectra[j][i] for j in xrange(num_channels)])\n\n elif args.multiple_sources:\n # Possibility (2): Single spectrum for many stars. Each spectrum is a\n # different source.\n sources = [[each] for each in all_spectra]\n\n else:\n # Possibility (1): Many spectra for single star\n sources = [all_spectra]\n\n return sources\n\n\ndef estimate(args):\n \"\"\"\n Return a point estimate of the model parameters theta given the data.\n \"\"\"\n\n # Make some checks\n _check_analysis_args(args)\n\n # Load the model and the data\n model = sick.models.Model(args.model)\n all_spectra = _parse_and_load_spectra(args)\n\n # Display some information about the model\n logger.info(\"Model information: {0}\".format(model))\n logger.info(\"Configuration:\")\n map(logger.info, yaml.dump(model.configuration).split(\"\\n\"))\n\n # Define headers that we want in the results filename \n default_headers = (\"RA\", \"DEC\", \"COMMENT\", \"ELAPSED\", \"FIBRE_NUM\", \"LAT_OBS\",\n \"LONG_OBS\", \"MAGNITUDE\",\"NAME\", \"OBJECT\", \"RO_GAIN\", \"RO_NOISE\", \"UTEND\",\n \"UTDATE\", \"UTSTART\", )\n default_metadata = {\n \"model\": model.hash, \n \"input_filenames\": \", \".join(args.spectrum_filenames),\n \"sick_version\": sick.__version__,\n }\n\n if args.read_from_filename:\n with open(args.spectrum_filenames[0], \"r\") as fp:\n all_filenames = map(str.strip, fp.readlines())\n\n # For each source, solve\n for i, spectra in enumerate(all_spectra, start=1):\n\n # Force spectra as a list\n if not isinstance(spectra, (list, tuple)):\n spectra = [spectra]\n\n logger.info(\"Starting on object #{0} (RA {1}, DEC {2} -- {3})\".format(i,\n spectra[0].headers.get(\"RA\", \"None\"),\n spectra[0].headers.get(\"DEC\", \"None\"),\n spectra[0].headers.get(\"OBJECT\", \"Unknown\")))\n\n # Create metadata and put header information in\n if args.skip > i - 1:\n logger.info(\"Skipping object #{0}\".format(i))\n continue\n\n if args.number_to_solve != \"all\" and i > (int(args.number_to_solve) + args.skip):\n logger.info(\"We have analysed {0} spectra. Exiting..\".format(args.number_to_solve))\n break\n\n # If there are many spectra to analyse, include the run ID in the output filenames.\n # Update filename prefix if we are reading from a file\n if args.read_from_filename:\n filename_prefix = sick.utils.default_output_prefix(all_filenames[i].split())\n\n else:\n filename_prefix = args.filename_prefix\n\n if len(all_spectra) > 1 and not args.read_from_filename:\n output = lambda x: os.path.join(args.output_dir,\n \"-\".join([filename_prefix, str(i), x]))\n else:\n output = lambda x: os.path.join(args.output_dir,\n \"-\".join([filename_prefix, x]))\n\n # Does a solution already exist for this star? If so are we authorised to clobber it?\n if os.path.exists(output(\"estimate.json\")):\n if not args.clobber:\n logger.info(\"Skipping object #{0} as a results file already exists\"\\\n \" ({1}) and we have been asked not to clobber it\".format(i,\n output(\"estimate.json\")))\n continue\n else:\n logger.warn(\"Overwriting existing file {0}\".format(output(\"estimate.json\")))\n\n metadata = {}\n header_columns = []\n for header in default_headers:\n if header not in spectra[0].headers: continue\n header_columns.append(header)\n metadata[header] = spectra[0].headers[header]\n\n metadata.update({\"run_id\": i})\n metadata.update(default_metadata)\n \n # Determine an initial point\n try:\n initial_theta, initial_r_chi_sq = model.initial_theta(spectra)\n\n except:\n logger.exception(\"Failed to get initial point\")\n if args.debug: raise\n continue\n\n logger.info(\"Initial theta point with reduced chi_sq = {0:.2f} is {1}\"\\\n .format(initial_r_chi_sq, model._dictify_theta(initial_theta)))\n\n\n metadata.update(dict(zip(\n [\"mean_snr_{}\".format(c) for c in model.channels],\n [np.nanmean(s.flux/(s.variance**0.5)) for s in spectra])))\n\n metadata.update({\n \"reduced_chi_sq\": initial_r_chi_sq,\n \"model_configuration\": model.configuration\n })\n\n # Produce a plot projecting the initial value\n if args.plotting:\n projected_filename = output(\"projected-initial-theta.{}\".format(\n args.plot_format))\n\n # Show physical parameters in the title?\n title = \", \".join([\"{0} = {1:.2f}\".format(p, v)\n for p, v in zip(model.grid_points.dtype.names, initial_theta)])\n\n fig = sick.plot.projection(model, spectra, theta=initial_theta,\n title=title)\n fig.savefig(projected_filename)\n logger.info(\"Created figure {}\".format(projected_filename))\n plt.close(\"all\")\n\n # Write the point estimate to disk\n logger.info(\"Saving point estimate to {0}\".format(output(\"estimate.json\")))\n with open(output(\"estimate.json\"), \"wb+\") as fp:\n json.dump(metadata, fp, indent=2)\n\n logger.info(\"Finished with source {0}\".format(i))\n\n logger.info(\"Fin.\")\n\n\n\ndef solve(args):\n \"\"\" \n Calculate posterior distributions for model parameters given the data.\n \"\"\"\n\n # Make some checks\n _check_analysis_args(args)\n\n # Load the model and the data\n model = sick.models.Model(args.model)\n all_spectra = _parse_and_load_spectra(args)\n\n # Display some information about the model\n logger.info(\"Model information: {0}\".format(model))\n logger.info(\"Configuration:\")\n map(logger.info, yaml.dump(model.configuration).split(\"\\n\"))\n\n # Define headers that we want in the results filename \n default_headers = (\"RA\", \"DEC\", \"COMMENT\", \"ELAPSED\", \"FIBRE_NUM\", \"LAT_OBS\",\n \"LONG_OBS\", \"MAGNITUDE\",\"NAME\", \"OBJECT\", \"RO_GAIN\", \"RO_NOISE\", \"UTEND\",\n \"UTDATE\", \"UTSTART\", )\n default_metadata = {\n \"model\": model.hash, \n \"input_filenames\": \", \".join(args.spectrum_filenames),\n \"sick_version\": sick.__version__,\n }\n\n if args.read_from_filename:\n with open(args.spectrum_filenames[0], \"r\") as fp:\n all_filenames = map(str.strip, fp.readlines())\n\n # For each source, solve\n for i, spectra in enumerate(all_spectra, start=1):\n\n # Force spectra as a list\n if not isinstance(spectra, (list, tuple)):\n spectra = [spectra]\n\n logger.info(\"Starting on object #{0} (RA {1}, DEC {2} -- {3})\".format(i,\n spectra[0].headers.get(\"RA\", \"None\"),\n spectra[0].headers.get(\"DEC\", \"None\"),\n spectra[0].headers.get(\"OBJECT\", \"Unknown\")))\n\n # Create metadata and put header information in\n if args.skip > i - 1:\n logger.info(\"Skipping object #{0}\".format(i))\n continue\n\n if args.number_to_solve != \"all\" and i > (int(args.number_to_solve) + args.skip):\n logger.info(\"We have analysed {0} spectra. Exiting..\".format(args.number_to_solve))\n break\n\n # If there are many spectra to analyse, include the run ID in the output filenames.\n # Update filename prefix if we are reading from a file\n if args.read_from_filename:\n filename_prefix = sick.utils.default_output_prefix(all_filenames[i].split())\n\n else:\n filename_prefix = args.filename_prefix\n\n if len(all_spectra) > 1 and not args.read_from_filename:\n output = lambda x: os.path.join(args.output_dir,\n \"-\".join([filename_prefix, str(i), x]))\n else:\n output = lambda x: os.path.join(args.output_dir,\n \"-\".join([filename_prefix, x]))\n\n # Does a solution already exist for this star? If so are we authorised to clobber it?\n if os.path.exists(output(\"result.json\")):\n if not args.clobber:\n logger.info(\"Skipping object #{0} as a results file already exists\"\\\n \" ({1}) and we have been asked not to clobber it\".format(i,\n output(\"result.json\")))\n continue\n else:\n logger.warn(\"Overwriting existing file {0}\".format(output(\"result.json\")))\n\n metadata = {}\n header_columns = []\n for header in default_headers:\n if header not in spectra[0].headers: continue\n header_columns.append(header)\n metadata[header] = spectra[0].headers[header]\n\n metadata.update({\"run_id\": i})\n metadata.update(default_metadata)\n \n # Determine an initial point\n try:\n initial_theta, initial_r_chi_sq = model.initial_theta(spectra)\n\n except:\n logger.exception(\"Failed to get initial point\")\n if args.debug: raise\n continue\n\n\n logger.info(\"Initial theta point with reduced chi_sq = {0:.2f} is {1}\"\\\n .format(initial_r_chi_sq, model._dictify_theta(initial_theta)))\n\n # Save metadata about the initial point\n metadata[\"initial_theta\"] = model._dictify_theta(initial_theta)\n metadata[\"initial_r_chi_sq\"] = initial_r_chi_sq\n\n # Produce a plot projecting the initial value\n if args.plotting:\n projected_filename = output(\"projected-initial-theta.{}\".format(\n args.plot_format))\n\n fig = sick.plot.projection(model, spectra, theta=initial_theta)\n fig.savefig(projected_filename)\n logger.info(\"Created figure {}\".format(projected_filename))\n\n # Optimise the point\n if model.configuration[\"settings\"][\"optimise\"]:\n optimised_theta, optimised_r_chi_sq, info = model.optimise(\n spectra, initial_theta=initial_theta, \n fixed=[\"z\"] + [\"z.{}\".format(c) for c in model.channels])\n\n logger.info(\"Optimised theta is {0}\".format(model._dictify_theta(optimised_theta)))\n walker_theta = optimised_theta\n\n # Save metadata about the optimised value\n metadata[\"optimised_theta\"] = model._dictify_theta(optimised_theta)\n metadata[\"optimised_r_chi_sq\"] = optimised_r_chi_sq\n \n if args.plotting:\n projected_filename = output(\"projected-optimised-theta.{}\".format(\n args.plot_format))\n\n fig = sick.plot.projection(model, spectra, theta=optimised_theta)\n fig.savefig(projected_filename)\n logger.info(\"Created figure {}\".format(projected_filename))\n\n else:\n # MCMC initial point will be the initial point\n walker_theta = initial_theta\n\n try:\n posteriors, sampler, info = model.infer(spectra, theta=walker_theta)\n\n except:\n logger.exception(\"Failed to analyse source #{0}:\".format(i))\n if args.debug: raise\n\n else:\n \n # Update results with the posteriors\n logger.info(\"Posteriors:\")\n max_parameter_len = max(map(len, model.parameters))\n for parameter in model.parameters:\n posterior_value, pos_uncertainty, neg_uncertainty = posteriors[parameter]\n logger.info(\" {0}: {1:.2e} ({2:+.2e}, {3:+.2e})\".format(\n parameter.rjust(max_parameter_len), posterior_value, \n pos_uncertainty, neg_uncertainty))\n\n metadata.update({\n parameter: posterior_value,\n \"u_maxabs_{0}\".format(parameter): np.abs([\n neg_uncertainty,\n pos_uncertainty\n ]).max(),\n \"u_pos_{0}\".format(parameter): pos_uncertainty,\n \"u_neg_{0}\".format(parameter): neg_uncertainty,\n })\n\n # Save information related to the analysis\n metadata.update(dict(zip(\n [\"mean_snr_{}\".format(c) for c in model.channels],\n [np.nanmean(s.flux/(s.variance**0.5)) for s in spectra])))\n\n chain_filename = output(\"chain.fits\")\n metadata.update({\n \"reduced_chi_sq\": info[\"reduced_chi_sq\"],\n \"maximum_log_probability\": np.nanmax(info[\"lnprobability\"]),\n \"chain_filename\": chain_filename if args.save_chain_files else \"\",\n \"time_elapsed\": info[\"time_elapsed\"],\n \"final_mean_acceptance_fraction\": info[\"mean_acceptance_fractions\"][-1],\n \"model_configuration\": model.configuration\n })\n for channel, length in info[\"autocorrelation_times\"].iteritems():\n metadata[\"tau_{}\".format(channel)] = length\n\n walkers = model.configuration[\"settings\"][\"walkers\"]\n chain_length = info[\"chain\"].shape[0] * info[\"chain\"].shape[1]\n chain = np.core.records.fromarrays(\n np.vstack([\n np.arange(1, 1 + chain_length),\n np.arange(1, 1 + chain_length) % walkers,\n info[\"chain\"].reshape(-1, len(model.parameters)).T,\n info[\"lnprobability\"].reshape(-1, 1).T\n ]),\n names=[\"Iteration\", \"Sample\"] + model.parameters + [\"ln_probability\"],\n formats=[\"i4\", \"i4\"] + [\"f8\"] * (1 + len(model.parameters)))\n\n # Save the chain\n if args.save_chain_files:\n logger.info(\"Saving chains to {0}\".format(chain_filename))\n primary_hdu = pyfits.PrimaryHDU()\n table_hdu = pyfits.BinTableHDU(chain)\n hdulist = pyfits.HDUList([primary_hdu, table_hdu])\n hdulist.writeto(chain_filename, clobber=True)\n\n else:\n logger.warn(\"Chain not saved to disk.\")\n\n # Write the result to disk\n logger.info(\"Saving results to {0}\".format(output(\"result.json\")))\n with open(output(\"result.json\"), \"wb+\") as fp:\n json.dump(metadata, fp, indent=2)\n\n # Close sampler pool\n if model.configuration[\"settings\"].get(\"threads\", 1) > 1:\n sampler.pool.close()\n sampler.pool.join()\n\n # Save sampler state\n with open(output(\"model.state\"), \"wb+\") as fp:\n pickle.dump([\n sampler.chain[:, -1, :],\n sampler.lnprobability[:, -1],\n sampler.random_state\n ], fp, -1)\n\n # Plot results\n if args.plotting:\n \n # Plot the mean acceptance fractions\n acceptance_plot_filename = output(\"acceptance.{0}\".format(args.plot_format))\n fig = sick.plot.acceptance_fractions(info[\"mean_acceptance_fractions\"],\n burn_in=model.configuration[\"settings\"][\"burn\"])\n fig.savefig(acceptance_plot_filename)\n logger.info(\"Created figure {0}\".format(acceptance_plot_filename))\n\n # Plot the chains\n chain_plot_filename = output(\"chain.{0}\".format(args.plot_format))\n fig = sick.plot.chains(info[\"chain\"],\n labels=sick.utils.latexify(model.parameters), truth_color='r',\n burn_in=model.configuration[\"settings\"][\"burn\"],\n truths=[posteriors[p][0] for p in model.parameters])\n fig.savefig(chain_plot_filename)\n logger.info(\"Created figure {0}\".format(chain_plot_filename))\n\n # Make a corner plot with just the astrophysical parameters\n corner_plot_filename = output(\"corner.{0}\".format(args.plot_format))\n indices = np.arange(len(model.grid_points.dtype.names))\n fig = sick.plot.corner(sampler.chain.reshape(-1, len(model.parameters))[:, indices],\n labels=sick.utils.latexify(model.grid_points.dtype.names),\n truth_color='r', quantiles=[.16, .50, .84], verbose=False,\n truths=[posteriors[p][0] for p in model.grid_points.dtype.names])\n fig.savefig(corner_plot_filename)\n logger.info(\"Created figure {0}\".format(corner_plot_filename))\n\n # Plot the autocorrelation\n autocorrelation_filename = output(\"auto-correlation.{0}\".format(args.plot_format))\n fig = sick.plot.autocorrelation(sampler.chain)\n fig.savefig(autocorrelation_filename)\n logger.info(\"Created figure {0}\".format(autocorrelation_filename))\n\n # Plot some spectra\n pp_spectra_plot_filename = output(\"projected-spectra.{0}\".format(args.plot_format))\n fig = sick.plot.projection(model, spectra, chain=sampler.chain)\n fig.savefig(pp_spectra_plot_filename)\n logger.info(\"Created figure {0}\".format(pp_spectra_plot_filename))\n \n # Closing the figures isn't enough; matplotlib leaks memory\n plt.close(\"all\")\n\n # Delete some things\n del sampler, chain\n if args.save_chain_files:\n del primary_hdu, table_hdu, hdulist\n\n logger.info(\"Fin.\")\n return True\n\n\ndef aggregate(args):\n \"\"\" Aggregate JSON-formatted results into a single tabular FITS file. \"\"\"\n\n if os.path.exists(args.output_filename):\n if not args.clobber:\n raise IOError(\"output filename {0} already exists and we have been \"\\\n \"asked not to clobber it\".format(args.output_filename))\n else:\n logger.warn(\"Overwriting existing filename {0}\".format(args.output_filename))\n \n # Let's just assume it all aggregates from JSON to a FITS filename\n results = []\n for filename in args.result_filenames:\n with open(filename, \"r\") as fp:\n try:\n results.append(json.load(fp))\n except:\n logger.exception(\"Could not read results filename {0}\".format(filename))\n if args.debug: raise\n \n else:\n logging.debug(\"Successfully loaded results from {0}\".format(filename))\n\n # Get header order and sort them\n columns = results[0].keys()\n\n sorted_columns = []\n # Logic: RA, DEC then all other uppercase fields in alphabetical order\n # Then any other fields that have associated u_* headers in alphabetical order, as\n # well as their u_* columns\n # Then all the others in alphabetical order\n if \"RA\" in columns:\n sorted_columns.append(\"RA\")\n\n if \"DEC\" in columns:\n sorted_columns.append(\"DEC\")\n\n uppercase_columns = []\n parameteral_columns = []\n for column in columns:\n if column.isupper() and column not in sorted_columns: uppercase_columns.append(column)\n elif \"u_pos_{0}\".format(column) in columns: parameteral_columns.append(column)\n \n uppercase_columns, parameteral_columns = map(sorted, [uppercase_columns, parameteral_columns])\n all_parameteral_columns = []\n variants = (\"{0}\", \"u_pos_{0}\", \"u_neg_{0}\", \"u_maxabs_{0}\")\n for column in parameteral_columns:\n all_parameteral_columns.extend([variant.format(column) for variant in variants])\n\n sorted_columns.extend(uppercase_columns)\n sorted_columns.extend(all_parameteral_columns)\n\n other_columns = sorted(set(columns).difference(sorted_columns))\n ignore_columns = (\"model_configuration\", \"optimised_theta\", \"initial_theta\")\n sorted_columns.extend(list(set(other_columns).difference(ignore_columns)))\n\n # Create data types\n formats = [(\"f8\", \"|S256\")[isinstance(results[-1][each], (str, unicode))] \\\n for each in sorted_columns]\n\n # Create table\n data = [[result.get(each, [\"\", np.nan][formats[i] == \"f8\"]) \\\n for i, each in enumerate(sorted_columns)] for result in results]\n results_table = np.core.records.fromrecords(data, names=sorted_columns,\n formats=formats)\n\n # Write results to filename \n primary_hdu = pyfits.PrimaryHDU()\n table_hdu = pyfits.BinTableHDU(results_table)\n hdulist = pyfits.HDUList([primary_hdu, table_hdu])\n hdulist.writeto(args.output_filename, clobber=args.clobber)\n\n logger.info(\"Successfully written results from {0} sources with {1} fields\"\\\n \" to {2}\".format(len(results), len(results[0]), args.output_filename))\n\n\ndef parser(input_args=None):\n \"\"\" Create a parser. \"\"\"\n\n parser = argparse.ArgumentParser(\n description=\"sick, the spectroscopic inference crank\",\n epilog=\"See 'sick COMMAND -h' for more information on a specific command.\"\\\n \" Documentation and examples available at https://github.com/andycasey/sick\")\n\n # Create subparsers\n subparsers = parser.add_subparsers(title=\"command\", dest=\"command\",\n description=\"Specify the action to perform.\")\n\n # Create a parent subparser\n parent_parser = argparse.ArgumentParser(add_help=False)\n parent_parser.add_argument(\"-v\", \"--verbose\", dest=\"verbose\",\n action=\"store_true\", default=False, help=\"Vebose mode. Logger will print\"\\\n \" debugging messages.\")\n parent_parser.add_argument(\"--clobber\", dest=\"clobber\", action=\"store_true\",\n default=False, help=\"Overwrite existing files if they already exist.\")\n parent_parser.add_argument(\"--debug\", dest=\"debug\", action=\"store_true\", \n default=False, help=\"Enable debug mode. Any suppressed exception during \"\\\n \"runtime will be re-raised.\")\n\n # Create parser for the aggregate command\n aggregate_parser = subparsers.add_parser(\"aggregate\", parents=[parent_parser],\n help=\"Aggregate JSON results into a tabular format.\")\n aggregate_parser.add_argument(\"output_filename\", type=str,\n help=\"Output filename to aggregate results into.\")\n aggregate_parser.add_argument(\"result_filenames\", nargs=\"+\",\n help=\"The JSON result filenames to combine.\")\n aggregate_parser.set_defaults(func=aggregate)\n\n # Create parser for the download command\n download_parser = subparsers.add_parser(\"download\", parents=[parent_parser],\n help=\"Download a pre-cached model from an online repository.\")\n download_parser.add_argument(\"model_grid_name\", nargs=\"?\",\n help=\"The name of the pre-cached model grid to download, or 'list' (de\"\\\n \"fault) to see what pre-cached models are available.\", default=\"list\")\n download_parser.set_defaults(func=download)\n\n # Create parser for the estimate command\n estimate_parser = subparsers.add_parser(\"estimate\", parents=[parent_parser],\n help=\"Compute a point estimate of the model parameters, given the data.\")\n estimate_parser.add_argument(\"model\", type=str,\n help=\"The model filename in YAML- or JSON-style formatting.\")\n estimate_parser.add_argument(\"-r\", action=\"store_true\", dest=\"read_from_filename\",\n default=False, help=\"Read input spectra from a single filename.\")\n estimate_parser.add_argument(\"spectrum_filenames\", nargs=\"+\",\n help=\"Filenames of (observed) spectroscopic data.\")\n estimate_parser.add_argument(\"-o\", \"--output-dir\", dest=\"output_dir\", nargs=\"?\",\n type=str, default=os.getcwd(), help=\"Directory for output files.\")\n estimate_parser.add_argument(\"--filename-prefix\", \"-p\", dest=\"filename_prefix\",\n type=str, help=\"The filename prefix to use for the output files.\")\n estimate_parser.add_argument(\"--multi-sources\", dest=\"multiple_sources\",\n action=\"store_true\", default=False, help=\"Each spectrum is considered \"\\\n \"a different source.\")\n estimate_parser.add_argument(\"--multi-plexing\", dest=\"multiplexing\",\n action=\"store_true\", default=False, help=\"Specify that each FITS file \"\\\n \"contains a single channel of spectrum for many stars. Multiplexing \"\\\n \"implies --multi-sources to be true.\")\n estimate_parser.add_argument(\"-n\", \"--number-to-solve\", dest=\"number_to_solve\",\n default=\"all\", help=\"Specify the number of sources to solve. This is \"\\\n \"only applicable when --multi-sources or --multi-plexing is used. The \"\\\n \"default is to solve for %(default)s sources.\")\n estimate_parser.add_argument(\"-s\", \"--skip\", dest=\"skip\", action=\"store\", \n type=int, default=0, help=\"Number of sources to skip. This is only \"\\\n \"applicable when --multi-sources or --multi-plexing is used. Default: \"\\\n \"%(default)s)\")\n estimate_parser.add_argument(\"--no-plots\", dest=\"plotting\", action=\"store_false\",\n default=True, help=\"Disable plotting.\")\n estimate_parser.add_argument(\"--plot-format\", \"-pf\", dest=\"plot_format\", \n action=\"store\", type=str, default=\"pdf\", help=\"Format for output plots\"\\\n \" (default: %(default)s)\")\n estimate_parser.set_defaults(func=estimate)\n\n # Create parser for the solve command\n solve_parser = subparsers.add_parser(\"solve\", parents=[parent_parser],\n help=\"Compute posterior probability distributions for the model \"\\\n \"parameters, given the data.\")\n solve_parser.add_argument(\"model\", type=str,\n help=\"The model filename in YAML- or JSON-style formatting.\")\n solve_parser.add_argument(\"-r\", action=\"store_true\", dest=\"read_from_filename\",\n default=False, help=\"Read input spectra from a single filename.\")\n solve_parser.add_argument(\"spectrum_filenames\", nargs=\"+\",\n help=\"Filenames of (observed) spectroscopic data.\")\n solve_parser.add_argument(\"-o\", \"--output-dir\", dest=\"output_dir\", nargs=\"?\",\n type=str, default=os.getcwd(), help=\"Directory for output files.\")\n solve_parser.add_argument(\"--filename-prefix\", \"-p\", dest=\"filename_prefix\",\n type=str, help=\"The filename prefix to use for the output files.\")\n solve_parser.add_argument(\"--multi-sources\", dest=\"multiple_sources\",\n action=\"store_true\", default=False, help=\"Each spectrum is considered \"\\\n \"a different source.\")\n solve_parser.add_argument(\"--multi-plexing\", dest=\"multiplexing\",\n action=\"store_true\", default=False, help=\"Specify that each FITS file \"\\\n \"contains a single channel of spectrum for many stars. Multiplexing \"\\\n \"implies --multi-sources to be true.\")\n solve_parser.add_argument(\"-n\", \"--number-to-solve\", dest=\"number_to_solve\",\n default=\"all\", help=\"Specify the number of sources to solve. This is \"\\\n \"only applicable when --multi-sources or --multi-plexing is used. The \"\\\n \"default is to solve for %(default)s sources.\")\n solve_parser.add_argument(\"-s\", \"--skip\", dest=\"skip\", action=\"store\", \n type=int, default=0, help=\"Number of sources to skip. This is only \"\\\n \"applicable when --multi-sources or --multi-plexing is used. Default: \"\\\n \"%(default)s)\")\n solve_parser.add_argument(\"--no-chain-files\", dest=\"save_chain_files\",\n help=\"Do not save the chains to disk.\", action=\"store_false\", default=True)\n solve_parser.add_argument(\"--no-plots\", dest=\"plotting\", action=\"store_false\",\n default=True, help=\"Disable plotting.\")\n solve_parser.add_argument(\"--plot-format\", \"-pf\", dest=\"plot_format\", \n action=\"store\", type=str, default=\"pdf\", help=\"Format for output plots\"\\\n \" (default: %(default)s)\")\n solve_parser.set_defaults(func=solve)\n\n # Create parser for the resume command\n resume_parser = subparsers.add_parser(\"resume\", parents=[parent_parser],\n help=\"Resume MCMC simulation from a previously calculated state.\")\n resume_parser.add_argument(\"model\", type=str,\n help=\"The model filename in YAML- or JSON-style formatting.\")\n resume_parser.add_argument(\"state_filename\", type=str,\n help=\"The filename containing the pickled MCMC state.\")\n resume_parser.add_argument(\"burn\", type=int,\n help=\"The number of MCMC steps to burn.\")\n resume_parser.add_argument(\"sample\", type=int,\n help=\"The number of MCMC steps to sample after burn-in.\")\n resume_parser.add_argument(\"spectrum_filenames\", nargs=\"+\",\n help=\"Filenames of (observed) spectroscopic data.\")\n resume_parser.add_argument(\"-o\", \"--output-dir\", dest=\"output_dir\", nargs=\"?\",\n type=str, default=os.getcwd(),\n help=\"Directory where to save output files to.\")\n resume_parser.add_argument(\"--filename-prefix\", \"-p\", dest=\"filename_prefix\",\n type=str, help=\"The filename prefix to use for the output files.\")\n resume_parser.add_argument(\"--multi-channel\", \"-mc\", dest=\"multiple_channels\",\n action=\"store_true\", default=False,\n help=\"Use if each source has multiple spectral channels. Default is false\"\\\n \", implying that any additional spectra refers to a different source.\")\n resume_parser.add_argument(\"-s\", \"--skip\", dest=\"skip\", action=\"store\",\n type=int, default=0, help=\"Number of sources to skip (default: %(default)s)\")\n resume_parser.add_argument(\"--no-plots\", dest=\"plotting\", action=\"store_false\",\n default=True, help=\"Disable plotting.\")\n resume_parser.add_argument(\"--plot-format\", \"-pf\", dest=\"plot_format\", \n action=\"store\", type=str, default=\"pdf\", help=\"Format for output plots\"\\\n \" (default: %(default)s)\")\n resume_parser.set_defaults(func=resume)\n\n cache_parser = subparsers.add_parser(\"cache\", parents=[parent_parser],\n help=\"Cache the provided model for fast access at run-time.\")\n cache_parser.add_argument(\"model\", type=str,\n help=\"The (YAML- or JSON-formatted) model filename.\")\n cache_parser.add_argument(\"grid_points_filename\", type=str,\n help=\"The filename to cache the grid point information to.\")\n cache_parser.add_argument(\"fluxes_filename\", type=str,\n help=\"The filename to cache the fluxes into.\")\n cache_parser.set_defaults(func=cache)\n\n args = parser.parse_args(input_args)\n \n # Setup logging, bro.\n logger.setLevel(logging.DEBUG if args.verbose else logging.INFO)\n\n # Create a default filename prefix based on the input filename arguments\n if args.command.lower() in (\"solve\", \"estimate\", \"optimise\", \"resume\") \\\n and args.filename_prefix is None:\n args.filename_prefix = sick.utils.default_output_prefix(args.spectrum_filenames)\n\n handler = logging.FileHandler(\"{}.log\".format(\n os.path.join(args.output_dir, args.filename_prefix)))\n formatter = logging.Formatter(\"%(asctime)s [%(levelname)s] %(message)s\")\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n \n return args\n\n \ndef main():\n \"\"\" Parse arguments and execute the correct sub-parser. \"\"\"\n\n args = parser()\n return args.func(args)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sick/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":38310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"616290081","text":"from gensim.models import KeyedVectors\nimport numpy as np\nimport json\nimport torch\nimport pickle\nfrom transformers import DistilBertConfig, DistilBertModel, DistilBertTokenizer\nfrom whoosh.index import create_in\nfrom whoosh.fields import *\nfrom whoosh.qparser import QueryParser, MultifieldParser\nfrom whoosh import scoring\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nimport copy\n\nclass Index:\n def __init__(self, w2v_model, processed_json_file, bert_model=None, bert_tokenizer=None):\n self.bert_model = bert_model\n self.bert_tokenizer = bert_tokenizer\n self.model = KeyedVectors.load(w2v_model)\n index_keys = []\n index_values = []\n data = []\n cur_set = set([])\n with open(processed_json_file) as f:\n objs = json.load(f)[30:]\n for j, obj in enumerate(objs):\n snippet = obj[\"snippet\"]\n snippet = ' '.join(snippet.split())\n snippet = snippet.replace(\"\\n\", \" \")\n obj[\"snippet\"] = snippet\n sents = nltk.sent_tokenize(snippet)\n i = 0\n while i < len(sents):\n newsnippet = \" \".join(sents[i: i+2])\n if newsnippet not in cur_set:\n newobj = copy.deepcopy(obj)\n newobj[\"snippet\"] = newsnippet\n if i == len(sents) - 1 and j < len(objs) - 1 and \"\" in objs[j+1][\"html\"]:\n newobj[\"html\"] = \"
\" + newobj[\"html\"] + objs[j+1][\"html\"] + \"
\"\n index_values.append(newobj)\n cur_set.add(newsnippet)\n i += 2\n\n # for line in f:\n # json_obj = json.loads(line)\n # json_obj[\"snippet\"] = json_obj[\"snippet\"].replace(u'\\xa0', u' ')\n # index_values.append(json_obj)\n self.create_whoosh_index(index_values)\n self.index_values = np.array(index_values)\n for value in index_values:\n index_keys.append(self.encode(value[\"snippet\"] + \" \" + value[\"header\"]))\n self.index_keys = np.stack(index_keys, axis=0)\n self.stop_words = set(stopwords.words('english'))\n\n def create_whoosh_index(self, json_objs):\n schema = Schema(\n id=NUMERIC(stored=True), filename=TEXT(stored=True),\n header=TEXT(stored=True), snippet=TEXT(stored=True))\n self.ix = create_in(\"indexdir\", schema)\n writer = self.ix.writer()\n for i, obj in enumerate(json_objs):\n writer.add_document(\n id=i, filename=obj[\"filename\"], header=obj[\"header\"],\n snippet=obj[\"snippet\"])\n writer.commit()\n\n def encode(self, text):\n if self.bert_model:\n return self.bert_encode(text)\n ave_vector = np.zeros((300,), dtype=float)\n words = text.split(\" \")\n for word in words:\n try:\n ave_vector += self.model[word.lower()]\n except KeyError:\n pass\n norm = np.linalg.norm(ave_vector)\n if norm > 0.:\n ave_vector /= norm\n return ave_vector\n\n def bert_encode(self, text):\n tokenized_ids = self.bert_tokenizer.encode(text)\n tokenized_ids = torch.tensor(tokenized_ids)[:512].unsqueeze(0)\n vectors = self.bert_model(tokenized_ids)[0].detach().numpy()\n vector = np.squeeze(np.mean(vectors, axis=1), axis=0)\n return vector# / np.linalg.norm(vector)\n\n def process_context(self, text):\n filtered_words = [\n word for word in word_list\n if word not in self.stop_words\n ]\n return \" \".join(word_list)\n\n\n def search(self, text, topn=5, context=\"\"):\n with self.ix.searcher(weighting=scoring.BM25F()) as searcher:\n querytext = text + \" \" + context\n query = MultifieldParser(\n [\"header\", \"snippet\"], self.ix.schema).parse(\" OR \".join(querytext.split(\" \")))\n results = searcher.search(query, limit=topn * 100)\n init_ids = np.array([res[\"id\"] for res in results])\n scores = np.array([r.score for r in results])\n mean_vector = self.encode(querytext)\n if init_ids.shape[0] > 0:\n sims = -np.dot(self.index_keys, mean_vector)\n scores = (scores - scores.min()) / (scores.max() - scores.min())\n sims[init_ids] -= scores\n top_idx = np.argsort(sims)[:topn*5]\n else:\n sims = -np.dot(self.index_keys, mean_vector)\n top_idx = np.argsort(sims)[:topn*5]\n top_vals = list(self.index_values[top_idx])\n cur_html_set = set([])\n ret_vals = []\n i = 0\n for i in range(len(top_vals)):\n if top_vals[i][\"html\"] in cur_html_set:\n continue\n ret_vals.append(top_vals[i])\n cur_html_set.add(top_vals[i][\"html\"])\n if len(ret_vals) >= topn:\n break\n return ret_vals\n\nif __name__ == \"__main__\":\n config_class, model_class, tokenizer_class = (DistilBertConfig, DistilBertModel, DistilBertTokenizer)\n config = config_class.from_pretrained(\"distilbert-base-uncased\")\n tokenizer = tokenizer_class.from_pretrained(\"distilbert-base-uncased\", do_lower_case=True)\n model = model_class.from_pretrained(\n \"../../finmodel.bin\", from_tf=False, config=config)\n idx = Index(\"../../finw2v.bin\", \"../../AAL.json\", None, None)#, model, tokenizer)\n with open(\"../../idx_dumpv4.pkl\", \"wb\") as f:\n pickle.dump(idx, f)\n # with open(\"../../idx_dumpv2.pkl\", \"rb\") as f:\n # idx = pickle.load(f)\n while True:\n x = input(\"query: \")\n y = input(\"context: \")\n print(idx.search(x, context=y))\n","sub_path":"backend/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":5804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"451008415","text":"#!/usr/bin/env python\n\n\"\"\" sonar2laser.py - Version 1.1 2013-12-20\n\n Translate the /sensor_msgs/Range to /sensor_msgs/LaserScan ,and publish topic.\n\n Created for the Pi Robot Project: http://www.pirobot.org\n Copyright (c) 2012 Patrick Goebel. All rights reserved.\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.5\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 at:\n \n http://www.gnu.org/licenses/gpl.html\n \n\"\"\"\n\nimport rospy\nfrom sensor_msgs.msg import LaserScan\nfrom sensor_msgs.msg import Range\n\nclass Sonar2Laser():\n def __init__(self):\n # Give the node a name\n rospy.init_node('sonar2laser', anonymous=False)\n\n self.sonar_topics = rospy.get_param('~sonar_topics',[])\n self.output_topic = rospy.get_param('~output_topic','sonar2laser')\n self.frame_id = rospy.get_param('~frame_id','sonar2laser')\n\n rospy.loginfo('sonar_topics:')\n rospy.loginfo(self.sonar_topics)\n rospy.loginfo('output_topic:')\n rospy.loginfo(self.output_topic)\n # Publisher of type nav_msgs/Odometry\n self.laserPub = rospy.Publisher(self.output_topic, LaserScan, queue_size=10)\n \n rospy.loginfo('wait for msg')\n # Wait for the topic to become available\n for topic in self.sonar_topics:\n rospy.wait_for_message(topic, Range)\n \n # Subscribe to the topic\n for topic in self.sonar_topics:\n rospy.Subscriber(topic, Range, self.pub_laser)\n \n rospy.loginfo(\"Translate Range msg to LaserScan msg\")\n \n def pub_laser(self, msg):\n laser = LaserScan()\n\n laser.header = msg.header\n laser.header.frame_id = self.frame_id\n laser.angle_min = 0\n laser.angle_max = 3.14\n laser.angle_increment = 0.01\n laser.time_increment = 0.01\n laser.scan_time = 0.1\n laser.range_min = 0.2\n laser.range_max = 4.5\n laser.ranges = [msg.range,msg.range]\n laser.intensities = [1,1]\n\n self.laserPub.publish(laser)\n \nif __name__ == '__main__':\n try:\n Sonar2Laser()\n rospy.spin()\n except:\n pass\n \n\n \n","sub_path":"youyou_robot/launch/sonar2laser.py","file_name":"sonar2laser.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"169034538","text":"#-*- coding: utf-8 -*-\nfrom django.conf.urls import include, url, patterns\nfrom rest_framework_nested import routers\nfrom ManicurToDay import settings\nfrom authentication.views import AccountViewSet, LoginView, LogoutView\nfrom ManicurToDay.views import IndexView\nfrom post.views import AccountClientViewSet, ClientViewSet\n\nrouter=routers.SimpleRouter()\nrouter.register(r'accounts', AccountViewSet)\nrouter.register(r'clients', ClientViewSet)\n\naccounts_router = routers.NestedSimpleRouter(\n router,r'accounts',lookup='account'\n)\naccounts_router.register(r'clients',AccountClientViewSet)\nurlpatterns =patterns(\n '',\n url(r'^api/v1/',include(router.urls)),\n url(r'^api/v1/',include(accounts_router.urls)),\n url(r'^api/v1/auth/login/$',LoginView.as_view(), name='login'),\n url(r'^api/v1/auth/logout/$',LogoutView.as_view(), name='logout'),\n url('^.*',IndexView.as_view(),name='index'),\n )\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += patterns('',\n url(r'^__debug__/', include(debug_toolbar.urls)),\n )\n \n \n","sub_path":"ManicurToDay/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"404096133","text":"from unidecode import unidecode\nimport re\nimport urllib2\nclass Util:\n\tdef __init__(self):\n\t\tself.URL_BASE = \"http://en.wikipedia.org/w/api.php\"\n\t\tself.blacklist = ['article', 'wikipedia', 'wiki', 'birth', 'people from', 'from', 'category', 'categories', 'pages', '.php', 'stubs', 'death', 'people', 'template', 'wiktio', 'en.', 'file', 'help', 'stub', 'list', 'disambiguation']\n\t\tself.CATEGORY = 'category'\n\t\tself.ARTICLE = 'topic'\n\t\tself.DISAMBIGUATION = 'disambiguation'\n\t\tself.SIBLING_REL = 'sibling'\n\t\tself.CATEGORY_REL = 'parent'\n\t\tself.SUBCAT_REL = 'subcat'\n\t\tself.DISAMB_REL = 'disambiguation'\n\t\tself.INF = 9999\n\n\tdef _contains(self, s, l):\n\t\tfor i in l:\n\t\t\tif s.lower().rfind(i.lower()) >= 0:\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef _clean(self, s):\n\t\ts = self._encode_str(s)\n\t\ts = urllib2.unquote(s)\n\t\ts = re.sub(r'/wiki/', '', s)\n\t\ts = re.sub(r' ', '_', s)\n\t\ts = re.sub(r'#.*', '', s)\n\t\treturn s\n\n\tdef _encode_str(self, s):\n\t\tif type(s) == unicode:\n\t\t\treturn unidecode(s)\n\t\telse:\n\t\t\treturn unidecode(s.decode(\"utf-8\", \"ignore\"))\n","sub_path":"tailor/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"573730702","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n # d = {}\n # for index, value in enumerate(nums):\n # if target - value in d:\n # return d[target - value], index\n # d[value] = index\n sorted_nums = sorted(nums)\n i = 0\n j = len(sorted_nums) - 1\n while i < j:\n sum = sorted_nums[i] + sorted_nums[j]\n if sum == target:\n return nums.index(sorted_nums[i]), nums.index(sorted_nums[j])\n elif sum < target:\n i += 1\n else:\n j -= 1\n\na = Solution()\nprint(a.twoSum([3,2,4], 6))\n\n\n\n","sub_path":"leetcode(1.TwoSum).py","file_name":"leetcode(1.TwoSum).py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"465063241","text":"#!/usr/bin/env python2\n#coding=utf-8\nimport sys\nimport os\n\"\"\"\n./transcode.py file1 [file2] [file3] ...\nThis program transfer file from utf-8 to gbk.\nTips: using \"./transcode.py `ls`\" to transfer all the file in this dirctory from utf-8 to gbk.\n\"\"\"\nif(len(sys.argv) < 2):\n print(\"No action specified.\")\n sys.exit()\nif(sys.argv[1].startswith('--')):\n option = sys.argv[1][2:]\n if(option == 'version'):\n print(\"Version 0.0.1\")\n elif(option == 'help'):\n print(\"\"\"\nThis program transfer file from utf-8 to gbk.\n\nusing formate: ./transcode.py file1 [file2] [file3] ...\nTips: using \"./transcode.py `ls`\" or \"./transcode.py *\" to transfer all the file in this dirctory from utf-8 to gbk.\n\n \"\"\")\n else:\n print(\"Unknown option!\")\n sys.exit()\nelif(sys.argv[1] == '*'):\n argument = os.system(\"ls\")\nelse:\n argument = sys.argv[1:]\n\nos.system(\"mkdir target\")\n\nselect = raw_input(\"Please input the choice:\\n\\t1. utf-8 -> gbk\\n\\t2. gbk -> utf-8\\n\")\nif select == '1':\n for file in argument:\n os.system(\"iconv -c -f utf-8 -t gbk \"+file+' > target/'+file)\n print (\"Completed!\\n\")\nelif select == '2':\n for file in argument:\n os.system(\"iconv -c -f gbk -t utf-8 \"+file+' > target/'+file)\n print (\"Completed!\\n\")\nelse:\n print (\"Invalid choice!\\n\")\n\n","sub_path":"transcode.py","file_name":"transcode.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"178878756","text":"class Solution:\n def reverseString(self, s: List[str]) -> None:\n index = 0\n while index < len(s)//2 and len(s) > 1:\n s[index], s[-1-index] = s[-1-index], s[index]\n index += 1\n return s\n\n#this doesn't work unless you increase recursion depth, but can't on Leetcode\nimport sys\nsys.setrecursionlimit(1500)\nclass Solution:\n left = 0\n right = -1\n \n def reverseString(self, s: List[str]) -> None:\n \"\"\"\n Do not return anything, modify s in-place instead.\n \"\"\"\n if self.left >= len(s) + self.right or len(s) <= 1:\n return ''\n \n hold = s[self.left]\n s[self.left] = s[self.right]\n s[self.right] = hold\n self.right -= 1\n self.left += 1\n \n self.reverseString(s)\n","sub_path":"python/344_reverseString.py","file_name":"344_reverseString.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"599221125","text":"import os\r\nfrom flask import Flask,jsonify, request, redirect, url_for, send_from_directory\r\nimport json\r\nimport logging\r\n\r\nclass Task(object):\r\n def __init__(self, filename, result, point):\r\n self.filename = filename\r\n self.result = result\r\n self.point = point\r\n\r\n def obj_dict(self):\r\n return {'filename': self.filename, 'result': self.result, 'point': self.point}\r\n\r\n#UPLOAD_FOLDER = 'uploads'\r\nALLOWED_EXTENSIONS = set(['exe', 'cpl', 'reg', 'ini', 'bat', 'com', 'dll', 'pif', 'lnk', 'scr', 'vbs', 'ocx', 'drv', 'sys'])\r\n#logging.basicConfig(level=logging.DEBUG)\r\napp = Flask(__name__)\r\n#app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\n\r\ndef allowed_file(filename):\r\n prop = filename.split('.')[-1]\r\n return prop in ALLOWED_EXTENSIONS\r\n\r\n@app.route('/upload-file', methods=['POST'])\r\ndef upload_file():\r\n file = request.files['file']\r\n if file and allowed_file(file.filename):\r\n # dua file vao cuckoo xu li https://cuckoo.readthedocs.io/en/latest/usage/api/\r\n print('----- found file: ', file.filename)\r\n #file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))\r\n\r\n # tra ve kq nhu vd duoi\r\n task = Task('1','2','3') \t\r\n return jsonify({'results' : task.obj_dict(), 'msg':'ok'})\r\n return jsonify({'msg': 'error'})\r\n\r\n@app.route('/upload-multifile', methods=['POST'])\r\ndef upload_files():\r\n #logging.info(request.files)\r\n if 'files[]' not in request.files:\r\n return jsonify({'msg': 'error'})\r\n files = request.files.getlist('files[]')\r\n for file in files:\r\n if file and allowed_file(file.filename):\r\n # Dua file vao cuckoo de xu li https://cuckoo.readthedocs.io/en/latest/usage/api/\r\n print('----- found file: ', file.filename)\r\n #file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))\r\n\r\n # tra ve kq nhu vd duoi \r\n task = []\r\n task.append(Task(1,2,3).obj_dict())\r\n task.append(Task(2,3,4).obj_dict())\r\n #results = [obj.obj_dict() for obj in task]\r\n return jsonify({'results' : task, 'msg' : 'ok'})\r\n\r\nif __name__ == '__main__':\r\n\tapp.run(host=\"127.0.0.1\", port = 8123, debug=True)","sub_path":"Web_API.py","file_name":"Web_API.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"432567087","text":"from pycqed.measurement.randomized_benchmarking.two_qubit_clifford_group \\\n import SingleQubitClifford, TwoQubitClifford\nfrom os.path import join, dirname, abspath\nfrom os import mkdir\nimport numpy as np\nfrom zlib import crc32\n\noutput_dir = join(abspath(dirname(__file__)), 'clifford_hash_tables')\ntry:\n mkdir(output_dir)\nexcept FileExistsError:\n pass\n\ndef construct_clifford_lookuptable(generator, indices):\n \"\"\"\n \"\"\"\n lookuptable = []\n for idx in indices:\n clifford = generator(idx=idx)\n # important to use crc32 hashing as this is a non-random hash\n hash_val = crc32(clifford.pauli_transfer_matrix.round().astype(int))\n lookuptable.append(hash_val)\n return lookuptable\n\ndef generate_hash_tables():\n print(\"Generating Clifford hash tables.\")\n single_qubit_hash_lut = construct_clifford_lookuptable(\n SingleQubitClifford, np.arange(24))\n with open(join(output_dir, 'single_qubit_hash_lut.txt'), 'w') as f:\n for h in single_qubit_hash_lut:\n f.write(str(h)+'\\n')\n\n two_qubit_hash_lut = construct_clifford_lookuptable(\n TwoQubitClifford, np.arange(11520))\n with open(join(output_dir, 'two_qubit_hash_lut.txt'), 'w') as f:\n for h in two_qubit_hash_lut:\n f.write(str(h)+'\\n')\n print(\"Successfully generated Clifford hash tables.\")\n\nif __name__ == '__main__':\n generate_hash_tables()\n","sub_path":"pycqed/measurement/randomized_benchmarking/generate_clifford_hash_tables.py","file_name":"generate_clifford_hash_tables.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"567356373","text":"\n#imports libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time as systime\nimport datetime as dtime\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nimport gc\n\n\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Make mapping for month\nmonth_enum={1:'jan',2:'feb',3:'mar',4:'apr',5:'may',6:'jun',7:'jul',8:'aug',9:'sep',10:'oct',11:'nov',12:'dec'}\n\n# Load input files\nTRAIN_FILENAME = 'train.csv'\nTEST_FILENAME = 'test.csv'\n\ntrain_raw = pd.read_csv('../input/'+TRAIN_FILENAME, parse_dates=['Dates'], index_col=False)\ntest_raw = pd.read_csv('../input/'+TEST_FILENAME, parse_dates=['Dates'], index_col=False)\n\n# Binarize Days, Month, District, Time\ndef feature_engineering(data):\n \n days = pd.get_dummies(data.DayOfWeek)\n district = pd.get_dummies(data.PdDistrict)\n month = pd.get_dummies(data.Dates.dt.month.map(month_enum))\n hour = data.Dates.dt.hour\n hour = pd.get_dummies(hour) \n \n #Append newly created dummy variables to dataframe\n new_data = pd.concat([hour, month, days, district], axis=1)\n \n return new_data\n\n# Prepare the data\ntrain = feature_engineering(train_raw)\n#test = pd.concat([test_raw['Id'],feature_engineering(test_raw)], axis=1)\ntest = feature_engineering(test_raw)\n\n# Encode distinct Categories into dummy variables\ncat_enc = LabelEncoder()\ncat_enc.fit(train_raw['Category'])\ntrain['CategoryEncoded'] = cat_enc.transform(train_raw['Category'])\n\n# Select the Predictors\nx_cols = list(train.columns[0:53].values)\n\n# Fit Logit model and estimate the class probability\n#clf = xgb.XGBClassifier(n_estimators=5)\n\nclf = AdaBoostClassifier(DecisionTreeClassifier(max_depth = 8),\n n_estimators = 40,\n learning_rate = 0.5, \n random_state = 1)\n\nclf.fit(train[x_cols], train['CategoryEncoded'])\npredicted = clf.predict_proba(test[x_cols])\n\n\n# Make the output data frame by mapping the probability estimates to categories\ncrime = cat_enc.fit_transform(train_raw.Category)\nresult=pd.DataFrame(predicted, columns=cat_enc.classes_)\n\n# I noticed that predicted estimates were having 10 decimal digits or even more.\n# Which was giving me memory insufficient error while trying to save it as .csv\n# For eg. I tried saving half of the output(442131 records) and .csv file generated\n# was of size 370mb. So I rounded of the digits to 4-5 decimal points and output file\n# size got reduced.\nresult=result.round(5)\n\n# Appending the Index column\nresult= pd.concat([test_raw['Id'], result], axis=1)\n\ndel train\ndel test\ndel train_raw\ndel test_raw\n\ngc.collect()\n\nresult.to_csv('submit.csv', index = False)\n\n\n\n","sub_path":"San_Francisco_Crime_AdaBoosting.py","file_name":"San_Francisco_Crime_AdaBoosting.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"533118361","text":"import boto3\nimport json\nimport os\n\nfrom boto3.dynamodb.conditions import Attr\n\ntabla_ordenes = os.environ[\"TABLA_ORDENES\"]\n\ndynamodb = boto3.resource(\"dynamodb\")\ntabla = dynamodb.Table(tabla_ordenes)\n\ndef lambda_handler(event, context):\n print(event)\n data = {}\n data[\"id\"] = event[\"id\"]\n data[\"articulo\"] = event[\"articulo\"]\n data[\"categoria_articulo\"] = event[\"categoria_articulo\"]\n data[\"metodo_pago\"] = event[\"metodo_pago\"]\n data[\"id_comprador\"] = event[\"id_comprador\"]\n data[\"nombre_comprador\"] = event[\"nombre_comprador\"]\n data[\"afiliado\"] = event[\"afiliado\"]\n data[\"estado\"] = \"Completada\"\n respuesta_put_item = tabla.put_item(\n Item=data \n )\n print(respuesta_put_item)\n","sub_path":"actualizar-orden.py","file_name":"actualizar-orden.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"11199139","text":"from fastapi import FastAPI\nimport pika\n\napp = FastAPI()\n\n\n# ヘルスチェック用\n@app.get(\"/\")\ndef read_root():\n return {\"Status\": \"OK\"}\n\n\n# RabbitMQ用\n@app.get(\"/add-job/{message}\")\ndef add_job(message: str):\n # RabbitMQサーバと接続(ホスト名にはコンテナ名を指定しているが,Dockerを使ってない場合はIPアドレスを指定)\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(host=\"rabbitmq\"))\n # チャンネルの確立\n channel = connection.channel()\n # メッセージを格納するためのキュー(task_queue)を作成\n channel.queue_declare(queue=\"task_queue\", durable=True)\n # メッセージをキュー(task_queue)に格納\n channel.basic_publish(\n exchange=\"\",\n routing_key=\"task_queue\",\n body=message,\n properties=pika.BasicProperties(\n delivery_mode=2, # メッセージの永続化\n ))\n # 接続のクローズ及びメッセージが配信されたことを確認\n connection.close()\n\n return {\"send\": message}\n","sub_path":"docker/fastapi/producer/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"219081838","text":"from defs import *\r\nfrom data_processing import best_model\r\n\r\n\r\nif sanity==1:\r\n\td[\"mainType\"] = \"Optimize_Model\"\r\n\td[\"_dataFile\"] = data_file\r\n\td[\"_maxChrNum\"] = -10\r\n\td[\"_minChrNum\"] = -1\r\nelse:\r\n\td[\"mainType\"] = \"mainSimulate\"\r\n\td[\"_freqFile\"] = freq_file\r\n\td[\"_simulationsIter\"] = 100\r\n\td[\"_simulationsJumpsStats\"] = \"expStats.txt\"\r\n\td[\"_maxChrNumForSimulations\"] = max(counts) * 10\r\n\td[\"_simulationsTreeLength\"] = 4\r\n\r\n\r\nd[\"_outDir\"] = outDir\r\nd[\"_treeFile\"] = tree_file\r\nd[\"_logFile\"] = \"log.txt\"\r\nd[\"_logValue\"] = 6\r\nd[\"_maxChrNum\"] = -10\r\nd[\"_minChrNum\"] = -1\r\nd[\"_maxOptimizationIterations\"] = 5\r\nd[\"_epsilonLLimprovement\"] = 0.01\r\nd[\"_optimizeIterNum\"] = \"0,1,3\"\r\nd[\"_optimizePointsNum\"] = \"5,2,1\"\r\nd[\"_branchMul\"] = 1\r\n\r\n\r\ndef initialize_defaults():\r\n\t'''\r\n\t\tinitialize parameters default values\r\n\t:return: parameters dictionary with fixed parameters\r\n\t'''\r\n\td = {}\r\n\r\n\td[\"_maxChrNum\"] = -10\r\n\td[\"_minChrNum\"] = -1\r\n\td[\"_branchMul\"] = 999\r\n\td[\"_simulationsNum\"] = 1000\r\n\td[\"_logFile\"] = \"log.txt\"\r\n\td[\"_logValue\"] = 6\r\n\td[\"_maxOptimizationIterations\"] = 5\r\n\td[\"_epsilonLLimprovement\"] = 0.01\r\n\td[\"_optimizeIterNum\"] = \"0,1,3\"\r\n\td[\"_optimizePointsNum\"] = \"5,2,1\"\r\n\td[\"_simulationsIter\"] = 100\r\n\td[\"_simulationsTreeLength\"] = 4\r\n\r\n\treturn d\r\n\r\ndef create_user_param_dict(filename):\r\n\td = {}\r\n\twith open(filename, \"r\") as params_file:\r\n\t\tfor line in params_file:\r\n\t\t\tline = line.strip()\r\n\t\t\tname = re.search(\"(.*)\\s(.*)\",line).group(1)\r\n\t\t\tval = re.search(\"(.*)\\s(.*)\", line).group(2)\r\n\t\t\td[name] = val\r\n\treturn d\r\n\r\ndef create_params_dict(outDir, dataFile, treeFile, params_from_user):\r\n\r\n\td = initialize_defaults()\r\n\r\n\td[\"_mainType\"] = \"mainSimulate\"\r\n\td[\"_outDir\"] = outDir\r\n\tif os.path.isfile(dataFile):\r\n\t\td[\"_dataFile\"] = dataFile\r\n\td[\"treeFile\"] = treeFile\r\n\r\n\tif os.path.isfile(params_from_user):\r\n\t\ttmp_d = create_user_param_dict(params_from_user)\r\n\telse:\r\n\t\t#########################>>>>>>>>>>>>>>>>>>>> need model for path names, but user don't necessarily specify model >>>>>>>>>>>>>>>######################\r\n\t\ttmp_d = best_model.get_params(main_res_dir + model + CE_res_filename,main_res_dir + model + root_freq_filename,max(counts) * 10) # parse from existing CE results file\r\n\t\tbntpv_vec = create_bntpv(main_res_dir + model_name + expectation_file, main_res_dir + model_name + mlAncTree,d[\"_baseNumber\"])\r\n\t\td[\"_baseTransitionProbs\"] = bntpv_vec\r\n\t\td[\"_maxChrNumForSimulations\"] = max(counts) * 10\r\n\t# d = {**d, **tmp_d}\r\n\treturn d\r\n\r\n","sub_path":"data_processing/params_processing.py","file_name":"params_processing.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"465457115","text":"import tkinter as tk\nfrom tkinter import ttk\nimport abc\n\n\nfrom frames.scrollable_frame import ScrollableFrame\n\n\nclass BaseSummary(ttk.Frame, abc.ABC):\n\n def __init__(self, container, controller, **kwargs):\n super().__init__(container, **kwargs)\n self.controller = controller\n\n # container for title\n self.title_container = tk.Frame(self, bd=10, relief='groove')\n self.title_container.pack(side='top', fill='both', expand=True)\n # container for entries\n self.container = ScrollableFrame(self, bd=10, relief='groove')\n self.container.pack(side='top', fill='both', expand=True)\n # container for buttons\n self.button_container = tk.Frame(self, bd=10, relief='groove')\n self.button_container.pack(side='top', fill='x', expand=True)\n\n def title_place(self, text):\n title = ttk.Label(\n self.title_container,\n text=text,\n font=40\n )\n title.config(anchor='center')\n title.pack(side='top', fill='x', expand=True)\n\n def container_place(self, text):\n self.container.frame.columnconfigure(0, weight=1)\n label = ttk.Label(\n self.container.frame,\n text=text\n )\n label.grid(row=0, column=0, sticky='nsew')\n\n def create_buttons(self, place):\n self.button_container.columnconfigure(0, weight=1)\n button1 = ttk.Button(\n self.button_container,\n text='Back'\n )\n button1.grid(row=0, column=0, sticky='ew')\n button1['command'] = lambda: self.controller.show_frame(place)","sub_path":"Lab5.5/frames/base_summary.py","file_name":"base_summary.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"355936483","text":"#!/usr/bin/python\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom git_admin.models import Repo, RepoType, MasterRepo, CommittedFile, Commit, FileExtension\nfrom optparse import make_option\nimport subprocess\nimport os\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\nSCRIPTS_PATH = getattr(settings, \"PATH_TO_SCMFORGE_SCRIPTS\", None)\n\n\nclass Command(BaseCommand):\n \"\"\" Manipulates statistics data \"\"\"\n option_list = BaseCommand.option_list + (\n make_option('--clean', action='store_true', dest='clean', default=False,\n help='Delete all Git repositories from database'),) + (\n make_option('--import', action='store_true', dest='import', default=False,\n help='Update all Git repositories in database basing on what is in the filesystem'), )+(\n make_option('--import-commits', action='store_true', dest='report', default=False, help='Generate stats'),)\n\n def handle(self, **options):\n if options['clean']:\n self.stdout.write(\"Number of commits before cleaning: %s\" % str(CommittedFile.objects.all().count()))\n CommittedFile.objects.all().delete()\n FileExtension.objects.all().delete()\n self.stdout.write(\"Number of commits after cleaning: %s\" % str(CommittedFile.objects.all().count()))\n elif options['import']:\n for repo in Repo.objects.all():\n repo.path = repo.path\n print(\"\\n\\n\\n### starting import for REPO: %s\" % repo.path)\n proc = subprocess.Popen([SCRIPTS_PATH + \"/git_commits_size.sh\", repo.path], stdout=subprocess.PIPE)\n commit_list = proc.stdout.readlines()\n for commit in commit_list:\n commit_split = commit.split(\" \", 2)\n new_commit = CommittedFile()\n new_extension.sha1 = commit_split[0]\n new_commit.size = int(commit_split[1])\n new_commit.filename = commit_split[2].replace(\"\\n\", \" \")\n new_commit.repo = repo\n if \".\" in os.path.basename(new_commit.filename):\n ext = os.path.basename(new_commit.filename).split(\".\")[-1]\n try:\n new_commit.extension = FileExtension.objects.get(extension=ext)\n except ObjectDoesNotExist:\n print(\"adding new extension to database: %s\" % ext)\n new_extension = FileExtension()\n new_extension.extension = ext\n new_extension.save()\n new_commit.extension = new_extension\n new_commit.save()\n print(\"added commit: %s %s %s \" % (new_commit.sha1, new_commit.size, new_commit.filename))\n print(\"..finished\")\n elif options['import-commits']:\n for repo in Repo.objects.all():\n print(repo.path)\n proc = subprocess.Popen([SCRIPTS_PATH + \"/git_full_log.sh\", repo.path], stdout=subprocess.PIPE)\n commit_list = proc.stdout.readlines()\n for commit in commit_list:\n print(commit)\n print([SCRIPTS_PATH + \"/git_commits_size.sh\", repo.path])\n","sub_path":"scmforge/git_admin/management/commands/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"176754699","text":"\"\"\"\nMY20 RYI Home Page\n\"\"\"\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support.select import Select\nimport openpyxl\nfrom bs4 import BeautifulSoup\nfrom requests.adapters import HTTPAdapter\nfrom selenium import webdriver\nimport requests\nfrom page.page import Page\nfrom proj21_escape_everyday.data.urls import current_url\nfrom proj21_escape_everyday.element.elements_define import ElementsDefine\n\nclass HomePage(Page):\n \"\"\"\n MY20 RYI Home Page\n \"\"\"\n def __init__(self, driver):\n \"\"\"\n init function\n :param driver:\n \"\"\"\n self.url = \"/{}/home\"\n super(HomePage, self).__init__(driver, current_url())\n self.element = ElementsDefine()\n\n def get_social_links(self):\n \"\"\"\n Get HomePage Social Link\n :return:\n \"\"\"\n social_links = self.find_elements(self.element.homepage_social_link)\n return [a.get_attribute(\"href\") for a in social_links if a.get_attribute(\"href\")]\n\n def check_response_code(self, url):\n headers = {\n # \"Connection\": \"close\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36\"\n }\n s = requests.Session()\n s.mount('http://', HTTPAdapter(max_retries=5)) # 失败之后重试\n s.mount('https://', HTTPAdapter(max_retries=5))\n r = s.get(url, headers=headers, timeout=20)\n return r.status_code\n\n def get_footer_links(self, locale):\n \"\"\"\n check footer links\n \"\"\"\n headers = {\n # \"Connection\": \"close\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36\"\n }\n url = f\"https://hdguest:MLP@2017@change-your-ride.proferochina.com/{locale}/home\"\n s = requests.Session()\n s.mount('http://', HTTPAdapter(max_retries=5)) # 失败之后重试\n s.mount('https://', HTTPAdapter(max_retries=5))\n r = s.get(url, headers=headers, timeout=20)\n bs = BeautifulSoup(r.text, \"html.parser\")\n footer_links = bs.find(name=\"div\", class_=\"footer_links-container\").find_all(\"a\")\n footer_li = []\n for item in footer_links:\n footer_li_child = []\n if len(item.get('href')):\n footer_li_child.append(item.get('href'))\n footer_li_child.append(item.get('target'))\n footer_li.append(footer_li_child)\n\n return footer_li\n\n","sub_path":"proj21_escape_everyday/page/home_page.py","file_name":"home_page.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"355469820","text":"import socket\nimport time\n\nclass SubscriberSocket(object):\n def __init__(self,ip,port):\n self.ip = ip\n self.port = port\n self.socket = None\n\n def establish_connection(self):\n self.socket = socket.socket() \n host = self.ip \n port = self.port \n self.socket.connect(('0.0.0.0', port))\n\n def receive(self):\n i = 0\n while 1:\n self.socket.send(bytes(str(i),'UTF-8'))\n data = self.socket.recv(1024).decode(\"utf-8\")\n if 'no more' in data:\n print(\"all publisher data received , sleeping for 10 seconds\")\n time.sleep(10)\n else:\n i += 1\n print(\"received data from publisher - \",data)\n time.sleep(1)\n\n def close(self):\n self.socket.close()\n","sub_path":"language_programs/pubsub/subscriber2/subscriber_socket.py","file_name":"subscriber_socket.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"265408657","text":"from nose import tools\nimport minIRC_Client\nfrom minIRC_Client import log\nfrom minIRC_Client.client import Client\nimport asyncio\nimport sys\n\nlogger = log.setup_custom_logger('root.tests', level=5)\n\nHOST = '127.0.0.1'\nPORT = 10101\n\nchannels = set()\nusers = {}\n\n\ndef setup():\n loop = asyncio.get_event_loop()\n client = Client(loop, name='Admin')\n coro = loop.create_connection(lambda: client, HOST, PORT)\n\n try:\n logger.debug(f'Trying to establish a connection to minIRC server on host: {HOST} port: {PORT}.')\n loop.run_until_complete(coro)\n except ConnectionRefusedError:\n logger.debug(f'Connection refused. host: {HOST} port: {PORT}')\n loop.close()\n sys.exit(1)\n\ndef teardown():\n print(\"TEAR DOWN!\")\n\ndef test_basic():\n print(\"I RAN!\")\n","sub_path":"tests/minIRC_Client_tests.py","file_name":"minIRC_Client_tests.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"23600957","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import Counter\nimport logging\nimport pandas as pd\nimport re\nimport numpy as np\n\n# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',\n# level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\ndef test1():\n # [seq_len, batch_size, hidden_size]\n h = torch.rand(10, 3, 5)\n print(h.shape)\n x = torch.tanh(h)\n print(x.shape)\n s = h.sum(dim=0)\n print(s.shape)\n z = s * x\n print(z)\n\n S = 0\n for time in range(h.size(0)):\n S += h[time] * x\n print(S == z)\n\n\ndef test2():\n x = torch.arange(24).reshape(2, 4, 3)\n print(x)\n print(x.sum(dim=1))\n print(x.sum(dim=0))\n\n\ndef test3():\n x = torch.tensor([[1, 2, 3],\n [0, 1, 4],\n [1, 1, 1]], dtype=torch.float)\n y = torch.ones(3, 3)\n z = torch.arange(9).reshape(3, 3).float()\n print(x*z + y*z)\n print((x+y)*z)\n print((x*z+y*z) == (x+y)*z)\n\n# def test4():\n# logging.info(\"ok\")\n\ndef test5():\n df = pd.read_csv('data/1.txt', header=None, sep='|||')\n # print(df.count())\n print(df.head())\n\ndef test6():\n with open(\"data/char_corpus.txt\", encoding='utf-8', errors='ignore') as fin:\n with open('data/char_tokens.txt', 'a', encoding='utf-8') as fout:\n for line in fin:\n line = re.sub(r'\\s+', '', line)\n fout.write(' '.join(list(line)))\n fout.write('\\n')\n\ndef test7():\n logger.info(\"hello world\")\n\ndef test8():\n x = np.random.randint(1, 50, 10)\n y = list(range(10))\n print(x, '\\n', y)\n z = list(zip(x, y)) # 打包\n z.sort(key=lambda t: t[0], reverse=True) # 指定取待排序元素的哪一项进行排序\n print(z)\n a, b = zip(*z) # 与zip相反,zip*可理解为解压\n print(a, '\\n', b)\n\n nums = ['flower', 'flow', 'flight']\n for i in zip(*nums):\n print(i)\n\nclass Instance(object):\n def __init__(self, wds, tag):\n self.wds = wds\n self.tag = tag\n def __str__(self):\n return ''.join(self.wds) + '|' + str(self.tag)\n\ndef test9():\n insts = [\n Instance(['我', '是', '天大人'], 1),\n Instance(['可恶'], 0),\n Instance(['它', '走了'], 0),\n Instance(['我', '爱', '我', '的', '祖国'], 1)\n ]\n\n # sorted(insts, key=lambda s: s.tag)\n insts.sort(key=lambda s: len(s.wds), reverse=True)\n\n for i in insts:\n print(i.wds, i.tag)\n\n\ndef test10():\n inputs = torch.randn(3, 64, 8)\n print(inputs.shape) # [3, 64, 8]\n inputs.transpose_(1, 2)\n print(inputs.shape)\n apool = nn.AdaptiveMaxPool1d(output_size=1)\n output = apool(inputs)\n print(output.shape) # [3, 64, 1]\n\n\ndef test11():\n # x = torch.arange(24).float().reshape((2, 3, 4))\n # print(x)\n # print(F.softmax(x[0][0] * x[0]))\n\n # for b in range(2):\n # for s in range(3):\n # t = x[b][s] * x[b]\n # print(t, F.softmax(t, dim=1))\n\n y = torch.arange(12).float().reshape(3, 4)\n print(y)\n print(F.softmax(y[0] * y))\n\n\ndef test12():\n x = torch.arange(24).float().reshape(2, 4, 3)\n print(x)\n print(x[-1], x[-2])\n print(torch.cat((x[-1], x[-2]), dim=1))\n\n\ndef test13():\n x = torch.arange(12).float().reshape(3, 4)\n print(x)\n print(F.softmax(x, dim=0))\n print(F.softmax(x, dim=1))\n","sub_path":"SentimentAnalyzeII/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"364248437","text":"import random\nfrom difflib import SequenceMatcher\n\nfrom app.Crawler.crawlImage import *\nfrom app.Crawler.crawlWord import *\nfrom app.Dictionary.dictionary import *\nfrom app.Model.Exercise import *\nfrom app.misc.etendu import etendu\n\n# A tester!!!\nclass ExerciseGenerator:\n @staticmethod\n def proposeChoices(word):\n freq = findLemmeFreq(word)\n if freq > 500:\n k = 300\n elif freq > 100:\n k = 100\n else:\n k = 5\n with connectBDD() as session:\n wordModel = session.query(Word).filter(Word.ortho == word)\n words = []\n for item in wordModel:\n words.append(item)\n if (len(words) > 0):\n maxFreq = words[0].freqlemfilms\n maxWord = words[0]\n for item in words:\n if item.freqlemfilms > maxFreq:\n maxFreq = item.freqlemfilms\n maxWord = item\n nature = maxWord.cgram\n proposition = session.query(Word).filter(Word.cgram == nature).filter(Word.freqlemfilms < (freq + k)).filter(\n Word.freqlemfilms > (freq - k))\n lemmes = []\n for item in proposition:\n lemmes.append(item.lemme)\n random.shuffle(lemmes)\n propositions = [lemmes[0], lemmes[1], lemmes[2], lemmes[3]]\n return propositions\n else:\n propositions = ['undefined', 'undefined', 'undefined', 'undefined']\n return propositions\n\n def generateExercise(self, word):\n pass\n\n\nclass BlankFillingExerciseGenerator(ExerciseGenerator):\n @staticmethod\n def similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\n def generateExercise(self, word):\n phrase = crawlPhrase(word)\n if phrase:\n wordList = phrase.split(' ')\n similarList = []\n for item in wordList:\n similarList.append(self.similar(item, word))\n valeurMax = max(similarList)\n position = similarList.index(valeurMax)\n wordList[position] = '_____'\n topic = ' '.join(wordList)\n choices = self.proposeChoices(word)\n ran = int(random.random() * 100) % 4\n choices[ran] = word\n return Exercise(topic, choices, ran)\n\n\nclass SynonymeExerciseGenerator(ExerciseGenerator):\n def generateExercise(self, word):\n synonyme = crawlSynonyme(word)\n if synonyme:\n topic = \"Choisissez le mot qui a le même sens que '\" + word + \"'\"\n choices = self.proposeChoices(word)\n ran = int(random.random() * 100) % 4\n choices[ran] = synonyme\n return Exercise(topic, choices, ran)\n\n\nclass AntonymeExerciseGenerator(ExerciseGenerator):\n def generateExercise(self, word):\n antonyme = crawlAntonyme(word)\n if antonyme:\n topic = \"Choisissez le mot qui est le contraire de '\" + word + \"'\"\n choices = self.proposeChoices(word)\n ran = int(random.random() * 100) % 4\n choices[ran] = antonyme\n return Exercise(topic, choices, ran)\n\n\nclass ImageExerciseGenerator(ExerciseGenerator):\n def generateExercise(self, word):\n topic = \"Choisissez l'image qui correspond à '\" + word + \"'\"\n choices = self.proposeChoices(word)\n ran = int(random.random() * 100) % 4\n choices[ran] = word\n images = []\n for choice in choices:\n choiceImage = crawlImage(choice)\n images.append(choiceImage)\n return Exercise(topic, images, ran)\n\n\n\nclass RandomExerciseGenerator(ExerciseGenerator):\n types = ['BlankFillingExerciseGenerator',\n 'SynonymeExerciseGenerator',\n 'AntonymeExerciseGenerator',\n 'ImageExerciseGenerator']\n\n def generateExercise(self, word):\n while True:\n ran = int(random.random() * 100) % len(self.types)\n generator = globals()[self.types[ran]]()\n exercise = generator.generateExercise(word)\n if exercise:\n return exercise\n else:\n continue\n\n\n#faut ecrire une classe d'adapteur!!!!!\nclass TotalRandomExerciseGenerator(RandomExerciseGenerator):\n def choisirMot(self):\n length = len(etendu)\n ran = int(random.random() * 1000) % (length-2)\n upper = etendu[ran]\n lower = etendu[ran + 1]\n with connectBDD() as session:\n words = session.query(Word).filter(Word.freqlemfilms >= lower) \\\n .filter(Word.freqlemfilms <= upper)\n lemmes = []\n for word in words:\n lemmes.append(word.lemme)\n return random.choice(lemmes)\n\n def generateRandomExercise(self):\n word = self.choisirMot()\n return self.generateExercise(word)\n\n\n\n#a = RandomExerciseGenerator()\n\n#ERROR!!!!!!!!!\nif __name__ == '__main__':\n\n b = RandomExerciseGenerator()\n exercise = b.generateExercise('content')\n print(exercise)\n #print(a.generateExercise('content'))\n\n\n","sub_path":"app/Exercise/ExerciseGenerator.py","file_name":"ExerciseGenerator.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"268224995","text":"# -*- mode: python ; coding: utf-8 -*-\nfrom kivy_deps import sdl2, glew\n\nblock_cipher = None\n\n\na = Analysis(['main.py'],\n pathex=['/home/gef/Documents/Hobbes-many/hobbes_debug/hobbes_python'],\n binaries=[],\n datas=[('media', './media'), ('hobbes.kv', '.')],\n hiddenimports=[],\n hookspath=[],\n runtime_hooks=[],\n excludes=[\n\n \"ffpyplayer\",\n \"xmlrpc\",\n \"defusedxml\",\n \"PIL\",\n \"docutils\",\n \"ssl\",\n \"crypto\",\n \"buildozer\",\n \"cairocffi\",\n \"CairoSVG\",\n \"m2r\",\n \"Pygments\",\n \"pyperclip\",\n \"urllib3\",\n \"zipp\",\n \"lib2to3\",\n \"virtualenv\",\n \"webencodings\",\n\n 'pygame.cdrom',\n 'pygame.cursors',\n 'pygame.display',\n 'pygame.draw',\n 'pygame.event',\n 'pygame.examples',\n 'pygame.font',\n 'pygame.freetype',\n 'pygame.gfxdraw',\n 'pygame.image',\n 'pygame.joystick',\n 'pygame.key',\n 'pygame.locals',\n 'pygame.mouse',\n 'pygame.mixer.music',\n 'pygame.overlay',\n 'pygame.pixelarray',\n 'pygame.scrap',\n 'pygame.sndarray',\n 'pygame.sprite',\n 'pygame.surface',\n 'pygame.surfarray',\n 'pygame.tests',\n 'pygame.time',\n 'pygame.transform',\n\n 'kivy.core.audio',\n\n 'kivy.core.audio.audio_avplayer',\n 'kivy.core.audio.audio_ffpyplayer',\n 'kivy.core.audio.audio_gstplayer',\n 'kivy.core.audio.audio_pygame',\n 'kivy.core.audio.audio_sdl2',\n\n 'kivy.core.camera',\n\n 'kivy.core.camera.camera_android',\n 'kivy.core.camera.camera_gi',\n 'kivy.core.camera.camera_opencv',\n 'kivy.core.camera.camera_picamera',\n\n 'kivy.core.clipboard.clipboard_android',\n 'kivy.core.clipboard.clipboard_dbusklipper',\n 'kivy.core.clipboard.clipboard_dummy',\n 'kivy.core.clipboard.clipboard_gtk3',\n 'kivy.core.clipboard.clipboard_nspaste',\n 'kivy.core.clipboard.clipboard_pygame',\n 'kivy.core.clipboard.clipboard_winctypes',\n\n 'kivy.core.spelling',\n\n 'kivy.core.spelling.spelling_enchant',\n 'kivy.core.spelling.spelling_osxappkit',\n\n 'kivy.core.text._text_pango',\n 'kivy.core.text.text_pango',\n 'kivy.core.text.text_pil',\n 'kivy.core.text.text_pygame',\n\n 'kivy.core.image.img_dds',\n 'kivy.core.image.img_ffpyplayer',\n 'kivy.core.image.img_gif',\n 'kivy.core.image.img_pil',\n 'kivy.core.image.img_pygame',\n 'kivy.core.image.img_tex',\n\n 'kivy.graphics.cgl_backend.cgl_debug',\n 'kivy.graphics.cgl_backend.cgl_mock',\n\n 'kivy.graphics.svg',\n 'kivy.graphics.tesselator',\n\n 'xml.etree.cElementTree'\n ],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n [],\n exclude_binaries=True,\n name='hobbes',\n debug=False,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n console=True )\ncoll = COLLECT(exe,\n a.binaries,\n a.zipfiles,\n a.datas,\n\t\t\t *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],\n strip=False,\n upx=True,\n upx_exclude=[],\n name='main')\n","sub_path":"main_windows.spec","file_name":"main_windows.spec","file_ext":"spec","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"650929244","text":"r\"\"\"Example of using mlbench : CIFAR10 + Resnet20 + MPI\"\"\"\n\nimport argparse\nimport torch.distributed as dist\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torch.nn.modules.loss import CrossEntropyLoss\n\nfrom mlbench_core.utils.pytorch import initialize_backends\nfrom mlbench_core.evaluation.pytorch.metrics import TopKAccuracy\nfrom mlbench_core.models.pytorch.resnet import ResNetCIFAR\nfrom mlbench_core.lr_scheduler.pytorch.lr import MultiStepLR\nfrom mlbench_core.controlflow.pytorch import TrainValidation\nfrom mlbench_core.utils.pytorch.checkpoint import Checkpointer\nfrom mlbench_core.dataset.imagerecognition.pytorch import CIFAR10V1, partition_dataset_by_rank\n\n\ndef main(run_id):\n r\"\"\"Main logic.\"\"\"\n num_parallel_workers = 2\n dataset_root = '/datasets/torch/cifar10'\n use_cuda = True\n batch_size = 128\n\n initialize_backends(comm_backend='mpi',\n logging_level='INFO',\n logging_file='/mlbench.log',\n use_cuda=use_cuda,\n seed=42,\n cudnn_deterministic=False,\n ckpt_run_dir='/checkpoints',\n delete_existing_ckpts=False)\n\n rank = dist.get_rank()\n world_size = dist.get_world_size()\n\n model = ResNetCIFAR(resnet_size=20,\n bottleneck=False,\n num_classes=10,\n version=1)\n\n optimizer = optim.SGD(model.parameters(),\n lr=0.1,\n momentum=0.9,\n weight_decay=1e-4,\n nesterov=True)\n\n # Create a learning rate scheduler for an optimizer\n scheduler = MultiStepLR(optimizer,\n milestones=[82, 109],\n gamma=0.1)\n\n # A loss_function for computing the loss\n loss_function = CrossEntropyLoss()\n\n if use_cuda:\n model = model.cuda()\n loss_function = loss_function.cuda()\n\n # Metrics like Top 1/5 Accuracy\n metrics = [TopKAccuracy(topk=1), TopKAccuracy(topk=5)]\n\n train_set = CIFAR10V1(dataset_root, train=True, download=True)\n val_set = CIFAR10V1(dataset_root, train=False, download=True)\n\n train_set = partition_dataset_by_rank(train_set, rank, world_size)\n\n train_loader = DataLoader(\n train_set, batch_size=batch_size, shuffle=True,\n num_workers=num_parallel_workers,\n pin_memory=use_cuda, drop_last=False)\n\n val_loader = DataLoader(\n val_set, batch_size=batch_size, shuffle=False,\n num_workers=num_parallel_workers,\n pin_memory=use_cuda, drop_last=False)\n\n checkpointer = Checkpointer(\n ckpt_run_dir='/checkpoints',\n rank=rank,\n checkpoint_all=True)\n\n controlflow = TrainValidation(\n model=model,\n optimizer=optimizer,\n loss_function=loss_function,\n metrics=metrics,\n scheduler=scheduler,\n batch_size=batch_size,\n train_epochs=164,\n rank=rank,\n world_size=world_size,\n run_id=run_id,\n dtype='fp32',\n validate=True,\n schedule_per='epoch',\n checkpoint=checkpointer,\n transform_target_type=None,\n average_models=True,\n use_cuda=True,\n max_batch_per_epoch=None)\n\n controlflow.run(\n dataloader_train=train_loader,\n dataloader_val=val_loader,\n dataloader_train_fn=None,\n dataloader_val_fn=None,\n resume=False,\n repartition_per_epoch=False)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Process run parameters')\n parser.add_argument('--run_id', type=str, help='The id of the run')\n args = parser.parse_args()\n main(args.run_id)\n","sub_path":"examples/resnet_cifar10_mpi.py","file_name":"resnet_cifar10_mpi.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"469143481","text":"import json\nimport time\nimport sys\n\nfrom urllib.request import urlopen as uReq\n\n\ndef fetchPrice():\n gbpjpy_url = \"http://finance.google.com/finance/info?client=ig&q=CURRENCY:GBPJPY\"\n\n uClient = uReq(gbpjpy_url)\n page = uClient.read()\n uClient.close()\n data = json.loads(page[6:283].decode())\n price = data[\"l\"]\n time = data[\"lt_dts\"]\n\n return (time,price)\n\np0 = 0\nwhile True:\n t, p = fetchPrice() # time and price\n if(p!=p0):\n #sys.stdout.write(\"Time: {}, Price: {}\".format(t, p))\n print(\"Time: {}, Price: {}\".format(t, p))\n\n time.sleep(60)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"614912297","text":"# t = open('telecode','w+')\n# with open('station_name','r') as f:\n# content = f.read()\n# list1 = content.split('@')\n# for l in list1:\n# print(l)\n# list2 = l.split('|')\n# #print(list2[1],list2[2])\n# string = list2[5]+\":\"+list2[1]+\":\"+list2[2]+\":\"+ list2[0]+\":\"+ list2[3]+\":\"+ list2[4]+\"\\n\"\n# t.writelines(string)\n#\n# f.close()\n\ndef get_telecode(station):\n with open('train/util/telecode','r') as t:\n list = t.readlines()\n for l in list:\n info = l.split(':')\n if info[1] == station:\n\n return info[2]\n","sub_path":"chep/train/util/get_telecode.py","file_name":"get_telecode.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"172849806","text":"import os\nimport secrets\nfrom PIL import Image\nfrom flask import render_template, url_for, flash, redirect, request\nfrom gymmate import app, db, bcrypt\nfrom gymmate.forms import RegistrationForm, LoginForm, UpdateAccountForm\nfrom gymmate.models import User, Post\nfrom flask_login import login_user, current_user, logout_user, login_required\nfrom subprocess import call\nfrom werkzeug.utils import secure_filename\nimport cv2\nimport numpy as np\nimport socket\nimport sys\nimport pickle\nimport struct\nimport time\n\n\n\n#------------------------------------------File Upload Code-------------------------------------------\n\n\nALLOWED_EXTENSIONS = set(['mp4'])\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n#@app.route('/uploader')\n#def upload_form():\n #return render_template('upload.html')\n\n\n@app.route('/uploader', methods=['POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n flash('No file selected for uploading')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n flash('File successfully uploaded')\n return redirect('/')\n else:\n flash('Allowed file types is mp4')\n return redirect(request.url)\n\n#--------------------------------------------------------------------------------------------------------------\n\n\n\n@app.route(\"/\")\n@app.route(\"/home\")\n@login_required\ndef home():\n return render_template('home.html',title='Home')\n\n\n \n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user and bcrypt.check_password_hash(user.password, form.password.data):\n login_user(user, remember=form.remember.data)\n next_page = request.args.get('next')\n return redirect(next_page) if next_page else redirect(url_for('home'))\n else:\n flash('Login Unsuccessful. Please check email and password', 'danger')\n return render_template('login.html', title='Login', form=form)\n\n\n\n\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html', title='About')\n\n\n@app.route(\"/video\")\ndef video():\n\treturn render_template('video.html',title='Videos')\n\n\n@app.route(\"/sending\")\ndef sending():\n return render_template('sending.html',title='Sending')\n\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = RegistrationForm()\n if form.validate_on_submit():\n hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')\n user = User(username=form.username.data, email=form.email.data, password=hashed_password)\n db.session.add(user)\n db.session.commit()\n flash('Your account has been created! You are now able to log in', 'success')\n return redirect(url_for('login'))\n return render_template('register.html', title='Register', form=form)\n\n\n@app.route(\"/logout\")\ndef logout():\n logout_user()\n return redirect(url_for('login'))\n\n\ndef save_picture(form_picture):\n random_hex = secrets.token_hex(8)\n _, f_ext = os.path.splitext(form_picture.filename)\n picture_fn = random_hex + f_ext\n picture_path = os.path.join(app.root_path, 'static/profile_pics', picture_fn)\n\n output_size = (125, 125)\n i = Image.open(form_picture)\n i.thumbnail(output_size)\n i.save(picture_path)\n\n return picture_fn\n\n\n@app.route(\"/account\", methods=['GET', 'POST'])\n@login_required\ndef account():\n form = UpdateAccountForm()\n if form.validate_on_submit():\n if form.picture.data:\n picture_file = save_picture(form.picture.data)\n current_user.image_file = picture_file\n current_user.username = form.username.data\n current_user.email = form.email.data\n db.session.commit()\n flash('Your account has been updated!', 'success')\n return redirect(url_for('account'))\n elif request.method == 'GET':\n form.username.data = current_user.username\n form.email.data = current_user.email\n image_file = url_for('static', filename='profile_pics/' + current_user.image_file)\n return render_template('account.html', title='Account',\n image_file=image_file, form=form)\n\n\n@app.route(\"/done\")\n@login_required\n\ndef display():\n return redirect('static/output.mp4')\n\n\n#-----------------------Python Code-------------------------------------------# \n\n\n\n@app.route(\"/user\",methods=['GET','POST'])\n@login_required\ndef returnuser(): \n #print(current_user.username)\n #print(current_user.email)\n call([\"python\",\"gymmate/userid.py\"])\n return redirect(\"http://127.0.0.1:5000/\", code=302)\n\n\n@app.route(\"/client\")\n@login_required\ndef client():\n \n try:\n cap = cv2.VideoCapture(1)\n clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n clientsocket.connect(('127.0.0.1', 8083))\n print(current_user.username)\n start=time.time()\n while (time.time()-start)<=120:\n ret,frame = cap.read()\n cv2.imshow('Recording frame',frame)\n cv2.waitKey(1)\n data = pickle.dumps(frame)\n clientsocket.sendall(struct.pack(\"L\", len(data)) + data)\n cap.release()\n\n except:\n print(\"Exception \")\n \n return redirect(\"http://127.0.0.1:5000/sending\", code=302)\n\n\n\n@app.route(\"/Server\")\n@login_required\ndef server():\n call(['python','gymmate/server-video.py'])\n print('Server Running')\n try:\n path1=r\"C:\\Users\\ragha\\Desktop\\Full deployement Code\\Gym Mate\\output.mp4\"\n path2=r\"C:\\Users\\ragha\\Desktop\\Full deployement Code\\Gym Mate\\gymmate\\static\\output.mp4\"\n os.rename(path1,path2)\n shutil.move(path1,path2)\n os.replace(path1,path2)\n except:\n print(\"An exception occured\")\n\n return redirect(\"http://127.0.0.1:5000/\", code=302)","sub_path":"gymmate/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"356712544","text":"from django.http import HttpResponse\nfrom django.shortcuts import render_to_response, redirect\nfrom django.template.context_processors import csrf\nfrom django.utils import translation\nfrom gallery.models import *\n\nfrom .models import *\nfrom contacts.models import Contacts\nfrom feedbacks.models import Feedback\nfrom products.models import ProductBrand, Product\nfrom services.models import Service, Plus\nfrom vacancies.models import Vacancy\nfrom psychologist.models import Psychologist\nfrom project50.models import Pluses, Project\nfrom vacancies.models import Applicant\n# Create your views here.\n\n\ndef main_view(request, context={}):\n context.update(csrf(request))\n context['all_services'] = Service.objects.all()\n context['socials'] = Social.objects.all()\n context['sliders'] = Service.objects.filter(is_slider=True)\n context['sponsors'] = Sponsor.objects.all()\n context['pluses'] = Plus.objects.all()\n try:\n contacts = Contacts.objects.get()\n except Contacts.MultipleObjectsReturned:\n contacts = Contacts.objects.all().last()\n context['contacts'] = contacts\n context['feedbacks'] = Feedback.objects.filter(is_active=True)\n context['products'] = Product.objects.all()\n context['services'] = Service.objects.filter(is_slider=False)\n context['vacancies'] = Vacancy.objects.all()\n context['brand'] = ProductBrand.objects.all()\n context['psychologist'] = Psychologist.objects.all()\n try:\n project = Project.objects.get()\n except Project.MultipleObjectsReturned:\n project = Project.objects.all().last()\n context['project'] = project\n context['project_plus'] = Pluses.objects.all()\n context['applicant'] = Applicant.objects.order_by('-pub_date')[0:3]\n try:\n context['service_buro'] = ServiceBuro.objects.get()\n except ServiceBuro.MultipleObjectsReturned:\n context['service_buro'] = ServiceBuro.objects.last()\n except ServiceBuro.DoesNotExist:\n pass\n try:\n context['psycho_text'] = PsychoText.objects.get()\n except PsychoText.MultipleObjectsReturned:\n context['psycho_text'] = PsychoText.objects.last()\n except PsychoText.DoesNotExist:\n pass\n try:\n context['feedback_text'] = FeedbackText.objects.get()\n except FeedbackText.MultipleObjectsReturned:\n context['feedback_text'] = FeedbackText.objects.last()\n except FeedbackText.DoesNotExist:\n pass\n return render_to_response('index.html', context)\n\n\ndef gallery(request, context={}):\n context.update(csrf(request))\n context['all_services'] = Service.objects.all()\n context['socials'] = Social.objects.all()\n context['sliders'] = Service.objects.filter(is_slider=True)\n context['sponsors'] = Sponsor.objects.all()\n context['pluses'] = Plus.objects.all()\n try:\n contacts = Contacts.objects.get()\n except Contacts.MultipleObjectsReturned:\n contacts = Contacts.objects.all().last()\n context['contacts'] = contacts\n context['event'] = Event.objects.all()\n context['images'] = Images.objects.all()\n return render_to_response('gallery.html', context)\n\n\ndef friends(request, context={}):\n context.update(csrf(request))\n context['all_services'] = Service.objects.all()\n context['socials'] = Social.objects.all()\n context['sponsors'] = Sponsor.objects.all()\n try:\n contacts = Contacts.objects.get()\n except Contacts.MultipleObjectsReturned:\n contacts = Contacts.objects.all().last()\n context['contacts'] = contacts\n return render_to_response('friends.html', context)","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"481358286","text":"from dataSource import Dataset,LEM,CampoVerde,DataSource,SARSource\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cycler import cycler\nclass DatasetStats():\n def __init__(self,dataset):\n self.dataset=dataset\n \n def calcAverageTimeseries(self,ims,mask):\n time_delta=self.dataset.getTimeDelta()\n print(time_delta)\n for channel in range(self.dataset.getBandN()):\n averageTimeseries=[]\n for t_step in range(0,self.dataset.t_len):\n im=ims[t_step,:,:,channel]\n #mask_t=mask[t_step]\n \n #print(\"im shape: {}, mask shape: {}\".format(im.shape,mask.shape))\n im=im.flatten()\n mask_t=mask.flatten()\n #print(\"im shape: {}, mask shape: {}\".format(im.shape,mask.shape))\n\n im=im[mask_t==1] # only train and test pixels (1 and 2)\n averageTimeseries.append(np.average(im))\n averageTimeseries=np.asarray(averageTimeseries)\n plt.figure(channel)\n fig, ax = plt.subplots()\n ax.plot(time_delta,averageTimeseries,marker=\".\")\n ax.set(xlabel='time ID', ylabel='band',title='Image average over time')\n plt.grid()\n print('averageTimeseries',averageTimeseries)\n plt.show()\n def calcAverageTimeseriesPerClass(self,ims,mask,label):\n print(\"Label shape\",label.shape)\n time_delta=self.dataset.getTimeDelta()\n print(time_delta)\n for channel in range(self.dataset.getBandN()):\n averageTimeseries=[]\n plt.figure(channel)\n fig, ax = plt.subplots()\n ax.set_prop_cycle(cycler('color', ['c', 'm', 'y', 'k','b', 'g', 'r']))\n\n# for clss,clss_name in zip([1,2,3,9],['soybean','maize','cotton','soil']):\n for clss,clss_name in zip([1,2,3,7,13],['soybean','maize','cotton','millet','soil']):\n# for clss,clss_name in zip(range(self.dataset.getClassN()),self.dataset.getClassList()):\n averageTimeseries=[]\n for t_step in range(0,self.dataset.t_len):\n # check available classes\n \n im=ims[t_step,:,:,channel]\n label_t=label[t_step]# label is (t,h,w,channel)\n label_t_unique=np.unique(label_t)\n if not (clss in label_t_unique):\n averageTimeseries.append(np.nan)\n continue\n #print(\"Label t shape\",label_t.shape)\n #mask_t=mask[t_step]\n \n #print(\"im shape: {}, mask shape: {}\".format(im.shape,mask.shape))\n im=im.flatten()\n mask=mask.flatten()\n label_t=label_t.flatten()\n #print(\"im shape: {}, mask shape: {}\".format(im.shape,mask.shape))\n \n # only train\n im=im[mask==1]\n label_t=label_t[mask==1]\n\n\n im=im[label_t==clss] # only train and test pixels (1 and 2) from clss\n averageTimeseries.append(np.average(im))\n averageTimeseries=np.asarray(averageTimeseries)\n ax.plot(time_delta,averageTimeseries,marker=\".\",label=clss_name)\n ax.legend()\n print('averageTimeseries',averageTimeseries)\n ax.set(xlabel='time ID', ylabel='band',title='Image average over time')\n plt.grid()\n #\n plt.show()\n \n\n\n\n","sub_path":"dataset/dataset/patches_extract_script/dataset_stats.py","file_name":"dataset_stats.py","file_ext":"py","file_size_in_byte":3603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"461858106","text":"# non-resonant leptogenesis with two decaying sterile neutrino using the Boltzmann equations. Note these kinetic equations do not include off diagonal flavour oscillations. Equations from 1112.4528\nimport ulysses\nimport numpy as np\nfrom odeintw import odeintw\n\nfrom ulysses.numba import jit\n\n@jit\ndef fast_RHS(y0,eps1tt,eps1mm,eps1ee,eps1tm,eps1te,eps1me,eps2tt,eps2mm,eps2ee,eps2tm,eps2te,eps2me,d1,d2,w1,w2,n1eq,n2eq,C):\n N1, N2, Ntt, Nbb = y0\n c1t,c1m,c1e,c2t,c2m,c2e = C\n c1tc = np.conjugate(c1t)\n c1mc = np.conjugate(c1m)\n c1ec = np.conjugate(c1e)\n\n c2tc = np.conjugate(c2t)\n c2mc = np.conjugate(c2m)\n c2ec = np.conjugate(c2e)\n\n #define the different RHSs for each equation\n rhs1 = -d1*(N1-n1eq)\n rhs2 = -d2*(N2-n2eq)\n rhs3 = eps1tt*d1*(N1-n1eq)+eps2tt*d2*(N2-n2eq)-0.5*w1*(2*c1t*c1tc*Ntt) -0.5*w2*(2*c2t*c2tc*Ntt)\n rhs4 = eps1mm*d1*(N1-n1eq)+eps2mm*d2*(N2-n2eq)-0.5*w1*(2*(c1m*c1mc+c1e*c1ec)*Nbb) -0.5*w2*(2*(c2m*c2mc+c2e*c2ec)*Nbb)\n\n RHStemp = [rhs1, rhs2, rhs3, rhs4]\n return RHStemp\n\nclass EtaB_2BE2F(ulysses.ULSBase):\n \"\"\"\n Two-flavoured Boltzmann equation (BE) with two decaying steriles. See arxiv:1112.4528.\n Note these kinetic equations do not include off diagonal flavour\n oscillations.\n \"\"\"\n\n def shortname(self): return \"2BE2F\"\n def flavourindices(self): return [2, 3]\n def flavourlabels(self): return [\"$N_{\\\\tau\\\\tau}$\", \"$N_{\\\\tau\\perp\\\\tau\\perp}$\"]\n\n def RHS(self, y0, z, ETA, _C, K):\n eps1tt,eps1mm,eps1ee,eps1tm,eps1te,eps1me,eps2tt,eps2mm,eps2ee,eps2tm,eps2te,eps2me = ETA\n k1term,k2term = K\n\n if z != self._currz or z == self.zmin:\n self._d1 = np.real(self.D1(k1term, z))\n self._w1 = np.real(self.W1(k1term, z))\n self._d2 = np.real(self.D2(k2term, z))\n self._w2 = np.real(self.W2(k2term, z))\n self._n1eq = self.N1Eq(z)\n self._n2eq = self.N2Eq(z)\n self._currz=z\n\n from ulysses.numba import List\n C=List()\n [C.append(c) for c in _C]\n\n return fast_RHS(y0,eps1tt,eps1mm,eps1ee,eps1tm,eps1te,eps1me,eps2tt,eps2mm,eps2ee,eps2tm,eps2te,eps2me,self._d1,self._d2,self._w1,self._w2,self._n1eq,self._n2eq, C)\n\n\n\n @property\n def EtaB(self):\n #Define fixed quantities for BEs\n _ETA = [\n np.real(self.epsilon(0,1,2,2)),\n np.real(self.epsilon(0,1,2,1)),\n np.real(self.epsilon(0,1,2,0)),\n np.real(self.epsilon(1,0,2,2)),\n np.real(self.epsilon(1,0,2,1)),\n np.real(self.epsilon(1,0,2,0))\n ]\n\n _HT = [\n np.real(self.hterm(2,0)),\n np.real(self.hterm(1,0)),\n np.real(self.hterm(0,0)),\n np.real(self.hterm(2,1)),\n np.real(self.hterm(1,1)),\n np.real(self.hterm(0,1))\n ]\n\n _K = [np.real(self.k1), np.real(self.k2)]\n y0 = np.array([0+0j,0+0j,0+0j,0+0j], dtype=np.complex128)\n\n _ETA = [\n np.real(self.epsilon1ab(2,2)),\n np.real(self.epsilon1ab(1,1)),\n np.real(self.epsilon1ab(0,0)),\n self.epsilon1ab(2,1) ,\n self.epsilon1ab(2,0) ,\n self.epsilon1ab(1,0),\n np.real(self.epsilon2ab(2,2)),\n np.real(self.epsilon2ab(1,1)),\n np.real(self.epsilon2ab(0,0)),\n self.epsilon2ab(2,1) ,\n self.epsilon2ab(2,0) ,\n self.epsilon2ab(1,0),\n ]\n _C = [ self.c1a(2), self.c1a(1), self.c1a(0),\n self.c2a(2), self.c2a(1), self.c2a(0)]\n _K = [np.real(self.k1), np.real(self.k2)]\n\n ys = odeintw(self.RHS, y0, self.zs, args = tuple([_ETA, _C, _K]))\n self.setEvolData(ys)\n return self.ys[-1][-1]\n","sub_path":"ulysses/etab2BE2F.py","file_name":"etab2BE2F.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"117790703","text":"#! python3\n# carSim.py - Traffic light simulation to show where to add assertion to debug program quickly.\n\n# ns = north south, ew = east west\nmarket_2nd = {'ns': 'green', 'ew': 'red'}\nmission_16th = {'ns': 'red', 'ew': 'green'}\n\ndef switchLights(stoplight):\n for key in stoplight.keys():\n if stoplight[key] == 'green':\n stoplight[key] = 'yellow'\n elif stoplight[key] == 'yellow':\n stoplight[key] = 'red'\n elif stoplight[key] == 'red':\n stoplight[key] = 'green'\n\n # added to debug the virtual cars crashing issue....\n assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight)\nswitchLights(market_2nd)\n","sub_path":"carSim.py","file_name":"carSim.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"538247593","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport os\nimport pickle\nfrom math import sqrt\n\nimport datetime\nimport time\nimport collections\nimport operator\n\nimport edtime\nimport edrconfig\nimport edrlog\nimport lrucache\nimport edsmserver\nfrom edentities import EDBounty\nfrom edri18n import _, _c, _edr\n\nEDRLOG = edrlog.EDRLog()\n\nclass EDRSystems(object):\n EDR_SYSTEMS_CACHE = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), 'cache/systems.v2.p')\n EDSM_SYSTEMS_CACHE = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), 'cache/edsm_systems.v2.p')\n EDR_NOTAMS_CACHE = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), 'cache/notams.v2.p')\n EDR_SITREPS_CACHE = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), 'cache/sitreps.v2.p')\n EDR_TRAFFIC_CACHE = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), 'cache/traffic.v2.p')\n EDR_CRIMES_CACHE = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), 'cache/crimes.v2.p')\n\n def __init__(self, server):\n edr_config = edrconfig.EDRConfig()\n\n try:\n with open(self.EDR_SYSTEMS_CACHE, 'rb') as handle:\n self.systems_cache = pickle.load(handle)\n except:\n self.systems_cache = lrucache.LRUCache(edr_config.lru_max_size(),\n edr_config.systems_max_age())\n\n try:\n with open(self.EDR_NOTAMS_CACHE, 'rb') as handle:\n self.notams_cache = pickle.load(handle)\n except:\n self.notams_cache = lrucache.LRUCache(edr_config.lru_max_size(),\n edr_config.notams_max_age())\n\n try:\n with open(self.EDR_SITREPS_CACHE, 'rb') as handle:\n self.sitreps_cache = pickle.load(handle)\n except:\n self.sitreps_cache = lrucache.LRUCache(edr_config.lru_max_size(),\n edr_config.sitreps_max_age())\n\n try:\n with open(self.EDR_CRIMES_CACHE, 'rb') as handle:\n self.crimes_cache = pickle.load(handle)\n except:\n self.crimes_cache = lrucache.LRUCache(edr_config.lru_max_size(),\n edr_config.crimes_max_age())\n\n try:\n with open(self.EDR_TRAFFIC_CACHE, 'rb') as handle:\n self.traffic_cache = pickle.load(handle)\n except:\n self.traffic_cache = lrucache.LRUCache(edr_config.lru_max_size(),\n edr_config.traffic_max_age())\n\n try:\n with open(self.EDSM_SYSTEMS_CACHE, 'rb') as handle:\n self.edsm_systems_cache = pickle.load(handle)\n except:\n self.edsm_systems_cache = lrucache.LRUCache(edr_config.lru_max_size(),\n edr_config.edsm_systems_max_age())\n\n self.reports_check_interval = edr_config.reports_check_interval()\n self.notams_check_interval = edr_config.notams_check_interval()\n self.timespan = edr_config.sitreps_timespan()\n self.server = server\n self.edsm_server = edsmserver.EDSMServer()\n\n def system_id(self, star_system, may_create=False):\n if not star_system:\n return None\n sid = self.systems_cache.get(star_system.lower())\n if sid:\n EDRLOG.log(u\"System {} is in the cache with id={}\".format(star_system, sid), \"DEBUG\")\n return sid\n\n sid = self.server.system_id(star_system, may_create)\n if sid:\n self.systems_cache.set(star_system.lower(), sid)\n EDRLOG.log(u\"Cached {}'s id={}\".format(star_system, sid), \"DEBUG\")\n return sid\n\n return None\n\n def persist(self):\n with open(self.EDR_SYSTEMS_CACHE, 'wb') as handle:\n pickle.dump(self.systems_cache, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open(self.EDR_NOTAMS_CACHE, 'wb') as handle:\n pickle.dump(self.notams_cache, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n with open(self.EDR_SITREPS_CACHE, 'wb') as handle:\n pickle.dump(self.sitreps_cache, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n with open(self.EDR_TRAFFIC_CACHE, 'wb') as handle:\n pickle.dump(self.traffic_cache, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open(self.EDR_CRIMES_CACHE, 'wb') as handle:\n pickle.dump(self.crimes_cache, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open(self.EDSM_SYSTEMS_CACHE, 'wb') as handle:\n pickle.dump(self.edsm_systems_cache, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n def distance(self, source_system, destination_system):\n if source_system == destination_system:\n return 0\n source = self.edsm_systems_cache.get(source_system.lower())\n destination = self.edsm_systems_cache.get(destination_system.lower())\n if not source:\n source = self.edsm_server.system(source_system)\n if source:\n self.edsm_systems_cache.set(source_system.lower(), source)\n if not destination:\n destination = self.edsm_server.system(destination_system)\n if destination:\n self.edsm_systems_cache.set(destination_system.lower(), destination)\n if source and destination:\n source_coords = source[0][\"coords\"]\n dest_coords = destination[0][\"coords\"] \n return sqrt((dest_coords[\"x\"] - source_coords[\"x\"])^2 + (dest_coords[\"y\"] - source_coords[\"y\"])^2 + (dest_coords[\"z\"] - source_coords[\"z\"])^2)\n raise ValueError('Unknown system')\n\n def timespan_s(self):\n return edtime.EDTime.pretty_print_timespan(self.timespan, short=True, verbose=True)\n\n def crimes_t_minus(self, star_system):\n if self.has_sitrep(star_system):\n system_reports = self.sitreps_cache.get(self.system_id(star_system))\n if \"latestCrime\" in system_reports:\n return edtime.EDTime.t_minus(system_reports[\"latestCrime\"])\n return None\n\n def traffic_t_minus(self, star_system):\n if self.has_sitrep(star_system):\n system_reports = self.sitreps_cache.get(self.system_id(star_system))\n if \"latestTraffic\" in system_reports:\n return edtime.EDTime.t_minus(system_reports[\"latestTraffic\"])\n return None\n \n def has_sitrep(self, star_system):\n if not star_system:\n return False\n self.__update_if_stale()\n sid = self.system_id(star_system)\n return self.sitreps_cache.has_key(sid)\n\n def has_notams(self, star_system):\n self.__update_if_stale()\n sid = self.system_id(star_system)\n return self.notams_cache.has_key(sid)\n\n def __has_active_notams(self, system_id):\n self.__update_if_stale()\n if not self.notams_cache.has_key(system_id):\n return False\n return len(self.__active_notams_for_sid(system_id)) > 0\n\n def active_notams(self, star_system):\n if self.has_notams(star_system):\n return self.__active_notams_for_sid(self.system_id(star_system))\n return None\n\n def __active_notams_for_sid(self, system_id):\n active_notams = []\n entry = self.notams_cache.get(system_id)\n all_notams = entry.get(\"NOTAMs\", None)\n js_epoch_now = edtime.EDTime.js_epoch_now()\n for notam in all_notams:\n active = True\n if \"from\" in notam:\n active &= notam[\"from\"] <= js_epoch_now\n if \"until\" in notam:\n active &= js_epoch_now <= notam[\"until\"]\n if active and \"text\" in notam:\n EDRLOG.log(u\"Active NOTAM: {}\".format(notam[\"text\"]), \"DEBUG\")\n active_notams.append(_edr(notam[\"text\"]))\n elif active and \"l10n\" in notam:\n EDRLOG.log(u\"Active NOTAM: {}\".format(notam[\"l10n\"][\"default\"]), \"DEBUG\")\n active_notams.append(_edr(notam[\"l10n\"]))\n return active_notams\n\n def systems_with_active_notams(self):\n summary = []\n self.__update_if_stale()\n systems_ids = self.notams_cache.keys()\n for sid in systems_ids:\n entry = self.notams_cache.get(sid)\n if not entry:\n continue \n star_system = entry.get(\"name\", None)\n if star_system and self.__has_active_notams(sid):\n summary.append(star_system)\n\n return summary\n\n def has_recent_activity(self, system_name):\n return self.has_recent_traffic(system_name) or self.has_recent_crimes(system_name) or self.has_recent_outlaws(system_name)\n\n def systems_with_recent_activity(self):\n systems_with_recent_crimes = {}\n systems_with_recent_traffic = {}\n systems_with_recent_outlaws = {}\n self.__update_if_stale()\n systems_ids = self.sitreps_cache.keys()\n for sid in systems_ids:\n sitrep = self.sitreps_cache.get(sid)\n star_system = sitrep.get(\"name\", None) if sitrep else None\n if self.has_recent_outlaws(star_system):\n systems_with_recent_outlaws[star_system] = sitrep[\"latestOutlaw\"]\n elif self.has_recent_crimes(star_system):\n systems_with_recent_crimes[star_system] = sitrep[\"latestCrime\"]\n elif self.has_recent_traffic(star_system):\n systems_with_recent_traffic[star_system] = sitrep[\"latestTraffic\"]\n\n summary = {}\n summary_outlaws = []\n systems_with_recent_outlaws = sorted(systems_with_recent_outlaws.items(), key=lambda t: t[1], reverse=True)\n for system in systems_with_recent_outlaws:\n summary_outlaws.append(u\"{} {}\".format(system[0], edtime.EDTime.t_minus(system[1], short=True)))\n if summary_outlaws:\n # Translators: this is for the sitreps feature; it's the title of a section to show systems with sighted outlaws \n summary[_c(u\"sitreps section|Outlaws\")] = summary_outlaws\n\n summary_crimes = []\n systems_with_recent_crimes = sorted(systems_with_recent_crimes.items(), key=lambda t: t[1], reverse=True)\n for system in systems_with_recent_crimes:\n summary_crimes.append(u\"{} {}\".format(system[0], edtime.EDTime.t_minus(system[1], short=True)))\n if summary_crimes:\n # Translators: this is for the sitreps feature; it's the title of a section to show systems with reported crimes\n summary[_c(u\"sitreps section|Crimes\")] = summary_crimes\n\n summary_traffic = []\n systems_with_recent_traffic = sorted(systems_with_recent_traffic.items(), key=lambda t: t[1], reverse=True)\n for system in systems_with_recent_traffic:\n summary_traffic.append(u\"{} {}\".format(system[0], edtime.EDTime.t_minus(system[1], short=True)))\n if summary_traffic:\n # Translators: this is for the sitreps feature; it's the title of a section to show systems with traffic\n summary[_c(u\"sitreps section|Traffic\")] = summary_traffic\n\n return summary\n\n def has_recent_crimes(self, star_system):\n if self.has_sitrep(star_system):\n system_reports = self.sitreps_cache.get(self.system_id(star_system))\n if system_reports is None or \"latestCrime\" not in system_reports:\n return False\n\n edr_config = edrconfig.EDRConfig()\n return self.is_recent(system_reports[\"latestCrime\"],\n edr_config.crimes_recent_threshold())\n return False\n\n def has_recent_outlaws(self, star_system):\n if self.has_sitrep(star_system):\n system_reports = self.sitreps_cache.get(self.system_id(star_system))\n if system_reports is None or \"latestOutlaw\" not in system_reports:\n return False\n\n edr_config = edrconfig.EDRConfig()\n return self.is_recent(system_reports[\"latestOutlaw\"],\n edr_config.outlaws_recent_threshold())\n return False\n\n def recent_crimes(self, star_system):\n sid = self.system_id(star_system)\n if not sid:\n return None\n recent_crimes = None\n if self.has_recent_crimes(star_system):\n if not self.crimes_cache.has_key(sid) or (self.crimes_cache.has_key(sid) and self.crimes_cache.is_stale(sid)):\n recent_crimes = self.server.recent_crimes(sid, self.timespan)\n if recent_crimes:\n self.crimes_cache.set(sid, recent_crimes)\n else:\n recent_crimes = self.crimes_cache.get(sid)\n return recent_crimes\n\n def has_recent_traffic(self, star_system):\n if self.has_sitrep(star_system):\n system_reports = self.sitreps_cache.get(self.system_id(star_system))\n if system_reports is None or \"latestTraffic\" not in system_reports:\n return False\n\n edr_config = edrconfig.EDRConfig()\n return self.is_recent(system_reports[\"latestTraffic\"],\n edr_config.traffic_recent_threshold())\n return False\n\n def recent_traffic(self, star_system):\n sid = self.system_id(star_system)\n if not sid:\n return None\n recent_traffic = None\n if self.has_recent_traffic(star_system):\n if not self.traffic_cache.has_key(sid) or (self.traffic_cache.has_key(sid) and self.traffic_cache.is_stale(sid)):\n recent_traffic = self.server.recent_traffic(sid, self.timespan)\n if recent_traffic:\n self.traffic_cache.set(sid, recent_traffic)\n else:\n recent_traffic = self.traffic_cache.get(sid)\n return recent_traffic\n\n def summarize_recent_activity(self, star_system):\n #TODO refactor/simplify this mess ;)\n summary = {}\n wanted_cmdrs = {}\n if self.has_recent_traffic(star_system):\n summary_sighted = []\n recent_traffic = self.recent_traffic(star_system)\n if recent_traffic is not None: # Should always be true... simplify. TODO\n summary_traffic = collections.OrderedDict()\n for traffic in recent_traffic:\n previous_timestamp = summary_traffic.get(traffic[\"cmdr\"], None)\n if traffic[\"timestamp\"] < previous_timestamp:\n continue\n karma = traffic.get(\"karma\", 0)\n bounty = EDBounty(traffic.get(\"bounty\", 0))\n if karma < 0 or bounty.is_significant():\n wanted_cmdrs[traffic[\"cmdr\"]] = [ traffic[\"timestamp\"], karma ]\n else:\n summary_traffic[traffic[\"cmdr\"]] = traffic[\"timestamp\"]\n for cmdr in summary_traffic:\n summary_sighted.append(u\"{} {}\".format(cmdr, edtime.EDTime.t_minus(summary_traffic[cmdr], short=True)))\n if summary_sighted:\n # Translators: this is for the sitrep feature; it's a section to show sighted cmdrs in the system of interest\n summary[_c(u\"sitrep section|Sighted\")] = summary_sighted\n \n if self.has_recent_crimes(star_system):\n summary_interdictors = []\n summary_destroyers = []\n recent_crimes = self.recent_crimes(star_system)\n if recent_crimes is not None: # Should always be true... simplify. TODO\n summary_crimes = collections.OrderedDict()\n for crime in recent_crimes:\n lead_name = crime[\"criminals\"][0][\"name\"]\n if lead_name not in summary_crimes or crime[\"timestamp\"] > summary_crimes[lead_name][0]: \n summary_crimes[lead_name] = [crime[\"timestamp\"], crime[\"offence\"]]\n for criminal in crime[\"criminals\"]:\n previous_timestamp = wanted_cmdrs[criminal[\"name\"]][0] if criminal[\"name\"] in wanted_cmdrs else None\n if previous_timestamp > crime[\"timestamp\"]:\n continue\n karma = criminal.get(\"karma\", 0)\n bounty = EDBounty(traffic.get(\"bounty\", 0))\n if karma < 0 or bounty.is_significant():\n wanted_cmdrs[criminal[\"name\"]] = [ crime[\"timestamp\"], karma]\n for criminal in summary_crimes:\n if summary_crimes[criminal][1] == \"Murder\":\n summary_destroyers.append(u\"{} {}\".format(criminal, edtime.EDTime.t_minus(summary_crimes[criminal][0], short=True)))\n elif summary_crimes[criminal][1] in [\"Interdicted\", \"Interdiction\"]:\n summary_interdictors.append(u\"{} {}\".format(criminal, edtime.EDTime.t_minus(summary_crimes[criminal][0], short=True)))\n if summary_interdictors:\n # Translators: this is for the sitrep feature; it's a section to show cmdrs who have been reported as interdicting another cmdr in the system of interest\n summary[_c(u\"sitrep section|Interdictors\")] = summary_interdictors\n if summary_destroyers:\n # Translators: this is for the sitrep feature; it's a section to show cmdrs who have been reported as responsible for destroying the ship of another cmdr in the system of interest; use a judgement-neutral term\n summary[_c(u\"sitreps section|Destroyers\")] = summary_destroyers\n \n wanted_cmdrs = sorted(wanted_cmdrs.items(), key=operator.itemgetter(1), reverse=True)\n if wanted_cmdrs:\n summary_wanted = []\n for wanted in wanted_cmdrs:\n summary_wanted.append(u\"{} {}\".format(wanted[0], edtime.EDTime.t_minus(wanted[1][0], short=True)))\n if summary_wanted:\n # Translators: this is for the sitrep feature; it's a section to show wanted cmdrs who have been sighted in the system of interest\n summary[_c(u\"sitreps section|Outlaws\")] = summary_wanted\n\n return summary\n\n def is_recent(self, timestamp, max_age):\n if timestamp is None:\n return False\n return (edtime.EDTime.js_epoch_now() - timestamp) / 1000 <= max_age\n\n def evict(self, star_system):\n try:\n del self.systems_cache[star_system]\n except KeyError:\n pass\n\n\n def __are_reports_stale(self):\n return self.__is_stale(self.sitreps_cache.last_updated, self.reports_check_interval)\n\n def __are_notams_stale(self):\n return self.__is_stale(self.notams_cache.last_updated, self.notams_check_interval)\n\n def __is_stale(self, updated_at, max_age):\n if updated_at is None:\n return True\n now = datetime.datetime.now()\n epoch_now = time.mktime(now.timetuple())\n epoch_updated = time.mktime(updated_at.timetuple())\n\n return (epoch_now - epoch_updated) > max_age\n\n def __update_if_stale(self):\n updated = False\n if self.__are_reports_stale():\n missing_seconds = self.timespan\n now = datetime.datetime.now()\n if self.sitreps_cache.last_updated:\n missing_seconds = min(self.timespan, (now - self.sitreps_cache.last_updated).total_seconds())\n sitreps = self.server.sitreps(missing_seconds)\n if sitreps:\n for system_id in sitreps:\n self.sitreps_cache.set(system_id, sitreps[system_id])\n self.sitreps_cache.last_updated = now\n updated = True\n\n if self.__are_notams_stale():\n missing_seconds = self.timespan\n now = datetime.datetime.now()\n if self.notams_cache.last_updated:\n missing_seconds = min(self.timespan, (now - self.notams_cache.last_updated).total_seconds())\n\n notams = self.server.notams(missing_seconds)\n if notams:\n for system_id in notams:\n self.notams_cache.set(system_id, notams[system_id])\n self.notams_cache.last_updated = now\n updated = True\n\n return updated","sub_path":"edr/edrsystems.py","file_name":"edrsystems.py","file_ext":"py","file_size_in_byte":20339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"638107654","text":"from haven import haven_chk as hc\nfrom haven import haven_results as hr\nfrom haven import haven_utils as hu\nimport torch\nimport torchvision\nimport tqdm\nimport pandas as pd\nimport pprint\nimport itertools\nimport os\nimport pylab as plt\nimport exp_configs\nimport time\nimport numpy as np\n\nfrom src import models\nfrom src import datasets\nfrom src import utils as ut\nfrom torchsummary import summary\n\nimport argparse\n\nfrom torch.utils.data import sampler\nfrom torch.utils.data.sampler import RandomSampler\nfrom torch.backends import cudnn\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader\nimport copy, shutil\ncudnn.benchmark = True\n\n\n\ndef test(exp_dict, savedir_base, datadir, num_workers=0, scan_id=None,savedir=''):\n # bookkeepting stuff\n # ==================\n model_path = os.path.join(savedir, 'model_best.pth')\n # Dataset\n # ==================\n # val set\n test_set = datasets.get_dataset(dataset_dict=exp_dict[\"dataset\"],\n split=\"val\",\n datadir=datadir,\n exp_dict=exp_dict,\n dataset_size=exp_dict['dataset_size'])\n if str(scan_id) != 'None':\n test_set.active_data = test_set.get_scan(scan_id)\n test_sampler = torch.utils.data.SequentialSampler(test_set)\n test_loader = DataLoader(test_set,\n sampler=test_sampler,\n batch_size=1,\n collate_fn=ut.collate_fn,\n num_workers=num_workers)\n\n # Model\n # ==================\n # chk = torch.load('best_model.ckpt')\n if torch.cuda.is_available():\n model = models.get_model(model_dict=exp_dict['model'],\n exp_dict=exp_dict,\n train_set=test_set).cuda()\n else:\n model = models.get_model(model_dict=exp_dict['model'],\n exp_dict=exp_dict,\n train_set=test_set).cpu()\n epoch = -1\n\n\n if str(model_path) != 'None':\n model_path = model_path\n model.load_state_dict(hu.torch_load(model_path))\n else:\n try:\n exp_dict_train = copy.deepcopy(exp_dict)\n del exp_dict_train['test_mode']\n savedir_train = os.path.join(savedir_base, hu.hash_dict(exp_dict_train))\n model_path = os.path.join(savedir_train, \"model_best.pth\")\n score_list = hu.load_pkl(os.path.join(savedir_train, 'score_list_best.pkl'))\n epoch = score_list[-1]['epoch']\n print('Loaded model at epoch %d with score %.3f' % epoch)\n model.load_state_dict(hu.torch_load(model_path))\n except:\n pass\n\n # print(model)\n pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n print(pytorch_total_params)\n with open(os.path.join(savedir, \"params.txt\"), \"w\") as f:\n f.write(str(pytorch_total_params))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-e', '--exp_group_list', default='open_source_pspnet',nargs=\"+\")\n parser.add_argument('-sb', '--savedir_base', default='CovidSeg/save')\n parser.add_argument('-d', '--datadir', default='CovidSeg/dataset')\n parser.add_argument(\"-r\", \"--reset\", default=1, type=int)\n parser.add_argument(\"-ei\", \"--exp_id\", default='unetplus_timm-resnest26d')\n parser.add_argument(\"-j\", \"--run_jobs\", default=0, type=int)\n parser.add_argument(\"-nw\", \"--num_workers\", type=int, default=0)\n parser.add_argument(\"-ec\", \"--encoder\", default='') # timm-efficientnet-b0\n parser.add_argument(\"-si\", \"--scan_id\", type=str, default=None)\n\n args = parser.parse_args()\n\n # Collect experiments\n # -------------------\n if args.exp_id is not None:\n # select one experiment\n savedir = os.path.join(args.savedir_base, args.exp_id)\n exp_dict = hu.load_json(os.path.join(savedir, 'exp_dict.json'))\n\n exp_list = [exp_dict]\n\n else:\n # select exp group\n exp_list = []\n for exp_group_name in [args.exp_group_list]:\n exp_list += exp_configs.EXP_GROUPS[exp_group_name]\n\n # format them for test\n for exp_dict in exp_list:\n exp_dict['test_mode'] = 1\n\n # Run experiments or View them\n # ----------------------------\n for exp_dict in exp_list:\n # do trainval\n test(exp_dict=exp_dict,\n savedir_base=args.savedir_base,\n datadir=args.datadir,\n num_workers=args.num_workers,\n scan_id=args.scan_id,\n savedir=savedir)\n","sub_path":"CovidSeg/count_params.py","file_name":"count_params.py","file_ext":"py","file_size_in_byte":4664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"16639249","text":"# N개의 수로 이뤄진 수열 A1,A2, ... An\n# 수와 수 사이에 끼워넣을 수 있는 N-1개의 연산자 + - * /\n# 숫자의 순서는 바꿀 수 없다.\n\n# 식의 계산은 연산 우선순위를 무시하고 앞에서부터 계산한다.\n# 나숫셈은 몫으로 결과\n# 음수를 양수로 나눌 때는 양수로 바꾼 뒤 몫을 음수로 바꾼다.\n\n# 최대, 최소\n\nimport sys\n\ninput = sys.stdin.readline\nN = int(input())\nnum = list(map(int, input().split()))\nop = list(map(int, input().split()))\n\nmaximum = -1e9\nminimum = 1e9\n\ndef dfs(depth, total, plus, minus, multiply, divide):\n global maximum, minimum\n if depth==N:\n maximum = max(total, maximum)\n minimum = min(total, minimum)\n return\n if plus:\n dfs(depth+1, total+num[depth], plus-1, minus, multiply, divide)\n if minus:\n dfs(depth + 1, total - num[depth], plus, minus-1, multiply, divide)\n if multiply:\n dfs(depth + 1, total * num[depth], plus, minus, multiply -1, divide)\n if divide:\n dfs(depth + 1, int(total / num[depth]), plus, minus, multiply, divide-1)\n\ndfs(1, num[0], op[0], op[1], op[2], op[3])\n\n\n\n\n\"\"\"\nimport sys\nfrom itertools import permutations\n\ninput = sys.stdin.readline\nN = int(input())\nnum = list(map(int, input().split()))\nop_num = list(map(int, input().split()))\nop_list = ['+', '-', '*', '/']\nop = []\n\nfor k in range(len(op_num)):\n for i in range(op_num[k]):\n op.append(op_list[k])\n\nmaximum = -1e9\nminimum = 1e9\n\ndef solve():\n global maximum, minimum\n for case in permutations(op, N-1):\n total = num[0]\n for r in range(1, N):\n if case[r-1] == '+':\n total += num[r]\n elif case[r-1] == '-':\n total -= num[r]\n elif case[r-1] == '*':\n total *= num[r]\n else:\n total = int(total/num[r])\n if total > maximum:\n maximum = total\n if total < minimum:\n minimum = total\n\nsolve()\nprint(maximum)\nprint(minimum)\n\"\"\"\n\n\n\n# from itertools import permutations, combinations\n#\n# N = int(input())\n# data = list(map(int, input().split()))\n# calculate_count = list(map(int, input().split()))\n# cheat = {\n# 0: '+',\n# 1: '-',\n# 2: '*',\n# 3: '/',\n# }\n# calculate = []\n# i = 0\n# for count in calculate_count:\n# if count == 0:\n# i += 1\n# continue\n# calculate.append(cheat[i] * count)\n# i += 1\n# print(calculate)\n#\n# value_result=[]\n# result = data[0]\n# i = 1\n# for case in permutations(calculate, sum(calculate_count)):\n# for calu in case:\n# if calu == \"+\":\n# result += data[i]\n# elif calu == \"-\":\n# result -= data[i]\n# elif calu == \"*\":\n# result *= data[i]\n# else:\n# if result >= 0:\n# result = result // data[i]\n# else:\n# result = -(-result // data[i])\n# value_result.append(result)\n#\n# print(value_result)","sub_path":"약점체크/연산자 끼워넣기.py","file_name":"연산자 끼워넣기.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"503368232","text":"# Author: Martin McBride\n# Created: 2019-06-04\n# Copyright (C) 2018, Martin McBride\n# License: MIT\n\nimport colorsys\nimport itertools\n\ncssColors = {\n\"indianred\":(205,92,92),\n\"lightcoral\":(240,128,128),\n\"salmon\":(250,128,114),\n\"darksalmon\":(233,150,122),\n\"lightsalmon\":(255,160,122),\n\"crimson\":(220,20,60),\n\"red\":(255,0,0),\n\"firebrick\":(178,34,34),\n\"darkred\":(139,0,0),\n\"pink\":(255,192,203),\n\"lightpink\":(255,182,193),\n\"hotpink\":(255,105,180),\n\"deeppink\":(255,20,147),\n\"mediumvioletred\":(199,21,133),\n\"palevioletred\":(219,112,147),\n\"coral\":(255,127,80),\n\"tomato\":(255,99,71),\n\"orangered\":(255,69,0),\n\"darkorange\":(255,140,0),\n\"orange\":(255,165,0),\n\"gold\":(255,215,0),\n\"yellow\":(255,255,0),\n\"lightyellow\":(255,255,224),\n\"lemonchiffon\":(255,250,205),\n\"lightgoldenrodyellow\":(250,250,210),\n\"papayawhip\":(255,239,213),\n\"moccasin\":(255,228,181),\n\"peachpuff\":(255,218,185),\n\"palegoldenrod\":(238,232,170),\n\"khaki\":(240,230,140),\n\"darkkhaki\":(189,183,107),\n\"lavender\":(230,230,250),\n\"thistle\":(216,191,216),\n\"plum\":(221,160,221),\n\"violet\":(238,130,238),\n\"orchid\":(218,112,214),\n\"fuchsia\":(255,0,255),\n\"magenta\":(255,0,255),\n\"mediumorchid\":(186,85,211),\n\"mediumpurple\":(147,112,219),\n\"blueviolet\":(138,43,226),\n\"darkviolet\":(148,0,211),\n\"darkorchid\":(153,50,204),\n\"darkmagenta\":(139,0,139),\n\"purple\":(128,0,128),\n\"rebeccapurple\":(102,51,153),\n\"indigo\":(75,0,130),\n\"mediumslateblue\":(123,104,238),\n\"slateblue\":(106,90,205),\n\"darkslateblue\":(72,61,139),\n\"greenyellow\":(173,255,47),\n\"chartreuse\":(127,255,0),\n\"lawngreen\":(124,252,0),\n\"lime\":(0,255,0),\n\"limegreen\":(50,205,50),\n\"palegreen\":(152,251,152),\n\"lightgreen\":(144,238,144),\n\"mediumspringgreen\":(0,250,154),\n\"springgreen\":(0,255,127),\n\"mediumseagreen\":(60,179,113),\n\"seagreen\":(46,139,87),\n\"forestgreen\":(34,139,34),\n\"green\":(0,128,0),\n\"darkgreen\":(0,100,0),\n\"yellowgreen\":(154,205,50),\n\"olivedrab\":(107,142,35),\n\"olive\":(128,128,0),\n\"darkolivegreen\":(85,107,47),\n\"mediumaquamarine\":(102,205,170),\n\"darkseagreen\":(143,188,143),\n\"lightseagreen\":(32,178,170),\n\"darkcyan\":(0,139,139),\n\"teal\":(0,128,128),\n\"aqua\":(0,255,255),\n\"cyan\":(0,255,255),\n\"lightcyan\":(224,255,255),\n\"paleturquoise\":(175,238,238),\n\"aquamarine\":(127,255,212),\n\"turquoise\":(64,224,208),\n\"mediumturquoise\":(72,209,204),\n\"darkturquoise\":(0,206,209),\n\"cadetblue\":(95,158,160),\n\"steelblue\":(70,130,180),\n\"lightsteelblue\":(176,196,222),\n\"powderblue\":(176,224,230),\n\"lightblue\":(173,216,230),\n\"skyblue\":(135,206,235),\n\"lightskyblue\":(135,206,250),\n\"deepskyblue\":(0,191,255),\n\"dodgerblue\":(30,144,255),\n\"cornflowerblue\":(100,149,237),\n\"royalblue\":(65,105,225),\n\"blue\":(0,0,255),\n\"mediumblue\":(0,0,205),\n\"darkblue\":(0,0,139),\n\"navy\":(0,0,128),\n\"midnightblue\":(25,25,112),\n\"cornsilk\":(255,248,220),\n\"blanchedalmond\":(255,235,205),\n\"bisque\":(255,228,196),\n\"navajowhite\":(255,222,173),\n\"wheat\":(245,222,179),\n\"burlywood\":(222,184,135),\n\"tan\":(210,180,140),\n\"rosybrown\":(188,143,143),\n\"sandybrown\":(244,164,96),\n\"goldenrod\":(218,165,32),\n\"darkgoldenrod\":(184,134,11),\n\"peru\":(205,133,63),\n\"chocolate\":(210,105,30),\n\"saddlebrown\":(139,69,19),\n\"sienna\":(160,82,45),\n\"brown\":(165,42,42),\n\"maroon\":(128,0,0),\n\"white\":(255,255,255),\n\"snow\":(255,250,250),\n\"honeydew\":(240,255,240),\n\"mintcream\":(245,255,250),\n\"azure\":(240,255,255),\n\"aliceblue\":(240,248,255),\n\"ghostwhite\":(248,248,255),\n\"whitesmoke\":(245,245,245),\n\"seashell\":(255,245,238),\n\"beige\":(245,245,220),\n\"oldlace\":(253,245,230),\n\"floralwhite\":(255,250,240),\n\"ivory\":(255,255,240),\n\"antiquewhite\":(250,235,215),\n\"linen\":(250,240,230),\n\"lavenderblush\":(255,240,245),\n\"mistyrose\":(255,228,225),\n\"gainsboro\":(220,220,220),\n\"lightgray\":(211,211,211),\n\"lightgrey\":(211,211,211),\n\"silver\":(192,192,192),\n\"darkgray\":(169,169,169),\n\"darkgrey\":(169,169,169),\n\"gray\":(128,128,128),\n\"grey\":(128,128,128),\n\"dimgray\":(105,105,105),\n\"dimgrey\":(105,105,105),\n\"lightslategray\":(119,136,153),\n\"lightslategrey\":(119,136,153),\n\"slategray\":(112,128,144),\n\"slategrey\":(112,128,144),\n\"darkslategray\":(47,79,79),\n\"darkslategrey\":(47,79,79),\n\"black\":(0,0,0),\n}\n\nclass Color():\n '''\n Holds a color value.\n\n Color is stored as a tuple (r, g, b, a), where each channel has a value between 0 and 1.\n\n Colour can be initialised with:\n - a grey value\n - a grey value + an alpha\n - r, g and b values (alpha defaults to 1)\n - r, g, b and a values\n - a CSS color name as a string (alpha defaults to 1)\n - a CSS color name as a string plus an alpha value (0 to 1)\n\n Color objects are immutable.\n\n get_rgb, get_rgba gets the colour values as a 3- or 4-tuple\n\n of_hsl, of_hsla creates a new Color from hsl values (color values are stored as RGB)\n\n get_r gets the red value (similar for b, g, a, h, s, l). h, s and l values are obtained by converting from rgb\n\n with_r creates a new Color from an existing colour by setting the r value (similar for b, g, a, h, s, l). For\n h, s, l values, the color is converted to hsl, modified, then converted back to rgb.\n\n with_r_factor creates a new Color from an existing colour by multiplying the r value by a factor. It is\n equivalent to with_r(get_r()*factor). Similar for b, g, a, h, s, l\n\n '''\n\n def __init__(self, *args):\n if len(args) == 1:\n if args[0] in cssColors:\n self.color = tuple([x/255 for x in cssColors[args[0]]]) + (1,)\n else:\n g = Color.clamp(args[0])\n self.color = (g,)*3 + (1,)\n elif len(args) == 2:\n if args[0] in cssColors:\n self.color = tuple([x/255 for x in cssColors[args[0]]]) + (args[1],)\n else:\n g = Color.clamp(args[0])\n a = Color.clamp(args[1])\n self.color = (g,) * 3 + (a,)\n elif len(args) == 3:\n self.color = tuple([Color.clamp(x) for x in args]) + (1,)\n elif len(args) == 4:\n self.color = tuple([Color.clamp(x) for x in args])\n else:\n raise ValueError(\"Color takes 1, 2, 3 or 4 arguments\")\n\n @staticmethod\n def of_hsl(h, s, l):\n h = Color.clamp(h)\n s = Color.clamp(s)\n l = Color.clamp(l)\n r, g, b = colorsys.hls_to_rgb(h, l, s)\n return Color(r, g, b)\n\n @staticmethod\n def of_hsla(h, s, l, a):\n h = Color.clamp(h)\n s = Color.clamp(s)\n l = Color.clamp(l)\n a = Color.clamp(a)\n r, g, b = colorsys.hls_to_rgb(h, l, s)\n return Color(r, g, b, a)\n\n @property\n def rgb(self):\n return tuple(self.color[:3])\n\n @property\n def rgba(self):\n return tuple(self.color)\n\n @property\n def r(self):\n return self.color[0]\n\n def with_r(self, newval):\n newval = Color.clamp(newval)\n return Color(newval, self.color[1], self.color[2], self.color[3])\n\n def with_r_factor(self, factor):\n return Color(self.color[0]*factor, self.color[1], self.color[2], self.color[3])\n\n @property\n def g(self):\n return self.color[1]\n\n def with_g(self, newval):\n newval = Color.clamp(newval)\n return Color(self.color[0], newval, self.color[2], self.color[3])\n\n def with_g_factor(self, factor):\n return Color(self.color[0], self.color[1]*factor, self.color[2], self.color[3])\n\n @property\n def b(self):\n return self.color[2]\n\n def with_b(self, newval):\n newval = Color.clamp(newval)\n return Color(self.color[0], self.color[1], newval, self.color[3])\n\n def with_b_factor(self, factor):\n return Color(self.color[0], self.color[1], self.color[2]*factor, self.color[3])\n\n @property\n def a(self):\n return self.color[3]\n\n def with_a(self, newval):\n newval = Color.clamp(newval)\n return Color(self.color[0], self.color[1], self.color[2], newval)\n\n def with_a_factor(self, factor):\n return Color(self.color[0], self.color[1], self.color[2], self.color[3]*factor)\n\n @property\n def h(self):\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n return h\n\n def with_h(self, newval):\n newval = Color.clamp(newval)\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n r, g, b = colorsys.hls_to_rgb(newval, l, s)\n return Color(r, g, b, self.color[3])\n\n def with_h_factor(self, factor):\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n r, g, b = colorsys.hls_to_rgb(Color.clamp(h*factor), l, s)\n return Color(r, g, b, self.color[3])\n\n @property\n def s(self):\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n return s\n\n def with_s(self, newval):\n newval = Color.clamp(newval)\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n r, g, b = colorsys.hls_to_rgb(h, l, newval)\n return Color(r, g, b, self.color[3])\n\n def with_s_factor(self, factor):\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n r, g, b = colorsys.hls_to_rgb(h, l, Color.clamp(s*factor))\n return Color(r, g, b, self.color[3])\n\n @property\n def l(self):\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n return l\n\n def with_l(self, newval):\n newval = Color.clamp(newval)\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n r, g, b = colorsys.hls_to_rgb(h, newval, s)\n return Color(r, g, b, self.color[3])\n\n def with_l_factor(self, factor):\n h, l, s = colorsys.rgb_to_hls(self.color[0], self.color[1], self.color[2])\n r, g, b = colorsys.hls_to_rgb(h, Color.clamp(l*factor), s)\n return Color(r, g, b, self.color[3])\n\n def lerp(self, other, factor):\n factor = Color.clamp(factor)\n col1 = self.rgba\n col2 = other.rgba\n col = [x*(1-factor) + y*factor for x, y in zip(col1, col2)]\n return Color(*col)\n\n def as_rgbstr(self):\n return 'rgb({}, {}, {})'.format(int(self.color[0] * 255),\n int(self.color[1] * 255),\n int(self.color[2] * 255))\n\n def as_rgb_bytes(self):\n return (int(self.color[0] * 255),\n int(self.color[1] * 255),\n int(self.color[2] * 255))\n\n def as_rgba_bytes(self):\n return (int(self.color[0] * 255),\n int(self.color[1] * 255),\n int(self.color[2] * 255),\n int(self.color[3] * 255))\n\n @staticmethod\n def clamp(v):\n try:\n v = min(1, max(0, v)) #Clamp v between 0 and 1\n except e:\n raise ValueError('Numerical value required') from e\n return v\n\n def __str__(self):\n return 'rgba' + str(self.color)\n\n def __getitem__(self, i):\n if i < 4:\n return self.color[i]\n else:\n raise IndexError()\n\n\ndef make_colormap(length, colors, bands=None):\n '''\n Create a colormap, a list of varying colors.\n :param length: Total size of list\n :param colors: List of colors, must be at least 2 long.\n :param bands: Relative size of each band. bands[i] gives the size of the band between color[i] and color[i+1].\n len(bands) must be exactly 1 less than len(colors). If bands is None, equal bands will be used.\n :return: a list of Color objects\n '''\n\n color_count = len(colors)\n\n # Check parameters\n if length <= 0:\n raise ValueError('length must be > 0')\n if color_count < 2:\n raise ValueError('colors list must have at least 2 elements')\n if not bands:\n bands = [1]*(color_count - 1)\n if color_count != len(bands) + 1:\n raise ValueError('colors list must be exactly 1 longer than bands list')\n\n\n band_total = sum(bands)\n band_breakpoints = [int(x*length/band_total) for x in itertools.accumulate(bands)]\n\n current_colour = 0\n band_index = 0\n colormap = [None]*length\n band_size = []\n for i in range(length):\n while band_breakpoints[current_colour] <= i:\n band_size.append(band_index)\n current_colour += 1\n band_index = 0\n colormap[i] = (current_colour, band_index)\n band_index += 1\n band_size.append(band_index)\n\n colormap = [colors[col].lerp(colors[col+1], band/(band_size[col]-1))\n for col, band in colormap ]\n\n return colormap\n","sub_path":"generativepy/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":12386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"639981821","text":"import pdb\nimport csv\nimport random\nfrom connection import connection\nfrom bigquery import client\n\nresults = client.query(\"\"\"\n SELECT * FROM `harvard-599-trendsetters.Genie.final_table_output_to_ui`\n\"\"\")\n\nwith connection:\n with connection.cursor() as cur:\n cur.execute(\"DELETE FROM relationships;\")\n connection.commit()\n\n count = 0\n for row in results:\n count += 1\n if count % 5000 == 0:\n print(count)\n connection.commit()\n\n change_recent = None\n if row[6] == \"N\":\n change_recent = False\n elif row[6] == \"Y\":\n change_recent = True\n cur.execute(\n \"INSERT INTO relationships VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT (id) DO NOTHING;\",\n (row[0], row[1][:-1], row[2], row[3], row[4] or \"\", row[5] or \"\", change_recent, row[7] and row[7][:-1] or 0, row[8] and row[8][:-1] or 0, row[9], row[10] or 0)\n )\n","sub_path":"front-end/loader/fetch_relationships.py","file_name":"fetch_relationships.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"328081417","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom urllib import urlencode\nimport base64\nfrom io import BytesIO\nfrom PIL import Image\nfrom splash.tests.test_proxy import BaseHtmlProxyTest\nfrom .test_execute import BaseLuaRenderTest\n\n\nclass OnRequestTest(BaseLuaRenderTest, BaseHtmlProxyTest):\n def test_request_log(self):\n resp = self.request_lua(\"\"\"\n function main(splash)\n local urls = {}\n local requests = {}\n splash:on_request(function(request)\n requests[#requests+1] = request.info\n urls[#urls+1] = request.url\n end)\n splash:go(splash.args.url)\n return requests, urls\n end\n \"\"\", {'url': self.mockurl(\"show-image\")})\n self.assertStatusCode(resp, 200)\n requests, urls = resp.json()\n\n # FIXME: it should return lists, and indices should be integer\n self.assertIn(\"show-image\", urls['1'])\n self.assertIn(\"slow.gif\", urls['2'])\n\n self.assertEqual(requests['1']['method'], 'GET')\n self.assertEqual(requests['1']['url'], urls['1'])\n\n def test_abort_request(self):\n resp = self.request_lua(\"\"\"\n function main(splash)\n splash:on_request(function(request)\n if string.find(request.url, \"gif\") ~= nil then\n request:abort()\n end\n end)\n splash:go(splash.args.url)\n return {har=splash:har(), png=splash:png()}\n end\n \"\"\", {'url': self.mockurl(\"show-image\")})\n self.assertStatusCode(resp, 200)\n data = resp.json()\n\n # the rendered image is not black (gif is not rendered)\n img = Image.open(BytesIO(base64.b64decode(data['png'])))\n self.assertEqual((255, 255, 255, 255), img.getpixel((10, 10)))\n\n # gif file is not in HAR log\n urls = [e['request']['url'] for e in data['har']['log']['entries']]\n self.assertTrue(any('show-image' in url for url in urls), urls)\n self.assertFalse(any('.gif' in url for url in urls), urls)\n\n def test_set_url(self):\n url = self.mockurl(\"http-redirect?code=302\")\n new_url = self.mockurl(\"jsrender\")\n resp = self.request_lua(\"\"\"\n function main(splash)\n splash:on_request(function(request)\n if request.url == splash.args.url then\n request:set_url(splash.args.new_url)\n end\n end)\n splash:go(splash.args.url)\n return splash:html()\n end\n \"\"\", {'url': url, 'new_url': new_url})\n self.assertStatusCode(resp, 200)\n self.assertIn('After', resp.content)\n\n def test_set_proxy(self):\n proxy_port = self.ts.mock_proxy_port\n resp = self.request_lua(\"\"\"\n function main(splash)\n assert(splash:go(splash.args.url))\n local html_1 = splash:html()\n\n splash:on_request(function(request)\n request:set_proxy{\n host=\"0.0.0.0\",\n port=splash.args.proxy_port\n }\n end)\n\n assert(splash:go(splash.args.url))\n local html_2 = splash:html()\n return html_1, html_2\n end\n \"\"\", {'url': self.mockurl(\"jsrender\"), 'proxy_port': proxy_port})\n self.assertStatusCode(resp, 200)\n html_1, html_2 = resp.json()\n self.assertNotProxied(html_1)\n self.assertProxied(html_2)\n\n def test_request_outside_callback(self):\n resp = self.request_lua(\"\"\"\n function main(splash)\n local req = nil\n splash:on_request(function(request)\n req = request\n end)\n assert(splash:go(splash.args.url))\n req:abort()\n return \"ok\"\n end\n \"\"\", {'url': self.mockurl(\"jsrender\")})\n self.assertStatusCode(resp, 400)\n self.assertErrorLineNumber(resp, 8)\n self.assertIn(\"request is used outside a callback\", resp.content)\n\n def test_set_header(self):\n resp = self.request_lua(\"\"\"\n function main(splash)\n splash:on_request(function(request)\n request:set_header(\"User-Agent\", \"Fooozilla\")\n request:set_header{name=\"Custom-header\", value=\"some-val\"}\n end)\n splash:go(splash.args.url)\n return splash:html()\n end\n \"\"\", {'url': self.mockurl(\"getrequest\")})\n self.assertStatusCode(resp, 200)\n\n self.assertIn(\"'custom-header': 'some-val'\", resp.text)\n self.assertIn(\"'user-agent': 'Fooozilla'\", resp.text)\n\n\nclass OnResponseHeadersTest(BaseLuaRenderTest, BaseHtmlProxyTest):\n def test_get_header(self):\n resp = self.request_lua(\"\"\"\n function main(splash)\n local header_value = nil\n splash:on_response_headers(function(response)\n header_value = response.headers['Content-Type']\n end)\n res = splash:http_get(splash.args.url)\n return header_value\n end\n \"\"\", {'url': self.mockurl(\"jsrender\")})\n\n self.assertStatusCode(resp, 200)\n self.assertEqual(resp.text, \"text/html\")\n\n def test_abort_on_response_headers(self):\n resp = self.request_lua(\"\"\"\n function main(splash)\n splash:on_response_headers(function(response)\n if response.headers['Content-Type'] == 'text/html' then\n response:abort()\n end\n end)\n res = splash:http_get(splash.args.url)\n return res\n end\n \"\"\", {'url': self.mockurl(\"jsrender\")})\n self.assertStatusCode(resp, 200)\n self.assertFalse(resp.json().get(\"content\").get(\"text\"))\n\n def test_response_used_outside_callback(self):\n resp = self.request_lua(\"\"\"\n function main(splash)\n local res = nil\n splash:on_response_headers(function(response)\n res = response\n end)\n splash:http_get(splash.args.url)\n res:abort()\n return \"ok\"\n end\n \"\"\", {'url': self.mockurl(\"jsrender\")})\n self.assertStatusCode(resp, 400)\n self.assertIn(\"response is used outside callback\", resp.text)\n\n def test_get_headers(self):\n headers = {\n \"Foo\": \"bar\",\n \"X-Proxy-Something\": \"1234\",\n \"X-Content-Type-Options\": \"nosniff\"\n }\n mocked_url = self.mockurl(\"set-header?\" + urlencode(headers))\n resp = self.request_lua(\"\"\"\n function main(splash)\n local headers = nil\n splash:on_response_headers(function(response)\n headers = response.headers\n response.abort()\n end)\n splash:http_get(splash.args.url)\n return headers\n end\"\"\", {\"url\": mocked_url})\n\n result = resp.json()\n\n self.assertStatusCode(resp, 200)\n\n for k, v in headers.iteritems():\n self.assertIn(k, result)\n self.assertEqual(result[k], headers[k])\n\n def test_other_response_attr(self):\n headers = {\n \"Foo\": \"bar\",\n }\n mocked_url = self.mockurl(\"set-header?\" + urlencode(headers))\n some_attrs = {\n \"url\": (unicode, mocked_url),\n \"status\": (int, 200),\n \"info\": (dict, {}),\n \"ok\": (bool, True),\n }\n\n resp = self.request_lua(\"\"\"\n function main(splash)\n local all_attrs = {}\n local attr_names = {\"url\", \"status\", \"info\", \"ok\", \"request\"}\n splash:on_response_headers(function(response)\n for key, value in pairs(attr_names) do\n all_attrs[value] = response[value]\n end\n end)\n splash:http_get(splash.args.url)\n return all_attrs\n end\"\"\", {\"url\": mocked_url})\n self.assertStatusCode(resp, 200)\n result = resp.json()\n\n for k, v in some_attrs.iteritems():\n self.assertIn(k, result)\n self.assertIsInstance(result[k], v[0])\n if v[1]:\n self.assertEqual(result[k], v[1], \"{} should equal {}\".format(k, v[1]))\n\n def test_request_in_callback(self):\n mocked_url = self.mockurl(\"set-header?\" + urlencode({\"alfa\": \"beta\"}))\n resp = self.request_lua(\"\"\"\n function main(splash)\n splash:on_response_headers(function(response)\n req_info = {}\n for key, value in pairs(response.request) do\n req_info[key] = response.request[key]\n end\n end)\n splash:on_request(function(request)\n request:set_header(\"hello\", \"world\")\n end)\n splash:http_get(splash.args.url)\n return req_info\n end\"\"\", {\"url\": mocked_url})\n self.assertStatusCode(resp, 200)\n resp = resp.json()\n for elem in [\"method\", \"url\", \"headers\"]:\n self.assertIn(elem, resp)\n self.assertEqual(resp[\"url\"], mocked_url)\n self.assertEqual(resp[\"method\"], \"GET\")\n self.assertEqual(resp[\"headers\"], {\"hello\": \"world\"})\n","sub_path":"splash/tests/test_execute_callbacks.py","file_name":"test_execute_callbacks.py","file_ext":"py","file_size_in_byte":9210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"395351884","text":"import random, numpy as np\r\n\r\nimport sys\r\nfrom sklearn import linear_model, metrics\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.linear_model import SGDClassifier\r\n\r\nimport os,re\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfTransformer\r\nfrom sklearn.feature_selection import SelectFromModel\r\nfrom sklearn.linear_model import SGDClassifier\r\nfrom sklearn.metrics import metrics\r\nfrom sklearn.pipeline import Pipeline\r\nfrom nltk.stem import *\r\nfrom nltk.stem.porter import *\r\nfrom sklearn.svm import LinearSVC\r\nimport nltk.stem\r\nimport matplotlib.pyplot as plt\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) != 3:\r\n print (\"Illegal use of Arguments: Best_configuration.py \")\r\n exit(1)\r\n train = sys.argv[1]\r\n test = sys.argv[2]\r\n ''' Extracting the training samples '''\r\n header_list = []\r\n labels = []\r\n i=0\r\n for root, dirs, files in os.walk('C:/Users/sthatipally/Downloads/Training'):\r\n for name in files:\r\n fo = open(root +\"/\"+name, \"r\")\r\n content = fo.read().replace('\\n', ' ')\r\n body = re.sub(r'^(.*) Lines: (\\d)+ ', \"\", content)\r\n header_list.append(unicode(body,errors='ignore'))\r\n labels.append(i)\r\n i=i+1\r\n\r\n ''' Extracting the testing samples '''\r\n header_test = []\r\n test_labels = []\r\n i = 0\r\n for root, dirs, files in os.walk('C:/Users/sthatipally/Downloads/Test'):\r\n for name in files:\r\n fo = open(root +\"/\"+name, \"r\")\r\n content = fo.read().replace('\\n', ' ')\r\n body = re.sub(r'^(.*) Lines: (\\d)+ ', \"\", content)\r\n header_test.append(unicode(body,errors='ignore'))\r\n test_labels.append(i)\r\n i=i+1\r\n\r\n def shuffle(train, test, size):\r\n shuffled_train = []\r\n shuffled_train_labels = []\r\n index =[]\r\n for i in range(len(labels)):\r\n index.append(i)\r\n random.shuffle(index)\r\n for i in index:\r\n shuffled_train.append(header_list[i])\r\n shuffled_train_labels.append((labels[i]))\r\n return shuffled_train[:size],shuffled_train_labels[:size]\r\n subsets = [(i+1)*100 for i in range(20)]\r\n\r\n from sklearn.naive_bayes import MultinomialNB\r\n def find_scores(estimator):\r\n sizes = []\r\n scores = []\r\n for i in subsets:\r\n text_clf = Pipeline([('vect', CountVectorizer()),('tfidf', TfidfTransformer()),('clf', estimator),])\r\n train, labels_sub = shuffle(header_list, labels, i)\r\n text_clf = text_clf.fit(train, labels_sub)\r\n predicted = text_clf.predict(header_test)\r\n sizes.append(i)\r\n scores.append(metrics.f1_score(test_labels, predicted, average='macro'))\r\n return (sizes,scores)\r\n\r\n sizes_NB,scores_NB = find_scores(MultinomialNB())\r\n print(sizes_NB,scores_NB)\r\n sizes_svm,scores_svm = find_scores(SGDClassifier(loss='hinge', penalty='l2',\r\n ))\r\n print(sizes_svm,scores_svm)\r\n sizes_log,scores_log = find_scores(linear_model.LogisticRegression())\r\n print(sizes_log,scores_log)\r\n sizes_RF,scores_RF = find_scores(RandomForestClassifier(n_estimators=100))\r\n print(sizes_RF,scores_RF)\r\n import numpy as np\r\n\r\n\r\n plt.figure()\r\n plt.title(\"learning curves\")\r\n plt.xlabel(\"Training examples\")\r\n plt.ylabel(\"Score\")\r\n plt.grid()\r\n plt.plot(sizes_NB, scores_NB, 'o-', color=\"r\",\r\n label=\"Bayes score\")\r\n plt.plot(sizes_log, scores_log, 'o-', color=\"g\",\r\n label=\"Logistic Score\")\r\n plt.plot(sizes_svm, scores_svm, 'o-', color=\"y\",\r\n label=\"SVM score\")\r\n plt.plot(sizes_RF, scores_RF, 'o-', color=\"b\",\r\n label=\"Random Forest score\")\r\n plt.legend(loc=\"best\")\r\n plt.show()","sub_path":"Learning_curves.py","file_name":"Learning_curves.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"308835060","text":"#!/usr/bin/python3\n#from sys import winver\nimport paramiko\nimport yaml\nimport os\nimport shutil\nimport ruamel.yaml\nfrom yaml.loader import Loader\n\n\n \nclass ConfigFileOtarieS1():\n def __init__(self, info_config, info_deployment, elastic_config):\n self.info_config = info_config\n self.elastic = elastic_config\n self.sourcename = 'source-otarie'\n self.new_source = info_config['name']\n self.deployment_info = info_deployment\n self.ressource_dir = info_config['ressource_dir']\n print(self.sourcename)\n print(self.deployment_info)\n \n def get_path_source(self):\n listsource = os.listdir(self.ressource_dir)\n if self.sourcename in listsource:\n return os.path.join(self.ressource_dir, self.sourcename)\n else:\n raise Warning(\"Source not found\")\n exit(-1)\n\n\n def get_path_script(self):\n return os.path.join(self.get_path_source(), 'scripts')\n \n def get_deployment_path(self):\n return self.deployment_info['deploymentPath']\n\n def get_path_new_source_from_deployment_server(self):\n return os.path.join(self.get_deployment_path(), self.new_source)\n\n def get_path_script_from_deployment_server(self):\n src = self.get_path_new_source_from_deployment_server()\n return os.path.join(src, 'scripts')\n\n def update_collecte_config_file(self):\n path_script = self.get_path_script()\n path_collect = os.path.join(path_script, 'collecte')\n path_collect_file = os.path.join(path_collect, 'config.yml')\n dirPath = os.path.join(self.get_path_new_source_from_deployment_server(), 'data')\n parse_dir = os.path.join(self.get_path_new_source_from_deployment_server(), 'parseDir')\n stream = open(path_collect_file, 'r')\n yaml = ruamel.yaml.YAML()\n yaml.indent(mapping=4, sequence=4, offset=2)\n yaml.preserve_quotes = True\n data = yaml.load(stream)\n data['source']['connection_type'] = self.info_config['accessMode']\n data['source']['host'] = self.info_config['ipAddress']\n data['source']['username'] = self.info_config['username']\n data['source']['password'] = self.info_config['password']\n data['source']['directory'] = self.info_config['path']\n data['source']['pattern_file'] = self.info_config['pattern']\n if self.info_config['date'] != '':\n data['source']['date'] = self.info_config['date']\n data['source']['format'] = self.info_config['format']\n data['destination']['directory'] = dirPath\n data['destination']['parse_dir'] = parse_dir\n\n with open(path_collect_file, 'w') as file:\n yaml.dump(data, file)\n \n def update_parsing_config_file(self):\n path_script = self.get_path_script()\n path_config = os.path.join(path_script, 'config')\n archdir = os.path.join(self.get_path_new_source_from_deployment_server(), 'archive')\n parsedir = os.path.join(self.get_path_new_source_from_deployment_server(), 'parseDir')\n path_parse_file = os.path.join(path_config, 'files_config.yml')\n stream = open(path_parse_file, 'r')\n yaml = ruamel.yaml.YAML()\n yaml.indent(mapping=4, sequence=4, offset=2)\n yaml.preserve_quotes = True\n data = yaml.load(stream)\n data['csv']['directory']= parsedir\n data['csv']['separateur']= self.info_config['separateur']\n data['csv']['column_to_convert'] = self.info_config['dateField']\n data['csv']['archive_directory'] = archdir\n\n with open(path_parse_file, 'w') as file:\n yaml.dump(data, file)\n\n\n def update_elastic_config_file(self):\n src_script = self.get_path_script_from_deployment_server()\n path_script = self.get_path_script()\n path_config = os.path.join(path_script, 'config')\n elastic_file = os.path.join(path_config, 'elastic_config.yml')\n config_dir_server = os.path.join(src_script, 'config')\n stream = open(elastic_file, 'r')\n yaml = ruamel.yaml.YAML()\n yaml.indent(mapping=4, sequence=4, offset=2)\n yaml.preserve_quotes = True\n data = yaml.load(stream)\n data['elastic']['host'] = self.elastic['hosts']\n data['elastic']['INDEX'] = self.info_config['indexName']\n data['elastic']['mapping'] = os.path.join(config_dir_server, 'mapping.json')\n \n with open(elastic_file, 'w') as file:\n yaml.dump(data, file)\n\n def create_new_source(self):\n src_dir = self.get_deployment_path()\n source_dir = self.get_path_source()\n ssh = paramiko.SSHClient()\n know_host = paramiko.AutoAddPolicy()\n ssh.set_missing_host_key_policy(know_host)\n ssh.connect(hostname=self.deployment_info['ipAddress'], port=22, username=self.deployment_info['username']\\\n ,password=self.deployment_info['password'])\n #print(src_dir)\n #zip_file = os.path.join(self.script_dir, 'script')\n name = 'source' \n shutil.make_archive(name, 'zip', source_dir)\n zip_file = name+'.zip'\n print('-----------------------------')\n print(zip_file)\n print(src_dir)\n ftp_client = ssh.open_sftp()\n des_dir = os.path.join(src_dir, 'source.zip')\n ftp_client.put(zip_file, des_dir)\n os.remove(zip_file) \n ftp_client.close()\n new_path = os.path.join(src_dir, self.new_source)\n cmd = 'unzip '+des_dir+' -d '+new_path+' && rm '+des_dir\n stdin, stdout, stderr = ssh.exec_command(cmd)\n print(stdout.read().decode())\n ssh.close()\n ","sub_path":"backend/src/traitement/createSourceOtarie.py","file_name":"createSourceOtarie.py","file_ext":"py","file_size_in_byte":5633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"190385608","text":"import pandas as pd\nimport plotly\nimport plotly.graph_objs as go\nimport sklearn.model_selection\nimport sklearn.decomposition\nfrom sklearn import metrics\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\n# 数据预处理\ngupiao = pd.read_csv('data_akbilgic.csv')\nco = gupiao[0:1].values[0]\nco = co[1:]\nco[0] += '_TL_BASED'\nco[1] += '_USD_BASED'\ngupiao = pd.DataFrame(gupiao.iloc[1:, 1:].values, columns=co).astype(float)\n\n\n# 数据降维\ndef pca(df, n):\n data = df.values\n data = data-data.mean(axis=0)\n cov = np.cov(data, rowvar=False)\n values, factors = np.linalg.eig(cov)\n order = np.argsort(values)\n order = order[:-(n+1):-1]\n factors1 = factors[:, order]\n low_data = np.dot(data, factors1)\n return low_data\nx = gupiao.iloc[:, 1:]\nx = pca(x, 2)\nx = pd.DataFrame(x)\ny = gupiao.iloc[:, 0:1]\nprint(y)\nprint(x[0])\nprint(x[1])\n\n# 画出第一项关于降维后其他项的图\nscatter=[]\ny_1 = list(float(u) for u in y.values)\nfor i in range(0,2):\n x_1 = list(float(u) for u in x[i].values)\n scatter.append(go.Scatter(\n x=y_1,\n y=x_1,\n name=str(i),\n mode='markers',\n marker=dict(\n size=3,\n )\n ))\nplotly.offline.plot(scatter, filename='原始数据2.html')\n\n\n# 线性回归训练\n\nx_train, x_test, y_train, y_test = \\\n sklearn.model_selection.train_test_split(x, y, test_size=0.2, random_state=888)\n# print(x_train.shape)\n# print(y_train.shape)\n# print(x_test.shape)\n# print(y_test.shape)\nlinreg = LinearRegression() # 建立线性模型类实例linreg\nlinreg.fit(x_train, y_train)\n# print(linreg.intercept_)\n# print(linreg.coef_)\n\n\n# 画出测试集预测值与真值的对应图\n# 重写一下.predict()方法的实现\n# def get_y(data):\n# y = linreg.intercept_[0]\n# for i2 in range(0, len(linreg.coef_[0])):\n# y += float(data.values[0][i2])*float(linreg.coef_[0][i2])\n# return y\n# y_test_prime = []\n# for i in x_test.index:\n# y_test_prime.append(get_y(x[i:i+1]))\n# print(y_test_prime)\ny_test = [float(i) for i in y_test.values]\ny_test_prime = linreg.predict(x_test)\ny_test_prime = [y_test_prime[i][0] for i in range(0,len(y_test_prime))]\nplot1 = go.Scatter(\n x=np.linspace(0, 1, num=len(y_test)),\n y=y_test,\n mode='markers+lines',\n name='test'\n)\nplot2 = go.Scatter(\n x=np.linspace(0, 1, num=len(y_test)),\n y=y_test_prime,\n mode='markers+lines',\n name='test_prime'\n)\nplotly.offline.plot([plot1, plot2], filename='降维.html')\n\n# 检查误差\np = (metrics.mean_squared_error(y_test, y_test_prime))**0.5\nprint(p)\n\n# 交叉验证\nfrom sklearn.model_selection import cross_val_predict\nlinreg = LinearRegression()\npredicted = cross_val_predict(linreg, x, y, cv=10)\np = (metrics.mean_squared_error(y, predicted))**0.5\nprint(p)\n","sub_path":"人工智能程序设计/class/5.9assignment/第一题/降维.py","file_name":"降维.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"186357059","text":"\"\"\"\nFile: demographic_eigen_centrality.py\n-------------------\n@author jmwebb\n@date 2016-05-19\n\nExperiment to determine which demographic groups have the\nhighest average/median eigenvector centrality.\n\"\"\"\n\nimport networkx as nx\nimport math\n\n\ndef _map_print(key, value):\n \"\"\"\n Pretty print feature for key-value pairs\n \"\"\"\n print(\n '\\t{0:11.11}:\\t{1}\\t'.format(\n key, value))\n\n\ndef _print_average_demo(eigenvec_centrality_totals):\n \"\"\"\n Calculates and prints the average eigenvector centrality\n for a given demographic group.\n\n @param eigenvec_centrality_totals: a dict mapping a demographic to\n a list of the eigenvector centrality for all nodes in that demographic\n \"\"\"\n averages = {}\n print('-' * 60)\n for attribute in eigenvec_centrality_totals:\n averages[attribute] = sum(eigenvec_centrality_totals[\n attribute]) / len(eigenvec_centrality_totals[attribute])\n\n for attribute, average in sorted(\n averages.items(), key=lambda x: -x[1]):\n _map_print(attribute, average)\n\n\ndef _print_median_demo(eigenvec_centrality_totals):\n \"\"\"\n Calculates and prints the average eigenvector centrality\n for a given demographic group.\n\n @param eigenvec_centrality_totals: a dict mapping a demographic to\n a list of the eigenvector centrality for all nodes in that demographic\n \"\"\"\n medians = {}\n print('-' * 60)\n for attribute in eigenvec_centrality_totals:\n sort = sorted(eigenvec_centrality_totals[attribute])\n medians[attribute] = sort[math.floor(len(sort) / 2)]\n\n for attribute, median in sorted(medians.items(), key=lambda x: -x[1]):\n _map_print(attribute, median)\n\n\ndef _calc_centrality_totals(graph):\n \"\"\"\n Calculates the eigenvector centrality for every node in\n a graph, then assigns those centralities to different\n demographic groups.\n\n @param graph: the graph to calculate centrality for\n @return a dict mapping gender string to list of centralities\n @return a dict mapping major name to list of centralities\n @return a dict mapping activity name to list of centralities\n \"\"\"\n eigen_centralities = nx.eigenvector_centrality(graph)\n gender_eigen_totals = {}\n major_eigen_totals = {}\n ec_eigen_totals = {}\n for node in graph.nodes(data=True):\n gender = node[1]['gender']\n major = node[1]['area_of_study']\n extra_currics = node[1]['extra_curricular']\n if gender in gender_eigen_totals:\n gender_eigen_totals[gender].append(eigen_centralities[node[0]])\n else:\n gender_eigen_totals[gender] = []\n if major in major_eigen_totals:\n major_eigen_totals[major].append(eigen_centralities[node[0]])\n else:\n major_eigen_totals[major] = []\n for ec in extra_currics:\n if ec in ec_eigen_totals:\n ec_eigen_totals[ec].append(eigen_centralities[node[0]])\n else:\n ec_eigen_totals[ec] = []\n\n return gender_eigen_totals, major_eigen_totals, ec_eigen_totals\n\n\ndef average_centralities(graph):\n \"\"\"\n Finds the average eigenvector centrality across all demographic groups\n in the provided graph.\n \"\"\"\n gender_eigen_totals, major_eigen_totals, ec_eigen_totals = _calc_centrality_totals(\n graph)\n\n print('Average Eigenvector Centrality by Demographic:')\n print('-' * 60)\n print('Gender stats:')\n _print_average_demo(gender_eigen_totals)\n print('Major stats:')\n _print_average_demo(major_eigen_totals)\n print('Extracurricular stats:')\n _print_average_demo(ec_eigen_totals)\n\n\ndef median_centralities(graph):\n \"\"\"\n Finds the median eigenvector centrality across all demographic groups\n in the provided graph.\n \"\"\"\n gender_eigen_totals, major_eigen_totals, ec_eigen_totals = _calc_centrality_totals(\n graph)\n\n print('Median Eigenvector Centrality by Demographic:')\n print('-' * 60)\n print('Gender stats:')\n _print_median_demo(gender_eigen_totals)\n print('Major stats:')\n _print_median_demo(major_eigen_totals)\n print('Extracurricular stats:')\n _print_median_demo(ec_eigen_totals)\n","sub_path":"demographic_eigen_centrality.py","file_name":"demographic_eigen_centrality.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"643187645","text":"from setuptools import setup\nimport os\nimport re\n\ndef find_version():\n with open('pionUploader.py', 'r') as version_file:\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file.read(), re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\nif os.name == \"nt\":\n scripts = None\n entry_points = {\n {\n 'console_scripts': ['tasmotizer=tasmotizer:main'],\n }\n }\nelse:\n scripts = ['pionUploader.py']\n entry_points = None\n\nsetup(\n name='PionUpploader',\n version=find_version(),\n url='https://github.com/pion-labs/pion-kits-firmware-uploader',\n py_modules=['pionUploader', 'gui', 'pionUploader_esptool', 'banner', 'utils'],\n license='GPLv3',\n author='Pion Labs',\n author_email='liftoff@pionlabs.com.br',\n description='Firmware uploader for PION Educational kits!',\n long_description=\"Dedicated flashing tool for the default firmware for PION Educational Satellite Kits\",\n python_requires='>=3.6',\n install_requires=[\n \"pyserial>=3.0\",\n \"PyQt5>=5.10\"\n ],\n entry_points=entry_points,\n scripts=scripts,\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\",\n ],\n project_urls={\n \"Issue Tracker\": \"https://github.com/pion-labs/pion-kits-firmware-uploader/issues\",\n \"Documentation\": \"https://github.com/pion-labs/pion-kits-firmware-uploader/wiki\",\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"515051924","text":"class Employee:\n\n raise_amount = 1.04\n def __init__(self,first,last,pay):\n self.first = first\n self.last = last\n self.pay = pay\n self.email = first+\".\"+last+\"@company.com\"\n \n def fullname(self): \n return '{} {}'.format(self.first,self.last) \n \n \n def raise_amount(self):\n self.pay = int(self.pay*raise_amount) \n \nemp1 = Employee(\"fahad\",\"mushahid\",230000)\nemp2 = Employee(\"rahul\",\"tenda\",121331)\n \nprint(emp1.email)\nprint(emp2.email)\n\nprint(emp1.fullname())\nprint(emp1.pay)\nemp1.raise_amount()\nprint(emp1.pay)\n\n","sub_path":"Employee.py","file_name":"Employee.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"577181923","text":"import os\nos.environ['NUMPY_EXPERIMENTAL_ARRAY_FUNCTION'] = '0'\n\nfrom naca4 import cluster_both, cluster_right, ellipse, trans_finite, converge, plot\nfrom pyHype.mesh.airfoil import NACA4\nimport numpy as np\n\nfarfield = 2\nny = 41\nnx = 31\nf = 0.0\n\nsource = {'ap': 0.5,\n 'cp': 1.0,\n 'aq': 100.0,\n 'cq': 10.0,\n 'p': [0, 1],\n 'q': [1]\n }\n\nairfoil = NACA4(airfoil='9410',\n angle_start=0,\n angle_end=180,\n aoa=5,\n npt=int(np.floor(ny/2)+1))\n\n# -------------------------------------------------------------\n# Mesh\n\nX = np.zeros((ny, nx))\nY = np.zeros((ny, nx))\n\ntheta = cluster_both(3 * np.pi / 2, np.pi / 2, ny, factor=1.5)\n\nr = ellipse(farfield + 1, farfield + 1, theta)\n\nX[:, 0] = r * np.cos(theta) + 1\nX[:, -1] = np.concatenate((np.flip(airfoil.x_lower), airfoil.x_upper[1:]))\nX[-1, :] = np.linspace(airfoil.x_upper[-1], airfoil.x_upper[-1], nx)\nX[0, :] = np.linspace(airfoil.x_upper[-1], airfoil.x_upper[-1], nx)\n\nY[:, 0] = r * np.sin(theta)\nY[:, -1] = np.concatenate((np.flip(airfoil.y_lower)+f, airfoil.y_upper[1:]+f))\nY[-1, :] = cluster_right(r[-1], airfoil.y_upper[-1] + f, nx, factor=3, flip=True)\nY[0, :] = cluster_right(-r[1], airfoil.y_lower[-1] + f, nx, factor=3, flip=True)\n\nX, Y = trans_finite(X, Y)\nXt, Yt = X.copy(), Y.copy()\n\n# -------------------------------------------------------------\n# Calculate mesh\n\n_eta = np.linspace(0, 1, nx - 2)\n_xi = np.linspace(0, 1, ny - 2)\neta, xi = np.meshgrid(_eta, _xi)\n\nX, Y = converge(X, Y, eta, xi, source)\n\n# Plot\nplot(X, Y, Xt, Yt)\nplot(X, Y, Xt, Yt, xlim=(-0.25, 1), ylim=(-0.5, 0.5), vert=True)\n","sub_path":"new_functions_testing/naca4_test.py","file_name":"naca4_test.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"592443192","text":"\n# Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.\n\nimport collections\n\nclass Solution(object):\n def firstUniqChar(self, s):\n if s is None:\n return -1\n\n freq = collections.Counter(s)\n for i in range(len(s)):\n if freq.get(s[i])==1:\n return i\n return -1\n\nif __name__ == '__main__':\n solution = Solution()\n print(solution.firstUniqChar(\"loveleetcode\"))","sub_path":"First Unique Character in a String.py","file_name":"First Unique Character in a String.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"586306261","text":"import torch.nn as nn\n\n\nclass DoubleUpconvUNet(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(DoubleUpconvUNet, self).__init__()\n self.l1 = nn.Upsample(scale_factor=2, mode='nearest')\n self.l2 = nn.ReflectionPad2d(1)\n self.l3 = nn.Conv2d(in_channels=in_channels, out_channels=in_channels//2, kernel_size=3, stride=1, padding=0,\n bias=True)\n self.l4 = nn.Conv2d(in_channels=in_channels//2, out_channels=out_channels, kernel_size=3, stride=1, padding=1,\n bias=True)\n\n self.l5 = nn.BatchNorm2d(out_channels)\n\n def forward(self, x):\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 return x\n","sub_path":"_fred-v1/model/models/DoubleUpconvUNet.py","file_name":"DoubleUpconvUNet.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"90818134","text":"from django.conf.urls import url\nfrom page import views\nfrom page.twviews import *\n\nurlpatterns = [\n # url(r'^categories/$', views.categories, name='categories'),\n # url(r'^(?:(?P\\d+)/)?$', views.index, name='index'),\n # url(r'^good/(?P[0-9]+)/$', views.good, name='good')\n url(r'^(?:(?P\\d+)/)?$', GoodListView.as_view(), name='index'),\n url(r'^good/(?P\\d+)/$', GoodDetailView.as_view(), name='good'),\n url(r'^(?P\\d+)/add/$', GoodCreate.as_view(), name='good_add'),\n url(r'^good/(?P\\d+)/edit/$', GoodUpdate.as_view(), name='good_edit'),\n url(r'^good/(?P\\d+)/delete/$', GoodDelete.as_view(), name='good_delete')\n]\n","sub_path":"page/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"337573907","text":"# Import modules\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport streamlit as st\r\n\r\n@st.cache()\r\ndef load_data():\r\n\t# Load the Adult Income dataset into DataFrame.\r\n\r\n\tdf = pd.read_csv('https://student-datasets-bucket.s3.ap-south-1.amazonaws.com/whitehat-ds-datasets/adult.csv', header=None)\r\n\tdf.head()\r\n\r\n\t# Rename the column names in the DataFrame using the list given above. \r\n\r\n\t# Create the list\r\n\tcolumn_name =['age', 'workclass', 'fnlwgt', 'education', 'education-years', 'marital-status', 'occupation', 'relationship', 'race','gender','capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income']\r\n\r\n\t# Rename the columns using 'rename()'\r\n\tfor i in range(df.shape[1]):\r\n\t df.rename(columns={i:column_name[i]},inplace=True)\r\n\r\n\t# Print the first five rows of the DataFrame\r\n\tdf.head()\r\n\r\n\t# Replace the invalid values ' ?' with 'np.nan'.\r\n\r\n\tdf['native-country'] = df['native-country'].replace(' ?',np.nan)\r\n\tdf['workclass'] = df['workclass'].replace(' ?',np.nan)\r\n\tdf['occupation'] = df['occupation'].replace(' ?',np.nan)\r\n\r\n\t# Delete the rows with invalid values and the column not required \r\n\r\n\t# Delete the rows with the 'dropna()' function\r\n\tdf.dropna(inplace=True)\r\n\r\n\t# Delete the column with the 'drop()' function\r\n\tdf.drop(columns='fnlwgt',axis=1,inplace=True)\r\n\r\n\treturn df\r\n\r\ncensus_df = load_data()\r\n\r\n# Write your code to filter streamlit warnings \r\nst.set_option('deprecation.showPyplotGlobalUse', False)\r\n\r\n# Write the code to design the web app\r\nst.title(\"Census Visualisation App\")\r\n \r\n# Add title on the main page and in the sidebar.\r\nst.sidebar.title(\"Menu\")\r\n# Using the 'if' statement, display raw data on the click of the checkbox.\r\nif st.sidebar.checkbox(\"Show Raw Data\"):\r\n st.subheader(\"Census Data Frame\")\r\n st.dataframe(census_df)\r\n st.write(f\"Number of rows are:{census_df.shape[0]} , Number of Columns are:{census_df.shape[1]}\") \r\n# Add a multiselect widget to allow the user to select multiple visualisations.\r\n# Add a subheader in the sidebar with the label \"Visualisation Selector\"\r\nst.sidebar.subheader(\"Visualisation Selector\")\r\n\r\n# Add a multiselect in the sidebar with label 'Select the Charts/Plots:'\r\n# Store the current value of this widget in a variable 'plot_list'.\r\nplt_typ = st.sidebar.multiselect(\"Select the Plot\" , ('Box Plot', 'Count Plot', 'Pie Chart'))\r\n\r\n# Display pie plot using matplotlib module and 'st.pyplot()'\r\nif 'Pie Chart' in plt_typ:\r\n st.subheader(\"Pie Chart\") \r\n plt_pie = st.sidebar.multiselect(\"Select the column for Pie chart\" , (\"income\" , \"gender\"))\r\n for i in plt_pie:\r\n data_pie = census_df[i].value_counts()\r\n plt.figure(figsize = (15 , 10))\r\n plt.title(f\"Pie Chart for {i}\")\r\n plt.pie(data_pie , labels = data_pie.index , autopct = \"%.2f%%\" , explode = np.linspace(0.05 , 0.15 , len(data_pie)))\r\n st.pyplot()\r\n\r\n# Display box plot using matplotlib module and 'st.pyplot()'\r\nif 'Box Plot' in plt_typ:\r\n st.subheader(\"Box Plot\")\r\n cols = st.sidebar.multiselect(\"Select the columns to create its Box Plot\" , ('income' , 'gender')) \r\n for i in cols:\r\n plt.figure(figsize = (15 , 10))\r\n plt.title(f\"Box Plot for {i}\")\r\n sns.boxplot(census_df[\"hours-per-week\"] , census_df[i])\r\n st.pyplot()\r\n\r\n# Display count plot using seaborn module and 'st.pyplot()' \r\nif 'Count Plot' in plt_typ:\r\n st.subheader(\"Count Plot\") \r\n plt.figure(figsize = (15 , 10))\r\n plt.title(f\"Count Plot for Workclass\")\r\n sns.countplot(census_df['workclass'] , hue = census_df[\"income\"])\r\n st.pyplot()\r\n","sub_path":"census.py","file_name":"census.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"121726109","text":"'''Create a generator that yields \"n\" random numbers between a low and high number (that are inputs).\nNote: Use the random library. For example:'''\n\nimport random\n\nrandom.randint(1,10)\ndef rand_num(low,high,n):\n for i in range(n):\n yield random.randint(low,high)\n\nfor ran_num in rand_num(1,15,10):\n print(ran_num)","sub_path":"generator_exercise_2.py","file_name":"generator_exercise_2.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"214012253","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-03-19\n# @Author : Joe\n\nimport numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\n\n# Feature Matching + Homography to find Objects\n\n# Goal\n\t# 在本节中,我们将在一副较复杂的图像中混合使用特征匹配和\n\t# calib3d模块中的findHomography来查找已知的物体。\n\n# Basics\n\t# 所以我们上节中做了什么呢?我们使用了一个未知图像,然后\n\t# 在它里面找到了一些特征点,我们再使用另外一副训练图像,\n\t# 也在图像中找到一些特征点,然后在这些特征点当中找到他们\n\t# 相互匹配的特征点。简单来说,我们在另外一副图像中找到了\n\t# 一些物体的某些部位的位置。这些信息足够让我们在训练图像\n\t# 中找到精确的物体。\n\n\t# 为了实现这个目标,我们使用了在 calib3d 模块中的函数,cv.findHomography()\n\t# 如果我们给这个函数传入了在两幅图像中都存在的一些点,这\n\t# 个函数将会找到这个物体的透视转换信息。然后我们就可以使\n\t# 用cv2.perspectiveTransform()来找到这个物体。它需要最\n\t# 少4个正确的点来找到这个变换。\n\n\t# 我们可以看到这里将会存在在匹配的时候会出现一些可能的错\n\t# 误信息将会影响到结果。解决这个问题,算法使用RANSAC或者\n\t# LEAST_MEDIAN(可以通过标记判断)。所以好的匹配提供了正\n\t# 确的预测被称��inliers,剩余的被称为outliers。\n\n# Code\nMIN_MATCH_COUNT = 10\nimg1 = cv.imread('box.png',0) # queryImage\nimg2 = cv.imread('box_in_scene.png',0) # trainImage\n# Initiate SIFT detector\nsift = cv.xfeatures2d.SIFT_create()\n# find the keypoints and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1,None)\nkp2, des2 = sift.detectAndCompute(img2,None)\nFLANN_INDEX_KDTREE = 1\nindex_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\nsearch_params = dict(checks = 50)\nflann = cv.FlannBasedMatcher(index_params, search_params)\nmatches = flann.knnMatch(des1,des2,k=2)\n# store all the good matches as per Lowe's ratio test.\ngood = []\nfor m,n in matches:\n if m.distance < 0.7*n.distance:\n good.append(m)\n\nif len(good)>MIN_MATCH_COUNT:\n\tsrc_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)\n\tdst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)\n\tM, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC,5.0)\n\tmatchesMask = mask.ravel().tolist()\n\th,w = img1.shape\n\tpts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n\tdst = cv.perspectiveTransform(pts,M)\n\timg2 = cv.polylines(img2,[np.int32(dst)],True,255,3, cv.LINE_AA)\nelse:\n\tprint( \"Not enough matches are found - {}/{}\".format(len(good), MIN_MATCH_COUNT) )\n\tmatchesMask = None\t\n\ndraw_params = dict(matchColor = (0,255,0), # draw matches in green color\n singlePointColor = None,\n matchesMask = matchesMask, # draw only inliers\n flags = 2)\nimg3 = cv.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)\nplt.imshow(img3, 'gray'),plt.show()","sub_path":"feature_detection_and_description/10_feature_matching_homography_to_find_objects.py","file_name":"10_feature_matching_homography_to_find_objects.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"519241716","text":"import config\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch\n\ndef train_epoch(network, loader, optimizer):\n cumu_loss = 0\n cumu_acc = 0\n total = 0\n\n criterion = nn.CrossEntropyLoss()\n for _, (data, target) in enumerate(loader):\n data, target = data.to(config.DEVICE), target.to(config.DEVICE)\n optimizer.zero_grad()\n\n loss = criterion(network(data), target)\n cumu_loss += loss.item()\n _, predicted = torch.max(network(data).data, 1)\n total += target.size(0)\n cumu_acc += (predicted == target).sum().item()\n\n loss.backward()\n optimizer.step()\n network.eval() \n return cumu_loss / len(loader), 100 * cumu_acc / total","sub_path":"day_3/Mnist_train_2/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"426638686","text":"from scipy.integrate import ode\nimport matplotlib.pyplot as plt\n\nfrom models import *\nfrom parameters import *\n\n\nrho_x = 0\nrho_y = 0\n\nrho_I0_a, rho_I0_b, rho_I1_a, rho_I1_b, rho_I2_a, rho_I2_b, rho_I3_a, rho_I3_b = 0, 5, 5, 0, 5, 0, 5, 0\n\nparams = (delta_L, gamma_L_X, n_y, theta_L_X, eta_x, omega_x, m_x, delta_x, delta_y, rho_x, rho_y, gamma_x, theta_x, r_X, r_Y, \n rho_I0_a, rho_I0_b, rho_I1_a, rho_I1_b, rho_I2_a, rho_I2_b, rho_I3_a, rho_I3_b)\n\n\nY0 = np.zeros(59)\n\n\n# number of cells: toggle switches\nN_I0 = np.array([1,1])\nN_I1 = np.array([1,1])\nN_I2 = np.array([1,1])\nN_I3 = np.array([1,1])\n\nY0[4:6] = N_I0\nY0[10:12] = N_I1\nY0[16:18] = N_I2\nY0[22:24] = N_I3\n\n# number of cells: mux\n#Y0[22-4+24:38-4+24] = 1 # number of cells\nY0[42:58] = 1 # number of cells\n\n# S0, S1\nS = np.array([0, 0])\nY0[24:26] = S\n\n\"\"\"\nsimulations\n\"\"\"\n\n# simulation parameters\nt_end = 1500\nN = t_end\n\n# initialization\n\nT = np.linspace(0, t_end, N)\n\nt1 = t_end\ndt = t_end/N\nT = np.arange(0,t1+dt,dt)\nY = np.zeros([1+N,59])\nY[0,:] = Y0\n\n\n# simulation\nr = ode(CLB_model_ODE).set_integrator('zvode', method='bdf')\nr.set_initial_value(Y0, T[0]).set_f_params(params)\n\ni = 1\nwhile r.successful() and r.t < t1:\n Y[i,:] = r.integrate(r.t+dt)\n i += 1\n\nout = Y[:,-1]\n\nS0, S1 = Y[:,24], Y[:,25]\n\nI0_a, I0_b = Y[:,2], Y[:,3]\nI1_a, I1_b = Y[:,8], Y[:,9]\nI2_a, I2_b = Y[:,14], Y[:,15]\nI3_a, I3_b = Y[:,20], Y[:,21]\n\n\n# plot\n\"\"\"\nax1 = plt.subplot(241)\nax1.plot(T, I0_a)\nax1.plot(T, I0_b)\nax1.legend([\"I0_a = I0\", \"I0_b\"])\nax1.set_title('I0 toggle')\n\nax2 = plt.subplot(242)\nax2.plot(T, I1_a)\nax2.plot(T, I1_b)\nax2.legend([\"I1_a = I1\", \"I1_b\"])\nax2.set_title('I1 toggle')\n\nax3 = plt.subplot(243)\nax3.plot(T, I2_a)\nax3.plot(T, I2_b)\nax3.legend([\"I2_a = I2\", \"I2_b\"])\nax3.set_title('I2 toggle')\n\nax4 = plt.subplot(244)\nax4.plot(T, I3_a)\nax4.plot(T, I3_b)\nax4.legend([\"I3_a = I3\", \"I3_b\"])\nax4.set_title('I3 toggle')\n\nax5 = plt.subplot(212)\nax5.plot(T,out)\nax5.set_title('out')\n\nplt.suptitle(f\"S = [{S[1]},{S[0]}]\")\nplt.show()\n\"\"\"\nax1 = plt.subplot(341)\nax1.plot(T, I0_a, color=\"#800000ff\", alpha=0.75)\nax1.plot(T, I0_b, color=\"#999999ff\", alpha=0.75)\nax1.legend([\"$I_0$\", \"$\\\\overline{I_0}$\"])\n#ax1.set_title('$I_0$ toggle')\nax1.set_xlabel(\"Time [min]\")\nax1.set_ylabel(\"Concentrations [nM]\")\n\n\nax2 = plt.subplot(342)\nax2.plot(T, I1_a, color = \"#00ff00ff\", alpha=0.75)\nax2.plot(T, I1_b, color = \"#666666ff\")#, alpha=0.75)\nax2.legend([\"$I_1$\", \"$\\\\overline{I_1}$\"])\n#ax2.set_title('$I_1$ toggle')\nax2.set_xlabel(\"Time [min]\")\nax2.set_ylabel(\"Concentrations [nM]\")\n\n\nax3 = plt.subplot(343)\nax3.plot(T, I2_a, color = \"#0000ffff\", alpha=0.75)\nax3.plot(T, I2_b, color = \"#ecececfe\")#, alpha=0.75)\nax3.legend([\"$I_2$\", \"$\\\\overline{I_2}$\"])\n#ax3.set_title('$I_2$ toggle')\nax3.set_xlabel(\"Time [min]\")\nax3.set_ylabel(\"Concentrations [nM]\")\n\n\nax4 = plt.subplot(344)\nax4.plot(T, I3_a, color = \"#800080ff\", alpha=0.75)\nax4.plot(T, I3_b, color = \"#999999fc\")#, alpha=0.75)\nax4.legend([\"$I_3$\", \"$\\\\overline{I_3}$\"])\n#ax4.set_title('$I_3$ toggle')\nax4.set_xlabel(\"Time [min]\")\nax4.set_ylabel(\"Concentrations [nM]\")\n\n\nax5 = plt.subplot(312)\nax5.plot(T,S0, color = \"#ff6600ff\", alpha=0.75)\nax5.plot(T,S1, color = \"#ffff00ff\")#, alpha=0.75)\nax5.legend([\"$S_0$\", \"$S_1$\"])\n#ax5.set_title('Select inputs')\nax5.set_xlabel(\"Time [min]\")\nax5.set_ylabel(\"Concentrations [nM]\")\n\n\nax6 = plt.subplot(313)\nax6.plot(T,out, color = \"#8080805a\", alpha=0.75)\n#ax6.set_title('out')\nax6.legend('out')\nax6.set_xlabel(\"Time [min]\")\nax6.set_ylabel(\"Concentrations [nM]\")\n\nplt.gcf().set_size_inches(15,10)\nplt.show()","sub_path":"cblb/_run_ode_model_clb.py","file_name":"_run_ode_model_clb.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"391911058","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Evaluation functions\n\"\"\"\n\n# external imports\n# ---\n\nimport logging\nimport numpy as np\nfrom sklearn.cluster import AgglomerativeClustering, KMeans\nfrom six import iteritems\nimport six\nimport importlib\nimport os\n\n# internal imports\n# ---\n\nimport web.datasets.synonymy\n\nfrom web.datasets.similarity import *\n\nfrom web.datasets.categorization import *\n\n# import of analogy datasets fetchers\n# and many other things (ex: itertools.product)\n# are accomplished within analogy_solver\n# ---\nfrom web.analogy_solver import *\n\nfrom web.embedding import Embedding\nfrom web.embeddings import load_toy_embedding\nfrom web.embeddings import load_embedding\n\n\ndef evaluate_on_all_datasets(w, wordrep_max_pairs=None):\n \"\"\"\n Evaluate Embedding w on all benchmarks\n\n Input\n -----\n\n w:\n\n Word embedding to evaluate\n (Embedding object or dict)\n\n wordrep_max_pairs:\n\n maximum number of pairs to be considered for the WordRep dataset\n (integer, ex: 50; the default used by the original authors was 1000)\n\n Output\n ------\n\n dfs:\n\n Table with results\n (pandas.DataFrame)\n\n \"\"\"\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n # Synonyms tasks\n # ---\n\n synonymy_datasets = []\n\n # synonymy_datasets.append(\"TOEFL\") # *new*\n # synonymy_datasets.append(\"ESL\") # *new*\n\n # Similarity tasks\n # ---\n\n similarity_datasets = []\n\n # similarity_datasets.append(\"MEN\")\n # similarity_datasets.append(\"WS353\")\n # similarity_datasets.append(\"WS353S\")\n # similarity_datasets.append(\"WS353R\")\n # similarity_datasets.append(\"SimLex999\")\n # similarity_datasets.append(\"RW\")\n # similarity_datasets.append(\"RG65\")\n # similarity_datasets.append(\"MTurk\")\n # similarity_datasets.append(\"TR9856\")\n # similarity_datasets.append(\"SimVerb3500\") # *new*\n\n # Analogy tasks\n # ---\n\n analogy_datasets = []\n\n analogy_datasets.append(\"Google\")\n analogy_datasets.append(\"MSR\")\n analogy_datasets.append(\"SemEval\")\n analogy_datasets.append(\"WordRep\")\n analogy_datasets.append(\"SAT\") # *new*\n analogy_datasets.append(\"BATS\") # *new*\n\n # Categorization tasks\n # ---\n\n categorization_datasets = []\n\n # categorization_datasets.append(\"AP\")\n # categorization_datasets.append(\"BLESS\")\n # categorization_datasets.append(\"battig\")\n # categorization_datasets.append(\"battig2010\") # *new*\n # categorization_datasets.append(\"ESSLLI_1a\")\n # categorization_datasets.append(\"ESSLLI_2b\")\n # categorization_datasets.append(\"ESSLLI_2c\")\n\n # Calculate results on synonymy\n # ---\n\n logger.info(\"\\nCalculating synonymy benchmarks\")\n\n results = {}\n\n for dataset in synonymy_datasets:\n\n df = evaluate_synonymy(w, dataset)\n\n msg = \"\\nResults for {}\\n---\\n{}\".format(dataset, df)\n\n logger.info(msg)\n\n df['task'] = 'synonymy'\n df['dataset'] = dataset\n\n results[dataset] = df\n\n # Calculate results on similarity\n # ---\n\n logger.info(\"\\nCalculating similarity benchmarks\")\n\n for dataset in similarity_datasets:\n\n if dataset == 'WS353R':\n\n mydataset = 'WS353'\n\n kwargs = {'which': 'relatedness'}\n\n elif dataset == 'WS353S':\n\n mydataset = 'WS353'\n\n kwargs = {'which': 'similarity'}\n\n else:\n mydataset = dataset\n\n kwargs = {}\n\n fetch_function_name = \"fetch_\" + mydataset\n module = importlib.import_module(\"web.datasets.similarity\")\n data = getattr(module, fetch_function_name)(**kwargs)\n\n df = evaluate_similarity(w, data.X, data.y)\n\n msg = \"\\nResults for {}\\n---\\n{}\".format(dataset, df)\n\n logger.info(msg)\n\n df['dataset'] = dataset\n df['task'] = 'similarity'\n\n results[dataset] = df\n\n # Calculate results on analogy\n # ---\n\n logger.info(\"\\nCalculating analogy benchmarks\")\n\n for dataset in analogy_datasets:\n\n if dataset == \"Google\":\n\n data = fetch_google_analogy()\n df = evaluate_analogy(w, data.X, data.y, category=data.category)\n\n df['dataset'] = dataset\n\n elif dataset == \"MSR\":\n\n data = fetch_msr_analogy()\n df = evaluate_analogy(w, data.X, data.y, category=data.category)\n\n df['dataset'] = dataset\n\n elif dataset == \"SemEval\":\n\n df = evaluate_on_semeval_2012_2(w)\n\n elif dataset == \"SAT\":\n\n df = evaluate_on_SAT(w)\n\n elif dataset == 'BATS':\n\n df = evaluate_on_BATS(w)\n\n elif dataset == \"WordRep\":\n\n df = evaluate_on_WordRep(w, max_pairs=wordrep_max_pairs)\n\n else:\n\n continue\n\n # msg = \"\\nResults for {}\\n---\\n{}\".format(dataset, df)\n msg = \"\\n\\nResults for {}\\n---\\n\".format(dataset)\n\n logger.info(msg)\n\n # print first four columns\n # ---\n\n print(\"\")\n print(df.iloc[:, 0:2])\n print(\"\")\n print(df.iloc[:, 2:4])\n print(\"\")\n\n results[dataset] = df\n\n # Calculate results on categorization\n # ---\n\n logger.info(\"\\nCalculating categorization benchmarks\")\n\n for dataset in categorization_datasets:\n\n fetch_function_name = \"fetch_\" + dataset\n\n module = importlib.import_module(\"web.datasets.categorization\")\n\n data = getattr(module, fetch_function_name)()\n\n result = evaluate_categorization(w, data.X, data.y)\n\n result['dataset'] = dataset\n\n msg = \"\\nResults for {}\\n---\\n{}\".format(dataset, result)\n\n logger.info(msg)\n\n results[dataset] = result\n\n # Construct pandas table\n # ---\n\n dfs = None\n\n for dataset, df in results.items():\n\n # print(dataset)\n # print(\"---\")\n # df.reset_index(inplace=True)\n # print(df)\n # print(df.shape)\n\n if dfs is None:\n\n dfs = df\n\n else:\n\n # non-concatenation axis is not aligned\n # (i.e., columns are not aligned and have to be)\n # ---\n\n # sort = True -> sort the columns\n # sort = False -> do not sort the columns\n # ---\n\n # dfs = pd.concat([dfs, df], axis=0, ignore_index=True, sort=True)\n dfs = pd.concat([dfs, df], axis=0, ignore_index=True, sort=False)\n\n columns = ['dataset', 'task', 'category',\n 'nb_items', 'nb_items_covered', 'nb_missing_words',\n 'performance', 'performance_type',\n 'performance2', 'performance_type2']\n\n dfs = dfs.reindex(columns=columns)\n\n return dfs\n\n\ndef evaluate_on_all_fast(w):\n \"\"\"\n Evaluate Embedding w on all fast-running benchmarks\n\n Parameters\n ----------\n w: Embedding or dict\n Embedding to evaluate.\n\n Returns\n -------\n results: pandas.DataFrame\n DataFrame with results, one per column.\n \"\"\"\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n # Calculate results on similarity\n # ---\n\n logger.info(\"Calculating similarity benchmarks\")\n\n similarity_tasks = {\n \"MEN\": fetch_MEN(),\n \"WS353\": fetch_WS353(),\n \"WS353R\": fetch_WS353(which=\"relatedness\"),\n \"WS353S\": fetch_WS353(which=\"similarity\"),\n \"SimLex999\": fetch_SimLex999(),\n \"RW\": fetch_RW(),\n \"RG65\": fetch_RG65(),\n \"MTurk\": fetch_MTurk(),\n \"TR9856\": fetch_TR9856(),\n \"SimVerb3500\": fetch_SimVerb3500(),\n }\n\n similarity_results = {}\n\n for name, data in iteritems(similarity_tasks):\n\n # compute Spearkan correlation\n # ---\n similarity_results[name] = evaluate_similarity(w, data.X, data.y)\n\n logger.info(\"Spearman correlation of scores on {} {}\".format(name, similarity_results[name]))\n\n # Calculate results on analogy\n # ---\n\n logger.info(\"Calculating analogy benchmarks\")\n\n analogy_tasks = {\n \"Google\": fetch_google_analogy(),\n \"MSR\": fetch_msr_analogy()\n }\n\n analogy_results = {}\n\n for name, data in iteritems(analogy_tasks):\n\n analogy_results[name] = evaluate_analogy(w, data.X, data.y)\n\n logger.info(\"Analogy prediction accuracy on {} {}\".format(name, analogy_results[name]))\n\n SemEval = evaluate_on_semeval_2012_2(w)\n\n for k in SemEval:\n\n analogy_results[k] = SemEval[k]\n\n logger.info(\"Analogy prediction accuracy on {} {}\".format(\"SemEval2012\", analogy_results[\"SemEval2012_2\"]))\n\n # Calculate results on categorization\n\n logger.info(\"Calculating categorization benchmarks\")\n\n categorization_tasks = {\n \"AP\": fetch_AP(),\n \"BLESS\": fetch_BLESS(),\n \"Battig\": fetch_battig(),\n \"ESSLLI_2c\": fetch_ESSLLI_2c(),\n \"ESSLLI_2b\": fetch_ESSLLI_2b(),\n \"ESSLLI_1a\": fetch_ESSLLI_1a()\n }\n\n categorization_results = {}\n\n # Calculate results using helper function\n\n for name, data in iteritems(categorization_tasks):\n\n categorization_results[name] = evaluate_categorization(w, data.X, data.y)\n\n logger.info(\"Cluster purity on {} {}\".format(name, categorization_results[name]))\n\n # Construct pandas table\n\n cat = pd.DataFrame([categorization_results])\n\n analogy = pd.DataFrame([analogy_results])\n\n sim = pd.DataFrame([similarity_results])\n\n results = cat.join(sim).join(analogy)\n\n return results\n\n\ndef evaluate_similarity(w, X, y):\n \"\"\"\n Calculate Spearman correlation\n between cosine similarity of the model\n and human rated similarity of word pairs\n\n Parameters\n ----------\n w : Embedding or dict\n Embedding or dict instance.\n\n X: array, shape: (n_samples, 2)\n Word pairs\n\n y: vector, shape: (n_samples,)\n Human ratings\n\n Returns\n -------\n cor: float\n Spearman correlation\n \"\"\"\n\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n missing_words = 0\n\n words = w.vocabulary.word_id\n\n nb_items_covered = 0\n\n for query in X:\n\n item_fully_covered = True\n\n for query_word in query:\n\n if query_word not in words:\n\n missing_words += 1\n\n item_fully_covered = False\n\n if item_fully_covered:\n\n nb_items_covered += 1\n\n if missing_words > 0:\n\n logger.warning(\"Missing {} words. Will replace them with mean vector\".format(missing_words))\n\n mean_vector = np.mean(w.vectors, axis=0, keepdims=True)\n\n A = np.vstack(w.get(word, mean_vector) for word in X[:, 0])\n\n B = np.vstack(w.get(word, mean_vector) for word in X[:, 1])\n\n scores = np.array([v1.dot(v2.T) / (np.linalg.norm(v1) * np.linalg.norm(v2)) for v1, v2 in zip(A, B)])\n\n correlation = scipy.stats.spearmanr(scores, y).correlation\n\n nb_items = len(y)\n\n data = [pd.Series(correlation, name=\"performance\"),\n pd.Series(nb_items, name=\"nb_items\"),\n pd.Series(nb_items_covered, name=\"nb_items_covered\"),\n pd.Series(missing_words, name=\"nb_missing_words\")]\n\n results = pd.concat(data, axis=1)\n\n results['performance_type'] = 'spearman correlation'\n\n return results\n\n\ndef calculate_purity(y_true, y_pred):\n \"\"\"\n Calculate purity for given true and predicted cluster labels.\n\n Parameters\n ----------\n y_true: array, shape: (n_samples, 1)\n True cluster labels\n\n y_pred: array, shape: (n_samples, 1)\n Cluster assignment.\n\n Returns\n -------\n purity: float\n Calculated purity.\n\n\n See:\n https://stats.stackexchange.com/questions/95731/how-to-calculate-purity\n \"\"\"\n assert len(y_true) == len(y_pred)\n\n nb_items = len(y_true)\n\n nb_clusters = len(set(true))\n\n true_clusters = np.zeros(shape=(nb_clusters, nb_items))\n\n pred_clusters = np.zeros_like(true_clusters)\n\n # convert the clustering labels to binary format\n # ---\n\n for id, cl in enumerate(set(y_true)):\n\n true_clusters[id] = (y_true == cl).astype(\"int\")\n\n for id, cl in enumerate(set(y_pred)):\n\n pred_clusters[id] = (y_pred == cl).astype(\"int\")\n\n M = pred_clusters.dot(true_clusters.T)\n\n purity = 1. / nb_items * np.sum(np.max(M, axis=1))\n\n\n results = {'purity': purity,\n 'nb_items': nb_items}\n\n return results\n\n\ndef evaluate_categorization(w, X, y, method=\"all\", seed=None):\n \"\"\"\n Evaluate embeddings on categorization task.\n\n Parameters\n ----------\n w: Embedding or dict\n Embedding to test.\n\n X: vector, shape: (n_samples, )\n Vector of words.\n\n y: vector, shape: (n_samples, )\n Vector of cluster assignments.\n\n method: string, default: \"all\"\n What method to use. Possible values are \"agglomerative\", \"kmeans\", \"all.\n If \"agglomerative\" is passed, method will fit AgglomerativeClustering\n (with very crude hyperparameter tuning to avoid overfitting).\n If \"kmeans\" is passed, method will fit KMeans.\n In both cases number of clusters is preset to the correct value.\n\n seed: int, default: None\n Seed passed to KMeans.\n\n Returns\n -------\n purity: float\n Purity of the best obtained clustering.\n\n Notes\n -----\n KMedoids method was excluded as empirically didn't improve over KMeans (for categorization\n tasks available in the package).\n \"\"\"\n\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n assert method in [\"all\", \"kmeans\", \"agglomerative\"], \"Uncrecognized method\"\n\n '''\n NaN happens when there are only 0s,\n which might happen for very rare words or\n very insufficient word vocabulary\n\n In order to prevent problems from happening\n further in the calculation, we could use nanmean()\n instead of mean()\n '''\n\n mean_vector = np.mean(w.vectors, axis=0, keepdims=True)\n # mean_vector = np.nanmean(w.vectors, axis=0, keepdims=True)\n\n words = np.vstack(w.get(word, mean_vector) for word in X.flatten())\n\n missing_words = sum([1 for word in X.flatten() if word not in w])\n # print(\"missing words:\", missing_words)\n\n ids = np.random.RandomState(seed).choice(range(len(X)), len(X), replace=False)\n\n # Evaluate clustering on several hyperparameters of AgglomerativeClustering and\n # KMeans\n best_purity = 0\n\n if method == \"all\" or method == \"agglomerative\":\n\n results = calculate_purity(y[ids], AgglomerativeClustering(n_clusters=len(set(y)),\n affinity=\"euclidean\",\n linkage=\"ward\").fit_predict(words[ids]))\n\n best_purity = results['purity']\n\n logger.debug(\"Purity={:.3f} using affinity={} linkage={}\".format(best_purity, 'euclidean', 'ward'))\n\n for affinity in [\"cosine\", \"euclidean\"]:\n\n for linkage in [\"average\", \"complete\"]:\n\n results = calculate_purity(y[ids], AgglomerativeClustering(n_clusters=len(set(y)),\n affinity=affinity,\n linkage=linkage).fit_predict(words[ids]))\n purity = results['purity']\n\n logger.debug(\"Purity={:.3f} using affinity={} linkage={}\".format(purity, affinity, linkage))\n\n best_purity = max(best_purity, purity)\n\n if method == \"all\" or method == \"kmeans\":\n\n results = calculate_purity(y[ids], KMeans(random_state=seed, n_init=10, n_clusters=len(set(y))).\n fit_predict(words[ids]))\n\n purity = results['purity']\n\n logger.debug(\"Purity={:.3f} using KMeans\".format(purity))\n\n best_purity = max(purity, best_purity)\n\n nb_items = len(y)\n\n nb_items_covered = nb_items - missing_words\n\n data = [pd.Series(best_purity, name=\"performance\"),\n pd.Series(nb_items, name=\"nb_items\"),\n pd.Series(nb_items_covered, name=\"nb_items_covered\"),\n pd.Series(missing_words, name=\"nb_missing_words\")]\n\n df = pd.concat(data, axis=1)\n\n df['performance_type'] = 'purity'\n\n df['task'] = 'categorization'\n\n return df\n\n\ndef evaluate_analogy(w, X, y, method=\"add\", k=None, category=None, batch_size=100):\n \"\"\"\n Simple method to score embedding using SimpleAnalogySolver\n\n used with MSR and GOOGLE datasets\n\n Other datasets use other evaluation methods\n\n Parameters\n ----------\n w : Embedding or dict\n Embedding or dict instance.\n\n method : {\"add\", \"mul\"}\n Method to use when finding analogy answer, see \"Improving Distributional Similarity\n with Lessons Learned from Word Embeddings\"\n\n X : array-like, shape (n_samples, 3)\n Analogy questions.\n\n y : array-like, shape (n_samples, )\n Analogy answers.\n\n k : int, default: None\n If not None will select k top most frequent words from embedding\n\n batch_size : int, default: 100\n Increase to increase memory consumption and decrease running time\n\n category : list, default: None\n Category of each example, if passed function returns accuracy per category\n in addition to the overall performance.\n Analogy datasets have \"category\" field that can be supplied here.\n\n Returns\n -------\n result: dict\n Results, where each key is for given category and special empty key \"\" stores\n summarized accuracy across categories\n \"\"\"\n\n print(\"\\nGoogle or MSR analogy task\\n---\\n\")\n\n print(\"Note: * indicates a missing word (i.e., a word not in the semantic space)\")\n\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n assert category is None or len(category) == y.shape[0], \"Passed incorrect category list\"\n\n solver = SimpleAnalogySolver(w=w, method=method, batch_size=batch_size, k=k)\n\n predictions = solver.predict(X)\n\n y_pred = predictions['predictions']\n\n nic = predictions['nb_items_covered']\n\n nmw = predictions['nb_missing_words']\n\n # informative message\n # ---\n\n for i, (my_X, my_pred, my_y) in enumerate(zip(X, y_pred, y)):\n\n msg = \" - Item \" + str(i) + \" : \"\n\n msg += \" - \".join([x if x in w else x + \"*\" for x in my_X])\n\n msg += \" : ... \" + my_pred + \" ?\"\n\n if my_pred == my_y:\n\n msg += \" CORRECT \"\n\n else:\n\n if my_y in w:\n\n my_y_str = my_y\n\n else:\n\n my_y_str = my_y + \"*\"\n\n msg += \" incorrect (Good answer: \" + my_y_str + \")\"\n\n print(msg)\n\n # calculate performance\n # ---\n\n accuracy = OrderedDict({\"all\": np.mean(y_pred == y)})\n\n count = OrderedDict({\"all\": len(y_pred)})\n\n correct = OrderedDict({\"all\": np.sum(y_pred == y)})\n\n nb_items_covered = OrderedDict({\"all\": np.sum(nic)})\n\n nb_missing_words = OrderedDict({\"all\": np.sum(nmw)})\n\n if category is not None:\n\n for cat in set(category):\n\n accuracy[cat] = np.mean(y_pred[category == cat] == y[category == cat])\n\n count[cat] = np.sum(category == cat)\n\n correct[cat] = np.sum(y_pred[category == cat] == y[category == cat])\n\n nb_items_covered[cat] = np.sum(nic[category == cat])\n\n nb_missing_words[cat] = np.sum(nmw[category == cat])\n\n df = pd.concat([pd.Series(accuracy, name=\"performance2\"),\n pd.Series(correct, name=\"performance\"),\n pd.Series(count, name=\"nb_items\"),\n pd.Series(nb_items_covered, name=\"nb_items_covered\"),\n pd.Series(nb_missing_words, name=\"nb_missing_words\"),\n ],\n axis=1)\n\n df['category'] = df.index\n\n df['performance_type'] = 'nb_items_correct'\n df['performance_type2'] = 'accuracy = nb_items_correct / nb_items'\n\n df['task'] = 'analogy'\n\n return df\n\n\ndef evaluate_on_semeval_2012_2(w):\n \"\"\"\n Simple method to score embedding\n\n Note:\n it is NOT using SimpleAnalogySolver\n but another method\n\n Parameters\n ----------\n w : Embedding or dict\n Embedding or dict instance.\n\n Returns\n -------\n result: pandas.DataFrame\n\n Results with spearman correlation\n per broad category\n with special key \"all\" for summary\n\n \"\"\"\n\n print(\"\\nSemEval 2012 analogy task\\n---\\n\")\n\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n data = fetch_semeval_2012_2()\n\n '''\n NaN happens when there are only 0s,\n which might happen for very rare words or\n very insufficient word vocabulary\n\n In order to prevent problems from happening\n further in the calculation, we could use nanmean()\n instead of mean()\n '''\n\n mean_vector = np.mean(w.vectors, axis=0, keepdims=True)\n # mean_vector = np.nanmean(w.vectors, axis=0, keepdims=True)\n\n categories = data.y.keys()\n\n results = defaultdict(list)\n nb_items = defaultdict(list)\n nb_missing_words = defaultdict(list)\n nb_items_covered = defaultdict(list)\n\n j = 0\n\n for c in categories:\n\n c_name = data.categories_names[c].split(\"_\")[0]\n\n j += 1\n\n print(\"\\n{}) Category {} : {}\\n---\".format(j, c, c_name))\n\n prototypes = data.X_prot[c]\n\n nmw = 0\n\n for words in prototypes:\n\n for word in words:\n\n if word not in w:\n\n nmw += 1\n\n if nmw > 0:\n\n nic = 0\n\n else:\n\n nic = 1\n\n nb_missing_words[c_name].append(nmw)\n nb_items[c_name].append(1)\n nb_items_covered[c_name].append(nic)\n\n # Get mean of left and right vector\n # ---\n\n prot_left = np.mean(np.vstack(w.get(word, mean_vector) for word in prototypes[:, 0]), axis=0)\n\n prot_right = np.mean(np.vstack(w.get(word, mean_vector) for word in prototypes[:, 1]), axis=0)\n\n questions = data.X[c]\n\n question_left = np.vstack(w.get(word, mean_vector) for word in questions[:, 0])\n\n question_right = np.vstack(w.get(word, mean_vector) for word in questions[:, 1])\n\n scores = np.dot(prot_left - prot_right, (question_left - question_right).T)\n\n # print(scores)\n # print(data.y[c])\n\n try:\n\n cor = scipy.stats.spearmanr(scores, data.y[c]).correlation\n\n except Exception as e:\n\n print(\"\\n\\n\\nERROR\")\n print()\n print(e)\n print()\n print(\"\\n\\nCategory:\\n\", c)\n print(\"\\n\\nscores:\\n\", scores)\n print(\"\\n\\nprot_left:\\n\", prot_left)\n print(\"\\n\\nprot_right:\\n\", prot_right)\n print(\"\\n\\nquestion_left:\\n\", question_left)\n print(\"\\n\\nquestion_right:\\n\", question_right)\n\n print(\"\\n\\ndata.y[c]:\\n\", data.y[c])\n\n print(\"\\n\\nMean vector:\\n\", mean_vector)\n print()\n\n cor = np.nan\n\n results[c_name].append(0 if np.isnan(cor) else cor)\n\n for i, (pl, pr) in enumerate(zip(prototypes[:, 0], prototypes[:, 1])):\n\n if pl not in w:\n pl = pl + \"*\"\n\n if pr not in w:\n pr = pr + \"*\"\n\n print(\"- Prototypes {} : ('{}' - '{}') \".format(i, pl, pr))\n\n for i, (ql, qr, s, d) in enumerate(zip(questions[:, 0], questions[:, 1], scores, data.y[c])):\n\n if ql not in w:\n ql = ql + \"*\"\n\n if qr not in w:\n qr = qr + \"*\"\n\n print(\"- Item {0} : ('{1}' - '{2}') = {3:.2f} --- {4}\".format(i, ql, qr, s, d))\n\n if cor is not np.nan:\n\n cor = round(cor, 3)\n\n print(\"---\\nSpearman correlation = \", cor)\n\n final_results = OrderedDict()\n final_nb_items = OrderedDict()\n final_nb_missing_words = OrderedDict()\n final_nb_items_covered = OrderedDict()\n\n # average correlation\n # ---\n final_results['all'] = sum(sum(v) for v in results.values()) / len(categories)\n\n final_nb_items['all'] = sum(sum(v) for v in nb_items.values())\n final_nb_missing_words['all'] = sum(sum(v) for v in nb_missing_words.values())\n final_nb_items_covered['all'] = sum(sum(v) for v in nb_items_covered.values())\n\n for k in results:\n\n # average correlation\n # ---\n final_results[k] = sum(results[k]) / len(results[k])\n\n final_nb_items[k] = sum(nb_items[k])\n final_nb_missing_words[k] = sum(nb_missing_words[k])\n final_nb_items_covered[k] = sum(nb_items_covered[k])\n\n df = pd.concat([pd.Series(final_results, name=\"performance\"),\n pd.Series(final_nb_items, name=\"nb_items\"),\n pd.Series(final_nb_items_covered, name=\"nb_items_covered\"),\n pd.Series(final_nb_missing_words, name=\"nb_missing_words\"),\n ],\n axis=1)\n\n # series = pd.Series(final_results)\n\n # df = series.to_frame(name='performance')\n\n df['category'] = df.index\n\n df['performance_type'] = 'average_correlation'\n\n df['dataset'] = 'SemEval'\n\n df['task'] = 'analogy'\n\n return df\n\n\ndef evaluate_on_WordRep(w, max_pairs=None, solver_kwargs={}):\n \"\"\"\n Evaluate on WordRep dataset\n\n Parameters\n ----------\n w : Embedding or dict\n Embedding or dict instance.\n\n max_pairs: int, default: None\n Each category will be constrained to maximum of max_pairs pairs\n (which results in max_pair * (max_pairs - 1) examples)\n\n solver_kwargs: dict, default: {}\n Arguments passed to SimpleAnalogySolver. It is suggested to limit number of words\n in the dictionary.\n\n References\n ----------\n Bin Gao, Jiang Bian, Tie-Yan Liu (2015)\n \"WordRep: A Benchmark for Research on Learning Word Representations\"\n \"\"\"\n\n print(\"\\nEvaluation of WordRep analogy with max_pairs = \", max_pairs, \"\\n---\")\n\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n data = fetch_wordrep()\n\n categories = set(data.category)\n\n accuracy = {}\n\n correct = {}\n\n count = {}\n\n missing = {}\n\n items_covered = {}\n\n for category in categories:\n\n print(\"Category : \", category, \"\\n---\")\n\n X_cat = data.X[data.category == category]\n\n if max_pairs:\n\n # further limit the number of pairs to consider\n # ---\n X_cat = X_cat[0:max_pairs]\n\n nb_pairs = X_cat.shape[0]\n\n nb_questions = nb_pairs * (nb_pairs - 1)\n\n logger.info(\"Processing {} with {} pairs, {} questions\".\n format(category, nb_pairs, nb_questions))\n\n # For each category construct question-answer pairs\n # ---\n\n X = np.zeros(shape=(nb_questions, 3), dtype=\"object\")\n\n y = np.zeros(shape=(nb_questions,), dtype=\"object\")\n\n id = 0\n\n # to find all permutations\n # iterate through the Cartesian product\n # ---\n\n for left, right in product(X_cat, X_cat):\n\n if not np.array_equal(left, right):\n\n # we exclude the cases when left = right\n # ---\n\n X[id, 0:2] = left\n\n X[id, 2] = right[0]\n\n y[id] = right[1]\n\n id += 1\n\n # Run solver\n # ---\n\n solver = SimpleAnalogySolver(w=w, **solver_kwargs)\n\n results = solver.predict(X)\n\n y_pred = results['predictions']\n\n nb_correct = float(np.sum(y_pred == y))\n\n for i, (x1,x2,x3,y_obs,y_true) in enumerate(zip(X[:,0],X[:,1],X[:,2], y_pred, y)):\n\n if x1 not in w:\n x1 = x1 + \"*\"\n\n if x2 not in w:\n x2 = x2 + \"*\"\n\n if x3 not in w:\n x3 = x3 + \"*\"\n\n if y_true not in w:\n y_true = y_true + \"*\"\n\n if y_obs == y_true:\n\n cor_msg = \"OK\"\n\n else:\n\n cor_msg = \"---> wrong ! Correct : \" + y_true\n\n print(\"- Item {} : {} - {}, {} - ... {} ? {}\".format(i, x1,x2,x3,y_obs,cor_msg))\n\n correct[category] = nb_correct\n\n count[category] = nb_questions\n\n accuracy[category] = nb_correct / nb_questions\n\n missing[category] = sum(results['nb_missing_words'])\n\n items_covered[category] = sum(results['nb_items_covered'])\n\n # Add summary results\n # ---\n\n for summary in ('all', 'wikipedia', 'wordnet'):\n\n missing[summary] = 0\n correct[summary] = 0\n count[summary] = 0\n items_covered[summary] = 0\n\n for c in categories:\n\n missing['all'] += missing[c]\n items_covered['all'] += items_covered[c]\n correct['all'] += correct[c]\n count['all'] += count[c]\n\n if c in data.wikipedia_categories:\n\n missing['wikipedia'] += missing[c]\n items_covered['wikipedia'] += items_covered[c]\n correct['wikipedia'] += correct[c]\n count['wikipedia'] += count[c]\n\n if c in data.wordnet_categories:\n\n missing['wordnet'] += missing[c]\n items_covered['wordnet'] += items_covered[c]\n correct['wordnet'] += correct[c]\n count['wordnet'] += count[c]\n\n accuracy['all'] = correct['all'] / count['all']\n accuracy['wikipedia'] = correct['wikipedia'] / count['wikipedia']\n accuracy['wordnet'] = correct['wordnet'] / count['wordnet']\n\n data = [pd.Series(accuracy, name=\"performance2\"),\n pd.Series(correct, name=\"performance\"),\n pd.Series(count, name=\"nb_items\"),\n pd.Series(items_covered, name=\"nb_items_covered\"),\n pd.Series(missing, name=\"nb_missing_words\")]\n\n df = pd.concat(data, axis=1)\n\n df['performance_type'] = 'nb_items_correct'\n df['performance_type2'] = 'accuracy = nb_items_correct / nb_items'\n\n df['category'] = df.index\n\n df['dataset'] = 'WordRep'\n\n df['task'] = 'analogy'\n\n return df\n\n\ndef evaluate_on_BATS(w, solver_kwargs={}):\n \"\"\"\n Evaluate on the BATS dataset\n\n Parameters\n ----------\n w : Embedding or dict\n Embedding or dict instance.\n\n solver_kwargs: dict, default: {}\n Arguments passed to SimpleAnalogySolver.\n Note: It is suggested to limit number of words in the dictionary.\n\n References\n ----------\n Gladkova, A., Drozd, A., & Matsuoka, S. (2016). Analogy-Based Detection of Morphological and Semantic Relations with Word Embeddings: What Works and What Doesn’t. In Proceedings of the NAACL-HLT SRW (pp. 47–54). San Diego, California, June 12-17, 2016: ACL. https://doi.org/10.18653/v1/N16-2002\n\n \"\"\"\n\n print(\"\\nEvaluation of BATS analogy\\n---\")\n\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n data = fetch_BATS()\n\n categories = set(data.category)\n\n # just used two categories --- for testing purposes\n # categories = list(categories)[0:2]\n\n accuracy = {}\n\n correct = {}\n\n items = {}\n\n items_covered = {}\n\n missing = {}\n\n for category in categories:\n\n print(\"\\nCategory : \" + category)\n\n pairs = data.X[data.category == category]\n\n # convert numpy array to list of lists\n # ---\n pairs = pairs.tolist()\n\n # we want to keep only the pairs covered\n # ---\n\n # filter 1\n # ---\n pairs = [(target_word, candidate) for target_word, candidate in pairs if target_word in w]\n\n # filter 2\n # ---\n final_pairs = []\n\n for target_word, candidate in pairs:\n\n found_word = False\n\n if \"/\" not in candidate:\n\n if candidate in w:\n\n found_word = True\n\n else:\n\n words = candidate.split(\"/\")\n\n for word in words:\n\n if word in w:\n\n # keep as a candidate the first word\n # found in the vocabulary\n # ---\n\n found_word = True\n\n candidate = word\n\n break\n\n if found_word:\n\n word_pair = (target_word, candidate)\n\n final_pairs.append(word_pair)\n\n nb_pairs = len(final_pairs)\n\n if nb_pairs == 0:\n\n continue\n\n nb_questions = nb_pairs * (nb_pairs - 1)\n\n logger.info(\"Processing {} with {} pairs, {} questions\".\n format(category, nb_pairs, nb_questions))\n\n # For each category construct question-answer pairs\n # ---\n\n X = np.zeros(shape=(nb_questions, 3), dtype=\"object\")\n\n y = np.zeros(shape=(nb_questions,), dtype=\"object\")\n\n id = 0\n\n # to find all permutations\n # iterate through the Cartesian product\n # ---\n\n for left, right in product(final_pairs, final_pairs):\n\n if not np.array_equal(left, right):\n\n # we exclude the cases when left = right\n # ---\n\n X[id, 0:2] = left\n\n X[id, 2] = right[0]\n\n y[id] = right[1]\n\n id += 1\n\n # Run solver\n # ---\n\n solver = SimpleAnalogySolver(w=w, **solver_kwargs)\n\n results = solver.predict(X)\n\n\n for i, (x1,x2,x3,y_obs,y_true) in enumerate(zip(X[:,0],X[:,1],X[:,2], results['predictions'], y)):\n\n if x1 not in w:\n x1 = x1 + \"*\"\n\n if x2 not in w:\n x2 = x2 + \"*\"\n\n if x3 not in w:\n x3 = x3 + \"*\"\n\n if y_true not in w:\n y_true = y_true + \"*\"\n\n if y_obs == y_true:\n\n cor_msg = \"OK\"\n\n else:\n\n cor_msg = \"---> wrong ! Correct : \" + y_true\n\n print(\"- Item {} : {} - {}, {} - ... {} ? {}\".format(i, x1,x2,x3,y_obs,cor_msg))\n\n\n nb_correct = float(np.sum(results['predictions'] == y))\n\n correct[category] = nb_correct\n\n items[category] = 2450\n\n items_covered[category] = nb_questions\n\n # missing[category] = np.NaN\n\n missing[category] = np.sum(results['nb_missing_words'])\n\n accuracy[category] = nb_correct / nb_questions\n\n # Add summary results\n # ---\n\n correct['all'] = sum(v for v in correct.values())\n items['all'] = sum(v for v in items.values())\n items_covered['all'] = sum(v for v in items_covered.values())\n missing['all'] = sum(v for v in missing.values())\n accuracy['all'] = correct['all'] / items_covered['all']\n\n data = [pd.Series(accuracy, name=\"performance2\"),\n pd.Series(correct, name=\"performance\"),\n pd.Series(missing, name=\"nb_missing_words\"),\n pd.Series(items, name=\"nb_items\"),\n pd.Series(items_covered, name=\"nb_items_covered\")]\n\n df = pd.concat(data, axis=1)\n\n df['category'] = df.index\n\n df['dataset'] = 'BATS'\n\n df['task'] = 'analogy'\n\n df['performance_type'] = 'nb_items_correct'\n df['performance_type2'] = 'accuracy = nb_items_correct / nb_items'\n\n return df\n\n\ndef cosine_similarity_dense(vector1, vector2):\n '''\n\n Takes a input dense vectors.\n\n Returns the angular difference between two vectors.\n\n It is calculated as the ratio of\n the dot product and\n the product of the magnitudes (norms) of the vectors.\n\n cos = v1 - v2 / |v1| * |v2|\n\n Note:\n\n it is useless to divide by the product of the norms if\n the vectors are already normalized.\n\n In the case where vectors are already normalized, the dot product suffices.\n '''\n\n dot_product = np.dot(vector1, vector2)\n\n vector1_mag = np.linalg.norm(vector1)\n\n vector2_mag = np.linalg.norm(vector2)\n\n result = dot_product / (vector1_mag * vector2_mag)\n\n return result\n\n\ndef answer_SAT_analogy_question(question, answers, w, solver):\n '''\n\n '''\n\n nb_rows = len(answers)\n\n # init\n # ---\n X = np.zeros(shape=(nb_rows, 3), dtype=\"object\")\n\n y = np.zeros(shape=(nb_rows,), dtype=\"object\")\n\n # for i in range(nb_rows):\n\n # print(\"triple\", i + 1, \":\", X[i, ], \"candidate:\", y[i])\n\n # filling\n # ---\n\n for i, answer in enumerate(answers):\n\n X[i, 0] = question[0]\n X[i, 1] = question[1]\n X[i, 2] = answer[0]\n y[i] = answer[1]\n\n # for i in range(nb_rows):\n\n # print(\"- triple\", i + 1, \":\", X[i, ], \"candidate:\", y[i])\n\n # prediction through the analogy solver\n # ---\n\n results = solver.predict(X)\n\n y_pred = results['predictions']\n missing_words = sum(results['nb_missing_words'])\n items_covered = sum(results['nb_items_covered'])\n\n selected_answer = None\n selected_cosine = None\n\n for i in range(nb_rows):\n\n # prediction\n # ---\n\n predicted_word = y_pred[i]\n\n predicted_vector = w[predicted_word]\n\n # candidate\n # ---\n\n candidate_word = y[i]\n\n cosine = None\n\n selected = \"\"\n\n if candidate_word in w:\n\n candidate_vector = w[candidate_word]\n\n cosine = cosine_similarity_dense(predicted_vector, candidate_vector)\n\n if selected_answer is None or cosine >= selected_cosine:\n\n selected_answer = i\n selected_cosine = cosine\n\n selected = \"SELECTED\"\n\n else:\n\n # print(\"The candidate word is not in the vocabulary. This item is ignored.\")\n\n candidate_word += \"*\"\n\n\n myX = [x if x in w else x+\"*\" for x in X[i, ]]\n\n myX = myX[0] + \" - \" + myX[1] + \", \" + myX[2]\n\n if cosine is not None:\n\n cosine = round(cosine, 3)\n\n else:\n\n cosine = \"?\"\n\n print(\"- triple\", i + 1, \":\", myX, \" ... \", candidate_word, \"? ---> prediction:\", predicted_word, \", cosine:\", cosine, selected)\n\n # i = selected_answer\n\n # print(\"\\nSelected answer: triple\", i + 1, \":\", X[i, ], \", candidate:\", y[i])\n\n if selected_answer == 0:\n\n print(\" OK \")\n\n else:\n\n print(\" --- incorrect --- \")\n\n results = {'selected_answer': selected_answer,\n 'nb_missing_words': missing_words,\n 'nb_items_covered': items_covered}\n\n return results\n\n\ndef evaluate_on_SAT(w, solver_kwargs={}):\n \"\"\"\n Evaluate on the SAT analogy dataset\n\n Parameters\n ----------\n w : Embedding or dict\n Embedding or dict instance.\n\n solver_kwargs: dict, default: {}\n Arguments passed to SimpleAnalogySolver. It is suggested to limit number of words\n in the dictionary.\n\n References\n ----------\n Turney, P. D., Littman, M. L., Bigham, J., & Shnayder, V. (2003). Combining independent modules to solve multiple-choice synonym and analogy problems. In Proceedings of the International Conference on Recent Advances in Natural Language Processing (RANLP-03).\n\n \"\"\"\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n solver = SimpleAnalogySolver(w=w, **solver_kwargs)\n # solver = SimpleAnalogySolver(w=w)\n\n data = fetch_SAT()\n\n nb_items = len(data.X)\n\n nb_items_correct = 0\n\n missing_words = 0\n\n items_covered = 0\n\n for i in range(nb_items):\n\n print(\"\\nSAT analogy question {}\\n---\".format(i))\n\n question = data.X[i].split(\"_\")\n\n answers = data.y[i, :]\n\n '''\n We split while testing for string to avoid attempting to split\n nan values, which occurs when there are 4 alternatives instead of 5.\n '''\n\n answers = [answer.split(\"_\") for answer in answers\n if isinstance(answer, six.string_types)]\n\n # print(question, answers)\n\n response = answer_SAT_analogy_question(question, answers, w, solver)\n\n nmw = response['nb_missing_words']\n\n missing_words += nmw\n\n if nmw == 0:\n\n items_covered += 1\n\n i = response['selected_answer']\n\n # print(i)\n\n if i == 0:\n # this is the good answer\n nb_items_correct += 1\n # print(\"\\n*** Yes! ***\")\n\n # print(\"\\nNumber of items:\", nb_items, \"Number of correct answers:\", nb_items_correct)\n\n accuracy = nb_items_correct / nb_items\n\n data = [pd.Series(accuracy, name=\"performance2\"),\n pd.Series(nb_items_correct, name=\"performance\"),\n pd.Series(nb_items, name=\"nb_items\"),\n pd.Series(items_covered, name=\"nb_items_covered\"),\n pd.Series(missing_words, name=\"nb_missing_words\")]\n\n df = pd.concat(data, axis=1)\n\n df['dataset'] = 'SAT'\n\n df['task'] = 'analogy'\n\n df['performance_type'] = 'nb_items_correct'\n df['performance_type2'] = 'accuracy = nb_items_correct / nb_items'\n\n return df\n\n\ndef answer_synonymy_question(question, answers, w):\n '''\n\n '''\n\n print(\"\\nWhat is the synonym of: \", question, \" ?\\n---\\n\")\n\n if question in w:\n\n question_vector = w[question]\n\n else:\n '''\n If we do not have a vector for the question,\n we cannot answer it.\n We do not try responding at random.\n The selected answer is therefore 'None'.\n '''\n\n response = {'selected_answer': None, 'selected_cosine': None}\n\n print(\"We don't know, because it is NOT in the word embedding.\", \"\\n\")\n\n return response\n\n selected_answer = None\n\n selected_cosine = None\n\n nb_answers = len(answers)\n\n # choose the answer which has the highest cosine\n # ---\n\n for i in range(nb_answers):\n\n answer = answers[i]\n\n msg = \"- answer \" + str(i) + \": \" + answer\n\n if answer in w:\n\n answer_vector = w[answer]\n\n cosine = cosine_similarity_dense(question_vector, answer_vector)\n\n msg += \" (cosine : \" + str(round(cosine, 3)) + \") \"\n\n if selected_answer is None or cosine >= selected_cosine:\n\n '''\n We keep the first answer found\n or the one that has the highest cosine.\n '''\n\n selected_answer = i\n\n selected_cosine = cosine\n\n msg += \" SELECTED \"\n\n else:\n\n msg += \" NOT in the word embedding! \"\n\n print(msg)\n\n response = {'selected_answer': selected_answer, 'selected_cosine': selected_cosine}\n\n return response\n\n\ndef evaluate_synonymy(w, dataset_name):\n '''\n\n Evaluate the words embedding on a synonymy dataset\n\n '''\n\n if isinstance(w, dict):\n\n w = Embedding.from_dict(w)\n\n # set the fetch function name\n # ---\n fetch_function_name = \"fetch_\" + dataset_name\n\n # retrieve the dataset\n # ---\n data = getattr(web.datasets.synonymy, fetch_function_name)()\n\n # the question\n # ---\n X = data.X\n\n # the answers\n # ---\n y = data.y\n\n nb_items = data.X.shape[0]\n\n # TEMP ---\n nb_questions = len(X)\n nb_answers = data.y.shape[1]\n print(nb_items, \"items, i.e., \", nb_questions, \"questions:\", X, \"\\n\")\n print(nb_answers, \"answers per items:\", y, \"\\n\")\n # --- TEMP\n\n nb_items_correct = 0\n\n nb_items_covered = 0\n\n nb_missing_words = 0\n\n for i in range(nb_items):\n\n question = X[i]\n\n answers = y[i]\n\n # print(question, answers)\n\n response = answer_synonymy_question(question, answers, w)\n\n selected_answer = response['selected_answer']\n selected_cosine = response['selected_cosine']\n\n # print(i)\n\n if selected_answer is not None:\n\n nb_items_covered += 1\n\n if selected_answer == 0:\n\n # this is the good answer\n # ---\n nb_items_correct += 1\n\n print(\"\\nGOOD answer.\\n\")\n\n else:\n\n print(\"\\nIncorrect answer!\\n\")\n\n else:\n\n # the word is not in the vocabulary\n # ---\n\n nb_missing_words += 1\n\n accuracy = nb_items_correct / nb_items_covered\n\n print(\"\\nPerformance to the synonym task\\n---\\n\")\n print(\"Number of good answers = \", str(nb_items_correct), \"\\n\")\n print(\"Number of items = \", str(nb_items), \"\\n\")\n print(\"Number of items covered = \", str(nb_items_covered), \"\\n\")\n print(\"Accuracy = nb items correct / nb items covered = \", str(accuracy), \"\\n\")\n\n data = [pd.Series(accuracy, name=\"performance2\"),\n pd.Series(nb_items_correct, name=\"performance\"),\n pd.Series(nb_items, name=\"nb_items\"),\n pd.Series(nb_items_covered, name=\"nb_items_covered\"),\n pd.Series(nb_missing_words, name=\"nb_missing_words\")]\n\n df = pd.concat(data, axis=1)\n\n df['performance_type'] = 'nb_items_correct'\n df['performance_type2'] = 'accuracy = nb_items_correct / nb_items_covered'\n\n return df\n\n\ndef test_toy_synonymy():\n '''\n\n '''\n print(\"\\n\\nTest toy words embeddings on synonymy\")\n print(\"---\")\n\n # logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%I:%M:%S')\n\n logger = logging.getLogger(__name__)\n\n w = load_toy_embedding()\n\n print(w)\n\n results = evaluate_synonymy(w, \"ESL\")\n\n output_path = os.path.expanduser(\"~/Downloads/results.csv\")\n results.to_csv(output_path)\n\n print(results)\n\n print(\"---THE END---\")\n\n\ndef test_toy_all():\n '''\n\n '''\n print(\"\\n\\nTest toy words embeddings on all datasets\")\n print(\"---\")\n\n # logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%I:%M:%S')\n\n logger = logging.getLogger(__name__)\n\n w = load_toy_embedding()\n\n print(w)\n\n results = evaluate_on_all_datasets(w, wordrep_max_pairs=50)\n\n output_path = os.path.expanduser(\"~/Downloads/results.csv\")\n results.to_csv(output_path)\n\n print(results)\n\n print(\"---THE END---\")\n\n\ndef test_ri_all():\n '''\n\n\n\n '''\n\n print(\"\\n\\nTests RI words embedding on all datasets\")\n print(\"---\")\n\n logger = logging.getLogger(__name__)\n\n input_file = '/media/patrick/my_data/DSM/07_models/RI/2_300_window/text-1.distvecs.decoded'\n\n w = load_embedding(fname=input_file,\n format=\"word2vec\",\n normalize=False,\n # normalize=True\n lower=False,\n clean_words=False)\n\n print(w)\n\n results = evaluate_on_all_datasets(w, wordrep_max_pairs=50)\n\n output_path = os.path.expanduser(\"~/Downloads/results2.csv\")\n results.to_csv(output_path)\n\n print(results)\n\n print(\"---THE END---\")\n\n\nif __name__ == \"__main__\":\n\n test_toy_synonymy()\n\n # test_ri_all()\n\n # test_toy_all()\n","sub_path":"web/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":46085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"638171311","text":"import configparser\r\nimport datetime\r\n\r\n\r\n# ===========Function: Write to log file==============\r\n# Arguments: [1]\r\n# Arguments: [Log Content]\r\ndef write_log(str1):\r\n config = configparser.ConfigParser()\r\n config.sections()\r\n config.read(\"config.ini\")\r\n config.sections()\r\n\r\n # Log config\r\n is_log = config[\"LOG\"][\"is_log\"]\r\n log_file_path = config[\"LOG\"][\"full_path\"] + str(datetime.date.today()) + \".txt\"\r\n # Open file and write log\r\n if is_log:\r\n log_file = open(log_file_path, \"w+\")\r\n log_file.writelines(str(datetime.datetime.now()) + \": \" + str1)\r\n log_file.close()\r\n# ====================================================\r\n\r\n","sub_path":"log_writer.py","file_name":"log_writer.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"139224644","text":"#!/usr/bin/python\n\nimport rospy\nfrom rospydemo.msg import *\n\nrospy.init_node('talker',anonymous=0)\npub=rospy.Publisher('chatter',Mes,queue_size=10)\nrate=rospy.Rate(1)\nwhile not rospy.is_shutdown():\n pub.publish('i am talker')\n rate.sleep()\n\n\n","sub_path":"src/talker.py","file_name":"talker.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"418496015","text":"from plyfile import PlyData\nimport os\nimport sys\n\nreconstruction_dir = sys.argv[1]\nreadpath = os.path.join(reconstruction_dir, \"PMVS\", \"models\", \"option-0000.ply\")\nfname = os.path.basename(os.path.dirname(os.path.dirname(reconstruction_dir)))\nwritepath = os.path.join(reconstruction_dir, \"PMVS\", \"models\", fname + \".ply\")\nplydata = PlyData.read(str(readpath))\nplydata = PlyData([plydata['vertex']], text=False, byte_order='<')\nplydata.write(str(writepath))","sub_path":"scripts/ply2bin.py","file_name":"ply2bin.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"35415311","text":"# -*- coding: utf-8 -*-\n\"\"\"\n8ball plugin\n\"\"\"\nimport re\nimport random\nfrom time import time\nfrom pydle.plugins import Plugin\n\np = Plugin(__name__)\n\noutcomes = [\n # positive\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 # neutral\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 # negative\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\n\n@p.cmd('8ball')\ndef make_prediction(event):\n \"\"\"Your classic 8ball\"\"\"\n # seed random generator\n question = re.sub(r'[^0-9a-z ]', '', event.arg.lower()).strip()\n\n if question:\n # ensure same answer for same question, 1hr interval\n s1 = sum(map(ord, question)) % 3600\n s2 = divmod(int(time()), 3600)[0] * 3600\n random.seed(s1+s2)\n\n prediction = random.choice(outcomes)\n\n if question:\n random.seed() # reseed PRGN\n\n event.reply_to_user(prediction)\n","sub_path":"pydle-8ball.py","file_name":"pydle-8ball.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"173703793","text":"import cv2\nimport sys\n\ndef mouse_event(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONUP:\n cv2.circle(img, (x, y), 50, (0,0,255))\n print(\"x=\"+str(x)+\",y=\"+str(y))\n\nimg = cv2.imread(\"piece_3.jpg\")\nheight = img.shape[0]\nwidth = img.shape[1]\nprint(\"height=\"+str(height)+\",width=\"+str(width))\nimg = cv2.resize(img, (int(width/2),int(height/2)))\ncv2.namedWindow(\"img\", cv2.WINDOW_NORMAL)\ncv2.setMouseCallback(\"img\", mouse_event)\ncv2.imshow(\"img\", img)\ninput1 = sys.stdin.readline()\nprint(\"input1=\"+input1)\nwhile(True):\n cv2.imshow(\"img\", img)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\ncv2.destroyAllWindows()\n","sub_path":"gui1.py","file_name":"gui1.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"634944831","text":"import os\nimport sys\nimport threading\nimport time\nimport requests\nimport xlwt\nimport configparser\nfrom terminaltables import SingleTable\nfrom bs4 import BeautifulSoup\n\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\nwebsites = [] # Parsable websites.\nproducts = []\n\n# Class declaration.\nclass website:\n def __init__(self, name, initials):\n self.name = name\n self.initials = initials\n self.products = []\n\n def add_product(self, product):\n self.products.append(product)\n\nclass product:\n def __init__(self, name, price):\n self.name = name\n self.price = price\n\ncls = lambda: os.system('cls') # Clears screen.\n\n# Displays the current status.\ndef print_status():\n loading_symbols = [\" --\", \" \\\\\", \" |\", \" /\", \" --\"]\n t = threading.currentThread()\n\n while getattr(t, \"do_run\", True):\n for i in range(0, 5):\n cls()\n print(\"\\n \" + message + loading_symbols[i])\n time.sleep(0.1)\n cls()\n\nt = threading.Thread(target=print_status)\nt.start()\n\n# Creates website objects and fills array.\nfile = open(\"source/websites.txt\", \"r\")\nlines = file.read().split(\"\\n\")\nfile.close()\n\nfor i, token in enumerate(lines):\n if token == \"\":\n continue\n name = token[:token.find(\";\")]\n initials = token[token.find(\";\") + 1:]\n websites.append(website(name, initials))\n\ndef website_exists(website_name):\n for i, token in enumerate(websites):\n if website_name in token.name:\n return i\n\ndef extract_price_from_product(url, website_name):\n data = requests.get(url).text\n soup = BeautifulSoup(data, \"html.parser\")\n\n price = \"\"\n\n try:\n if website_name == \"bike-discount\" or website_name == \"sportsonline\":\n price = soup.find(\"span\", {\"class\": \"price\"}).text\n\n elif website_name == \"fitnessdigital\":\n price = soup.find(\"strong\", {\"class\": \"price center-block\"}).text\n\n elif website_name == \"deporvillage\":\n price = soup.find(\"span\", {\"class\": \"price\"}).text\n\n elif website_name == \"runnerinn\":\n price = soup.find(\"p\", {\"class\": \"valPrice\"}).text\n\n elif website_name == \"bike24\":\n price = soup.find(\"span\", {\"class\": \"text-value js-price-value\"}).text\n\n elif website_name == \"decathlon\":\n price = soup.find(\"span\", {\"id\": \"real_price_value\"}).text\n\n elif website_name == \"retto\":\n price = soup.find(\"span\", {\"class\": \"priceact\"}).text\n\n except AttributeError:\n return\n\n price = price.replace(\" \", \"\")\n price = price.replace(\" \", \"\")\n price = price.replace(\"€\", \"\")\n price = price.replace(\",\", \".\")\n\n return float(price)\n\n# Analyse the URL file.\nfile = open(\"source/url.txt\", \"r\")\nlines = file.read().split(\"\\n\")\nfile.close()\n\nlink_count = 0\n\ncurrent_product = \"\"\nfor i, token in enumerate(lines):\n\n link_count += 1\n message = \"Parsing URLs (\" + str(link_count) + \"/\" + str(len(lines)) + \")...\"\n\n if \"#\" in token: # Finds products.\n current_product = token[2:]\n products.append(current_product)\n elif token == \"\":\n continue\n else:\n temp = token[token.find(\".\") + 1:]\n temp = temp[:-len(temp) + temp.find(\".\")]\n\n web_index = website_exists(temp)\n\n price = extract_price_from_product(token, temp)\n if price == None:\n continue\n\n prod = product(current_product, price)\n #print(str(prod.name) + \" \" + str(prod.price))\n websites[web_index].add_product(prod)\n #print(len(websites[web_index].products))\n\ndef construct_table():\n table_data = []\n\n # Adds headers (website initials).\n header_row = [\"\"]\n for i, token in enumerate(websites):\n header_row.append(websites[i].initials)\n table_data.append(header_row)\n\n normal_row = []\n for i, name in enumerate(products):\n normal_row.append(name)\n\n for j, prods in enumerate(websites):\n found = False\n\n for k, prod in enumerate(websites[j].products):\n if name == prod.name:\n normal_row.append(str(prod.price))\n found = True\n break\n\n if not found:\n normal_row.append(\"-\")\n\n table_data.append(list(normal_row))\n normal_row.clear()\n\n return table_data\n\n# Creates .xls sheet with parsed information.\ndef construct_sheet(sheet, style):\n\n for i, token in enumerate(websites): # Fills header row.\n sheet.write(2, i+2, websites[i].initials, style)\n\n for i, name in enumerate(products):\n sheet.write(i+3, 1, name, style)\n\n for j, prods in enumerate(websites):\n found = False\n\n for k, prod in enumerate(websites[j].products):\n if name == prod.name:\n sheet.write(i+3, j+2, prod.price)\n found = True\n break\n\n# Avoiding aditional dependencies...\ndef str_2_bool(string):\n if string.upper() == \"TRUE\":\n return True\n else:\n return False\n\nif str_2_bool(config.get(\"output\", \"console_table\")):\n table_data = construct_table()\n table = SingleTable(table_data)\n print(table.table)\n\nif str_2_bool(config.get(\"output\", \"spreadsheet_table\")):\n message = \"Creating output.xls...\"\n book = xlwt.Workbook(encoding=\"utf-8\")\n sheet = book.add_sheet(\"Sheet 1\", cell_overwrite_ok=True)\n h_style = xlwt.easyxf(\"font: bold on\")\n construct_sheet(sheet, h_style)\n book.save(\"output.xls\")\n time.sleep(1)\n\n# Disables the output threading.\nt.do_run = False\nt.join()\n","sub_path":"comparator.py","file_name":"comparator.py","file_ext":"py","file_size_in_byte":5606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"285585037","text":"import logging\nimport logging.handlers\nimport os\n\nlogger = logging.getLogger(\"LanguageClient\")\nlogpath = os.path.join(os.getenv(\"TMP\", \"/tmp\"), \"LanguageClient.log\")\nlogpath_server = os.path.join(os.getenv(\"TMP\", \"/tmp\"), \"LanguageServer.log\")\nfileHandler = logging.handlers.RotatingFileHandler(\n logpath, maxBytes=20 * 1024 * 1024, backupCount=2)\nfileHandler.setFormatter(\n logging.Formatter(\n \"%(asctime)s %(levelname)-7s [%(threadName)-10s] %(message)s\",\n \"%H:%M:%S\"))\nlogger.addHandler(fileHandler)\nlogger.setLevel(logging.WARN)\n\n\ndef setLoggingLevel(level) -> None:\n \"\"\"\n Set logging level.\n \"\"\"\n logger.setLevel({\n \"ERROR\": 40,\n \"WARNING\": 30,\n \"INFO\": 20,\n \"DEBUG\": 10,\n }[level])\n","sub_path":"rplugin/python3/LanguageClient/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"422532184","text":"from .origin_service import OriginService\nfrom .origin_channels import OriginChannels\nfrom .origin_epg import OriginEPG\n\nimport fHDHR.exceptions\n\n\nclass OriginEPG_StandIN():\n def __init__(self):\n pass\n\n def update_epg(self, channels):\n return {}\n\n\nclass OriginChannels_StandIN():\n def __init__(self):\n pass\n\n def get_channels(self):\n return []\n\n def get_channel_stream(self, chandict, allchandict):\n return [{\"number\": chandict[\"number\"], \"stream_url\": None}], False\n\n\nclass OriginServiceWrapper():\n\n def __init__(self, fhdhr):\n self.fhdhr = fhdhr\n\n self.servicename = fhdhr.config.dict[\"main\"][\"servicename\"]\n\n self.setup_success = None\n self.setup()\n\n def setup(self):\n\n try:\n self.origin = OriginService(self.fhdhr)\n self.setup_success = True\n self.fhdhr.logger.info(\"%s Setup Success\" % self.servicename)\n except fHDHR.exceptions.OriginSetupError as e:\n self.fhdhr.logger.error(e)\n self.setup_success = False\n\n if self.setup_success:\n self.channels = OriginChannels(self.fhdhr, self.origin)\n self.epg = OriginEPG(self.fhdhr)\n else:\n self.channels = OriginChannels_StandIN()\n self.epg = OriginEPG_StandIN()\n\n def get_channels(self):\n return self.channels.get_channels()\n\n def get_channel_stream(self, chandict, allchandict):\n return self.channels.get_channel_stream(chandict, allchandict)\n\n def update_epg(self, channels):\n return self.epg.update_epg(channels)\n\n def get_status_dict(self):\n\n if self.setup_success:\n status_dict = {\n \"Setup\": \"Success\",\n }\n\n try:\n full_status_dict = self.origin.get_status_dict()\n for status_key in list(full_status_dict.keys()):\n status_dict[status_key] = full_status_dict[status_key]\n return status_dict\n except AttributeError:\n return status_dict\n else:\n return {\n \"Setup\": \"Failed\",\n }\n\n def __getattr__(self, name):\n ''' will only get called for undefined attributes '''\n if hasattr(self.fhdhr, name):\n return eval(\"self.fhdhr.\" + name)\n if hasattr(self.origin, name):\n return eval(\"self.origin.\" + name)\n elif hasattr(self.channels, name):\n return eval(\"self.channels.\" + name)\n elif hasattr(self.epg, name):\n return eval(\"self.epg.\" + name)\n else:\n raise AttributeError(name)\n","sub_path":"fHDHR/origin/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"213244455","text":"class Solution(object):\n def cherryPickup(self, grid):\n def bestpath(grid):\n N = len(grid)\n NINF = float('-inf')\n dp = [[NINF] * N for _ in range(N)]\n dp[-1][-1] = grid[-1][-1]\n for i in range(N-1, -1, -1):\n for j in range(N-1, -1, -1):\n if grid[i][j] >= 0 and (i != N-1 or j != N-1):\n new_val_of_col = dp[i+1][j] if i+1 < N else NINF\n new_val_of_row = dp[i][j+1] if j+1 < N else NINF\n\n dp[i][j] = max(new_val_of_col, new_val_of_row)\n dp[i][j] += grid[i][j]\n\n print('aaa')\n for row in dp:\n for cell in row:\n print(\"{:0>2}\".format(cell), end=\" \")\n print()\n\n if dp[0][0] < 0:\n return None\n\n ans = [(0, 0)]\n i = j = 0\n while i != N-1 or j != N-1:\n if j+1 == N or i+1 < N and dp[i+1][j] >= dp[i][j+1]:\n i += 1\n else:\n j += 1\n ans.append((i, j))\n return ans\n\n ans = 0\n path = bestpath(grid)\n\n for i, j in path:\n ans += grid[i][j]\n grid[i][j] = 0\n\n for i, j in bestpath(grid):\n ans += grid[i][j]\n\n return ans\n\n\nif __name__ == \"__main__\":\n s = Solution()\n test_case_1 = [\n [0,1,-1],\n [1,0,-1],\n [1,1,1]]\n test_case_2 = [\n [1,1,1,1,0,0,0],\n [0,0,0,1,0,0,0],\n [0,0,0,1,0,0,1],\n [1,0,0,1,0,0,0],\n [0,0,0,1,0,0,0],\n [0,0,0,1,0,0,0],\n [0,0,0,1,1,1,1]]\n\n print(s.cherryPickup(test_case_1))\n","sub_path":"leetcode/p0741_cherry_pick/solution_greedy.py","file_name":"solution_greedy.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"352921492","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/8/8 下午3:14\n# @Author : ShaHeTop-Almighty-ares\n# @Email : yang6333yyx@126.com\n# @File : views.py\n# @Software: PyCharm\n\nfrom flask import views, request\nfrom .service import MatchService\nfrom .repository import MatchModel\nfrom utils.apiResult import api_result\nfrom app.cms.views import bp\nfrom app.cms.userLogin.cms_decorators import login_required\n\n\n@bp.route('/xxx')\ndef xxx():\n from app.cms.userLogin.models import Article, CMSUser\n x = CMSUser.query.filter_by(username='yyx').first()\n print(x)\n print(x.articles[0].title, type(x.articles), type(x.articles[0]))\n a = Article.query.filter_by(id=1).first()\n print(a)\n print(a.user.id)\n print(a.user.username)\n print(a.user.articles, type(a.user.articles[0]))\n return 'text import bp'\n\n\nclass MatchView(views.MethodView):\n # decorators = [login_required]\n\n def get(self):\n data = request.args.to_dict()\n return api_result(code=200, message='', data=MatchService().read(data))\n\n @login_required\n def post(self):\n data = request.get_json()\n match = MatchService().add_match(data)\n if MatchModel(match).add():\n return api_result(code=201, message='', data=data)\n\n @login_required\n def put(self):\n data = request.get_json()\n m = MatchService().up_match(data)\n match = MatchModel.up(m)\n if match:\n return api_result(code=200, message='update ok', data=[])\n\n @login_required\n def delete(self):\n data = request.get_json()\n m = MatchService().del_match(data)\n match = MatchModel.delete(m)\n if match:\n return api_result(code=204, message='delete ok', data=[])\n","sub_path":"Flask_Projects/HuntingBall/app/cms/match/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"281112379","text":"\nfrom aws_ir.libs import connection\nfrom aws_ir.libs import compromised\n\nfrom aws_ir.plugins import disableaccess_key\nfrom aws_ir.plugins import revokests_key\n\n\"\"\"Compromise class for Key Compromise Procedure\"\"\"\nclass Compromise(object):\n\n def __init__(self,\n examiner_cidr_range='0.0.0.0/0',\n compromised_access_key_id=None,\n region='us-west-2',\n case=None,\n logger=None\n ):\n\n if compromised_access_key_id==None:\n raise ValueError(\n 'Must specifiy an access_key_id for the compromised key.'\n )\n\n self.case_type = 'Key'\n self.compromised_access_key_id = compromised_access_key_id\n self.region = region\n self.case = case\n self.logger = logger\n\n\n def mitigate(self):\n \"\"\"Any steps that run as part of key compromises.\"\"\"\n access_key = self.compromised_access_key_id\n compromised_resource = compromised.CompromisedMetadata(\n compromised_object_inventory = {\n 'access_key_id': access_key,\n 'region': self.region\n },\n case_number=self.case.case_number,\n type_of_compromise='key_compromise'\n ).data()\n\n client = connection.Connection(\n type='client',\n service='iam',\n region=compromised_resource['region']\n ).connect()\n\n self.logger.event_to_logs(\n \"Attempting key disable.\"\n )\n\n\n # step 1 - disable access key\n disableaccess_key.Disableaccess(\n client=client,\n compromised_resource = compromised_resource,\n dry_run=False\n )\n\n\n # step 2 - revoke and STS tokens issued prior to now\n revokests_key.RevokeSTS(\n client=client,\n compromised_resource = compromised_resource,\n dry_run=False\n )\n\n self.logger.event_to_logs(\n \"STS Tokens revoked issued prior to NOW.\"\n )\n\n self.logger.event_to_logs(\n \"Disable complete. Uploading results.\"\n )\n\n self.case.teardown(\n region=self.region,\n resource_id=self.compromised_access_key_id\n )\n","sub_path":"aws_ir/plans/key.py","file_name":"key.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"67633741","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAll spiders should yield data shaped according to the Open Civic Data\nspecification (http://docs.opencivicdata.org/en/latest/data/event.html).\n\"\"\"\nimport datetime\nimport json\nfrom urllib.parse import parse_qs, urljoin\n\nimport dateutil.parser\nimport pytz\nimport scrapy\n\nfrom city_scrapers.constants import CITY_COUNCIL\nfrom city_scrapers.spider import Spider\n\n\nclass ChiCityCouncilSpider(Spider):\n name = 'chi_citycouncil'\n agency_name = 'Chicago City Council'\n timezone = 'America/Chicago'\n allowed_domains = ['ocd.datamade.us']\n\n endpoint = \"https://ocd.datamade.us/events/\"\n query = {\n \"start_date__gt\": str(datetime.date.today()),\n \"sort\": \"start_date\",\n \"jurisdiction\": \"ocd-jurisdiction/country:us/state:il/place:chicago/government\",\n }\n # the response doesn't include the address for city hall\n address = '121 N LaSalle Dr, Chicago, IL'\n\n def start_requests(self):\n yield scrapy.FormRequest(\n url=self.endpoint, method='GET', formdata=self.query, callback=self.parse\n )\n\n def parse(self, response):\n \"\"\"\n This is not a traditional spider, rather, this is a wrapper\n around the Open Civic Data API to which the Chicago City Clerk\n Legistar site info has already been scraped.\n We will attempt to return all events that have been uploaded in the\n future, i.e. past today's date.\n \"\"\"\n data = json.loads(response.text)\n for url in self._gen_requests(data):\n yield scrapy.Request(url, callback=self._parse_item)\n\n if self._addtl_pages(data):\n params = parse_qs(response.url)\n params['page'] = self._next_page(data)\n yield scrapy.FormRequest(\n url=self.endpoint, method='GET', formdata=params, callback=self.parse\n )\n\n def _gen_requests(self, data):\n for result in data['results']:\n event_url = urljoin(self.endpoint, '../' + result['id'] + '/')\n yield event_url\n\n @staticmethod\n def _addtl_pages(data):\n max_page = data['meta']['max_page']\n page = data['meta']['page']\n return max_page > page\n\n @staticmethod\n def _next_page(data):\n current_page = data['meta']['page']\n return current_page + 1\n\n def _parse_item(self, response):\n data = json.loads(response.text)\n start = self._parse_time(data.get('start_date', ''))\n end = self._parse_time(data.get('end_date', ''))\n documents = self._parse_documents(data['documents'])\n location = self._parse_location(data)\n item = {\n '_type': 'event',\n 'name': data['name'],\n 'location': location,\n 'id': data['id'],\n 'event_description': data['description'],\n 'classification': CITY_COUNCIL,\n 'start': start,\n 'end': end,\n 'all_day': data['all_day'],\n 'documents': documents,\n 'sources': data['sources'],\n 'status': data['status']\n }\n end_date = item['end']['date']\n state_date = item['start']['date']\n item['end']['date'] = state_date if end_date is None else end_date\n item['id'] = self._generate_id(item)\n return item\n\n def _parse_location(self, data):\n return {\n 'address': self.address,\n 'name': data['location']['name'].strip(),\n }\n\n def _parse_time(self, timestamp):\n if len(timestamp) <= 0:\n return {'date': None, 'time': None, 'note': ''}\n\n tz = pytz.timezone(self.timezone)\n dt = dateutil.parser.parse(timestamp).astimezone(tz)\n return {\n 'date': dt.date(),\n 'time': dt.time(),\n 'note': '',\n }\n\n @staticmethod\n def _parse_documents(documents):\n parsed_documents = []\n for document in documents:\n for link in document['links']:\n parsed_document = {\"url\": link['url'], 'note': document['note']}\n parsed_documents.append(parsed_document)\n return parsed_documents\n","sub_path":"city_scrapers/spiders/chi_citycouncil.py","file_name":"chi_citycouncil.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"23557038","text":"import json\n\nfrom Minerals.serializers import MineralSerializer\n\njson_data = open('minerals.json').read()\n\ndata = json.loads(json_data)\n\nfor item in data:\n print(item)\n ms = MineralSerializer(data=item)\n if ms.is_valid():\n ms.save()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"163811284","text":"from sklearn.model_selection import train_test_split # train_test_split - Splitting Training Set\nimport pandas as pd # pandas - Data Science Utilities\n\nimport SelectionValidation as sv\nimport CSVUtil as csvUtil\nimport DataPrep.LabelUtil as labelUtil\nimport DataPrep.MethodDemo as md\nimport DataPrep.AugConfig as config\n\n# Hyper parameters\nSAMPLE_SIZE = 25000\nTEST_RATIO = 0.2\nBATCH_SIZE = 2\nDATASET_DIR = \"E:\\\\Developing\\\\TrainingSet\\\\\"\nDATASET_CSV = \"TrainingSetAnalysis.csv\"\n\n# CLI messages\nSCALE_MENU = \"\\nAvailable scale of dataset:\\nA Sampled 50k images.\\nB Whole DataSet\"\nSCALE_DICT = {\"A\": \"Sampled_50k\", \"B\": \"WholeDataSet\"}\nMODEL_MENU = \"\\nAvailable model to train:\\nCNNProto\\nResNet50\\nVGG16\\nVGG19\"\nMODEL_DICT = {\"CNNProto\": 256, \"ResNet50\": 224, \"VGG16\": 224, \"VGG19\": 224}\nWELCOME_MESG = \"Please select or input:\"\n\n# Read csv file using pandas\nwith csvUtil.get_dataframe(DATASET_DIR, DATASET_CSV) as csv_file:\n print(\"File opening...\")\n raw_data = csv_file\n print(\"File open success!\")\n# CLI menus\ninput_validation = sv.SelectionValidation(selection_dict=SCALE_DICT,\n menu_message=SCALE_MENU,\n welcome_message=WELCOME_MESG)\nscale_select = input_validation.validation()\n\ninput_validation = sv.SelectionValidation(selection_dict=MODEL_DICT,\n menu_message=MODEL_MENU,\n welcome_message=WELCOME_MESG)\nmodel_select = input_validation.validation()\n\n# Mode confirm\nprint(\"Mode \" + SCALE_DICT[scale_select] + \" have been selected.\\n\")\n\nif scale_select == \"A\":\n print(\"Since 25,000 original images will be used, data augmentation will be turned ON.\")\n # Sample SAMPLE_SIZE images\n raw_data = raw_data.sample(n=SAMPLE_SIZE, replace=False, weights=None, random_state=1)\n\nelse:\n print(\"Since all of the images will be used, data augmentation will be turned OFF.\")\n\n# Append labels for DataFrame items\nraw_data['HasShip'] = labelUtil.label_gen(raw_data['EncodedPixels'].values)\n# Visualize results\nlabelUtil.label_stat_bar(input_tuple=labelUtil.label_num_calc(raw_data['HasShip'].values),\n save_dir=DATASET_DIR)\n# Spilt up images\ntrain_data, test_data = train_test_split(raw_data, random_state=1, test_size=TEST_RATIO)\n\n# Visualizing image augmentation effect\nsample_df = pd.read_csv(DATASET_DIR + 'Sample.csv')\nsample_df['Directory'] = DATASET_DIR + sample_df['ImageId']\nsample_df['HasShip'] = labelUtil.label_gen(sample_df['EncodedPixels'].values)\n\nif scale_select == \"A\":\n selected_config = config.sample_train_config\nelse:\n selected_config = config.preprocess_config\n\n# DataFrameIterator: Generates unlimited number of images according to the configuration\n# A.k.a Source of the pre-processed images\nprep_train = config.prep_exec(config=selected_config,\n input_df=train_data,\n batch_size=BATCH_SIZE,\n side_length=MODEL_DICT[model_select])\nprep_test = config.prep_exec(config=selected_config,\n input_df=test_data,\n batch_size=BATCH_SIZE,\n side_length=MODEL_DICT[model_select])\nsample = md.MethodDemo(train_config=config.sample_train_config,\n test_config=config.preprocess_config,\n input_df=sample_df,\n side_length=MODEL_DICT[model_select],\n save_dir=DATASET_DIR + \"Sample\")\nsample.output_aug_sample()\n","sub_path":"ShipDetection/DataPrep/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"107635334","text":"build_frame = [[1, 0, 0, 1], [1, 1, 1, 1], [2, 1, 0, 1], [2, 2, 1, 1], [5, 0, 0, 1], [5, 1, 0, 1], [4, 2, 1, 1], [3, 2, 1, 1]]\nn = 5\nbuild_frame2 = [[0, 0, 0, 1], [2, 0, 0, 1], [4, 0, 0, 1], [0, 1, 1, 1], [1, 1, 1, 1], [2, 1, 1, 1], [3, 1, 1, 1], [2, 0, 0, 0], [1, 1, 1, 0], [2, 2, 0, 1]]\ndef check(x, y, a, result):\n if a == 0:\n if [x, y-1, 0] in result or [x-1, y, 1] in result or [x,y,1] in result or y == 0:\n return True\n return False\n elif a == 1:\n if [x, y-1, 0] in result or [x+1, y-1, 0] in result or ([x-1, y, 1] in result and [x+1, y, 1] in result):\n return True\n return False\n\n\ndef solution(n, build_frame):\n result = []\n for data in bulid_frame:\n x, y, a, b = data\n if b == 1:\n if check(x, y, a, result):\n result.append([x, y, a])\n else:\n result.remove([x, y, a])\n for val in result:\n nx, ny, na = val\n if check(nx, ny, na, result) == False:\n result.append([x, y, a])\n break\n result.sort(key = lambda x : (x[0], x[1], x[2]))\n return result\n\nprint(solution(n, build_frame2))\n","sub_path":"Q12_기둥과 보 설치.py","file_name":"Q12_기둥과 보 설치.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"132213967","text":"## Script (Python) \"iol_onOpenDocument\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=\n##title=\n##\n\"\"\"\nStandardizzazione dele operazioni da svolgere all'apertura di una richiesta\n\"\"\"\n\ndb = context.getParentDatabase()\n#tipo_domanda = genera_tipo_domanda(plominoDocument.getFormName())\n# all'apertura di nuovo documento plominoDocument è un plominoForm\nif context.isNewDocument():\n \n if 'rinnovo' == context.naming_manager('tipo_richiesta'):\n parentDocument = db.getDocument(context.REQUEST.get('parentDocument'))\n if parentDocument.naming_manager('tipo_richiesta') != 'periodica':\n return \"ATTENZIONE! Non è possibile rinnovare una richiesta NON periodica.\"\n \n if parentDocument.getItem('numero_rinnovi') == 2:\n return \"ATTENZIONE! Non è possibile rinnovare ulteriormente la pratica selezionata!\"\n\nreturn ''\n","sub_path":"src/gisweb/iol/skins/iol_templates/iol_old/iol_onOpenDocument.py","file_name":"iol_onOpenDocument.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"526048673","text":"\"\"\"Pirograph image processing.\n\nPygame implementation, based heavily on earlier Technology Wishing Well\ncode and Mike Cook's Kaleido Cam from the Mag Pi, December 2017.\n\nNote that this code will only work on V4L2 systems: ie. Linux and Raspberry Pi.\nSorry, Mac and Windows users.\n\n...so for testing reasons, this instrumented version just loads an image from disk.\n\"\"\"\n\nimport pygame\n# import pygame.camera\nimport os, time\nfrom tkinter import Tk\nfrom tkinter.filedialog import asksaveasfilename\nfrom PIL import Image, ImageStat, ImageOps, ImageDraw\n\n# os.system(\"sydo modprobe bcm2835-v4l2\") # needed for Pi camera\nTk().withdraw()\npygame.init()\n# pygame.camera.init()\nos.environ['SDL_VIDEO_WINDOW_POS'] = 'center'\npygame.display.set_caption(\"Pirograph\")\npygame.event.set_allowed(None)\npygame.event.set_allowed([pygame.KEYDOWN, pygame.QUIT])\n\nimagesize = 800 # basic image size.\nscreen = pygame.display.set_mode([imagesize, imagesize], 0, 32)\n\n# find, open and start camera\n# cam_list = pygame.camera.list_cameras()\n# print(cam_list)\n# webcam = pygame.camera.Camera(cam_list[0], (1920, 1080))\n# webcam.start()\n\npreRot = 0.0\nautoRotate = False\nsavePath = \"\"\nframeNumber = 0\nsaveSource = False\n\n# Config variables (can adapt at runtime)\nfull_screen = 0\nvideo_framerate = 0\nthreshold_low = 40\nthreshold_high = 230\nframe_count = 1\n\n\ndef main():\n x = 0\n while x in range(10):\n checkForEvent()\n showScreen()\n print(x)\n x += 1\n # print(\"\")\n\ndef showScreen():\n global camFrame, preRot, frame_count\n # camFrame = webcam.get_image()\n camFrame = pygame.image.load('test_image.jpeg')\n frame_count += 1\n if autoRotate:\n preRot += 0.5\n if preRot > 360:\n preRot -= 360\n rotFrame = pygame.transform.scale(camFrame, (imagesize, imagesize)) # ensure square\n rotFrame.set_alpha(greyscale(rotFrame))\n rotFrame = rot_center(rotFrame, preRot) # Rotate\n sqFrame = pygame.Surface((imagesize, imagesize))\n sqFrame.blit(rotFrame, (0, 0))\n else:\n thisFrame = pygame.transform.scale(camFrame, (imagesize, imagesize))\n thisFrame.set_alpha(greyscale(thisFrame))\n sqFrame = pygame.Surface((imagesize, imagesize))\n sqFrame.blit(thisFrame, (0, 0))\n screen.blit(sqFrame, (0, 0))\n pygame.display.update()\n\n\ndef rot_center(image, angle):\n # rotate an image while keeping its center and size\n orig_rect = image.get_rect()\n rot_image = pygame.transform.rotate(image, angle)\n rot_rect = orig_rect.copy()\n rot_rect.center = rot_image.get_rect().center\n rot_image = rot_image.subsurface(rot_rect).copy()\n return rot_image\n\n\ndef terminate():\n # webcam.stop()\n pygame.quit()\n os._exit(1)\n\n\ndef greyscale(self, img):\n \"\"\"See https://stackoverflow.com/questions/10261440/how-can-i-make-a-greyscale-copy-of-a-surface-in-pygame/10693616#10693616.\"\"\"\n arr = pygame.surfarray.pixels3d(img)\n avgs = [[(r*0.298+ g*0.587 + b*0.114) for (r, g, b) in col] for col in arr]\n arr = arr.dot([0.298, 0.587, 0.114])[:,:,None].repeat(3, axis=2)\n return pygame.surfarray.make_surface(arr)\n\n\ndef checkForEvent():\n global savePath, autoRotate, saveSource, preRot\n event = pygame.event.poll()\n if event.type == pygame.QUIT:\n terminate()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n terminate()\n if event.key == pygame.K_r:\n autoRotate = not autoRotate\n print(\"Autorotate: \", autoRotate)\n if autoRotate:\n preRot = 0\n\n\nif __name__ == '__main__':\n main()","sub_path":"experiments/pirograph__partial_instrumented.py","file_name":"pirograph__partial_instrumented.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"653687543","text":"#!/usr/bin/env python\n# coding: utf-8\nimport sys\nfrom operator import add\nfrom pyspark import SparkConf, SparkContext, SQLContext \nfrom pyspark.sql import SparkSession\n\n#infile = \"hdfs://128.104.222.61:9000/CS744/inputdata/enwiki-pages-articles/link-enwiki-20180601-pages-articles14.xml-p7697599p7744799\"\ninfile = \"hdfs://128.104.222.61:9000/CS744/inputdata/enwiki-pages-articles/link-enwiki-20180601-pages-articles*\"\nfileOut = 'hdfs://128.104.222.61:9000/CS744/outputdata/outputranks_bigsample.txt'\n\ndef flaten(tup):\n key,value = tup # (URL, (List of links, rank))\n links,rank = value\n n = len(links)\n out = [(dest,rank/n) for dest in links]\n #out.append((key, 0))# append the src also to this list, with no rank from this scenario\n return out\n\nconf = SparkConf().setMaster(\"spark://128.104.222.61:7077\").setAppName(\"TableData\")\nsc = SparkContext(conf = conf)\nnoofpartitions = 120\n\ndef partitioner(key):\n\treturn hash(key)\n\ndata = sc.textFile(infile)\n\nlinks = data.map(lambda x: x.split('\\t'))#break line\nlinks = links.filter(lambda l: ':' not in l[1] or l[1][0:9] == 'Category:')#ignore some\nlinks = links.map(lambda l: [k.lower() for k in l])#to lowercase\nlinks = links.groupBy(lambda l: l[0])#group by key as from value\nlinks = links.map(lambda x : (x[0], [l[1] for l in list(x[1])]))#convert iterator to list of values\nprint(\"No of partitions of links RDD before custom partition: {}\").format(links.getNumPartitions())\n#links = links.partitionBy(noofpartitions,partitioner) \nprint(\"No of partitions of links RDD after custom partition: {}\").format(links.getNumPartitions())\n\nlinks.cache()#saving as in-memory objects\n\nr0 = 1.0\niterations = 10\n\nranks = links.keys().map(lambda x: (x,r0))\n\nfor i in range(iterations):\n contribs = links.join(ranks).flatMap(flaten)\n ranks = contribs.reduceByKey(add).mapValues(lambda x: 0.15 + (0.85)*x)\n\nranks.saveAsNewAPIHadoopFile(fileOut, \"org.apache.hadoop.mapreduce.lib.output.TextOutputFormat\",\"org.apache.hadoop.io.Text\",\"org.apache.hadoop.io.Text\")\n\n","sub_path":"scripts/PageRank_part3Task4.py","file_name":"PageRank_part3Task4.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"2299809","text":"#hopscotch.py\r\n#\r\n#function that draws a hopscotch court with the parameters for a turtle, edge length, and pen width\r\n#usage: ???\r\n# % python hopscotch.py t, edgeLen, penWidth\r\n#\r\n#Helen Gao, 7-9-2018 by 11am\r\n\r\nimport turtle #import the turtle library\r\nbob = turtle.Turtle() #create a turtle named bob\r\ndef square(t, edgeLen): #this function takes the parameters t for turtle and edgeLen for the edge length of the square\r\n for i in range(4): #since it is a square, drawing one side can be repeated four times\r\n t.fd(edgeLen) #the turtle moves forward the designated edge length\r\n t.rt(90) #the turtle turns 90 degrees in preparation for drawing the next edge length\r\ndef twosquares(t, edgeLen): #this function draws two square side by side using the above square function and uses the same parameters\r\n square(t, edgeLen) #drawing a square\r\n t.fd(edgeLen) #moves to the top right corner of the first square so the turtle can start drawing the next square\r\n square(t, edgeLen) #draws the second square\r\ndef threesquares(t, edgeLen): #this function draws a square on top of two squares using the square function and the twosquares function\r\n square(t, edgeLen) #draws the top square\r\n t.rt(90) #turns the turtle so it faces downwards\r\n t.fd(edgeLen) #moves down the length of the square so the turtle is at the bottom left corner of the first square\r\n t.lt(90) #turtle turns left 90 degrees so it faces to the right\r\n t.bk(edgeLen/2) #turtle moves back 1/2 the length of the side length so that the twosquares function will be centered properly\r\n twosquares(t, edgeLen) #turtle draws two squares\r\n t.rt(90) #turtle turns so that it's facing downwards\r\n t.fd(edgeLen) #turtle moves down the center of the two triangles\r\n t.lt(90) #turtle turns left so that it faces to the right\r\n t.bk(edgeLen/2) #turtle moves back so that it will be centered when it draws the single square\r\ndef hopscotch_court(t, edgeLen, penWidth): #this function creates the hopscotch court using the parameters t for turtle, edgeLen for edge length, and penWidth for pen size\r\n t.penup() #the turtle's pen goes up so it doesn't draw when repositioning\r\n t.setpos(-edgeLen/2, edgeLen*3) #the turtle's position is set so that the starting point is half the length of the edge to the left (because the first square is a full edge length long, this will center it) and since the hopscotch court is six edge lengths tall, placing it at a y-value of three edge lengths will also center the court vertically\r\n t.pendown() #the turtle's pen goes down to start drawing\r\n t.pensize(penWidth) #sets the pen size to the given pen width\r\n for i in range(2): #since the hopscotch court has two sets of three squares, the threesquares function can be run twice\r\n threesquares(t, edgeLen) #runs threesquares with the parameters t and edgeLen\r\n square(t, edgeLen) #draws the seventh square after finishing the first 2*3=6 squares\r\n t.rt(90) #the turtle turns right so that it faces down\r\n t.fd(edgeLen) #the turtle moves forward so that it is at the bottom left corner of the seventh square\r\n t.lt(90) #the turtle turns left so that it faces right in preparation for drawing the next square\r\n square(t, edgeLen) #the turtle draws the last square\r\n t.ht() #hiding the turtle now. bye turtle. we still love him though\r\nhopscotch_court(bob, 75, 6) #draws the hopscotch court with the turtle bob, each square having edges of length 75 pixels, and the width of the lines being 6 pixels\r\nturtle.mainloop() #the window stays open for our viewing pleasure\r\n\r\n#note: got the ideas for repeated square functions and centering the drawing at joe's thursday section","sub_path":"hopscotch.py","file_name":"hopscotch.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"632009941","text":"import uuid\nfrom functools import wraps\nfrom utils import log\n\nfrom flask import (\n session,\n request,\n abort,\n redirect,\n url_for,\n )\n\nfrom models.user import User\n\n\ndef current_user():\n uid = session.get('user_id', -1)\n\n u = User.one(id=uid)\n log('current', u.username)\n return u\n\n\ncsrf_tokens = dict()\n\n\ndef csrf_required(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n token = request.args['token']\n u = current_user()\n if token in csrf_tokens and csrf_tokens[token] == u.id:\n csrf_tokens.pop(token)\n return f(*args, **kwargs)\n else:\n abort(401)\n\n return wrapper\n\n\ndef new_csrf_token():\n u = current_user()\n token = str(uuid.uuid4())\n csrf_tokens[token] = u.id\n return token\n\n\ndef login_required(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n u = current_user()\n if u.is_guest():\n return redirect(url_for('index.index'))\n else:\n return f(*args, **kwargs)\n\n return wrapper\n\n\ndef same_user_required(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n u = current_user()\n id = int(request.args['id'])\n\n if u.is_admin() or id == u.id:\n return f(*args, **kwargs)\n else:\n return redirect(url_for('topic.index'))\n\n return wrapper\n\n\ndef admin_required(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n u = current_user()\n\n if u.is_admin():\n return f(*args, **kwargs)\n else:\n return redirect(url_for('topic.index'))\n\n return wrapper\n\n","sub_path":"routes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"157088859","text":"\"\"\"\n把两个向量想象成空间的两条线段,都是从原点出发([0, 0, ...]),指向不同的方向。\n两条线段之间形成一个夹角,如果夹角为0°,则方向相同、线段重合;\n如果夹角为90°,则形成直角,方向完全不相似;\n如果夹角为180°,则方向正好相反。\n夹角越小,就代表越相似。\n\"\"\"\nimport numpy as np\n\n\ndef cos_similar(vector_a, vector_b):\n \"\"\"\n 计算两个向量之间的余弦相似度\n :param vector_a: 向量a\n :param vector_b: 向量b\n :return: sim\n \"\"\"\n vector_a = np.mat(vector_a)\n vector_b = np.mat(vector_b)\n num = float(vector_a * vector_b.T) # * 表示数量积,dot表示矢量乘法\n\n # np.linalg.norm() 求范数,默认是二范数(ord = 2)\n denum = np.linalg.norm(vector_a) * np.linalg.norm(vector_b)\n \n cos = num / denum\n sim = 0.5 + 0.5 * cos # 归一化\n return sim\n # return cos\n\n\na = [1, 2, 3]\nb = [1, 2, 4]\n\nprint(cos_similar(a, b))\n","sub_path":"65+韩润华+南昌/week2/demo_cos.py","file_name":"demo_cos.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"422998020","text":"import torch.nn as nn\n\n\nclass PNet(nn.Module):\n def __init__(self):\n super(PNet, self).__init__()\n self.backbone = nn.Sequential(\n nn.Conv2d(3, 8, kernel_size=3),\n nn.BatchNorm2d(8),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(8, 16, kernel_size=3),\n nn.BatchNorm2d(16),\n nn.ReLU(inplace=True),\n nn.Conv2d(16, 32, kernel_size=3),\n # nn.BatchNorm2d(32),\n nn.ReLU(inplace=True)\n )\n self.roi_cls_head = nn.Conv2d(32, 2, kernel_size=1)\n self.roi_reg_head = nn.Conv2d(32, 4, kernel_size=1)\n\n def forward(self, x):\n x = self.backbone(x)\n roi_cls = self.roi_cls_head(x)\n roi_reg = self.roi_reg_head(x)\n return roi_cls, roi_reg\n","sub_path":"mtcnn/modeling/pnet.py","file_name":"pnet.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"348270085","text":"# 4837. [파이썬 S/W 문제해결 기본] 2일차 - 부분집합의 합\n\nT = int(input())\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\nn = len(arr)\n\nlst = []\nfor i in range(1< redirect to settings\n def test_oob_roll(self):\n result = self.client.post('/stories/new/roll', data={'dice_number': 9, 'dice_img_set': 'standard'})\n self.assertRedirects(result, '/stories/new/settings')\n\n # Redirect from session (abc fails, throws ValueError, gets 8 from session, out of range -> redirect)\n def test_oob_roll_sess(self):\n with self.client.session_transaction() as sess:\n sess['dice_number'] = 8\n result = self.client.post('/stories/new/roll', data={'dice_number': 'abc', 'dice_img_set': 'standard'})\n self.assertRedirects(result, '/stories/new/settings')\n\n # Correct execution's flow of roll\n def test_roll(self):\n with self.client.session_transaction() as sess:\n sess['dice_number'] = 2\n rnd.seed(2) # File die0.txt\n self.client.post('/stories/new/roll', data={'dice_number': 4, 'dice_img_set': 'animal'})\n self.assert_template_used('roll_dice.html')\n","sub_path":"monolith/views/tests/test_dice.py","file_name":"test_dice.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"392591714","text":"\"\"\"\r\n\r\n Collaborative Filtering: Modeling Methods\r\n\r\n\"\"\"\r\n\r\nimport math\r\nimport random\r\n\r\nimport algebric_operations\r\nimport data_treatment\r\nimport model\r\nimport utils\r\n\r\ndef _update_p_matrix(p_matrix, q_matrix, user_index, item_index, error, lambda_value=0.1, gamma_value=0.01):\r\n\r\n for row in range(len(p_matrix)):\r\n\r\n p_matrix[row][user_index] += gamma_value * (error * q_matrix[row][item_index] - lambda_value * p_matrix[row][user_index])\r\n\r\n return p_matrix\r\n\r\ndef _update_q_matrix(q_matrix, p_matrix, user_index, item_index, user, amount_items, ratings, error, lambda_value=0.05, gamma_value=0.01):\r\n\r\n for row in range(len(q_matrix)):\r\n\r\n q_matrix[row][item_index] += gamma_value * (error * (p_matrix[row][user_index] + 1/math.sqrt(amount_items) * ratings[user][row])) - lambda_value * q_matrix[row][item_index]\r\n\r\n return q_matrix\r\n\r\ndef _update_y_matrix(y_matrix, q_matrix, users_items, user, items, amount_items, error, lambda_value=0.1, gamma_value=0.01):\r\n\r\n for row, item in enumerate(users_items[user]):\r\n\r\n item_index = items[item]\r\n\r\n for column in range(len(y_matrix[item_index])):\r\n\r\n y_matrix[item_index][column] += gamma_value * (error * 1/math.sqrt(amount_items) * q_matrix[column][item_index] - lambda_value * y_matrix[item_index][column])\r\n\r\n return y_matrix\r\n\r\ndef _update_residual_items(residual_items, item_index, error, gamma_value=0.01, lambda_value=0.05):\r\n\r\n\r\n residual_items[item_index] += gamma_value * (error - lambda_value * residual_items[item_index])\r\n\r\n return residual_items\r\n\r\ndef _update_residual_users(residual_users, user_index, error, gamma_value=0.01, lambda_value=0.05):\r\n\r\n\r\n residual_users[user_index] += gamma_value * (error - lambda_value * residual_users[user_index])\r\n\r\n return residual_users\r\n\r\ndef calculate_first_estimation(users, users_items, latent_factors_size, y_matrix, items):\r\n\r\n # first estimation of the ratings\r\n estimation = {}\r\n\r\n for user in users.keys():\r\n # array of zeros\r\n zero_array = [0] * latent_factors_size\r\n\r\n for item in users_items[user]: # items consumed by the user\r\n\r\n zero_array = algebric_operations.sum_two_arrays(zero_array, y_matrix[items[item]])\r\n\r\n estimation[user] = zero_array\r\n\r\n return estimation\r\n\r\ndef retrieve_column(matrix, column):\r\n\r\n column_array = []\r\n\r\n for value in range(len(matrix)):\r\n\r\n column_array.append(matrix[value][column])\r\n\r\n return column_array\r\n\r\ndef svd_prediction(p_matrix, q_matrix):\r\n\r\n return sum(list(map(lambda x, y: x*y, p_matrix, q_matrix)))\r\n\r\ndef svd_rmse(historic_rating_matrix, matrix_users_items, users, items, ratings_mean, residual_users, residual_items, ratings, q_matrix, y_matrix, users_items, latent_factors_size):\r\n\r\n total_error = 0\r\n\r\n for row in matrix_users_items:\r\n\r\n user, item = row[0], row[1] \r\n\r\n user_index, item_index = users[user], items[item]\r\n\r\n ratings[user] = [0] * latent_factors_size\r\n\r\n for item in users_items[user]:\r\n\r\n ratings[user] = algebric_operations.sum_two_arrays(ratings[user], y_matrix[item_index])\r\n\r\n prediction = (ratings_mean + residual_users[user_index] + residual_items[item_index] + svd_prediction(ratings[user], retrieve_column(q_matrix, item_index)))\r\n\r\n total_error += (historic_rating_matrix[user_index][item_index] - prediction) ** 2\r\n\r\n return math.sqrt(total_error/len(matrix_users_items))\r\n\r\n\r\ndef make_prediction(historic_data, prediction_data, ratings, ratings_mean, users, items, q_matrix, residual_users, residual_items, users_items, y_matrix, latent_factors_size):\r\n\r\n predictions = []\r\n\r\n #items_mean = utils.measure_column_mean(historic_data)\r\n\r\n for row in prediction_data:\r\n\r\n user, item = row[0], row[1]\r\n\r\n '''if user in users.keys() and item not in items.keys():\r\n\r\n user_index = users[user]\r\n\r\n prediction = users_mean[user]\r\n\r\n elif item in items.keys() and user not in users.keys():\r\n\r\n item_index = items[item]\r\n\r\n prediction = items_mean[item]'''\r\n\r\n if user not in users.keys() or item not in items.keys():\r\n\r\n prediction = ratings_mean\r\n\r\n else:\r\n\r\n user_index, item_index = users[user], items[item]\r\n\r\n ratings[user] = [0] * latent_factors_size\r\n\r\n for item in users_items[user]:\r\n\r\n ratings[user] = algebric_operations.sum_two_arrays(ratings[user], y_matrix[item_index])\r\n\r\n\r\n prediction = (ratings_mean + residual_users[user_index] + residual_items[item_index] + svd_prediction(ratings[user], retrieve_column(q_matrix, item_index)))\r\n\r\n predictions.append(prediction) \r\n\r\n return predictions\r\n\r\n\r\ndef singular_value_decomposition_pp(data, latent_factors_size, epochs):\r\n \"\"\"\r\n\r\n Based on the code available in:\r\n\r\n https://github.com/cheungdaven/recommendation\r\n\r\n Based on the paper of:\r\n\r\n https://people.engr.tamu.edu/huangrh/Spring16/papers_course/matrix_factorization.pdf\r\n\r\n\r\n \"\"\"\r\n random.seed()\r\n\r\n users_items, users, items = data_treatment.retrieve_guide_features(data['Historic Data'])\r\n\r\n matrix_users_items = data_treatment.mount_matrix_user_item(users_items)\r\n\r\n ratings_mean = utils.measure_average_rating(data['Historic Data'])\r\n\r\n # a matrix users x items\r\n historic_rating_matrix = model.generate_historic_data_matrix(data['Historic Data'], 'users', users, items, ratings_mean)\r\n\r\n #users_mean = utils.measure_row_mean(historic_rating_matrix)\r\n\r\n #historic_rating_matrix = utils.subtraction_matrix_row_mean(historic_rating_matrix, users_mean)\r\n\r\n # users latent matrix\r\n p_matrix = algebric_operations.generate_random_matrix(latent_factors_size, len(users))\r\n\r\n # itens latent matrix\r\n q_matrix = algebric_operations.generate_random_matrix(latent_factors_size, len(items))\r\n\r\n # prediction matrix\r\n y_matrix = algebric_operations.generate_random_matrix(len(items), latent_factors_size)\r\n\r\n ratings = calculate_first_estimation(users, users_items, latent_factors_size, y_matrix, items)\r\n\r\n residual_items = [random.uniform(0, 1) for item in range(0, len(items))]\r\n\r\n residual_users = [random.uniform(0, 1) for user in range(0, len(users))]\r\n\r\n for epoch in range(epochs):\r\n\r\n for row in matrix_users_items:\r\n\r\n user, item = row[0], row[1]\r\n\r\n user_index, item_index = users[user], items[item]\r\n\r\n amount_items = len(users_items[user])\r\n\r\n # diving all the values of a a array by the sqrt of the users amount of items\r\n ratings[user] = list(map(lambda value: value/math.sqrt(amount_items), ratings[user]))\r\n\r\n # retriving all the values of a specific column\r\n column_array = retrieve_column(p_matrix, users[user])\r\n\r\n ratings[user] = algebric_operations.sum_two_arrays(ratings[user], column_array)\r\n\r\n predicted_rating = ratings_mean + residual_items[item_index] + residual_users[user_index] + svd_prediction(ratings[user], retrieve_column(q_matrix, item_index))\r\n\r\n measured_error = historic_rating_matrix[user_index][item_index] - predicted_rating # error_metric(historic_rating_matrix[users[user]][item_index], predicted_rating)\r\n\r\n # cost O(n)\r\n p_matrix = _update_p_matrix(p_matrix, q_matrix, user_index, item_index, measured_error)\r\n\r\n # cost O(n)\r\n q_matrix = _update_q_matrix(q_matrix, p_matrix, user_index, item_index, user, amount_items, ratings, measured_error)\r\n\r\n # reconstruction matrix - this will be the closest to the original matrix - cost O(n**2)\r\n y_matrix = _update_y_matrix(y_matrix, q_matrix, users_items, user, items, amount_items, measured_error)\r\n\r\n # cost O(1)\r\n residual_items = _update_residual_items(residual_items, item_index, measured_error)\r\n\r\n # cost O(1)\r\n residual_users = _update_residual_users(residual_users, user_index, measured_error)\r\n\r\n print(svd_rmse(historic_rating_matrix, matrix_users_items, users, items, ratings_mean, residual_users, residual_items, ratings, q_matrix, y_matrix, users_items, latent_factors_size))\r\n\r\n predictions = make_prediction(historic_rating_matrix, data['Prediction Data'], ratings, ratings_mean, users, items, q_matrix, residual_users, residual_items, users_items, y_matrix, latent_factors_size)\r\n\r\n for index, prediction in enumerate(predictions):\r\n\r\n data['Prediction Data'][index].append(str(prediction))\r\n\r\n data['Prediction Data'].insert(0, ['UserId', 'ItemId', 'Prediction'])\r\n\r\n utils.write_table(data['Prediction Data'], \"Outputs/predictions.txt\")\r\n\r\n","sub_path":"model_based.py","file_name":"model_based.py","file_ext":"py","file_size_in_byte":8781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"346923929","text":"# Module for geocoding matched land registry postcodes\nimport pandas as pd\nimport numpy as np\nfrom numpy import nan\nimport itertools\nimport csv\nimport logging\nimport time\n\ndef get_landreg_for_geocoding(land_registry_df, codex, name_col, geo_cols):\n\t# Select elements within land_registry_df that have been matched\n\tlandreg_geo = land_registry_df.loc[land_registry_df[name_col].isin(codex[name_col])]\n\tlandreg_geo = landreg_geo.reindex(columns = geo_cols)\n\treturn landreg_geo\n\n# Given location of missing post code entry, searches nearby entries for same addresses to fill postcode from\ndef suggest_entry_for_missing_val(df, column_to_fill, columns_matched_on):\n\told_indices = df.index\n\tdf.set_index(np.arange(df.shape[0]), inplace=True)\n\tdf['SUGGESTED_'+column_to_fill]=df[column_to_fill]\n\tfor row_index,row in df.iterrows():\n\t# Selects the elements of DataFrame row with missing entry in 'column_to_fill' to be matched against other rows\n\t\tif pd.isnull(row[column_to_fill]):\n\t\t\telements_to_compare = row.reindex(columns_matched_on)\n\t\t\t# Selects elements of neighbouring entries for comparison. Break stops loop once match is found.\n\t\t\tfor i in range(max(0,row_index-2),row_index) + range(min(len(df),row_index+1), min(len(df),row_index+3)):\t\n\t\t\t\tcomparator = (df.ix[i]).reindex(columns_matched_on)\n\t\t\t\tif elements_to_compare.equals(comparator):\n\t\t\t\t\tdf.ix[row_index,'SUGGESTED_'+column_to_fill]= df.ix[i,column_to_fill]\n\t\t\t\t\tbreak\n\tdf.set_index(old_indices, inplace=True)\n\treturn df\n\n#Not currently used\ndef suggest_missing_entry_values(df, column_to_fill, columns_matched_on):\n\told_indices = df.index\n\tdf.set_index(np.arange(df.shape[0]), inplace=True)\n\tdf['SUGGESTED_'+column_to_fill]=df[column_to_fill]\n\tsub_df = df.loc[df[column_to_fill].isnull()] # This line does not work. Works whens used in separate function (see below) but position in this func is incorrect\n\tfor row_index, row in sub_df.iterrows():\n\t\telements_to_compare = row.reindex(columns_matched_on)\n\t\t# Selects elements of neighbouring entries for comparison. Break stops loop once match is found.\n\t\tfor i in range(max(0,row_index-2),row_index) + range(min(len(df),row_index+1), min(len(df),row_index+3)):\t\n\t\t\tcomparator = (df.ix[i]).reindex(columns_matched_on)\n\t\t\tif elements_to_compare.equals(comparator):\n\t\t\t\tdf.ix[row_index,'SUGGESTED_'+column_to_fill]= df.ix[i,column_to_fill]\n\t\t\t\tbreak\n\tdf.set_index(old_indices, inplace=True)\n\ndef get_sub_df(df, col):\n\tsub_df = df.loc[df[col].isnull()]\n\treturn sub_df\n\t\ndef pcd_clean(string):\n\ttry:\n\t\tstring=str(string)\n\t\tstring=string.upper()\n\t\tstring=string.replace(' ' ,'')\n\t\treturn string\n\texcept AttributeError:\n\t\tprint('Attribute Error when cleaning the following input to pcd_clean: ' + string)\n\t\treturn string\n\texcept (UnicodeDecodeError, UnicodeEncodeError):\n\t\tprint('Unicode Error when cleaning the input to pcd_clean')\n\t\treturn string\n\texcept:\n\t\tprint('Unexpected error when cleaning string', sys.exc_info()[0])\n\t\treturn string\n\t\traise","sub_path":"lr_geocode.py","file_name":"lr_geocode.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"124276239","text":"from django import template\nfrom django.utils import safestring\nfrom django.utils import html\n\nregister = template.Library()\n\n\n@register.filter()\ndef bootstrap_tags(tags):\n bootstrap_alerts = ['debug', 'info', 'success', 'warning']\n output = \"\"\n for tag in tags.split():\n if tag in bootstrap_alerts:\n tag_output = ' alert-{0}'.format(tag)\n elif tag == 'error': # django error == bootstrap danger\n tag_output = ' alert-danger'\n else:\n tag_output = ' {0}'.format(html.conditional_escape(tag))\n\n output += tag_output\n\n return safestring.mark_safe(output)\n","sub_path":"utils/templatetags/bootstrap_tags.py","file_name":"bootstrap_tags.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"596647625","text":"def remove_domain():\n file_name = input('Enter reverse or forward filename: ')\n with open(file_name, 'r') as file:\n lines = file.readlines()\n list_domains = []\n for index, line in enumerate(lines):\n check_line = line.split()\n if check_line and 'IN' in check_line and '@' not in check_line:\n list_domains.append(dict(index=index, ip=check_line[-1], domain=check_line[0]))\n if list_domains:\n for index, domain in enumerate(list_domains):\n print('{}.- {} -------- {} '.format(index + 1, domain['domain'], domain['ip']))\n number = int(input('Enter number of domain to delete: '))\n with open(file_name, 'w') as file:\n for index, line in enumerate(lines):\n if list_domains[number - 1]['index'] != index:\n file.write(line)\n","sub_path":"remove_domain.py","file_name":"remove_domain.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"123811090","text":"'''\n@author: Jeremy Bayley\n@email : TheEnvironmentGuy@gmail.com\n@websight : TheEnvironmentGuy.com\n\nFriday March 25 2016\nBlender 2.77\n\n-*- coding: utf-8 -*-\n'''\n\nimport bpy\nimport ImperialPrimitives as ip\n\ninch = 0.0254\nfoot = 0.3048\nstud_length = foot*8\n\nceiling_height = foot*8\nwall_length = foot*6\ndrywall_size = [foot*4, inch/2, foot*8]\nwoodstock_size = [inch*2.5, foot*8, inch*1.5]\nstud_distance = inch*16\n\n\ndef Main():\n bpy.ops.mesh.primitive_cube_add()\n ip.SetupObject(size=[11,2,3])\n\n\n\nif __name__ == '__main__':\n Main()\n","sub_path":"blenderWallBuilder/WallBuilder.py","file_name":"WallBuilder.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"314857335","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 12 08:16:45 2017\n\n@author: George\n\"\"\"\n\n#import math\nimport numpy as np\n#import h5py\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom resnets_utils import *\nfrom PIL import Image\nfrom scipy import ndimage\nimport copy\nfrom keras.models import Model, load_model\nfrom tqdm import tqdm\nimport glob, os\n\n\n#load model\n#fileName = \"kerasModel_20171201-001742\"\n#fileName = \"kerasModel_20171204-062622\"\n#fileName = \"kerasModel_20180221-025551\" #40,000 images in training\n#fileName = \"kerasModel_20180302-024740\" #80,000 images in training\n#fileName = \"kerasModel_20180311-103037\" #100,000 images in training + 4,100 notBuilding Idaho examples\n#fileName = \"kerasModel_20180312-083230\" #120,000 images in training + 10,600 notBuilding Idaho examples\nfileName = \"kerasModel_20180317-114850\" #120,000 images in training + 10,600 notBuilding Idaho examples + 1648 building Idaho examples\n\nmodel_filePath = r\"C:\\\\Google Drive\\\\code\\\\python_code\\\\tensorFlow\\\\buildingIdentification\\\\results\\\\\" + fileName\n\nmodel = load_model(model_filePath)\nresultsPath = r\"C:\\\\Google Drive\\\\code\\\\python_code\\\\tensorFlow\\\\buildingIdentification\\\\results\\\\kerasModel_results\\\\\"\nsavePath = r\"C:\\\\Google Drive\\\\code\\\\python_code\\\\tensorFlow\\\\buildingIdentification\\\\results\\\\kerasModel_results\\\\\" + fileName\n\n\n#load map\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\tyrol-e10.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\innsbruck20.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\sfo3.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\bellingham19.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\sfo25.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\tyrol-e18.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\tyrol-e28.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\bloomington5.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\bellingham21.tif\"\n#mapPath = r\"J:\\AerialImageDataset\\AerialImageDataset\\test\\images\\bloomington23.tif\"\nmapPath = r\"C:\\Users\\George\\Desktop\\testImages\\test4.jpg\"\n#mapPath = r\"C:\\Users\\George\\Desktop\\buildingClassifier\\finalClips\\NAIP20150.jpg\"\n\n#load mapArray from image file\nmapArray = np.array(ndimage.imread(mapPath, flatten=False))\n\n\n# =============================================================================\n# ##load image from lat/long coordinates - using imageCapture in resnets_utils\n# centerPoint = (-114.318634, 43.522553) #(long,lat)\n# zoom = 19 \n# NW_lat_long, SE_lat_long = getNWSECorners(centerPoint,zoom)\n# result = get_maps_image(NW_lat_long, SE_lat_long, zoom=zoom)\n# saveImagePath = r\"C:\\Users\\George\\Desktop\\testImages\\test_lat_long.jpg\"\n# result.save(saveImagePath,\"JPEG\")\n# mapArray = np.array(result)\n# =============================================================================\n\n\n\n#get list of arrays\ndef getDataList(mapArray, startX, endX, startY, endY):\n mapArray = mapArray[startX:endX,startY:endY]\n imgwidth, imgheight , colours = mapArray.shape\n \n #split map into sections\n dataList = []\n num_px = 100\n #imageVectorSize = num_px * num_px * 3\n \n #square maps only\n def crop(mapArray,height,width):\n imgwidth, imgheight , colours = mapArray.shape\n for i in range(imgheight-height):\n for j in range(imgwidth-width):\n yield mapArray[i:i+height, j:j+width]\n \n height=num_px\n width=num_px\n start_num=0\n for k,piece in enumerate(crop(mapArray,height,width),start_num):\n dataList.append(piece)\n return dataList\n\n\ndef getPredictionArray(dataList, savePath, x, y, i):\n \n imgwidth = 200\n imgheight = 200\n num_px = 100\n \n # Loading the data (cat/non-cat)\n X_test_orig = np.array(dataList)\n Y_test_orig = np.zeros(len(dataList), dtype=\"int\")\n Y_test_orig = Y_test_orig.reshape(1,Y_test_orig.shape[0])\n classes = np.array(('notBuilding','building'), dtype=\"str\")\n \n num_labels = np.size(classes)\n \n # Normalize image vectors\n X_test = X_test_orig/255.\n # Convert training and test labels to one hot matrices\n Y_test = convert_to_one_hot(Y_test_orig, num_labels)\n \n \n print (\"number of images to process = \" + str(X_test.shape[0]))\n print (\"X_test shape: \" + str(X_test.shape))\n print (\"Y_test shape: \" + str(Y_test.shape))\n \n \n image_predictions_original = model.predict(X_test, verbose=1)\n \n predict_image = []\n\n##majority vote allocation \n for result in image_predictions_original :\n if result[0] > result[1]:\n predict_image.append(0)\n else:\n predict_image.append(1)\n\n\n### for result in image_predictions_original :\n# if result[1] > 0.75:\n# predict_image.append(1)\n# else:\n# predict_image.append(0)\n \n \n image_predictions = np.array(predict_image)\n \n array = image_predictions.reshape((imgwidth - num_px, imgheight- num_px))\n #array = np.flipud(array)\n array = np.uint8(array*255)\n \n saveFile = savePath + \"_array_\" + str(i) + \"_\" + str(x) + \"-\" + str(y) + \".txt\"\n np.savetxt(saveFile, array, delimiter=',')\n\n return\n\n\ndef displayResults(folderPath):\n os.chdir(folderPath)\n \n fileList = []\n for file in glob.glob(\"*.txt\"):\n fileList.append(file)\n\n\n array0 = np.genfromtxt(fileList[0],delimiter=\",\")\n for i in range(1,5):\n array = np.genfromtxt(fileList[i],delimiter=\",\")\n array0 = np.hstack((array0,array))\n\n array1 = np.genfromtxt(fileList[5],delimiter=\",\")\n for i in range(6,10):\n array = np.genfromtxt(fileList[i],delimiter=\",\")\n array1 = np.hstack((array1,array))\n\n array2 = np.genfromtxt(fileList[10],delimiter=\",\")\n for i in range(11,15):\n array = np.genfromtxt(fileList[i],delimiter=\",\")\n array2 = np.hstack((array2,array))\n\n array3 = np.genfromtxt(fileList[15],delimiter=\",\")\n for i in range(16,20):\n array = np.genfromtxt(fileList[i],delimiter=\",\")\n array3 = np.hstack((array3,array))\n\n array4 = np.genfromtxt(fileList[20],delimiter=\",\")\n for i in range(21,25):\n array = np.genfromtxt(fileList[i],delimiter=\",\")\n array4 = np.hstack((array4,array))\n\n imageArray = np.vstack((array0,array1,array2,array3,array4))\n \n img = Image.fromarray(imageArray)\n# plt.figure()\n# plt.imshow(img)\n return img\n\n\n\n#reduce map size for large map\nstartXloc = 200 #actually Y!\n#endX = startX + 200\nstartYloc = 200 #actually X!\n#endY = startY + 200\n\nfor i in range(3):\n \n for x in tqdm(range(5)):\n print(\"Run :\" + str(x))\n print(\"----------------\")\n startX = startXloc + (x * 100)\n endX = startX + 200\n \n for y in range(5):\n startY = startYloc + (y *100)\n endY = startY + 200\n \n dataList = getDataList(mapArray, startX, endX, startY, endY)\n getPredictionArray(dataList, savePath, startX, startY, i)\n print(\"-------------\")\n startYloc = startYloc + 500\n \n\n\n### Uncomment to display results\n#piece = displayResults(resultsPath)\n#\n#startX = startXloc\n#endX = startX + (6 * 100)\n#startY = startYloc\n#endY = startY + (6 * 100)\n#\n#num_px = 100\n#\n#\n##img = Image.open(mapPath)\n#mapArray = np.array(ndimage.imread(mapPath, flatten=False))\n#mapArray = mapArray[startX:endX,startY:endY]\n#img = Image.fromarray(mapArray)\n#\n#img2 = copy.deepcopy(img)\n#\n#img2.paste(piece,(int(num_px/2),int(num_px/2)))\n#\n#\n#fig1 = plt.figure(1)\n#plt.title(\"Input image\")\n#plt.imshow(img)\n#fig1.show()\n#\n#fig2 = plt.figure(2)\n#plt.title(\"Neural Net Output\")\n#plt.imshow(img2)\n#fig2.show()\n#\n#\n##get pixels that are white\n#data = piece.getdata()\n#height = 500\n#width = 500\n#pixelList = []\n#\n#for i in range(height):\n# for j in range(width):\n# stride = (width*i) + j\n# pixelList.append((j, i, data[stride]))\n#\n#whites = []\n#for pixel in pixelList:\n# if pixel[2] > 0:\n# whites.append(pixel[0:2])\n#\n#\n#whites = [list(elem) for elem in whites]\n#\n#x_values = [x[0] for x in whites]\n#y_values = [y[1] for y in whites]\n#\n#plt.scatter(x_values,y_values)\n#\n##np.array of white pixels\n#X = np.array(whites)\n\n\n\n# =============================================================================\n# #filter out green-ish from original image\n# mapArrayGreen = mapArray[:,:,2]#>155\n# mapArrayGreen = mapArrayGreen.astype(float)\n# mapArrayGreen = mapArrayGreen[50:200+50,50:200+50]#*255\n# \n# meanArray = np.mean(np.array([mapArrayGreen,array]),axis=0)\n# \n# meanArray = meanArray[:,:]>80\n# \n# img3 = copy.deepcopy(img)\n# meanArray = meanArray.astype(float)*255\n# piece2 = Image.fromarray(meanArray)\n# \n# img3.paste(piece2,(int(num_px/2),int(num_px/2)))\n# \n# \n# fig3 = plt.figure(3)\n# plt.title(\"Neural Net averaged with Blue channel Output\")\n# plt.imshow(img3)\n# fig3.show()\n# =============================================================================\n","sub_path":"tensorFlow/buildingIdentification/ResNet_analyzeImages_loadWholeImage_iterateOverLargeImage.py","file_name":"ResNet_analyzeImages_loadWholeImage_iterateOverLargeImage.py","file_ext":"py","file_size_in_byte":9053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"173334343","text":"from utils.pretrained_wordembed import *\nimport pandas as pd\nimport pickle\n\nclass Data:\n\n def __init__(self):\n self.char_to_idx = {}\n self.tag_to_idx = {}\n self.word_to_idx = {}\n self.reverse_tag_to_idx = {}\n self.training_path = None\n self.validation_path = None\n self.evaluation_path = None\n self.char_embedding_dim = None\n self.word_embedding_dim = None\n self.char_hidden_dim = None\n self.word_hidden_dim = None\n self.param_name = None\n self.learning_rate = None\n self.pretrained_word_embed_path = None\n self.pretrain_word_emb = None\n self.char_model = None\n self.word_model = None\n self.batch_size = None\n self.GPU = None\n self.epoch = None\n self.optimizer = None\n self.model_save_path = None\n self.data_save_path = None\n self.infer_path = None\n self.mode = None\n self.NER = None\n self.result_save_path = None\n\n def readConfig(self,file_path):\n lines = open(file_path, 'r').readlines()\n for line in lines:\n if len(line) == 1 or line[0] == '#':\n continue\n param_name, value = line.replace(' ', '').split('=')[0], line.replace(' ', '').split('=')[1].replace('\\n','')\n\n if str(param_name) == \"training_path\":\n self.training_path = value\n\n elif param_name == 'validation_path':\n self.validation_path = value\n\n elif param_name == 'evaluation_path':\n self.evaluation_path = value\n\n elif param_name == 'char_embedding_dim':\n self.char_embedding_dim = int(value)\n\n elif param_name == 'word_embedding_dim':\n self.word_embedding_dim = int(value)\n\n elif param_name == 'char_hidden_dim':\n self.char_hidden_dim = int(value)\n\n elif param_name == 'word_hidden_dim':\n self.word_hidden_dim = int(value)\n\n elif param_name == 'epoch':\n self.epoch = int(value)\n\n elif param_name == 'learning_rate':\n self.learning_rate = float(value)\n\n elif param_name == 'pretained_word_embed_path':\n self.pretrained_word_embed_path = value\n\n elif param_name == 'char_model':\n self.char_model = value\n\n elif param_name == 'word_model':\n self.word_model = value\n\n elif param_name == 'batch_size':\n self.batch_size = int(value)\n\n elif param_name == 'GPU':\n self.GPU = value\n\n elif param_name == 'optimizer':\n self.optimizer = value\n\n elif param_name == 'model_save_path':\n self.model_save_path = value\n\n elif param_name == 'data_save_path':\n self.data_save_path = value\n\n elif param_name == 'infer_path':\n self.infer_path = value\n\n elif param_name == 'mode':\n self.mode = value\n\n elif param_name == 'NER':\n self.NER = bool(value)\n\n elif param_name == 'result_save_path':\n self.result_save_path = value\n\n\n \n def buildDictionary(self):\n files = [self.training_path, self.evaluation_path, self.validation_path]\n frames = [pd.read_csv(file,header=None,low_memory=False,encoding='utf-8') for file in files]\n data = pd.concat(frames)\n column0, column1, column2 = data[data.columns[0]],data[data.columns[1]],data[data.columns[2]]\n preIdx = '0'\n preToken = ''\n STRINGS = []\n TAGS = []\n string_tmp = []\n tag_tmp = []\n for idx, token, tag in zip(column0, column1, column2):\n idx = str(idx)\n token = str(token)\n tag = str(tag)\n if preIdx != idx:\n STRINGS.append(string_tmp)\n TAGS.append(tag_tmp)\n string_tmp = []\n tag_tmp = []\n\n string_tmp.append(token)\n tag_tmp.append(tag)\n preIdx = idx\n\n\n for item in zip(STRINGS, TAGS):\n sentence = item[0]\n tags = item[1]\n for tag in tags:\n if tag not in self.tag_to_idx:\n self.tag_to_idx[tag] = len(self.tag_to_idx) + 1\n self.reverse_tag_to_idx[len(self.reverse_tag_to_idx)+1] = tag\n\n sen_list = sentence\n for word in sen_list:\n word = word.lower()\n if word not in self.word_to_idx:\n self.word_to_idx[word] = len(self.word_to_idx)+1\n for char in word:\n if char not in self.char_to_idx:\n self.char_to_idx[char] = len(self.char_to_idx)+1\n\n self.word_to_idx[\"WORD_PAD\"] = 0\n self.char_to_idx[\"CHAR_PAD\"] = 0\n\n\n def getPretrainedEmbedding(self):\n self.pretrain_word_emb = build_pretrain_embedding(embedding_path=self.pretrained_word_embed_path,\\\n word_alphabet = list(self.word_to_idx.keys()))\n\n def saveData(self):\n f = open(self.data_save_path, 'wb')\n pickle.dump(self.__dict__, f, 2)\n f.close()\n\n def load(self,path):\n f = open(path, 'rb')\n tmp_dict = pickle.load(f)\n f.close()\n self.__dict__.update(tmp_dict)\n\n\n\n","sub_path":"model/Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"575745056","text":"\"\"\"Fakegram middleware catalog.\"\"\"\n\n# Django \nfrom django.shortcuts import redirect\nfrom django.urls import reverse\n\nclass PofileCompletionMiddleware:\n\t\"\"\"Profile completition middleware.\n\n\tEnsure every user that is interacting with the plattform\n\thave their profile picture and biography.\t\n\t\"\"\"\n\t\n\tdef __init__(self, get_response):\n\t\t\"\"\"Middleware initialization.\"\"\"\n\t\tself.get_response = get_response\n\n\tdef __call__(self, request):\n\t\t\"\"\"Code to be executed for each request before the view is called.\"\"\"\n\t\tif not request.user.is_anonymous:\n\t\t\tif not request.user.is_staff:\n\t\t\t\tprofile = request.user.profile\n\t\t\t\tif not profile.picture or not profile.biography:\n\t\t\t\t\tif request.path not in [reverse('users:update_profile'), reverse('users:logout')]: # nos da la url a partir de su nombre\n\t\t\t\t\t\treturn redirect('users:update_profile')\n\n\t\tresponse = self.get_response(request)\n\t\treturn response\n\n# lo instalamos en settins.py, llamándolo por su ruta después del resto de middlewares","sub_path":"fakegram/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"310863607","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport torchvision\n\ndef main():\n print('cuda device count: ', torch.cuda.device_count())\n net = torchvision.models.mobilenet_v3_small(pretrained=True)\n #net.fc = nn.Linear(512, 2)\n net = net.eval()\n net = net.to('cuda:0')\n print(net)\n tmp = torch.ones(1, 3, 224, 224).to('cuda:0')\n out = net(tmp)\n print('mobilenet out:', out.shape)\n torch.save(net, \"mobilenetv3.pth\")\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"mobilenet/mobilenetv3.py","file_name":"mobilenetv3.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"82239998","text":"import pandas as pd\nfrom amply import Amply\n\nfrom otoole.preprocess.datafile_to_datapackage import (\n convert_amply_data_to_list,\n convert_amply_to_dataframe,\n load_parameter_definitions,\n)\n\n\ndef test_amply():\n\n Amply(\n \"\"\"set REGION;\n # set REGION := SIMPLICITY;\n set TECHNOLOGY;\n set TECHNOLOGY := ETHPLANT GAS_EXTRACTION;\n set MODE_OF_OPERATION;\n set MODE_OF_OPERATION := 1 2;\n set YEAR;\n set YEAR := 2014;\n end;\"\"\"\n )\n\n\ndef test_convert_amply_to_dataframe():\n\n config = {\n \"VariableCost\": {\n \"type\": \"param\",\n \"indices\": [\"REGION\", \"TECHNOLOGY\", \"MODE_OF_OPERATION\", \"YEAR\"],\n \"dtype\": \"float\",\n \"default\": 0,\n },\n \"REGION\": {\"type\": \"set\", \"dtype\": \"str\"},\n \"YEAR\": {\"dtype\": \"int\", \"type\": \"set\"},\n \"MODE_OF_OPERATION\": {\"dtype\": \"int\", \"type\": \"set\"},\n \"TECHNOLOGY\": {\"dtype\": \"str\", \"type\": \"set\"},\n }\n\n amply = Amply(\n \"\"\"set REGION;\n set REGION := SIMPLICITY;\n set TECHNOLOGY;\n set TECHNOLOGY := ETHPLANT GAS_EXTRACTION;\n set MODE_OF_OPERATION;\n set MODE_OF_OPERATION := 1 2;\n set YEAR;\n set YEAR := 2014;\"\"\"\n )\n amply.load_string(\"param VariableCost {REGION,TECHNOLOGY,MODE_OF_OPERATION,YEAR};\")\n # amply.load_string(\"\"\"param default 0 : VariableCost :=\n # SIMPLICITY ETHPLANT 1 2014 2.89\n # SIMPLICITY ETHPLANT 2 2014 999999.0\n # SIMPLICITY GAS_EXTRACTION 1 2014 7.5\n # SIMPLICITY GAS_EXTRACTION 2 2014 999999.0\"\"\")\n amply.load_string(\n \"\"\"\nparam VariableCost default 0.0001 :=\n[SIMPLICITY,ETHPLANT,*,*]:\n2014 :=\n1 2.89\n2 999999.0\n[SIMPLICITY,GAS_EXTRACTION,*,*]:\n2014 :=\n1 7.5\n2 999999.0;\"\"\"\n )\n actual = convert_amply_to_dataframe(amply, config)\n expected = pd.DataFrame(\n data=[\n [\"SIMPLICITY\", \"ETHPLANT\", 1, 2014, 2.89],\n [\"SIMPLICITY\", \"ETHPLANT\", 2, 2014, 999999.0],\n [\"SIMPLICITY\", \"GAS_EXTRACTION\", 1, 2014, 7.5],\n [\"SIMPLICITY\", \"GAS_EXTRACTION\", 2, 2014, 999999.0],\n ],\n columns=[\"REGION\", \"TECHNOLOGY\", \"MODE_OF_OPERATION\", \"YEAR\", \"VALUE\"],\n )\n\n pd.testing.assert_frame_equal(actual[\"VariableCost\"], expected)\n\n\ndef test_convert_amply_data_to_list_of_lists():\n\n data = {\n \"SIMPLICITY\": {\n \"ETHPLANT\": {1.0: {2014.0: 2.89}, 2.0: {2014.0: 999999.0}},\n \"GAS_EXTRACTION\": {1.0: {2014.0: 7.5}, 2.0: {2014.0: 999999.0}},\n }\n }\n expected = [\n [\"SIMPLICITY\", \"ETHPLANT\", 1.0, 2014.0, 2.89],\n [\"SIMPLICITY\", \"ETHPLANT\", 2.0, 2014.0, 999999.0],\n [\"SIMPLICITY\", \"GAS_EXTRACTION\", 1.0, 2014.0, 7.5],\n [\"SIMPLICITY\", \"GAS_EXTRACTION\", 2.0, 2014.0, 999999.0],\n ]\n actual = convert_amply_data_to_list(data)\n assert actual == expected\n\n\ndef test_load_parameters():\n\n config = {\"TestParameter\": {\"type\": \"param\", \"indices\": [\"index1\", \"index2\"]}}\n\n actual = load_parameter_definitions(config)\n expected = \"param TestParameter {index1,index2};\\n\"\n assert actual == expected\n\n\ndef test_load_sets():\n\n config = {\"TestSet\": {\"type\": \"set\"}}\n\n actual = load_parameter_definitions(config)\n expected = \"set TestSet;\\n\"\n assert actual == expected\n","sub_path":"tests/preprocess/test_file2package.py","file_name":"test_file2package.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"571543061","text":"import logging\n\n_logger = logging.getLogger(__name__)\n\n__all__ = [\n \"camera_efficiency_log_file_name\",\n \"camera_efficiency_results_file_name\",\n \"camera_efficiency_simtel_file_name\",\n \"convert_telescope_model_name_to_yaml\",\n \"get_site_from_telescope_name\",\n \"get_telescope_type\",\n \"is_valid_name\",\n \"layout_telescope_list_file_name\",\n \"ray_tracing_file_name\",\n \"ray_tracing_plot_file_name\",\n \"ray_tracing_results_file_name\",\n \"simtel_array_config_file_name\",\n \"simtel_telescope_config_file_name\",\n \"simtools_instrument_name\",\n \"split_telescope_model_name\",\n \"validate_camera_name\",\n \"validate_layout_array_name\",\n \"validate_model_version_name\",\n \"validate_name\",\n \"validate_simtel_mode_name\",\n \"validate_site_name\",\n \"validate_sub_system_name\",\n \"validate_telescope_id_name\",\n \"validate_telescope_model_name\",\n \"validate_telescope_name_db\",\n]\n\nlst = \"LST\"\nmst = \"MST\"\nsct = \"SCT\"\nsst = \"SST\"\n\nall_telescope_class_names = {\n lst: [\"lst\"],\n mst: [\"mst\"],\n sct: [\"sct\"],\n sst: [\"sst\"],\n}\n\nall_camera_names = {\n \"SST\": [\"sst\"],\n \"ASTRI\": [\"astri\"],\n \"GCT\": [\"gct\", \"gct-s\"],\n \"1M\": [\"1m\"],\n \"FlashCam\": [\"flashcam\", \"flash-cam\"],\n \"NectarCam\": [\"nectarcam\", \"nectar-cam\"],\n \"SCT\": [\"sct\"],\n \"LST\": [\"lst\"],\n}\n\nall_structure_names = {\"Structure\": [\"Structure\", \"structure\"]}\n\nall_site_names = {\"South\": [\"paranal\", \"south\"], \"North\": [\"lapalma\", \"north\"]}\n\nall_model_version_names = {\n \"2015-07-21\": [\"\"],\n \"2015-10-20-p1\": [\"\"],\n \"prod4-v0.0\": [\"\"],\n \"prod4-v0.1\": [\"\"],\n \"2018-02-16\": [\"\"],\n \"prod3_compatible\": [\"p3\", \"prod3\", \"prod3b\"],\n \"prod4\": [\"p4\"],\n \"post_prod3_updates\": [\"\"],\n \"2016-12-20\": [\"\"],\n \"2018-11-07\": [\"\"],\n \"2019-02-22\": [\"\"],\n \"2019-05-13\": [\"\"],\n \"2019-11-20\": [\"\"],\n \"2019-12-30\": [\"\"],\n \"2020-02-26\": [\"\"],\n \"2020-06-28\": [\"prod5\"],\n \"prod4-prototype\": [\"\"],\n \"default\": [],\n \"Current\": [],\n \"Latest\": [],\n}\n\nall_simtel_mode_names = {\n \"RayTracing\": [\"raytracing\", \"ray-tracing\"],\n \"RayTracingSingleMirror\": [\n \"raytracing-singlemirror\",\n \"ray-tracing-singlemirror\",\n \"ray-tracing-single-mirror\",\n ],\n \"Trigger\": [\"trigger\"],\n}\n\nall_layout_array_names = {\n \"4LST\": [\"4-lst\", \"4lst\"],\n \"1LST\": [\"1-lst\", \"1lst\"],\n \"4MST\": [\"4-mst\", \"4mst\"],\n \"1MST\": [\"1-mst\", \"mst\"],\n \"4SST\": [\"4-sst\", \"4sst\"],\n \"1SST\": [\"1-sst\", \"sst\"],\n \"Prod5\": [\"prod5\", \"p5\"],\n \"TestLayout\": [\"test-layout\"],\n}\n\ncorsika_to_simtools_names = {\n \"OBSLEV\": \"corsika_obs_level\",\n}\n\n\ndef validate_sub_system_name(name):\n \"\"\"\n Validate a sub system name (optics structure or camera).\n\n Parameters\n ----------\n name: str\n Name of the subsystem.\n\n Returns\n -------\n str\n Validated name.\n \"\"\"\n return validate_name(name, {**all_camera_names, **all_structure_names})\n\n\ndef validate_camera_name(name):\n \"\"\"\n Validate a camera name.\n\n Parameters\n ----------\n name: str\n Camera name\n\n Returns\n -------\n str\n Validated name.\n \"\"\"\n return validate_name(name, all_camera_names)\n\n\ndef validate_telescope_id_name(name):\n \"\"\"\n Validate a telescope ID name\n\n Valid names e.g.,\n - D\n - telescope ID\n\n Parameters\n ----------\n name: str\n Telescope ID name.\n\n Returns\n -------\n str\n Validated name.\n\n Raises\n ------\n ValueError\n If name is not valid.\n \"\"\"\n\n if name == \"D\" or name.isdigit():\n return name\n\n msg = f\"Invalid telescope ID name {name}\"\n _logger.error(msg)\n raise ValueError(msg)\n\n\ndef validate_model_version_name(name):\n \"\"\"\n Validate a model version name.\n\n Parameters\n ----------\n name: str\n Model version name.\n\n Returns\n -------\n str\n Validated name.\n \"\"\"\n return validate_name(name, all_model_version_names)\n\n\ndef validate_simtel_mode_name(name):\n \"\"\"\n Validate a sim_telarray mode name.\n\n Parameters\n ----------\n name: str\n sim_telarray mode name.\n\n Returns\n -------\n str\n Validated name.\n \"\"\"\n return validate_name(name, all_simtel_mode_names)\n\n\ndef validate_site_name(name):\n \"\"\"\n Validate a site name.\n\n Parameters\n ----------\n name: str\n Site name.\n\n Returns\n -------\n str\n Validated name.\n \"\"\"\n return validate_name(name, all_site_names)\n\n\ndef validate_layout_array_name(name):\n \"\"\"\n Validate a layout array name.\n\n Parameters\n ----------\n name: str\n Layout array name.\n\n Returns\n -------\n str\n Validated name.\n \"\"\"\n return validate_name(name, all_layout_array_names)\n\n\ndef validate_name(name, all_names):\n \"\"\"\n Validate a name given the all_names options. For each key in all_names, a list of options is \\\n given. If name is in this list, the key name is returned.\n\n Parameters\n ----------\n name: str\n Name to validate.\n all_names: dict\n Dictionary with valid names.\n Returns\n -------\n str\n Validated name.\n\n Raises\n ------\n ValueError\n If name is not valid.\n \"\"\"\n\n if not is_valid_name(name, all_names):\n msg = f\"Invalid name {name}\"\n _logger.error(msg)\n raise ValueError(msg)\n for main_name, list_of_names in all_names.items():\n if name.lower() in list_of_names + [main_name.lower()]:\n if name != main_name:\n _logger.debug(f\"Correcting name {name} -> {main_name}\")\n return main_name\n return None\n\n\ndef is_valid_name(name, all_names):\n \"\"\"\n Check if name is valid.\n\n Parameters\n ----------\n name: str\n Name to validated.\n all_names: dict\n Dictionary with valid names.\n\n Returns\n -------\n bool\n True if name is valid. Otherwise, false.\n \"\"\"\n\n if not isinstance(name, str):\n return False\n for main_name in all_names.keys():\n if name.lower() in all_names[main_name] + [main_name.lower()]:\n return True\n return False\n\n\ndef validate_telescope_model_name(name):\n \"\"\"\n Validate a telescope model name.\n\n Parameters\n ----------\n name: str\n Telescope model name.\n\n Returns\n -------\n str\n Validated name.\n \"\"\"\n\n tel_class, tel_type = split_telescope_model_name(name)\n tel_class = validate_name(tel_class, all_telescope_class_names)\n if \"flashcam\" in tel_type:\n tel_type = tel_type.replace(\"flashcam\", \"FlashCam\")\n if \"nectarcam\" in tel_type:\n tel_type = tel_type.replace(\"nectarcam\", \"NectarCam\")\n if \"1m\" in tel_type:\n tel_type = tel_type.replace(\"1m\", \"1M\")\n if \"gct\" in tel_type:\n tel_type = tel_type.replace(\"gct\", \"GCT\")\n if \"astri\" in tel_type:\n tel_type = tel_type.replace(\"astri\", \"ASTRI\")\n if \"-d\" in \"-\" + tel_type:\n tel_type = tel_type.replace(\"d\", \"D\")\n\n return tel_class + \"-\" + tel_type\n\n\ndef split_telescope_model_name(name):\n \"\"\"\n Split a telescope name into class and type.\n\n Parameters\n ----------\n name: str\n Telescope name.\n\n Returns\n -------\n str, str\n class (LST, MST, SST ...) and type (any complement).\n \"\"\"\n\n name_parts = name.split(\"-\")\n tel_class = name_parts[0]\n tel_type = \"-\".join(name_parts[1:])\n return tel_class, tel_type\n\n\ndef get_site_from_telescope_name(name):\n \"\"\"\n Get site name (South or North) from the (validated) telescope name.\n\n Parameters\n ----------\n name: str\n Telescope name.\n\n Returns\n -------\n str\n Site name (South or North).\n \"\"\"\n return validate_site_name(name.split(\"-\")[0])\n\n\ndef validate_telescope_name_db(name):\n \"\"\"\n Validate a telescope DB name.\n\n Parameters\n ----------\n name: str\n\n Returns\n -------\n str\n Validated name.\n \"\"\"\n site = get_site_from_telescope_name(name)\n tel_model_name = \"-\".join(name.split(\"-\")[1:])\n\n return f\"{validate_site_name(site)}-{validate_telescope_model_name(tel_model_name)}\"\n\n\ndef convert_telescope_model_name_to_yaml(name):\n \"\"\"\n Get telescope name following the old convention (yaml files) from the current telescope name.\n\n Parameters\n ----------\n name: str\n Telescope model name.\n\n Returns\n -------\n str\n Telescope name (old convention).\n\n Raises\n ------\n ValueError\n if name is not valid.\n \"\"\"\n tel_class, tel_type = split_telescope_model_name(name)\n new_name = tel_class + \"-\" + tel_type\n old_names = {\n \"SST-D\": \"SST\",\n \"SST-1M\": \"SST-1M\",\n \"SST-ASTRI\": \"SST-2M-ASTRI\",\n \"SST-GCT\": \"SST-2M-GCT-S\",\n \"MST-FlashCam-D\": \"MST-FlashCam\",\n \"MST-NectarCam-D\": \"MST-NectarCam\",\n \"SCT-D\": \"SCT\",\n \"LST-D234\": \"LST\",\n \"LST-1\": \"LST\",\n }\n\n if new_name not in old_names:\n raise ValueError(f\"Telescope name {name} could not be converted to yml names\")\n\n return old_names[new_name]\n\n\ndef simtools_instrument_name(site, telescope_class_name, sub_system_name, telescope_id_name):\n \"\"\"\n Instrument name following simtools naming convention\n\n Parameters\n ----------\n site: str\n South or North.\n telescope_class_name: str\n LST, MST, ...\n sub_system_name: str\n FlashCam, NectarCam\n telescope_id_name: str\n telescope ID (e.g., D, numerial value)\n\n Returns\n -------\n instrument: name: str\n Instrument name.\n \"\"\"\n\n return (\n validate_site_name(site)\n + \"-\"\n + validate_name(telescope_class_name, all_telescope_class_names)\n + \"-\"\n + validate_sub_system_name(sub_system_name)\n + \"-\"\n + validate_telescope_id_name(telescope_id_name)\n )\n\n\ndef simtel_telescope_config_file_name(\n site, telescope_model_name, model_version, label, extra_label\n):\n \"\"\"\n sim_telarray config file name for a telescope.\n\n Parameters\n ----------\n site: str\n South or North.\n telescope_model_name: str\n LST-1, MST-FlashCam, ...\n model_version: str\n Version of the model.\n label: str\n Instance label.\n extra_label: str\n Extra label in case of multiple telescope config files.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = f\"CTA-{site}-{telescope_model_name}-{model_version}\"\n name += f\"_{label}\" if label is not None else \"\"\n name += f\"_{extra_label}\" if extra_label is not None else \"\"\n name += \".cfg\"\n return name\n\n\ndef simtel_array_config_file_name(array_name, site, version, label):\n \"\"\"\n sim_telarray config file name for an array.\n\n Parameters\n ----------\n array_name: str\n Prod5, ...\n site: str\n South or North.\n version: str\n Version of the model.\n label: str\n Instance label.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = f\"CTA-{array_name}-{site}-{version}\"\n name += f\"_{label}\" if label is not None else \"\"\n name += \".cfg\"\n return name\n\n\ndef simtel_single_mirror_list_file_name(\n site, telescope_model_name, model_version, mirror_number, label\n):\n \"\"\"\n sim_telarray mirror list file with a single mirror.\n\n Parameters\n ----------\n site: str\n South or North.\n telescope_model_name: str\n North-LST-1, South-MST-FlashCam, ...\n model_version: str\n Version of the model.\n mirror_number: int\n Mirror number.\n label: str\n Instance label.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = f\"CTA-single-mirror-list-{site}-{telescope_model_name}-{model_version}\"\n name += f\"-mirror{mirror_number}\"\n name += f\"_{label}\" if label is not None else \"\"\n name += \".dat\"\n return name\n\n\ndef layout_telescope_list_file_name(name, label):\n \"\"\"\n File name for files required at the RayTracing class.\n\n Parameters\n ----------\n name: str\n Name of the array.\n label: str\n Instance label.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n file_name = f\"telescope_positions-{name}\"\n file_name += f\"_{label}\" if label is not None else \"\"\n file_name += \".ecsv\"\n return file_name\n\n\ndef ray_tracing_file_name(\n site,\n telescope_model_name,\n source_distance,\n zenith_angle,\n off_axis_angle,\n mirror_number,\n label,\n base,\n):\n \"\"\"\n File name for files required at the RayTracing class.\n\n Parameters\n ----------\n site: str\n South or North.\n telescope_model_name: str\n LST-1, MST-FlashCam, ...\n source_distance: float\n Source distance (km).\n zenith_angle: float\n Zenith angle (deg).\n off_axis_angle: float\n Off-axis angle (deg).\n mirror_number: int\n Mirror number. None if not single mirror case.\n label: str\n Instance label.\n base: str\n Photons, stars or log.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = (\n f\"{base}-{site}-{telescope_model_name}-d{source_distance:.1f}\"\n f\"-za{zenith_angle:.1f}-off{off_axis_angle:.3f}\"\n )\n name += f\"_mirror{mirror_number}\" if mirror_number is not None else \"\"\n name += f\"_{label}\" if label is not None else \"\"\n name += \".log\" if base == \"log\" else \".lis\"\n return name\n\n\ndef ray_tracing_results_file_name(site, telescope_model_name, source_distance, zenith_angle, label):\n \"\"\"\n Ray tracing results file name.\n\n Parameters\n ----------\n site: str\n South or North.\n telescope_model_name: str\n LST-1, MST-FlashCam, ...\n source_distance: float\n Source distance (km).\n zenith_angle: float\n Zenith angle (deg).\n label: str\n Instance label.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = f\"ray-tracing-{site}-{telescope_model_name}-d{source_distance:.1f}-za{zenith_angle:.1f}\"\n name += f\"_{label}\" if label is not None else \"\"\n name += \".ecsv\"\n return name\n\n\ndef ray_tracing_plot_file_name(\n key, site, telescope_model_name, source_distance, zenith_angle, label\n):\n \"\"\"\n Ray tracing plot file name.\n\n Parameters\n ----------\n key: str\n Quantity to be plotted (d80_cm, d80_deg, eff_area or eff_flen)\n site: str\n South or North.\n telescope_model_name: str\n LST-1, MST-FlashCam, ...\n source_distance: float\n Source distance (km).\n zenith_angle: float\n Zenith angle (deg).\n label: str\n Instance label.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = (\n f\"ray-tracing-{site}-{telescope_model_name}-{key}-\"\n f\"d{source_distance:.1f}-za{zenith_angle:.1f}\"\n )\n name += f\"_{label}\" if label is not None else \"\"\n name += \".pdf\"\n return name\n\n\ndef camera_efficiency_results_file_name(site, telescope_model_name, zenith_angle, label):\n \"\"\"\n Camera efficiency results file name.\n\n Parameters\n ----------\n site: str\n South or North.\n telescope_model_name: str\n LST-1, MST-FlashCam, ...\n zenith_angle: float\n Zenith angle (deg).\n label: str\n Instance label.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = f\"camera-efficiency-{site}-{telescope_model_name}-za{zenith_angle:.1f}\"\n name += f\"_{label}\" if label is not None else \"\"\n name += \".ecsv\"\n return name\n\n\ndef camera_efficiency_simtel_file_name(site, telescope_model_name, zenith_angle, label):\n \"\"\"\n Camera efficiency simtel output file name.\n\n Parameters\n ----------\n site: str\n South or North.\n telescope_model_name: str\n LST-1, MST-FlashCam-D, ...\n zenith_angle: float\n Zenith angle (deg).\n label: str\n Instance label.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = f\"camera-efficiency-{site}-{telescope_model_name}-za{zenith_angle:.1f}\"\n name += f\"_{label}\" if label is not None else \"\"\n name += \".dat\"\n return name\n\n\ndef camera_efficiency_log_file_name(site, telescope_model_name, zenith_angle, label):\n \"\"\"\n Camera efficiency log file name.\n\n Parameters\n ----------\n site: str\n South or North.\n telescope_model_name: str\n LST-1, MST-FlashCam-D, ...\n zenith_angle: float\n Zenith angle (deg).\n label: str\n Instance label.\n\n Returns\n -------\n str\n File name.\n \"\"\"\n name = f\"camera-efficiency-{site}-{telescope_model_name}-za{zenith_angle:.1f}\"\n name += f\"_{label}\" if label is not None else \"\"\n name += \".log\"\n return name\n\n\ndef get_telescope_type(telescope_name):\n \"\"\"\n Guess telescope type from name, e.g. \"LST\", \"MST\", ...\n\n Parameters\n ----------\n telescope_name: str\n Telescope name\n\n Returns\n -------\n str\n Telescope type.\n \"\"\"\n\n _class, _ = split_telescope_model_name(telescope_name)\n try:\n if _class[0:3] in all_telescope_class_names:\n return _class[0:3]\n\n except IndexError:\n pass\n\n return \"\"\n\n\ndef translate_corsika_to_simtools(corsika_par):\n \"\"\"\n Translate the name of a CORSIKA parameter to the name used in simtools.\n\n Parameters\n ----------\n corsika_par: str\n Name of the corsika parameter to be translated.\n\n \"\"\"\n\n try:\n return corsika_to_simtools_names[corsika_par]\n except KeyError:\n msg = f\"Translation not found. We will proceed with the original parameter name:\\\n {corsika_par}.\"\n _logger.debug(msg)\n return corsika_par\n\n\ndef translate_simtools_to_corsika(simtools_par):\n \"\"\"\n Translate the name of a simtools parameter to the name used in CORSIKA.\n\n Parameters\n ----------\n simtools_par: str\n Name of the simtools parameter to be translated.\n \"\"\"\n\n simtools_to_corsika_names = {\n new_key: new_value for new_value, new_key in corsika_to_simtools_names.items()\n }\n try:\n return simtools_to_corsika_names[simtools_par]\n except KeyError:\n msg = f\"Translation not found. We will proceed with the original parameter name:\\\n {simtools_par}.\"\n _logger.debug(msg)\n return simtools_par\n","sub_path":"simtools/util/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":18218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"217515745","text":"def main():\n\n n = int(input(\"Número: \"))\n resultado(n)\n\n\ndef resultado(n):\n perfeito = 0 # contador\n while n > 0:\n quadrado = n ** 0.5 # tirar raiz quadrada\n if quadrado % 1 == 0: # verifica o resto da divisão\n print(f'{n} - {quadrado}')\n perfeito += 1 # incrementa o contador\n if perfeito == 1: # para a função se achar o primeiro resultado\n break\n n -= 1\n\n\nmain()\n","sub_path":"Python/Fabio03_while/parte_1/q14-menor_quadrado.py","file_name":"q14-menor_quadrado.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486071465","text":"import time\nimport os\nimport numpy as np\nnp.seterr(all='ignore')\n\nfrom functools import partial\nfrom collections import OrderedDict\nimport json\n\nimport wx\nimport wx.lib.scrolledpanel as scrolled\nimport wx.lib.agw.flatnotebook as flat_nb\n\nimport wx.dataview as dv\n\nfrom wxutils import (SimpleText, pack, Button, HLine, Choice, Check,\n MenuItem, GUIColors, GridPanel, CEN, RCEN, LCEN,\n FRAMESTYLE, Font, FileSave, FileOpen)\n\nfrom lmfit import Parameter, Parameters, fit_report\ntry:\n from lmfit.model import save_modelresult, load_modelresult\n HAS_MODELSAVE = True\nexcept ImportError:\n HAS_MODELSAVE = False\n\nimport lmfit.models as lm_models\nfrom lmfit.printfuncs import gformat, CORREL_HEAD\n\nfrom larch import Group, site_config\nfrom larch.utils import index_of\nfrom larch.utils.jsonutils import encode4js, decode4js\n\nfrom larch.wxlib import (ReportFrame, BitmapButton, ParameterWidgets,\n FloatCtrl, SetTip)\n\nfrom larch_plugins.std import group2dict\nfrom larch_plugins.io.export_modelresult import export_modelresult\nfrom larch_plugins.wx.icons import get_icon\nfrom larch_plugins.wx.parameter import ParameterPanel\n\nLCEN = wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL\nCEN |= wx.ALL\n\nFNB_STYLE = flat_nb.FNB_NO_X_BUTTON|flat_nb.FNB_NO_NAV_BUTTONS\n\nModelTypes = ('Peaks', 'General', 'Steps')\n\nModelChoices = {'steps': ('', 'Linear Step', 'Arctan Step',\n 'ErrorFunction Step', 'Logistic Step', 'Rectangle'),\n 'general': ('', 'Constant', 'Linear',\n 'Quadratic', 'Exponential', 'PowerLaw'),\n 'peaks': ('', 'Gaussian', 'Lorentzian',\n 'Voigt', 'PseudoVoigt', 'DampedHarmonicOscillator',\n 'Pearson7', 'StudentsT', 'SkewedGaussian',\n 'Moffat', 'BreitWigner', 'Donaich', 'Lognormal'),\n }\n\nFitMethods = (\"Levenberg-Marquardt\", \"Nelder-Mead\", \"Powell\")\n\nMIN_CORREL = 0.0010\n\nclass FitResultFrame(wx.Frame):\n def __init__(self, parent=None, controller=None, datagroup=None, **kws):\n\n wx.Frame.__init__(self, None, -1, title='Fit Results',\n style=FRAMESTYLE, size=(600, 675), **kws)\n self.parent = parent\n self.controller = controller\n self.larch = controller.larch\n self.datagroup = datagroup\n self.build()\n self.show()\n\n def build(self):\n sizer = wx.GridBagSizer(10, 5)\n sizer.SetVGap(2)\n sizer.SetHGap(2)\n\n panel = scrolled.ScrolledPanel(self)\n self.SetMinSize((600, 450))\n self.colors = GUIColors()\n\n # title row\n self.wids = wids = {}\n title = SimpleText(panel, 'Fit Results', font=Font(12),\n colour=self.colors.title, style=LCEN)\n\n wids['data_title'] = SimpleText(panel, '< > ', font=Font(12),\n colour=self.colors.title, style=LCEN)\n\n wids['hist_tag'] = SimpleText(panel, 'Fit #1', font=Font(12),\n colour=self.colors.title, style=LCEN)\n\n wids['hist_info'] = SimpleText(panel, ' ___ ', font=Font(12),\n colour=self.colors.title, style=LCEN)\n\n sizer.Add(title, (0, 0), (1, 2), LCEN)\n sizer.Add(wids['data_title'], (0, 2), (1, 2), LCEN)\n sizer.Add(wids['hist_tag'], (0, 4), (1, 1), LCEN)\n sizer.Add(wids['hist_info'], (0, 5), (1, 1), LCEN)\n\n irow = 1\n wids['model_desc'] = SimpleText(panel, '', font=Font(12))\n sizer.Add(wids['model_desc'], (irow, 0), (1, 5), LCEN)\n\n irow += 1\n sizer.Add(HLine(panel, size=(400, 3)), (irow, 0), (1, 5), LCEN)\n\n irow += 1\n title = SimpleText(panel, '[[Fit Statistics]]', font=Font(12),\n colour=self.colors.title, style=LCEN)\n sizer.Add(title, (irow, 0), (1, 4), LCEN)\n\n for label, attr in (('Fit method', 'method'),\n ('# Fit Evaluations', 'nfev'),\n ('# Data Points', 'ndata'),\n ('# Fit Variables', 'nvarys'),\n ('# Free Points', 'nfree'),\n ('Chi-square', 'chisqr'),\n ('Reduced Chi-square', 'redchi'),\n ('Akaike Info Criteria', 'aic'),\n ('Bayesian Info Criteria', 'bic')):\n irow += 1\n wids[attr] = SimpleText(panel, '?')\n sizer.Add(SimpleText(panel, \" %s = \" % label), (irow, 0), (1, 1), LCEN)\n sizer.Add(wids[attr], (irow, 1), (1, 1), LCEN)\n\n irow += 1\n sizer.Add(HLine(panel, size=(400, 3)), (irow, 0), (1, 5), LCEN)\n\n irow += 1\n title = SimpleText(panel, '[[Variables]]', font=Font(12),\n colour=self.colors.title, style=LCEN)\n sizer.Add(title, (irow, 0), (1, 1), LCEN)\n\n self.wids['copy_params'] = Button(panel, 'Update Model with Best Fit Values',\n size=(250, -1), action=self.onCopyParams)\n\n sizer.Add(self.wids['copy_params'], (irow, 1), (1, 3), LCEN)\n\n dvstyle = dv.DV_SINGLE|dv.DV_VERT_RULES|dv.DV_ROW_LINES\n pview = self.wids['params'] = dv.DataViewListCtrl(panel, style=dvstyle)\n self.wids['paramsdata'] = []\n pview.AppendTextColumn('Parameter', width=150)\n pview.AppendTextColumn('Best-Fit Value', width=100)\n pview.AppendTextColumn('Standard Error', width=100)\n pview.AppendTextColumn('Info ', width=275)\n\n for col in (0, 1, 2, 3):\n this = pview.Columns[col]\n isort, align = True, wx.ALIGN_LEFT\n if col in (1, 2):\n isort, align = False, wx.ALIGN_RIGHT\n this.Sortable = isort\n this.Alignment = this.Renderer.Alignment = align\n\n pview.SetMinSize((650, 200))\n pview.Bind(dv.EVT_DATAVIEW_SELECTION_CHANGED, self.onSelectParameter)\n\n irow += 1\n sizer.Add(pview, (irow, 0), (1, 5), LCEN)\n\n irow += 1\n sizer.Add(HLine(panel, size=(400, 3)), (irow, 0), (1, 5), LCEN)\n\n irow += 1\n title = SimpleText(panel, '[[Correlations]]', font=Font(12),\n colour=self.colors.title, style=LCEN)\n\n self.wids['all_correl'] = Button(panel, 'Show All',\n size=(100, -1), action=self.onAllCorrel)\n\n self.wids['min_correl'] = FloatCtrl(panel, value=MIN_CORREL,\n minval=0, size=(60, -1), gformat=True)\n\n ctitle = SimpleText(panel, 'minimum correlation: ')\n sizer.Add(title, (irow, 0), (1, 1), LCEN)\n sizer.Add(ctitle, (irow, 1), (1, 1), LCEN)\n sizer.Add(self.wids['min_correl'], (irow, 2), (1, 1), LCEN)\n sizer.Add(self.wids['all_correl'], (irow, 3), (1, 1), LCEN)\n\n irow += 1\n\n cview = self.wids['correl'] = dv.DataViewListCtrl(panel, style=dvstyle)\n\n cview.AppendTextColumn('Parameter 1', width=150)\n cview.AppendTextColumn('Parameter 2', width=150)\n cview.AppendTextColumn('Correlation', width=100)\n\n for col in (0, 1, 2):\n this = cview.Columns[col]\n isort, align = True, wx.ALIGN_LEFT\n if col == 1:\n isort = False\n if col == 2:\n align = wx.ALIGN_RIGHT\n this.Sortable = isort\n this.Alignment = this.Renderer.Alignment = align\n cview.SetMinSize((450, 200))\n\n irow += 1\n sizer.Add(cview, (irow, 0), (1, 5), LCEN)\n irow += 1\n sizer.Add(HLine(panel, size=(400, 3)), (irow, 0), (1, 5), LCEN)\n\n pack(panel, sizer)\n panel.SetupScrolling()\n\n mainsizer = wx.BoxSizer(wx.VERTICAL)\n mainsizer.Add(panel, 1, wx.GROW|wx.ALL, 1)\n\n pack(self, mainsizer)\n self.Show()\n self.Raise()\n\n def onSelectParameter(self, evt=None):\n if self.wids['params'] is None:\n return\n if not self.wids['params'].HasSelection():\n return\n item = self.wids['params'].GetSelectedRow()\n pname = self.wids['paramsdata'][item]\n\n cormin= self.wids['min_correl'].GetValue()\n self.wids['correl'].DeleteAllItems()\n\n fit_history = getattr(self.datagroup, 'fit_history', [])\n result = fit_history[-1]\n this = result.params[pname]\n if this.correl is not None:\n sort_correl = sorted(this.correl.items(), key=lambda it: abs(it[1]))\n for name, corval in reversed(sort_correl):\n if abs(corval) > cormin:\n self.wids['correl'].AppendItem((pname, name, \"% .4f\" % corval))\n\n def onAllCorrel(self, evt=None):\n fit_history = getattr(self.datagroup, 'fit_history', [])\n params = fit_history[-1].params\n parnames = list(params.keys())\n\n cormin= self.wids['min_correl'].GetValue()\n correls = {}\n for i, name in enumerate(parnames):\n par = params[name]\n if not par.vary:\n continue\n if hasattr(par, 'correl') and par.correl is not None:\n # print(par, par.correl)\n for name2 in parnames[i+1:]:\n if (name != name2 and name2 in par.correl and\n abs(par.correl[name2]) > cormin):\n correls[\"%s$$%s\" % (name, name2)] = par.correl[name2]\n\n sort_correl = sorted(correls.items(), key=lambda it: abs(it[1]))\n sort_correl.reverse()\n\n self.wids['correl'].DeleteAllItems()\n\n for namepair, corval in sort_correl:\n name1, name2 = namepair.split('$$')\n self.wids['correl'].AppendItem((name1, name2, \"% .4f\" % corval))\n\n def onCopyParams(self, evt=None):\n fit_history = getattr(self.datagroup, 'fit_history', [])\n self.parent.fit_panel.update_start_values(fit_history[-1])\n\n def show(self, datagroup=None):\n if datagroup is not None:\n self.datagroup = datagroup\n\n fit_history = getattr(self.datagroup, 'fit_history', [])\n if len(fit_history) < 1:\n print(\"No fit reults to show for datagroup \", self.datagroup)\n result = fit_history[-1]\n wids = self.wids\n wids['method'].SetLabel(result.method)\n wids['ndata'].SetLabel(\"%d\" % result.ndata)\n wids['nvarys'].SetLabel(\"%d\" % result.nvarys)\n wids['nfree'].SetLabel(\"%d\" % result.nfree)\n wids['nfev'].SetLabel(\"%d\" % result.nfev)\n wids['redchi'].SetLabel(\"%f\" % result.redchi)\n wids['chisqr'].SetLabel(\"%f\" % result.chisqr)\n wids['aic'].SetLabel(\"%f\" % result.aic)\n wids['bic'].SetLabel(\"%f\" % result.bic)\n wids['hist_info'].SetLabel(\"%d\" % len(fit_history))\n wids['hist_tag'].SetLabel(\"Latest Fit\") #\n\n wids['data_title'].SetLabel(self.datagroup.filename)\n\n wids['model_desc'].SetLabel(result.model_repr)\n wids['params'].DeleteAllItems()\n wids['paramsdata'] = []\n for i, param in enumerate(result.params.values()):\n pname = param.name\n try:\n val = gformat(param.value)\n except (TypeError, ValueError):\n val = ' ??? '\n\n serr = ' N/A '\n if param.stderr is not None:\n serr = gformat(param.stderr, length=9)\n\n extra = ' '\n if param.expr is not None:\n extra = ' = %s ' % param.expr\n elif param.init_value is not None:\n extra = ' (init=% .7g)' % param.init_value\n elif not param.vary:\n extra = ' (fixed)'\n\n wids['params'].AppendItem((pname, val, serr, extra))\n wids['paramsdata'].append(pname)\n\n self.Refresh()\n\nclass PrePeakPanel(wx.Panel):\n def __init__(self, parent=None, controller=None, **kws):\n\n wx.Panel.__init__(self, parent, -1, size=(550, 625), **kws)\n self.parent = parent\n self.controller = controller\n self.larch = controller.larch\n self.fit_components = OrderedDict()\n self.fit_model = None\n self.fit_params = None\n self.user_added_params = None\n self.summary = None\n self.sizer = wx.GridBagSizer(10, 6)\n self.build_display()\n self.pick2_timer = wx.Timer(self)\n self.pick2_group = None\n self.Bind(wx.EVT_TIMER, self.onPick2Timer, self.pick2_timer)\n self.pick2_t0 = 0.\n self.pick2_timeout = 15.\n\n self.pick2erase_timer = wx.Timer(self)\n self.pick2erase_panel = None\n self.Bind(wx.EVT_TIMER, self.onPick2EraseTimer, self.pick2erase_timer)\n\n def build_display(self):\n\n self.mod_nb = flat_nb.FlatNotebook(self, -1, agwStyle=FNB_STYLE)\n self.mod_nb.SetTabAreaColour(wx.Colour(250,250,250))\n self.mod_nb.SetActiveTabColour(wx.Colour(254,254,195))\n\n self.mod_nb.SetNonActiveTabTextColour(wx.Colour(10,10,128))\n self.mod_nb.SetActiveTabTextColour(wx.Colour(128,0,0))\n self.mod_nb.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onNBChanged)\n\n pan = self.panel = GridPanel(self, ncols=4, nrows=4, pad=2, itemstyle=LCEN)\n\n self.btns = {}\n for name in ('ppeak_elo', 'ppeak_emin', 'ppeak_emax', 'ppeak_ehi'):\n bb = BitmapButton(pan, get_icon('plus'),\n action=partial(self.on_selpoint, opt=name),\n tooltip='use last point selected from plot')\n self.btns[name] = bb\n\n opts = dict(size=(65, -1), gformat=True, precision=1,\n # action=self.UpdatePlot,\n )\n\n self.ppeak_emin = FloatCtrl(pan, value=-30, **opts)\n self.ppeak_emax = FloatCtrl(pan, value=0, **opts)\n self.ppeak_elo = FloatCtrl(pan, value=-15, **opts)\n self.ppeak_ehi = FloatCtrl(pan, value=-5, **opts)\n\n self.ppeak_bkgfit = Button(pan, 'Fit Pre-edge Baseline', size=(175, 30),\n action=self.onPreedgeBaseline)\n\n self.model_type = Choice(pan, size=(100, -1),\n choices=ModelTypes,\n action=self.onModelTypes)\n\n self.model_func = Choice(pan, size=(200, -1),\n choices=ModelChoices['peaks'],\n action=self.addModel)\n\n pan.Add(SimpleText(pan, 'Fit Energy Range: '), newrow=True)\n pan.Add(self.btns['ppeak_emin'])\n pan.Add(self.ppeak_emin)\n pan.Add(SimpleText(pan, ':'))\n pan.Add(self.btns['ppeak_emax'])\n pan.Add(self.ppeak_emax)\n\n t = SimpleText(pan, 'Pre-edge Peak Range: ')\n t.SetToolTip('Range used as mask for background')\n\n pan.Add(t, newrow=True)\n pan.Add(self.btns['ppeak_elo'])\n pan.Add(self.ppeak_elo)\n pan.Add(SimpleText(pan, ':'))\n pan.Add(self.btns['ppeak_ehi'])\n pan.Add(self.ppeak_ehi)\n pan.Add(self.ppeak_bkgfit)\n\n pan.Add(SimpleText(pan, ' Add Model Type: '), newrow=True)\n pan.Add(self.model_type, dcol=3)\n pan.Add(SimpleText(pan, ' Model: '), dcol=2)\n pan.Add(self.model_func)\n\n\n pan.pack()\n\n# rsizer.Add(SimpleText(range_row, 'Fit Range X=[ '), 0, LCEN, 3)\n# rsizer.Add(xmin_sel, 0, LCEN, 3)\n# rsizer.Add(self.xmin, 0, LCEN, 3)\n# rsizer.Add(SimpleText(range_row, ' : '), 0, LCEN, 3)\n# rsizer.Add(xmax_sel, 0, LCEN, 3)\n# rsizer.Add(self.xmax, 0, LCEN, 3)\n# rsizer.Add(SimpleText(range_row, ' ] '), 0, LCEN, 3)\n# rsizer.Add(Button(range_row, 'Full Data Range', size=(150, -1),\n# action=self.onResetRange), 0, LCEN, 3)\n# pack(range_row, rsizer)\n\n\n# self.plot_comps = Check(pan, label='Plot Components?',\n# default=True, size=(150, -1))\n#\n# rsizer.Add(Button(a, 'Run Fit',\n# size=(100, -1), action=self.onRunFit), 0, RCEN, 3)\n# self.savebtn = Button(action_row, 'Save Fit',\n# size=(100, -1), action=self.onSaveFitResult)\n# self.savebtn.Disable()\n# rsizer.Add(self.savebtn, 0, LCEN, 3)\n#\n# rsizer.Add(Button(action_row, 'Plot Current Model',\n# size=(175, -1), action=self.onShowModel), 0, LCEN, 3)\n# rsizer.Add(self.plot_comps, 0, LCEN, 3)\n#\n# pack(action_row, rsizer)\n#\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.AddMany([((10, 10), 0, LCEN, 10), (pan, 0, LCEN, 10),\n ((10, 10), 0, LCEN, 10),\n (HLine(self, size=(550, 3)), 0, LCEN, 4),\n ((10,10), 0, LCEN, 2),\n (self.mod_nb, 1, LCEN|wx.GROW, 10)])\n\n pack(self, sizer)\n\n def onPreedgeBaseline(self, evt=None):\n print(\" on preedge baseline\")\n\n\n def onNBChanged(self, event=None):\n idx = self.mod_nb.GetSelection()\n\n def onModelTypes(self, event=None):\n modtype = event.GetString().lower()\n self.model_func.SetChoices(ModelChoices[modtype])\n\n def addModel(self, event=None, model=None):\n if model is None and event is not None:\n model = event.GetString()\n if model is None or model.startswith('<'):\n return\n\n p = model[0].lower()\n curmodels = [\"%s%i_\" % (p, i+1) for i in range(1+len(self.fit_components))]\n for comp in self.fit_components:\n if comp in curmodels:\n curmodels.remove(comp)\n\n prefix = curmodels[0]\n\n label = \"%s(prefix='%s')\" % (model, prefix)\n title = \"%s: %s\" % (prefix[:-1], (model+' '*8)[:8])\n mclass_kws = {'prefix': prefix}\n if 'step' in model.lower():\n form = model.lower().replace('step', '').strip()\n\n if form.startswith('err'): form = 'erf'\n label = \"Step(form='%s', prefix='%s')\" % (form, prefix)\n title = \"%s: Step %s\" % (prefix[:-1], form[:3])\n mclass = lm_models.StepModel\n mclass_kws['form'] = form\n minst = mclass(form=form, prefix=prefix)\n else:\n mclass = getattr(lm_models, model+'Model')\n minst = mclass(prefix=prefix)\n\n panel = GridPanel(self.mod_nb, ncols=1, nrows=1, pad=1, itemstyle=CEN)\n\n def SLabel(label, size=(80, -1), **kws):\n return SimpleText(panel, label,\n size=size, style=wx.ALIGN_LEFT, **kws)\n usebox = Check(panel, default=True, label='Use in Fit?', size=(150, -1))\n bkgbox = Check(panel, default=False, label='Is Background?', size=(150, -1))\n\n delbtn = Button(panel, 'Delete Component', size=(150, -1),\n action=partial(self.onDeleteComponent, prefix=prefix))\n\n pick2msg = SimpleText(panel, \" \", size=(125, -1))\n pick2btn = Button(panel, 'Pick Values from Data', size=(200, -1),\n action=partial(self.onPick2Points, prefix=prefix))\n\n # SetTip(mname, 'Label for the model component')\n SetTip(usebox, 'Use this component in fit?')\n SetTip(bkgbox, 'Label this component as \"background\" when plotting?')\n SetTip(delbtn, 'Delete this model component')\n SetTip(pick2btn, 'Select X range on Plot to Guess Initial Values')\n\n panel.Add(SLabel(label, size=(275, -1), colour='#0000AA'),\n dcol=3, style=wx.ALIGN_LEFT, newrow=True)\n panel.Add(usebox, dcol=2)\n panel.Add(bkgbox, dcol=2)\n\n panel.Add(pick2btn, dcol=3, style=wx.ALIGN_LEFT, newrow=True)\n panel.Add(pick2msg, dcol=3, style=wx.ALIGN_RIGHT)\n panel.Add(delbtn, style=wx.ALIGN_LEFT)\n\n # panel.Add((10, 10), newrow=True)\n # panel.Add(HLine(panel, size=(150, 3)), dcol=4, style=wx.ALIGN_CENTER)\n\n panel.Add(SLabel(\"Parameter \"), style=wx.ALIGN_LEFT, newrow=True)\n panel.AddMany((SLabel(\" Value\"), SLabel(\" Type\"), SLabel(' Bounds'),\n SLabel(\" Min\", size=(60, -1)),\n SLabel(\" Max\", size=(60, -1)),\n SLabel(\" Expression\")))\n\n parwids = OrderedDict()\n parnames = sorted(minst.param_names)\n\n for a in minst._func_allargs:\n pname = \"%s%s\" % (prefix, a)\n if (pname not in parnames and\n a in minst.param_hints and\n a not in minst.independent_vars):\n parnames.append(pname)\n\n for pname in parnames:\n sname = pname[len(prefix):]\n hints = minst.param_hints.get(sname, {})\n\n par = Parameter(name=pname, value=0, vary=True)\n if 'min' in hints:\n par.min = hints['min']\n if 'max' in hints:\n par.max = hints['max']\n if 'value' in hints:\n par.value = hints['value']\n if 'expr' in hints:\n par.expr = hints['expr']\n\n pwids = ParameterWidgets(panel, par, name_size=100, expr_size=175,\n float_size=80, prefix=prefix,\n widgets=('name', 'value', 'minval',\n 'maxval', 'vary', 'expr'))\n parwids[par.name] = pwids\n panel.Add(pwids.name, newrow=True)\n\n panel.AddMany((pwids.value, pwids.vary, pwids.bounds,\n pwids.minval, pwids.maxval, pwids.expr))\n\n for sname, hint in minst.param_hints.items():\n pname = \"%s%s\" % (prefix, sname)\n if 'expr' in hint and pname not in parnames:\n par = Parameter(name=pname, value=0, expr=hint['expr'])\n\n pwids = ParameterWidgets(panel, par, name_size=100, expr_size=400,\n float_size=80, prefix=prefix,\n widgets=('name', 'value', 'expr'))\n parwids[par.name] = pwids\n panel.Add(pwids.name, newrow=True)\n panel.Add(pwids.value)\n panel.Add(pwids.expr, dcol=5, style=wx.ALIGN_RIGHT)\n pwids.value.Disable()\n\n\n # panel.Add(delbtn, dcol=2)\n # panel.Add(HLine(panel, size=(250, 3)), dcol=3, style=wx.ALIGN_CENTER)\n\n fgroup = Group(prefix=prefix, title=title, mclass=mclass,\n mclass_kws=mclass_kws, usebox=usebox, panel=panel,\n parwids=parwids, float_size=65, expr_size=150,\n pick2_msg=pick2msg)\n\n self.fit_components[prefix] = fgroup\n panel.pack()\n\n self.mod_nb.AddPage(panel, title, True)\n sx,sy = self.GetSize()\n self.SetSize((sx, sy+1))\n self.SetSize((sx, sy))\n\n def onDeleteComponent(self, evt=None, prefix=None):\n fgroup = self.fit_components.get(prefix, None)\n if fgroup is None:\n return\n\n for i in range(self.mod_nb.GetPageCount()):\n if fgroup.title == self.mod_nb.GetPageText(i):\n self.mod_nb.DeletePage(i)\n\n for attr in dir(fgroup):\n setattr(fgroup, attr, None)\n\n self.fit_components.pop(prefix)\n\n sx,sy = self.GetSize()\n self.SetSize((sx, sy+1))\n self.SetSize((sx, sy))\n\n def onPick2EraseTimer(self, evt=None):\n \"\"\"erases line trace showing automated 'Pick 2' guess \"\"\"\n self.pick2erase_timer.Stop()\n panel = self.pick2erase_panel\n ntrace = panel.conf.ntrace - 1\n trace = panel.conf.get_mpl_line(ntrace)\n panel.conf.get_mpl_line(ntrace).set_data(np.array([]), np.array([]))\n panel.conf.ntrace = ntrace\n panel.draw()\n\n def onPick2Timer(self, evt=None):\n \"\"\"checks for 'Pick 2' events, and initiates 'Pick 2' guess\n for a model from the selected data range\n \"\"\"\n try:\n plotframe = self.controller.get_display(stacked=False)\n curhist = plotframe.cursor_hist[:]\n plotframe.Raise()\n except:\n return\n\n if (time.time() - self.pick2_t0) > self.pick2_timeout:\n msg = self.pick2_group.pick2_msg.SetLabel(\" \")\n plotframe.cursor_hist = []\n self.pick2_timer.Stop()\n return\n\n if len(curhist) < 2:\n self.pick2_group.pick2_msg.SetLabel(\"%i/2\" % (len(curhist)))\n return\n\n self.pick2_group.pick2_msg.SetLabel(\"done.\")\n self.pick2_timer.Stop()\n\n # guess param values\n xcur = (curhist[0][0], curhist[1][0])\n xmin, xmax = min(xcur), max(xcur)\n\n dgroup = getattr(self.larch.symtable, self.controller.groupname)\n x, y = dgroup.x, dgroup.y\n i0 = index_of(dgroup.x, xmin)\n i1 = index_of(dgroup.x, xmax)\n x, y = dgroup.x[i0:i1+1], dgroup.y[i0:i1+1]\n\n mod = self.pick2_group.mclass(prefix=self.pick2_group.prefix)\n parwids = self.pick2_group.parwids\n try:\n guesses = mod.guess(y, x=x)\n except:\n return\n\n for name, param in guesses.items():\n if name in parwids:\n parwids[name].value.SetValue(param.value)\n\n dgroup._tmp = mod.eval(guesses, x=dgroup.x)\n plotframe = self.controller.get_display(stacked=False)\n plotframe.cursor_hist = []\n plotframe.oplot(dgroup.x, dgroup._tmp)\n self.pick2erase_panel = plotframe.panel\n\n self.pick2erase_timer.Start(5000)\n\n\n def onPick2Points(self, evt=None, prefix=None):\n fgroup = self.fit_components.get(prefix, None)\n if fgroup is None:\n return\n\n plotframe = self.controller.get_display(stacked=False)\n plotframe.Raise()\n\n plotframe.cursor_hist = []\n fgroup.npts = 0\n self.pick2_group = fgroup\n\n if fgroup.pick2_msg is not None:\n fgroup.pick2_msg.SetLabel(\"0/2\")\n\n self.pick2_t0 = time.time()\n self.pick2_timer.Start(250)\n\n def onSaveFitResult(self, event=None):\n dgroup = self.get_datagroup()\n deffile = dgroup.filename.replace('.', '_') + '.fitresult'\n wcards = 'Fit Results(*.fitresult)|*.fitresult|All files (*.*)|*.*'\n\n outfile = FileSave(self, 'Save Fit Result',\n default_file=deffile,\n wildcard=wcards)\n\n if outfile is not None:\n try:\n save_modelresult(dgroup.fit_history[-1], outfile)\n except IOError:\n print('could not write %s' % outfile)\n\n def onLoadFitResult(self, event=None):\n\n wcards = 'Fit Results(*.fitresult)|*.fitresult|All files (*.*)|*.*'\n\n mfile = FileOpen(self, 'Load Fit Result',\n default_file='', wildcard=wcards)\n model = None\n\n if mfile is not None:\n try:\n model = load_modelresult(mfile)\n except IOError:\n print('could not read model result %s' % mfile)\n return\n if model is None:\n return\n print(\" Loading Model (work in progress) \", model)\n\n def onExportFitResult(self, event=None):\n dgroup = self.get_datagroup()\n deffile = dgroup.filename.replace('.', '_') + '_result.xdi'\n wcards = 'All files (*.*)|*.*'\n\n outfile = FileSave(self, 'Export Fit Result',\n default_file=deffile,\n wildcard=wcards)\n\n if outfile is None:\n return\n\n dgroup = self.get_datagroup()\n\n i1, i2, xv1, xv2 = self.get_xranges(dgroup.x)\n x = dgroup.x[slice(i1, i2)]\n y = dgroup.y[slice(i1, i2)]\n yerr = None\n if hasattr(dgroup, 'yerr'):\n yerr = dgroup.yerr\n if not isinstance(yerr, np.ndarray):\n yerr = yerr * np.ones(len(y))\n else:\n yerr = yerr[slice(i1, i2)]\n\n export_modelresult(dgroup.fit_history[-1], filename=outfile,\n datafile=dgroup.filename,\n ydata=y, yerr=yerr, x=x)\n\n\n def onResetRange(self, event=None):\n dgroup = self.get_datagroup()\n self.xmin.SetValue(min(dgroup.x))\n self.xmax.SetValue(max(dgroup.x))\n\n def on_selpoint(self, evt=None, opt='xmin'):\n xval = None\n try:\n xval = self.larch.symtable._plotter.plot1_x\n except:\n xval = None\n if xval is not None:\n if opt == 'xmin':\n self.xmin.SetValue(xval)\n elif opt == 'xmax':\n self.xmax.SetValue(xval)\n\n def get_datagroup(self):\n dgroup = None\n if self.controller.groupname is not None:\n try:\n dgroup = getattr(self.larch.symtable,\n self.controller.groupname)\n except:\n pass\n return dgroup\n\n def get_xranges(self, x):\n xmin, xmax = min(x), max(x)\n i1, i2 = 0, len(x)\n _xmin = self.xmin.GetValue()\n _xmax = self.xmax.GetValue()\n if _xmin > min(x):\n i1 = index_of(x, _xmin)\n xmin = x[i1]\n if _xmax < max(x):\n i2 = index_of(x, _xmax) + 1\n xmax = x[i2]\n xv1 = max(min(x), xmin - (xmax-xmin)/5.0)\n xv2 = min(max(x), xmax + (xmax-xmin)/5.0)\n return i1, i2, xv1, xv2\n\n def build_fitmodel(self):\n \"\"\" use fit components to build model\"\"\"\n dgroup = self.get_datagroup()\n fullmodel = None\n params = Parameters()\n self.summary = {'components': [], 'options': {}}\n for comp in self.fit_components.values():\n if comp.usebox is not None and comp.usebox.IsChecked():\n for parwids in comp.parwids.values():\n params.add(parwids.param)\n self.summary['components'].append((comp.mclass.__name__, comp.mclass_kws))\n thismodel = comp.mclass(**comp.mclass_kws)\n if fullmodel is None:\n fullmodel = thismodel\n else:\n fullmodel += thismodel\n\n self.fit_model = fullmodel\n self.fit_params = params\n\n if dgroup is not None:\n i1, i2, xv1, xv2 = self.get_xranges(dgroup.x)\n xsel = dgroup.x[slice(i1, i2)]\n dgroup.xfit = xsel\n dgroup.yfit = self.fit_model.eval(self.fit_params, x=xsel)\n dgroup.ycomps = self.fit_model.eval_components(params=self.fit_params,\n x=xsel)\n return dgroup\n\n def onShowModel(self, event=None):\n dgroup = self.build_fitmodel()\n if dgroup is not None:\n with_components = (self.plot_comps.IsChecked() and\n len(dgroup.ycomps) > 1)\n\n self.plot_fitmodel(dgroup, show_resid=False,\n with_components=with_components)\n\n def plot_fitmodel(self, dgroup, show_resid=False, with_components=None):\n if dgroup is None:\n return\n i1, i2, xv1, xv2 = self.get_xranges(dgroup.x)\n ysel = dgroup.y[slice(i1, i2)]\n\n plotframe = self.controller.get_display(stacked=True)\n plotframe.plot(dgroup.xfit, ysel, new=True, panel='top',\n xmin=xv1, xmax=xv2, label='data',\n xlabel=dgroup.plot_xlabel, ylabel=dgroup.plot_ylabel,\n title='Fit: %s' % dgroup.filename )\n\n plotframe.oplot(dgroup.xfit, dgroup.yfit, label='fit')\n\n plotframe.plot(dgroup.xfit, ysel-dgroup.yfit, grid=False,\n marker='o', markersize=4, linewidth=1, panel='bot')\n\n if with_components is None:\n with_components = (self.plot_comps.IsChecked() and\n len(dgroup.ycomps) > 1)\n if with_components:\n for label, _y in dgroup.ycomps.items():\n plotframe.oplot(dgroup.xfit, _y, label=label,\n style='short dashed')\n\n line_opts = dict(color='#AAAAAA', label='_nolegend_',\n linewidth=1, zorder=-5)\n plotframe.panel_bot.axes.axhline(0, **line_opts)\n axvline = plotframe.panel.axes.axvline\n if i1 > 0:\n axvline(dgroup.x[i1], **line_opts)\n\n if i2 < len(dgroup.x):\n axvline(dgroup.x[i2-1], **line_opts)\n\n plotframe.panel.canvas.draw()\n\n\n def onRunFit(self, event=None):\n dgroup = self.build_fitmodel()\n if dgroup is None:\n return\n i1, i2, xv1, xv2 = self.get_xranges(dgroup.x)\n dgroup.xfit = dgroup.x[slice(i1, i2)]\n ysel = dgroup.y[slice(i1, i2)]\n weights = np.ones(len(ysel))\n\n if hasattr(dgroup, 'yerr'):\n yerr = dgroup.yerr\n if not isinstance(yerr, np.ndarray):\n yerr = yerr * np.ones(len(ysel))\n else:\n yerr = yerr[slice(i1, i2)]\n yerr_min = 1.e-9*ysel.mean()\n yerr[np.where(yerr < yerr_min)] = yerr_min\n weights = 1.0/yerr\n\n result = self.fit_model.fit(ysel, params=self.fit_params,\n x=dgroup.xfit, weights=weights,\n method='leastsq')\n self.summary['xmin'] = xv1\n self.summary['xmax'] = xv2\n for attr in ('aic', 'bic', 'chisqr', 'redchi', 'ci_out', 'covar',\n 'flatchain', 'success', 'nan_policy', 'nfev', 'ndata',\n 'nfree', 'nvarys', 'init_values'):\n self.summary[attr] = getattr(result, attr)\n self.summary['params'] = result.params\n\n\n dgroup.yfit = result.best_fit\n dgroup.ycomps = self.fit_model.eval_components(params=result.params,\n x=dgroup.xfit)\n\n\n with_components = (self.plot_comps.IsChecked() and len(dgroup.ycomps) > 1)\n\n self.plot_fitmodel(dgroup, show_resid=True, with_components=with_components)\n\n # print(\" == fit model == \", self.fit_model)\n # print(\" == fit result == \", result)\n\n result.model_repr = self.fit_model._reprstring(long=True)\n\n self.autosave_modelresult(result)\n if not hasattr(dgroup, 'fit_history'):\n dgroup.fit_history = []\n dgroup.fit_history.append(result)\n\n\n self.parent.show_subframe('result_frame', FitResultFrame,\n datagroup=dgroup,\n controller=self.controller)\n\n # self.update_start_values(result)\n self.savebtn.Enable()\n\n for m in self.parent.afterfit_menus:\n self.parent.menuitems[m].Enable(True)\n\n def update_start_values(self, result):\n \"\"\"fill parameters with best fit values\"\"\"\n allparwids = {}\n for comp in self.fit_components.values():\n if comp.usebox is not None and comp.usebox.IsChecked():\n for name, parwids in comp.parwids.items():\n allparwids[name] = parwids\n\n for pname, par in result.params.items():\n if pname in allparwids:\n allparwids[pname].value.SetValue(par.value)\n\n def autosave_modelresult(self, result, fname=None):\n \"\"\"autosave model result to user larch folder\"\"\"\n xasguidir = os.path.join(site_config.usr_larchdir, 'xasgui')\n if not os.path.exists(xasguidir):\n try:\n os.makedirs(xasguidir)\n except OSError:\n print(\"Warning: cannot create XAS GUI user folder\")\n return\n if not HAS_MODELSAVE:\n print(\"Warning: cannot save model results: upgrade lmfit\")\n return\n if fname is None:\n fname = 'autosave.fitresult'\n fname = os.path.join(xasguidir, fname)\n save_modelresult(result, fname)\n","sub_path":"plugins/xasgui/prepeak_panel.py","file_name":"prepeak_panel.py","file_ext":"py","file_size_in_byte":36077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"12372490","text":"from django.core.exceptions import ValidationError\nimport json\nfrom json_tricks import dumps\nfrom core.exceptions.customexceptions import ApiException\n\nclass ActionValidator():\n\n def validateFields(value):\n\n fields=[]\n if (not value):\n raise ValidationError(\"Invalid value. \"+str(value))\n\n if (value) and (value.__class__.__name__==\"str\"):\n return True\n\n fields=value if value.__class__.__name__ == \"list\" else [value]\n\n for field in fields:\n if field.__class__.__name__ == \"dict\":\n if \"function\" in field:\n if not \"function_name\" in field[\"function\"]:\n raise ValidationError(\"A function requires a function_name property. \"+dumps(field)) \n\n if (not \"fields\" in field[\"function\"]) or (len(field[\"function\"][\"fields\"])==0):\n raise ValidationError(\"A function requires a fields property. \"+dumps(field)) \n \n for param in field[\"function\"][\"fields\"]:\n ActionValidator.validateFields(param)\n\n elif \"event_field\" in field:\n if (field[\"event_field\"].strip()==\"\"):\n raise ValidationError(\"An event_field requires a not blank value. \"+dumps(field))\n elif \"workflow\" in field:\n if not \"id\" in field[\"workflow\"]:\n raise ValidationError(\"A workflow requires a not blank id. \"+dumps(field))\n if not \"name\" in field[\"workflow\"]:\n raise ValidationError(\"A workflow requires a not blank name. \"+dumps(field))\n if not \"parameters\" in field[\"workflow\"]:\n raise ValidationError(\"A workflow requires a not blank parameters. \"+dumps(field))\n else:\n raise ValidationError(\"Invalid value/field. \"+dumps(field)) \n else:\n return True \n\n\n def validateAction(value):\n\n action=json.loads(value)\n\n if (not \"type\" in action):\n raise ValidationError(\"An action required a type property. \"+dumps(action))\n\n if (action[\"type\"]!=\"assign\"): \n raise ValidationError(\"The action type should be one 'assign'. \"+dumps(action))\n\n if (not \"value\" in action):\n raise ValidationError(\"An 'assign' action requires a value property. \"+dumps(action))\n \n if (action[\"value\"]):\n if (\"workflow\" in action[\"value\"]):\n if (\"target\" in action):\n raise ValidationError(\"A 'workflow' action mustn't have target. \"++dumps(action))\n else:\n if (not \"target\" in action or len(action[\"target\"])==0):\n raise ValidationError(\"An 'assign' action requires a target property. \"+dumps(action))\n\n return ActionValidator.validateFields(action[\"value\"])\n","sub_path":"action/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"600076059","text":"def main():\r\n\r\n print('\\n Welcome to Square Builder ')\r\n \"sq_dimension = valid_check()\"\r\n make_square(valid_check())\r\n\r\n\r\ndef valid_check():\r\n dimension = int(input('\\n Enter Square Dimension as a single int: '))\r\n while not (dimension > 0):\r\n print('\\n Not a Valid int')\r\n dimension = int(input('\\n Enter Square Dimension as a single int: '))\r\n else:\r\n return dimension\r\n\r\n\r\ndef make_square(int, border_shape='-'):\r\n\r\n top_line = int * (border_shape+' ')\r\n print(' ' + top_line)\r\n\r\n spaces = ' ' * ((int * 3) - 4)\r\n side_length = (' ' + border_shape + spaces + border_shape)\r\n\r\n length = (int - 2)\r\n while length > 0:\r\n print(side_length)\r\n length -= 1\r\n\r\n print(' ' + top_line)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"StandaloneProjects/Shapebuilder.py","file_name":"Shapebuilder.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"452889661","text":"\"\"\"\nDescription\n\n合并(归并)排序的核心思想是:每次从中间位置将数组分组再分别排序。请实现其非递归方案。\n\n\nInput\n\n输入的每一行表示一个元素为正整数的数组,所有值用空格隔开,第一个值为数值长度,其余为数组元素值。\n\n\nOutput\n\n输出的每一行为排序结果,用空格隔开,末尾不要空格。\n\n\nSample Input 1\n\n13 24 3 56 34 3 78 12 29 49 84 51 9 100\nSample Output 1\n\n3 3 9 12 24 29 34 49 51 56 78 84 100\n\"\"\"\nimport math\nimport sys\n\ndef merge(list, low, mid, high):\n left = list[low:mid]\n right = list[mid:high]\n l = 0\n r = 0\n result = []\n while l < len(left) and r < len(right):\n if left[l] < right[r]:\n result.append(left[l])\n l += 1\n else:\n result.append(right[r])\n r += 1\n result += left[l:]\n result += right[r:]\n list[low:high]=result\n\n\ndef merge_sort():\n for line in sys.stdin:\n temp_list = line.split()\n if not temp_list:\n break\n data_list = []\n length = int(temp_list[0])\n for i in range(1, length + 1):\n data_list.append(int(temp_list[i]))\n\n # time=math.log(length,2)\n # for i in range(1,time+1):\n # merge(e for e in data_list)\n\n i = 1\n while i < length: # 子数组长度\n low = 0\n while low < length:\n mid = low + i\n high = min(mid + i, length)\n if mid Mapping[str, Any]:\n return {\n \"fingerprint\": self.fingerprint,\n \"op\": self.op,\n \"desc\": self.desc,\n \"type\": self.type.value,\n \"parent_span_ids\": self.parent_span_ids,\n \"cause_span_ids\": self.cause_span_ids,\n \"offender_span_ids\": self.offender_span_ids,\n }\n\n @property\n def title(self) -> str:\n return GROUP_TYPE_TO_TEXT.get(self.type, \"N+1 Query\")\n\n @classmethod\n def from_dict(cls, data: dict):\n return cls(\n data[\"fingerprint\"],\n data[\"op\"],\n data[\"desc\"],\n GroupType(data[\"type\"]),\n data[\"parent_span_ids\"],\n data[\"cause_span_ids\"],\n data[\"offender_span_ids\"],\n )\n\n def __eq__(self, other):\n if not isinstance(other, PerformanceProblem):\n return NotImplemented\n return (\n self.fingerprint == other.fingerprint\n and self.offender_span_ids == other.offender_span_ids\n and self.type == other.type\n )\n\n def __hash__(self):\n # This will de-duplicate on fingerprint and type and only for offending span ids.\n # Fingerprint should incorporate the 'uniqueness' enough that parent and span checks etc. are not required.\n return hash((self.fingerprint, frozenset(self.offender_span_ids), self.type))\n","sub_path":"src/sentry/utils/performance_issues/performance_problem.py","file_name":"performance_problem.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"255369843","text":"# Copyright 2014 - Savoir-Faire Linux inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport requests\n\nfrom surveil.tests.integration import integration_test\n\n\nclass TestMergedIngegrationSurveil(\n integration_test.MergedIntegrationTest\n):\n\n def test_hello(self):\n self.assertEqual(\n requests.get(\"http://localhost:8999/v2/hello\").text,\n 'Hello World!'\n )\n\n\nclass TestSeparatedIntegrationSurveil(\n integration_test.SeparatedIntegrationTests\n):\n\n def test_create_host(self):\n \"\"\"Creates a host and asserts that is is monitored by Alignak.\"\"\"\n config_hosts = (TestSeparatedIntegrationSurveil.\n client.status.hosts.list())\n\n self.assertFalse(\n any(host['host_name'] == 'integrationhosttest'\n for host in config_hosts)\n )\n\n TestSeparatedIntegrationSurveil.client.config.hosts.create(\n host_name='integrationhosttest',\n address='127.0.0.1',\n )\n\n TestSeparatedIntegrationSurveil.client.config.reload_config()\n\n def function():\n status_hosts = (TestSeparatedIntegrationSurveil.\n client.status.hosts.list())\n self.assertTrue(\n any(host['host_name'].decode() == 'integrationhosttest'\n for host in status_hosts)\n\n )\n\n self.assertTrue(\n self.try_for_x_seconds(\n function,\n time_to_wait=180,\n cooldown=10,\n exception=AssertionError,\n message=\"Could not find host in status.\"\n )\n )\n\n def test_delete_host(self):\n self.test_create_host()\n\n TestSeparatedIntegrationSurveil.client.config.hosts.delete(\n 'integrationhosttest'\n )\n\n TestSeparatedIntegrationSurveil.client.config.reload_config()\n\n def function():\n status_hosts = (TestSeparatedIntegrationSurveil.\n client.status.hosts.list())\n self.assertFalse(\n any(host['host_name'].decode() == 'integrationhosttest'\n for host in status_hosts)\n )\n\n self.assertTrue(\n self.try_for_x_seconds(\n function,\n time_to_wait=180,\n cooldown=10,\n exception=AssertionError,\n message=\"Host was not deleted\"\n )\n )\n","sub_path":"surveil/tests/integration/test_surveil.py","file_name":"test_surveil.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"311760640","text":"'''\nSymbolTable\nA symbol table that keeps a correspondence between symbolic \nlabels and numeric addresses.\n\n@author: Kyle June\n'''\n\nDEFAULT_SYMBOLS = {\n 'SP': 0,\n 'LCL': 1,\n 'ARG': 2,\n 'THIS': 3,\n 'THAT': 4,\n 'R0': 0,\n 'R1': 1,\n 'R2': 2,\n 'R3': 3,\n 'R4': 4,\n 'R5': 5,\n 'R6': 6,\n 'R7': 7,\n 'R8': 8,\n 'R9': 9,\n 'R10': 10,\n 'R11': 11,\n 'R12': 12,\n 'R13': 13,\n 'R14': 14,\n 'R15': 15,\n 'SCREEN': 16384,\n 'KBD': 24576\n}\n\nclass SymbolTable(object):\n '''\n Creates a new empty symbol table.\n '''\n def __init__(self):\n table = {}\n table.update(DEFAULT_SYMBOLS)\n self._table = table\n \n '''\n Adds the pair (symbol, address) to the table.\n \n @param: symbol string\n @param: address int\n '''\n def addEntry(self, symbol, address):\n self._table.update({symbol: address})\n \n '''\n Does the symbol table contain the given symbol?\n \n @param: symbol string\n @return: Boolean\n '''\n def contains(self, symbol):\n return symbol in self._table\n \n '''\n Returns the address associated with the symbol.\n \n @param: symbol string\n @return: int\n '''\n def getAddress(self, symbol):\n return self._table.get(symbol)\n","sub_path":"SymbolTable.py","file_name":"SymbolTable.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"218259348","text":"#%%\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\nfrom pathlib import Path\nimport argparse\nfrom ckonlpy.tag import Twitter\nfrom ckonlpy.tag import Postprocessor\ntwitter = Twitter()\nimport ast\n\n\n# 각 attr keyword가 review에 포함되면 각 attr에 해당하는 review들을 분류\n#%%\nattr_df=pd.read_excel(Path(\"G:/공유 드라이브/속성사전/Data/Electronics/RiceCooker/2. Seed D_전기밥솥_copy_jk_20201130.xlsx\")\n ,sheet_name='1B')\nreview_df=pd.read_csv(Path(\"G:/공유 드라이브/속성사전/Data/Electronics/RiceCooker/review_20201129.csv\"))\n\nreview_list=[(body,rating)for body, rating in zip(review_df['body'],review_df['rating'])]\n\n# %%\n#attr별로 리뷰 모아주려고 만든 dict\ncooker_review = {}\nfor attr in attr_df['attrs']:\n cooker_review[attr]=[]\n\n#attr별로 filter 1차로 걸 키워드 모아놓은 dict\n\n\ncooker_filter = {}\nfor _, _attr, _filter in attr_df[['attrs','filter_1']].itertuples():\n cooker_filter[_attr]=ast.literal_eval(_filter)\n\n#review_list에서 분류되지 않은 남은 리뷰들 넣는 list\nremain_review = []\n# for body in review_list[6:9]:\nn_review_list_end=len(review_list)\nn_review_list_start=1\n\nfor body in review_list:\n n_review_list_start+=1\n print(n_review_list_start/n_review_list_end*100)\n # print('\\n=====body 시작=====')\n # print(' 문장: ', body[0])\n attrBreak = False\n filter_1Break = False\n \n n_attr_start = 1\n n_attr_end = len(cooker_filter)\n for attr in cooker_filter:\n # print('attr:', attr)\n\n n_attr_start+=1\n\n n_filter_1_start=1\n n_filter_1_end=len(cooker_filter[attr])\n for filter_1 in cooker_filter[attr]:\n # print(' 1차필터: ',filter_1)\n if filter_1 in body[0]:\n # print(f' 1차필터는 \"{body[0]}\"에 포함된다')\n cooker_review[attr].append(body)\n attrBreak=True\n # 한 리뷰에 하나의 attr_2가 들어감\n break\n\n else:\n n_filter_1_start+=1\n #제일 마지막으로 남은 리뷰만 저장하기 위함\n if (n_filter_1_start == n_filter_1_end) and (n_attr_start == n_attr_end):\n remain_review.append(body)\n # continue\n \n if attrBreak is True: #다음 리뷰로 이동\n break\n\nprint('\\n*** 분류된 문서 ***\\n', cooker_review)\nprint('\\n*** 분류되지 않은 문서 ***\\n', remain_review)\n\n#%%\ntemp=pd.concat({k:pd.Series(v) for k,v in cooker_review.items()}).reset_index()\ntemp['body']=[_tuple[0] for _tuple in temp[0]]\ntemp['rating']=[_tuple[1] for _tuple in temp[0]]\ntemp.drop(columns=['level_1',0], inplace=True)\ntemp.columns = ['attr_2','name','rating']\n\n#%%\n########## 4,5점 긍정 - 1,2점 부정으로 옮기기 ########\nattr_pos = {}\nfor attr in attr_df['attrs']:\n attr_pos[attr]=[]\nattr_neg = {}\nfor attr in attr_df['attrs']:\n attr_neg[attr]=[]\n\nfor _,attr,body, rating in temp.itertuples():\n if rating in [4,5]:\n\n attr_pos[attr].append(body)\n elif rating in [1,2]:\n attr_neg[attr].append(body)\n else:\n pass\n \n\nfor attr in attr_pos:\n attr_pos[attr]='; '.join(attr_pos[attr])\nfor attr in attr_neg:\n attr_neg[attr]='; '.join(attr_neg[attr])\n\n\npos_neg = pd.concat([pd.DataFrame.from_dict(attr_pos,orient='index',columns=['pos'])\n,pd.DataFrame.from_dict(attr_neg,orient='index',columns=['neg'])]\n, axis = 1)\n\n\n# %%\n#### attr별 카운트 구하기#####\ncooker_review_attr_count = {}\nfor key in cooker_review.keys():\n cooker_review_attr_count[key] = len(cooker_review[key])\nattr2_count_df=pd.DataFrame.from_dict(cooker_review_attr_count,orient='index',columns=['count'])\npd.concat([pos_neg, attr2_count_df],axis=1).to_excel('./temp.xlsx')\n# %%\n\n#%%\n# '알려진' in '안알려진'\n# twitter.pos('안알려진', stem=True, norm=True)\n\n#%%\n# twitter.pos('가벼움', stem=True, norm=True)\n\n# twitter.add_dictionary(['가볍다','가벼움','가벼워서'], 'keyword', force=True)\n# twitter.pos('솥이 가벼워서 괜찮아요', stem=True, norm=True)\n# twitter.pos('바람이 정말 세서', stem=True, norm=True)\n# twitter.add_dictionary(['풀스텐','풀스텐 커버','가벼워서'], 'keyword', force=True)\n# twitter.pos('솥이 가벼워서 괜찮아요', stem=True, norm=True)\n\n\n#%%\n# # ['가벼' in body for body in body_list]\n# def f0002():\n# # passtags = {'Keyword'}\n# # postprocessor = Postprocessor(twitter, passtags = passtags)\n# # postprocessor.pos('풀스텐 내솥 내솥, 뚜껑 모두 스테인리스에 뚜껑 분리도 되는게 참 신기하네요. ')\n# # pass\n\n\n \n# if __name__ == '__main__':\n# # f0001(args.FILE_PATH,args.EXPORT_PATH,args.FREQ_N)\n# f0002()\n\n\n\"\"\"\n# parser = argparse.ArgumentParser()\n# parser.add_argument('--FILE_PATH','-in')\n# parser.add_argument('--EXPORT_PATH','-out')\n# parser.add_argument('--FREQ_N','-n', type=int)\n# args = parser.parse_args()\n# args.FILE_PATH = '../Data/eye_df.csv'\n# args.EXPORT_PATH = '../Data/eye_df_count.xlsx'\n# args.FREQ_N = 200\n\ndef f0001(FILE_PATH, EXPORT_PATH, FREQ_N=200):\n # Read Review File\n # FILE_PATH = '../Data/BabyProducts/MilkPowder/분유.csv'\n review=pd.read_csv(Path(FILE_PATH))\n N_review = len(review)\n token_ls = []\n \n for i in range(2080,2083):\n # for i in range(N_review):\n # print(i)\n body = review['body'][i]\n if pd.isna(body):\n continue\n word_pos=okt.pos(body, stem=True, norm=True)\n [token_ls.append(token) for token, pos in word_pos if pos=='Noun']\n count_obj = Counter(token_ls)\n count = count_obj.most_common(FREQ_N)\n # save excel\n temp_dict = dict(count)\n temp_df=pd.DataFrame({'keyword':temp_dict.keys(), 'count':temp_dict.values()})\n temp_df.sort_values(by='count',ascending=False,inplace=True)\n temp_df.to_excel(Path(EXPORT_PATH),index=False)\n return \n\n# count_200=f0001('../Data/BabyProducts/MilkPowder/분유.csv'\n# ,'../Data/BabyProducts/MilkPowder/_분유_count.xlsx'\n# ,200)\n\"\"\"","sub_path":"Code/0001to0002_NLP.py","file_name":"0001to0002_NLP.py","file_ext":"py","file_size_in_byte":6117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"517042290","text":"from rest_framework import serializers\nfrom .models import *\n\nimport json\nimport requests\n\nclass PipelinesSerializer(serializers.Serializer):\n pipelineschemas = serializers.JSONField()\n\n\nclass SessionSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n \n email = serializers.CharField(required=False, allow_blank=True, max_length=100)\n description = serializers.CharField(max_length=1000, default = \"\")\n pipeline = serializers.CharField(max_length=100)\n config = serializers.JSONField()\n observation = serializers.CharField(max_length=100000, default = \"\")\n observation2 = serializers.CharField(max_length=100000, default = \"\")\n \n status = serializers.CharField(max_length = 20, default = \"Staging\")\n staging = serializers.CharField(max_length = 20, default = \"new\")\n pipeline_version = serializers.CharField(max_length=100, default = \"\", read_only=True)\n pipeline_response = serializers.CharField(max_length = 1000, default = \"\")\n date_created = serializers.DateTimeField(read_only=True)\n date_modified = serializers.DateTimeField(read_only=True)\n \n # di_image = serializers.ImageField(required=False)\n di_fits = serializers.CharField(max_length=100, default = \"\")\n rw_fits = serializers.CharField(max_length=100, default = \"\")\n# stageid = serializers.CharField(max_length=30, default = \"\")\n stage_reqid = serializers.IntegerField(default = 0)\n stage2_reqid = serializers.IntegerField(default = 0)\n transfer_id = serializers.IntegerField(default = 0)\n transfer2_id = serializers.IntegerField(default = 0)\n\n\n def create(self, validated_data):\n return Session.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.description = validated_data.get('description', instance.description)\n instance.pipeline = validated_data.get('pipeline', instance.pipeline)\n instance.config = validated_data.get('config', instance.config)\n instance.observation = validated_data.get('observation', instance.observation)\n instance.observation2 = validated_data.get('observation2', instance.observation2)\n\n instance.pipeline_version = validated_data.get('pipeline_version', instance.pipeline_version)\n instance.pipeline_response = validated_data.get('pipeline_response', instance.pipeline_response)\n instance.status = validated_data.get('status', instance.status)\n instance.staging = validated_data.get('staging', instance.staging)\n\n instance.date_created = validated_data.get('date_created', instance.date_created)\n instance.date_modified = validated_data.get('date_modified', instance.date_modified)\n \n instance.di_fits = validated_data.get('di_fits', instance.di_fits)\n instance.rw_fits = validated_data.get('rw_fits', instance.rw_fits)\n \n# instance.stageid = validated_data.get('stageid', instance.stageid)\n instance.stage_reqid = validated_data.get('stage_reqid', instance.stage_reqid)\n instance.stage2_reqid = validated_data.get('stage2_reqid', instance.stage2_reqid)\n instance.transfer_id = validated_data.get('transfer_id', instance.transfer_id)\n instance.transfer2_id = validated_data.get('transfer2_id', instance.transfer2_id)\n \n instance.save()\n return instance\n","sub_path":"lofar_workflow_api/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"537241942","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/7/24 10:32\n\nfrom flask_script import Manager,Server\nfrom app import app\nfrom app.models import Words\n\nmanager = Manager(app)\nmanager.add_command('runserver',Server(host='0.0.0.0',port=5000,use_debugger=True))\n\n@manager.command\ndef save_word():\n words = Words(name='wz11',content='this is first words')\n words.save()\n\nif __name__ == '__main__':\n app.run()","sub_path":"24/my-words-pad/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"281179726","text":"import math\nimport sys\nimport time\nsys.path.insert(0, \"..\\\\..\\\\eulerlib-py\")\nimport FactorTable\n\nMAX = 19999999\nMAXPRIME = MAX//100\nstart = time.time()\nft = FactorTable.FactorTable(MAX)\nprint(\"FT Done.\")\nprint(time.time()-start)\n##strprimes = [str(i) for i in ft.PrimesInRange(0,MAX)]\n##for i in range(len(strprimes)-1,-1,-1):\n## if len(strprimes[i]) <= len(str(MAX))-2:\n## MAXINDEX = i+1\n## print(i,strprimes[i])\n## break\n\nprint(\"Tables Done\")\ndef intconcat(x,y):\n return int(x*10**(1+math.floor(math.log10(y)))+y)\ndef IsPrimePair(x,y):\n a = intconcat(x,y)\n b = intconcat(y,x)\n if a > MAX or b > MAX:\n return None\n return ft.IsPrime(a) and ft.IsPrime(b)\n\nres = {}\nfor p in ft.PrimesInRange(3,int(math.sqrt(MAX))+1):\n for pp in ft.PrimesInRange(3,MAXPRIME):\n if IsPrimePair(p,pp):\n if p not in res:\n res[p] = []\n if pp not in res:\n res[pp] = []\n res[p].append(pp)\n## res[pp].append(p)\n##print(res)\nsums = []\nfor b in res:\n for c in res[b]:\n intr = set(res[b]) & set(res[c])\n if len(intr) > 0:\n## res[c].remove(b)\n for d in list(intr):\n if d == b or d == c: continue\n intr = intr & set(res[d])\n if len(intr) > 0:\n print(b,c,d,intr)\n## res[d].remove(c)\n for e in list(intr):\n if e==b or e==c or e==d: continue\n intr = intr & set(res[e])\n if len(intr) > 0:\n sums.append(sum([b,c,d,e,min(intr)]))\n print(sums[-1],b,c,d,e,intr)\n##print(min(sums))\nprint(time.time()-start) \n####def Search(pairList,lastindex,MaxDepth,CurrentDepth):\n#### if CurrentDepth >= MaxDepth: return\n#### for i,p in enumerate(strprimes[lastindex+1:MAXINDEX]):\n#### bools = [IsPrimePair(x,p) for x in pairList]\n#### if None in bools: break\n#### if all(bools):\n#### pairList.append(p)\n#### if len(pairList) >= MaxDepth:\n#### print(pairList,lastindex,MaxDepth,CurrentDepth)\n#### if CurrentDepth < MaxDepth:\n#### Search(pairList,i,MaxDepth,CurrentDepth+1)\n#### pairList.pop()\n####for i,p in enumerate(strprimes):\n#### Search([p],i,5,1)\n##for i,num in enumerate(strprimes):\n## for j,num2 in enumerate(strprimes[i+1:]):\n## pp = IsPrimePair(num,num2)\n## if pp is None: break\n## if pp:\n## for k,num3 in enumerate(strprimes[j+1:]):\n## pp1 = IsPrimePair(num3,num2)\n## pp2 = IsPrimePair(num3,num)\n## if pp1 is None or pp2 is None: break\n## if pp1 and pp2:\n#### print(num,num2,num3)\n## for l,num4 in enumerate(strprimes[k+1:]):\n## pp1 = IsPrimePair(num4,num3)\n## pp2 = IsPrimePair(num4,num2)\n## pp3 = IsPrimePair(num4,num)\n## if pp1 is None or pp2 is None or pp3 is None: break\n## if pp1 and pp2 and pp3:\n## print(num,num2,num3,num4)\n## for m,num5 in enumerate(strprimes[l+1]):\n## pp1 = IsPrimePair(num5,num4)\n## pp2 = IsPrimePair(num5,num3)\n## pp3 = IsPrimePair(num5,num2)\n## pp4 = IsPrimePair(num5,num)\n## if pp1 is None or pp2 is None or pp3 is None: break\n## if pp1 and pp2 and pp3 and pp4:\n## print(num,num2,num3,num4,num5)\n##\n##\n","sub_path":"60/60.py","file_name":"60.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"562842716","text":"import logging\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\n\ncatcols = ['protocol_type', 'service', 'flag']\n\nnumcols = ['duration', 'src_bytes', 'dst_bytes', 'wrong_fragment', 'urgent', 'hot', 'num_failed_logins',\n 'num_compromised', 'root_shell', 'su_attempted', 'num_root', 'num_file_creations',\n 'num_shells', 'num_access_files', # 'num_outbound_cmds',\n 'count', 'srv_count', 'dst_host_count', 'dst_host_srv_count',\n 'land', 'logged_in', 'is_host_login', 'is_guest_login']\n\nratecols = ['serror_rate',\n 'srv_serror_rate', 'rerror_rate', 'srv_rerror_rate', 'same_srv_rate', 'diff_srv_rate',\n 'srv_diff_host_rate', 'dst_host_same_srv_rate',\n 'dst_host_diff_srv_rate', 'dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate',\n 'dst_host_serror_rate', 'dst_host_srv_serror_rate', 'dst_host_rerror_rate', 'dst_host_srv_rerror_rate']\n\n\ndef fit_encoders(dataset):\n ohe = OneHotEncoder(handle_unknown='ignore')\n ohe.fit(dataset[catcols].values)\n scaler = StandardScaler()\n scaler.fit(dataset[numcols].values)\n return ohe, scaler\n\n\ndef transform(dataset, ohe, scaler):\n a1 = scaler.transform(dataset[numcols])\n a2 = ohe.transform(dataset[catcols]).toarray()\n a3 = dataset[ratecols].values\n labels = (dataset[\"labels\"].values != 'normal').astype(int)\n return np.append(np.append(a1, a2, axis=1), a3, axis=1), labels\n\n\ndef read_files():\n train_dataset = pd.read_csv('data/kdd/kdd_train.csv')\n test_dataset = pd.read_csv('data/kdd/kdd_test.csv')\n return train_dataset, test_dataset\n\n\ndef get_coherent_split():\n train_dataset, test_dataset = read_files()\n logging.debug(train_dataset.head())\n ohe, scaler = fit_encoders(train_dataset)\n x_train, y_train = transform(train_dataset, ohe, scaler)\n x_test, y_test = transform(test_dataset, ohe, scaler)\n return x_train, y_train, x_test, y_test\n\n\ndef get_random_split():\n train_dataset_coherent, test_dataset_coherent = read_files()\n\n train_dataset_anomaly_count = len(train_dataset_coherent[train_dataset_coherent['labels'] != 'normal'])\n train_dataset_benign_count = len(train_dataset_coherent) - train_dataset_anomaly_count\n logging.debug(\"KDD train set anomaly count : \" + str(train_dataset_anomaly_count) +\n \", benign count : \" + str(train_dataset_benign_count))\n\n test_dataset_anomaly_count = len(test_dataset_coherent[test_dataset_coherent['labels'] != 'normal'])\n test_dataset_benign_count = len(test_dataset_coherent) - test_dataset_anomaly_count\n logging.debug(\"KDD test set anomaly count : \" + str(test_dataset_anomaly_count) +\n \", benign count : \" + str(test_dataset_benign_count))\n\n while True: # Try to generate splits until valid (should not be necessary with OHE handle_unknown='ignore')\n try:\n # Combine datasets, build new index\n combined_dataset = pd.concat([train_dataset_coherent, test_dataset_coherent], ignore_index=True)\n combined_dataset_benign = combined_dataset[combined_dataset['labels'] == 'normal']\n combined_dataset_anomaly = combined_dataset[combined_dataset['labels'] != 'normal']\n\n # Randomly sample 22544 test samples, rest are train samples\n # Keep anomaly/benign ratio from original split\n test_dataset_benign = combined_dataset_benign.sample(n=test_dataset_benign_count)\n train_dataset_benign = combined_dataset_benign.drop(test_dataset_benign.index)\n test_dataset_anomaly = combined_dataset_anomaly.sample(n=test_dataset_anomaly_count)\n train_dataset_anomaly = combined_dataset_anomaly.drop(test_dataset_anomaly.index)\n train_dataset = pd.concat([train_dataset_benign, train_dataset_anomaly])\n test_dataset = pd.concat([test_dataset_benign, test_dataset_anomaly])\n logging.debug(\"(Shape KDD Random Split) Train : \" + str(train_dataset.shape) +\n \", Test : \" + str(test_dataset.shape))\n logging.debug(train_dataset.head())\n ohe, scaler = fit_encoders(train_dataset)\n x_train, y_train = transform(train_dataset, ohe, scaler)\n x_test, y_test = transform(test_dataset, ohe, scaler)\n return x_train, y_train, x_test, y_test\n except ValueError:\n logging.info(\"Discarding split, retrying...\")\n","sub_path":"data/kdd.py","file_name":"kdd.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"205841282","text":"import os\nimport random\nimport string\n\nimport pytest\n\nfrom rpi import operating_system\nfrom rpi.connections import Connections\nfrom rpi.exceptions import NeccessaryArgumentError, UserNotFoundError, InvalidMailAddressError, \\\n SpreadsheetNotFoundError, SheetNotFoundError\n\n\ndef test_connections_disable():\n status = operating_system() == 'W'\n assert Connections.DISABLE == status\n\n\ndef test_notification():\n Connections.DISABLE = False\n\n with pytest.raises(NeccessaryArgumentError, match=\"The 'file' argument is needed in\"):\n Connections.notify('test_title', 'test_message', 'test_user')\n\n with pytest.raises(NeccessaryArgumentError, match=\"Multicast can't be used without\"):\n Connections.notify('test_title', 'test_message', 'multicast')\n\n with pytest.raises(PermissionError, match=\"'force' must be True in order to use broadcast.\"):\n Connections.notify('test_title', 'test_message', 'broadcast')\n\n random_user = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(15))\n\n with pytest.raises(UserNotFoundError, match=random_user):\n Connections.notify('test_title', 'test_message', random_user, force=True)\n\n assert Connections.notify('test_title', 'test_message', 'test', force=True) is True\n\n\ndef test_mail():\n with pytest.raises(InvalidMailAddressError, match=\"'test_destination' is not a valid email\"):\n Connections.send_email('test_destination', 'test_subject', 'test_message')\n\n with pytest.raises(TypeError, match=\"destinations must be iterable or str\"):\n Connections.send_email(18, 'test_subject', 'test_message')\n\n\ndef test_to_google_spreadsheets():\n data = tuple((random.randint(0, 10) for _ in range(10)))\n\n with pytest.raises(SpreadsheetNotFoundError, match='test_file'):\n Connections.to_google_spreadsheets('test_file', 'test_sheet', data)\n\n with pytest.raises(SheetNotFoundError, match='test_sheet'):\n Connections.to_google_spreadsheets('pylog', 'test_sheet', data)\n\n\ndef test_from_google_spreadsheets():\n with pytest.raises(SpreadsheetNotFoundError, match='test_file'):\n Connections.from_google_spreadsheets('test_file', 'test_sheet')\n\n with pytest.raises(SheetNotFoundError, match='test_sheet'):\n Connections.from_google_spreadsheets('pylog', 'test_sheet')\n\n data = Connections.from_google_spreadsheets('pylog', 'puertos')\n\n assert len(data) > 0\n\n\nif __name__ == '__main__':\n pytest.main([os.path.basename(__file__), '-v'])\n","sub_path":"tests/test_connections.py","file_name":"test_connections.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"514650849","text":"class Solution:\n '''Simple algorithm to iterate through the list finding the elements which sum to the target.'''\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n index = []\n for i in range(len(nums)):\n for j in range((i+1), len(nums)):\n if nums[i] + nums[j] == target:\n index.append(i)\n index.append(j)\n \n return index\n\n\n\n def twoSum_ideal(nums, target):\n '''Creates key-value pair of the number and the index, if the difference between any subsequent numbers in the array and the target is in the dictionary, it's index can quickly be identified.'''\n h = {}\n for i, num in enumerate(nums):\n n = target - num\n if n not in h:\n h[num] = i\n else:\n return [h[n], i]\n\nif __name__ == '__main__':\n print(Solution.twoSum(nums = [2,15,11,7],target = 9))\n print(Solution.twoSum_ideal(nums = [2,15,11,7],target = 9))\n\n \n","sub_path":"Easy/TwoSum.py","file_name":"TwoSum.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"45447137","text":"import math\ndef gcd(y,x):\n q=y//x\n r=y-q*x\n print(y,'=',q,'*',x,'+',r)\n if r==0:\n if x<0:\n x=1\n return x\n else:\n return gcd(x,r)\n\ndef gcd_comp(y,x):\n\tz=y/x\n\tq=complex(round(z.real),round(z.imag))\n\tr=y-q*x\n\tprint(y,'=',q,'*',x,'+',r)\n\tif r==0:\n\t\treturn x\n\telse:\n\t\treturn gcd_comp(x,r)\n \n\ndef is_num(x):\n try:\n int(x)\n return True\n except:\n return False\n\ndef norm():\n y=input(\"Insert first number: \")\n while not is_num(y):\n print(\"Not an integer!!\")\n y=input(\"Insert first number: \")\n x=input(\"Insert second number: \")\n while not is_num(y):\n print(\"Not an integer!!\")\n x=input(\"Insert second number: \")\n print('gcd(',y,',',x,')=',gcd(int(y),int(x)))\n\ndef comp():\n y_r=input(\"Insert real part of first number: \")\n while not is_num(y_r):\n print(\"Not an integer!!\")\n y_r=input(\"Insert real part of first number: \")\n y_i=input(\"Insert imaginary part of first number: \")\n while not is_num(y_i):\n print(\"Not an integer!!\")\n y_i=input(\"Insert imaginary part of first number: \")\n\n x_r=input(\"Insert real part of second number: \")\n while not is_num(x_r):\n print(\"Not an integer!!\")\n x_r=input(\"Insert real part of second number: \")\n x_i=input(\"Insert imaginary part of second number: \")\n while not is_num(x_i):\n print(\"Not an integer!!\")\n x_i=input(\"Insert imaginary part of second number: \")\n \n print('gcd(',complex(int(y_r),int(y_i)),',',complex(int(x_r),int(x_i)), \\\n ')=',gcd_comp(complex(int(y_r),int(y_i)),complex(int(x_r),int(x_i))))\n \n\nchoice=input(\"insert 'z' for regular integer, 'c' for complex integers: \")\nwhile choice!='z' and choice!='c':\n print('bad input!')\n choice=input(\"insert 'z' for regular integer, 'c' for complex integers: \")\n \nif choice=='z':\n norm()\nelse:\n comp()\n\n\n\n","sub_path":"Python/gcd func.py","file_name":"gcd func.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"177498630","text":"# Read tremor counts into a named tuple\n# We would like to read both Wech and Idesan's tremor catalogs. \n\nimport numpy as np \nimport matplotlib.pyplot as plt \nimport sys\nimport collections\nimport glob\nimport datetime as dt \n\nTremorCat = collections.namedtuple(\"TremorCat\",['dtarray','lonarray','latarray']);\n\ndef read_input_tremor(tremortype):\n\t# The driver of the inputs (optional)\n\treadfuncs={\"wech\":read_wech,\n\t\"wech_custom\":read_wech_custom,\n\t\"ide\":read_ide,\n\t\"pnsn_052019\":read_pnsn052019};\n\tfilenames={\"wech\":\"../../GPS_POS_DATA/tremor/08_01_2009_10_31_2018.txt\",\n\t\"wech_custom\":\"../../GPS_POS_DATA/tremor/revised_Wech_2015_2017.txt\",\n\t\"ide\":\"../../GPS_POS_DATA/tremor/trm_Cascadia.20050101.3652.92921871.csv\",\n\t\"pnsn_052019\":\"../../GPS_POS_DATA/tremor/PNSN_052019/\"};\n\ttremor=readfuncs[tremortype](filenames[tremortype]);\n\treturn tremor;\n\n\n\n\n\ndef read_wech(filename):\n\tdtarray=[]; lonarray=[]; latarray=[];\n\tstart=0;\n\n\tifile=open(filename,'r');\n\tfor line in ifile:\n\t\ttemp=line.split();\n\t\tif 'yyyy-mm-dd' in line or 'DateTime' in line: # If the header is still inside. \n\t\t\tstart=1; continue;\n\t\tif len(temp)==5: # If we've removed the header already. \n\t\t\tstart=1;\n\t\tif start==1 and len(temp)>0:\n\t\t\tdtarray.append(dt.datetime.strptime(temp[0]+' '+temp[1].split('.')[0],\"%Y-%m-%d %H:%M:%S\"));\n\t\t\tlonarray.append(float(temp[3]));\n\t\t\tlatarray.append(float(temp[2]));\n\t\tif len(latarray)==180000:\n\t\t\tbreak;\n\tifile.close();\n\n\twech_tremor = TremorCat(dtarray=np.flipud(dtarray), lonarray=np.flipud(lonarray), latarray=np.flipud(latarray));\n\tprint(\"Successfully read %d tremor counts from %s \" % (len(wech_tremor.dtarray),filename));\n\treturn wech_tremor;\n\n\ndef read_wech_custom(filename):\n\tdtarray=[]; lonarray=[]; latarray=[];\n\tstart=0;\n\n\tifile=open(filename,'r');\n\tfor line in ifile:\n\t\ttemp=line.split();\n\t\tif 'DateTime' in line: # If the header is still inside. \n\t\t\tstart=1; continue;\n\t\tif len(temp)==5: # If we've removed the header already. \n\t\t\tstart=1;\n\t\tif start==1 and len(temp)>0:\n\t\t\tdtarray.append(dt.datetime.strptime(temp[0]+' '+temp[1].split('.')[0],\"%Y-%m-%d %H:%M:%S\"));\n\t\t\tlonarray.append(float(temp[2]));\n\t\t\tlatarray.append(float(temp[3]));\n\t\tif len(latarray)==180000:\n\t\t\tbreak;\n\tifile.close();\n\n\twech_tremor = TremorCat(dtarray=dtarray, lonarray=lonarray, latarray=latarray);\n\tprint(\"Successfully read %d tremor counts from %s \" % (len(wech_tremor.dtarray),filename));\n\treturn wech_tremor;\n\n\ndef read_ide(filename):\n\tdtarray=[]; lonarray=[]; latarray=[];\n\tifile=open(filename,'r');\n\tfor line in ifile:\n\t\ttemp=line.split(',');\n\t\tif len(temp)>1:\n\t\t\tdtarray.append(dt.datetime.strptime(temp[0]+' '+temp[1],\"%Y-%m-%d %H:%M:%S\"));\n\t\t\tlonarray.append(float(temp[3]));\n\t\t\tlatarray.append(float(temp[2]));\n\tifile.close();\t\n\n\tide_tremor = TremorCat(dtarray=dtarray, lonarray=lonarray, latarray=latarray);\n\tprint(\"Successfully read %d tremor counts from %s \" % (len(ide_tremor.dtarray),filename));\n\treturn ide_tremor;\n\ndef read_pnsn052019_file(filename):\n\tdtarray=[]; lonarray=[]; latarray=[]; \n\tifile=open(filename,'r');\n\tifile.readline();\n\tfor line in ifile:\n\t\ttemp=line.split(',');\n\t\tif len(temp)<=2:\n\t\t\tcontinue;\n\t\tif temp[0]=='lat':\n\t\t\tcontinue;\n\t\tlonarray.append(float(temp[1]));\n\t\tlatarray.append(float(temp[0]));\n\t\tdtarray.append(dt.datetime.strptime(temp[3],\" %Y-%m-%d %H:%M:%S \"));\n\tifile.close();\n\ttremor=TremorCat(dtarray=dtarray, lonarray=lonarray, latarray=latarray);\n\treturn tremor;\n\n\ndef read_pnsn052019(dirname):\n\tdtarray=[]; lonarray=[]; latarray=[];\n\tfiles=glob.glob(dirname+\"*.csv\");\n\tfiles=sorted(files);\n\tfor i in range(len(files)):\n\t\ttremor_1yr = read_pnsn052019_file(files[i]);\n\t\tprint(len(tremor_1yr.dtarray));\n\t\tfor i in range(len(tremor_1yr.dtarray)):\n\t\t\tdtarray.append(tremor_1yr.dtarray[i]);\n\t\t\tlonarray.append(tremor_1yr.lonarray[i]);\n\t\t\tlatarray.append(tremor_1yr.latarray[i]);\n\ttremor=TremorCat(dtarray=dtarray, lonarray=lonarray, latarray=latarray);\n\tprint(\"Successfully read %d tremor counts from %s\" % (len(tremor.dtarray), dirname) );\n\treturn tremor;\n\n\n\ndef write_tremor_as_txt(tremor, filename):\n\tofile=open(filename,'w');\n\tfor i in range(len(tremor.dtarray)):\n\t\tofile.write(\"%s %f %f\\n\" % (dt.datetime.strftime(tremor.dtarray[i],\"%Y-%m-%d\"), tremor.lonarray[i], tremor.latarray[i]) );\n\tofile.close();\n\treturn;\n\n\n\n","sub_path":"Tremor/tremor/tremor_io.py","file_name":"tremor_io.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"593708863","text":"# ==================================================\n#\n# Lection 13.\n#\n# asymptotics: O(N)\n#\n# ==================================================\n\nfrom module import A_stack\nimport ast\n\ndef isint(item):\n try:\n int(item)\n return True\n except ValueError:\n return False\n\ndef backPolandNotation(notation:list):\n for token in notation:\n if isint(token):\n A_stack.push(token)\n else:\n y = A_stack.pop()\n x = A_stack.pop()\n z = eval(str(x) + str(token) + str(y))\n A_stack.push(z)\n \n return A_stack.pop()\n\nnotation = ['2', '7', \"+\", 5, \"*\"]\n\nprint(backPolandNotation(notation))\n\n","sub_path":"Lection_13_check_brackets_sequence/Lection_13_back_poland_notation.py","file_name":"Lection_13_back_poland_notation.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"1348201","text":"from .svr_libs import *\r\n\r\ndef getData(csv):\r\n data = pd.read_csv(csv)\r\n\r\n data['heat_fuel'] = data['heat_fuel'].apply({'gas': 0, 'cogeneration': 1}.get)\r\n data['heat_type'] = data['heat_type'].apply({'individual': 0, 'central': 1, ' district': 2}.get)\r\n data['front_door_structure'] = data['front_door_structure'].apply({'corridor': 0, 'stairway': 1, 'mixed': 2}.get)\r\n\r\n\r\n data['city'] = data['city'].astype('category', copy = False)\r\n data['heat_fuel'] = data['heat_fuel'].astype('category', copy = False)\r\n data['heat_type'] = data['heat_type'].astype('category', copy = False)\r\n data['transaction_month'] = data['transaction_month'].astype('category', copy = False)\r\n data['year_of_completion'] = data['year_of_completion'].astype('category', copy = False)\r\n data['front_door_structure'] = data['front_door_structure'].astype('category', copy = False)\r\n data['address_by_law_first5'] = data['address_by_law_first5'].astype('category', copy = False)\r\n\r\n data = data.drop(['Unnamed: 0'], axis = 1)\r\n return data\r\n\r\ndef splitData(csv):\r\n data = getData(csv)\r\n\r\n X = data.drop(['real_price'], axis = 1)\r\n Y = data[['real_price']]\r\n\r\n x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.3, random_state = 0)\r\n return x_train, x_test, y_train, y_test\r\n\r\ndef svrMain(csv, epsilon):\r\n x_train, x_test, y_train, y_test = splitData(csv)\r\n\r\n model = LinearSVR(epsilon = epsilon)\r\n model.fit(x_train, y_train)\r\n\r\n pred = model.predict(x_test)\r\n\r\n svr_r2 = r2_score(pred, y_test)\r\n svr_mse = mean_squared_error(pred, y_test)\r\n svr_rmse = np.sqrt(svr_mse)\r\n return print('r2 : ', svr_r2, ', mse : ', svr_mse, ', rmse : ', svr_rmse)","sub_path":"encore_academy/apt real transaction price prediction/algorithmcodes/Python/svr/svr_funcs.py","file_name":"svr_funcs.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"407707622","text":"##############################################################################\n# Parte do livro Introdução à Programação com Python\n# Autor: Nilo Ney Coutinho Menezes\n# Editora Novatec (c) 2010-2020\n# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8\n# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3\n# Terceira Edição - Janeiro/2019 - ISBN 978-85-7522-718-3\n#\n# Site: https://python.nilo.pro.br/\n#\n# Arquivo: exercicios3\\capitulo 09\\exercicio-09-05.py\n##############################################################################\n\npares = open(\"pares.txt\", \"r\")\nsaída = open(\"pares_invertido.txt\", \"w\")\n\nL = pares.readlines()\nL.reverse()\nfor l in L:\n saída.write(l)\n\npares.close()\nsaída.close()\n\n# Observe que lemos todas as linhas antes de fazer a inversão\n# Esta abordagem não funciona com arquivos grandes\n# Alternativa usando with:\n#\n##with open(\"pares.txt\",\"r\") as pares, open(\"pares_invertido.txt\",\"w\") as saída:\n## L = pares.readlines()\n## L.reverse()\n## for l in L:\n## saída.write(l)\n","sub_path":"exercicios_resolvidos3/exercicios3/capitulo 09/exercicio-09-05.py","file_name":"exercicio-09-05.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"270118300","text":"# -*- coding: utf-8 -*-\n# file: lca_glove.py\n# author: yangheng \n# Copyright (C) 2020. All Rights Reserved.\n\nimport torch\nimport torch.nn as nn\n\nimport numpy as np\nfrom pytorch_transformers.modeling_bert import BertPooler, BertSelfAttention, BertConfig\n\nclass SelfAttention(nn.Module):\n def __init__(self, config, opt):\n super(SelfAttention, self).__init__()\n self.opt = opt\n self.config = config\n self.SA = BertSelfAttention(config)\n self.tanh = torch.nn.Tanh()\n\n def forward(self, inputs):\n zero_vec = np.zeros((inputs.size(0), 1, 1, self.opt.max_seq_len))\n zero_tensor = torch.tensor(zero_vec).float().to(self.opt.device)\n SA_out = self.SA(inputs, zero_tensor)\n return self.tanh(SA_out[0])\n\nclass LCE_GLOVE(nn.Module):\n\n def __init__(self, embedding_matrix, opt):\n super(LCE_GLOVE, self).__init__()\n # Only few of the parameters are necessary in the config.json, such as hidden_size, num_attention_heads\n self.config = BertConfig.from_json_file(\"utils/bert_config.json\")\n self.opt = opt\n self.embed = nn.Embedding.from_pretrained(torch.tensor(embedding_matrix, dtype=torch.float))\n self.lc_embed = nn.Embedding(2, opt.embed_dim)\n self.global_encoder1 = SelfAttention(self.config, opt)\n self.local_encoder1 = SelfAttention(self.config, opt)\n self.local_encoder2 = SelfAttention(self.config, opt)\n self.mha = SelfAttention(self.config, opt)\n self.pool = BertPooler(self.config)\n self.dropout = nn.Dropout(opt.dropout)\n self.linear = nn.Linear(opt.embed_dim * 2, opt.embed_dim)\n self.dense = nn.Linear(opt.embed_dim, opt.polarities_dim)\n self.classifier = nn.Linear(opt.embed_dim, 2)\n\n def forward(self, inputs):\n text_global_indices = inputs[0]\n text_local_indices = inputs[1]\n lce_ids = inputs[2]\n mask_matrix = inputs[3]\n\n # embedding layer\n global_out = self.embed(text_global_indices)\n local_out = self.embed(text_local_indices)\n\n global_out = self.global_encoder1(global_out)\n\n if self.opt.lce:\n lc_embedding = self.lc_embed(lce_ids)\n global_out = torch.mul(lc_embedding, global_out)\n local_out = self.local_encoder1(local_out)\n\n # dropout\n global_out = self.dropout(global_out).to(self.opt.device)\n local_out = self.dropout(local_out).to(self.opt.device)\n\n # LCF layer\n local_out = torch.mul(local_out, mask_matrix)\n local_out = self.local_encoder2(local_out)\n\n # dropout\n global_out = self.dropout(global_out).to(self.opt.device)\n local_out = self.dropout(local_out).to(self.opt.device)\n\n cat_features = torch.cat((local_out, global_out), dim=-1)\n cat_features = self.linear(cat_features)\n\n lce_logits = self.classifier(cat_features)\n lce_logits = lce_logits.view(-1, 2)\n lce_ids = lce_ids.view(-1)\n\n # output layer\n pooled_out = self.pool(cat_features)\n sen_logits = self.dense(pooled_out)\n\n if self.opt.lcp:\n return sen_logits, lce_logits, lce_ids\n else:\n return sen_logits\n","sub_path":"models/lc_apc/lce_glove.py","file_name":"lce_glove.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"366380407","text":"\"\"\"!\nSimulation of Moller scattering events and detector signals (using SLIC).\n\"\"\"\nfrom hpsmc.generators import EGS5\nfrom hpsmc.tools import BeamCoords, RandomSample, SLIC\n\njob.description = 'Moller from generation to slic'\n\n## Get job input file targets\ninputs = list(job.input_files.values())\n\nif 'nevents' in job.params:\n nevents = job.params['nevents']\nelse:\n nevents = 250000\n\n## Generate beam\negs5 = EGS5(name=\"moller_v3\")\n\n## Rotate events into beam coordinates\nrot = BeamCoords()\n\n## Simulate events\nslic = SLIC(nevents=nevents+1)\n\n## Run the job\njob.add([egs5, rot, slic])\n","sub_path":"python/jobs/moller_gen_to_slic_job.py","file_name":"moller_gen_to_slic_job.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"237483476","text":"import os\nfrom pathlib import Path\n\nimport pandas as pd\nimport pytest\nfrom rdkit import Chem\n\nimport janitor.chemistry\n\ntest_data_dir = Path(os.path.dirname(os.path.abspath(__file__))) / \"test_data\"\n\n\n@pytest.fixture\ndef chemdf():\n df = pd.read_csv(\n test_data_dir / \"corrected_smiles.txt\", sep=\"\\t\", header=None\n ).head(10)\n df.columns = [\"id\", \"smiles\"]\n return df\n\n\n@pytest.mark.parametrize(\"progressbar\", [None, \"terminal\"])\n@pytest.mark.chemistry\ndef test_smiles2mol(chemdf, progressbar):\n chemdf = chemdf.smiles2mol(\"smiles\", \"mol\", progressbar)\n assert \"mol\" in chemdf.columns\n for elem in chemdf[\"mol\"]:\n assert isinstance(elem, Chem.rdchem.Mol)\n\n\n@pytest.mark.chemistry\ndef test_morganbits(chemdf):\n morgans = chemdf.smiles2mol(\"smiles\", \"mol\").morganbits(\"mol\")\n assert morgans.shape == (10, 2048)\n","sub_path":"tests/test_chemistry.py","file_name":"test_chemistry.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"431737990","text":"from __future__ import print_function\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom flask import Flask, request, send_file, redirect, jsonify, Response\nimport json\nimport datetime\nimport os\n\napp = Flask(__name__)\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\nfootprint={datetime.date(year=2019, month=10, day=19): 25,datetime.date(year=2019, month=10, day=18): 23,\n\tdatetime.date(year=2019, month=10, day=17): 40,datetime.date(year=2019, month=10, day=16): 10}\n\nfoodar = []\ntransportationar = []\nelectricityar = []\nfoodMap = {\"meat\": 27, \"diary\": 1.9, \"grain\": 2.7, \"vegetables\": 2.0}\n\n\ndef root_dir(): # pragma: no cover\n return os.path.abspath(os.path.dirname(__file__))\n\n\ndef get_file(filename): # pragma: no cover\n try:\n src = os.path.join(root_dir(), filename)\n # Figure out how flask returns static files\n # Tried:\n # - render_template\n # - send_file\n # This should not be so non-obvious\n return open(src).read()\n except IOError as exc:\n return str(exc)\n\n\n# No caching at all for API endpoints.\n@app.after_request\ndef add_header(response):\n # response.cache_control.no_store = True\n response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'\n response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n response.headers['Pragma'] = 'no-cache'\n response.headers['Expires'] = '-1'\n return response\n\n@app.route(\"/\", methods=[\"GET\"])\ndef main():\n\tcontent = get_file('../index.html')\n\treturn Response(content, mimetype=\"text/html\")\n\n@app.route(\"/food\", methods=[\"GET\"])\ndef main1():\n\tcontent = get_file('../food.html')\n\treturn Response(content, mimetype=\"text/html\")\n\n@app.route(\"/transportation\", methods=[\"GET\"])\ndef main2():\n\tcontent = get_file('../transportation.html')\n\treturn Response(content, mimetype=\"text/html\")\n\n@app.route(\"/electricity\", methods=[\"GET\"])\ndef main3():\n\tcontent = get_file('../electricity.html')\n\treturn Response(content, mimetype=\"text/html\")\n\n@app.route(\"/daily\", methods=[\"GET\"])\ndef daily():\n\treturn str(footprint[datetime.date.today()] if datetime.date.today() in footprint else 0)\n\n@app.route(\"/graph\", methods=[\"GET\"])\ndef graph():\n #data = json.loads(request.json)\n xvals = sorted(list(footprint.keys()))\n #print(str(xvals) + \" \" + str([footprint[x] for x in xvals]), file=sys.stderr)\n yvals = [footprint[x] for x in xvals]\n plt.figure(figsize=(12,9))\n plt.plot(xvals, yvals, \"ko-\")\n\n plt.xlabel(\"day\")\n plt.ylabel(\"carbon emission (lbs)\")\n plt.title(\"Your daily carbon emission history\")\n plt.xlim([min(xvals) - datetime.timedelta(days=2), max(xvals)+datetime.timedelta(days=2)])\n plt.ylim([min(yvals) - 5, max(yvals) + 5])\n os.remove(\"./graph.png\")\n plt.savefig(\"./graph.png\")\n return send_file(\"./graph.png\", mimetype='image/gif')\n\n@app.route(\"/getFood\", methods=[\"GET\"])\ndef getFood():\n\treturn jsonify(foodar)\n\n@app.route(\"/getTransportation\", methods=[\"GET\"])\ndef getTransportation():\n\treturn jsonify(transportationar)\n\n@app.route(\"/getElectricity\", methods=[\"GET\"])\ndef getElectricity():\n\treturn jsonify(electricityar)\n\n@app.route(\"/foodAdd\", methods=[\"POST\"])\ndef food():\n\tdata = request.form\n\td = datetime.date.today()\n\tif(not d in footprint):\n\t\tfootprint[d] = 0\n\tfootprint[d] += float(foodMap[data[\"food type\"]]) * float(data[\"amount\"])\n\tfoodar.append(\"You ate \" + str(data[\"amount\"]) + \" ozs of \" + data[\"food type\"])\n\treturn redirect(\"/\", code=302)\n\n@app.route(\"/transportationAdd\", methods=[\"POST\"])\ndef transportation():\n\tdata = request.form\n\td = datetime.date.today()\n\tprint(data, file=sys.stderr)\n\tif(not d in footprint):\n\t\tfootprint[d] = 0\n\tfootprint[d] += float(data[\"miles\"]) / float(data[\"mpg\"]) * 20\n\ttransportationar.append(\"You traveled \" + str(data[\"miles\"]) + \" miles\")\n\treturn redirect(\"/\", code=302)\n\n@app.route(\"/electricityAdd\", methods=[\"POST\"])\ndef electricity():\n\tdata = request.form\n\td = datetime.date.today()\n\tif(not d in footprint):\n\t\tfootprint[d] = 0\n\tfootprint[d] += float(data[\"electricity\"])\n\telectricityar.append(\"You used \" + str(data[\"electricity\"]) + \" kilowatt-hours of electricity.\")\n\treturn redirect(\"/\", code=302)\n\nif __name__ == \"__main__\":\n app.run(debug=True,host=\"0.0.0.0\",port=\"5000\")","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"146913422","text":"# Author: Xu Wang\r\n# Email: i@xuwang.im\r\n#\r\n# Filename: database.py\r\n#\r\n#\r\n\r\nfrom sqlalchemy import *\r\nfrom twitter import Tweet\r\nfrom utils import log\r\nimport config\r\nimport logging\r\n# logging.basicConfig()\r\n# logging.getLogger('sqlalchemy').setLevel(logging.DEBUG)\r\n\r\ndef engine_connection():\r\n \"\"\"\r\n Return a meta data of the connection\r\n :return:\r\n \"\"\"\r\n connection = 'mysql+pymysql://%s:%s@%s/%s?charset=utf8'\\\r\n % (config.db_user, config.db_passwd, config.db_host, config.db_database)\r\n return MetaData(bind=create_engine(connection, pool_recycle=5))\r\n\r\n\r\ndef get_table(table, metadata):\r\n \"\"\"\r\n Return the object of Table table in database bind to metadata\r\n :param metadata: metadata bind to a database connection\r\n :param table: table name\r\n :return: table object in sqlalchemy\r\n \"\"\"\r\n return Table(table, metadata, autoload=True)\r\n\r\n\r\nclass NewUsers:\r\n \"\"\"\r\n Operations on New_Users table.\r\n \"\"\"\r\n def __init__(self, table=None):\r\n \"\"\"\r\n\r\n :param table: Name of New_Users table\r\n :return:\r\n \"\"\"\r\n if table is None:\r\n name = config.New_Users\r\n else:\r\n name = table\r\n self.__table = get_table(name, engine_connection())\r\n\r\n def __lock_by_screen(self, screen):\r\n \"\"\"\r\n Set inuse of screen to be 1\r\n :param screen:\r\n :return: None\r\n \"\"\"\r\n self.__set_inuse_by_screen(1, screen)\r\n\r\n def __set_inuse_by_screen(self, inuse, screen):\r\n \"\"\"\r\n Set inuse of screen in table\r\n :param inuse: 0 or 1\r\n :param screen: screen name\r\n :return:\r\n \"\"\"\r\n if inuse not in [0, 1]:\r\n raise ValueError('Illegal value for inuse')\r\n print(screen)\r\n self.__table.update(self.__table.c.screen == screen).execute(inuse=inuse)\r\n\r\n def remove_by_screen(self, screen):\r\n \"\"\"\r\n Remove user by screen\r\n :param screen:\r\n :return:\r\n \"\"\"\r\n try:\r\n self.__table.delete(self.__table.c.screen == screen).execute()\r\n log(screen)\r\n except Exception as e:\r\n # in the case screen is not in table\r\n log(str(e))\r\n\r\n def add_by_screen(self, screen):\r\n \"\"\"\r\n Add a user by screen into table\r\n :param screen:\r\n :return:\r\n \"\"\"\r\n try:\r\n self.__table.insert().execute(screen=screen)\r\n log(screen)\r\n except Exception as e:\r\n # will receive an exception when user exists in the table, ignore it\r\n log(str(e))\r\n\r\n def get_user_screen(self):\r\n \"\"\"\r\n Get a unlocked (inuse = 0) user and lock it\r\n :return: a user by screen\r\n \"\"\"\r\n screen = self.__get_free_screen()\r\n if screen is None:\r\n return None\r\n else:\r\n self.__lock_by_screen(screen)\r\n return screen\r\n\r\n def add_from_mentions(self, tweet, Users):\r\n \"\"\"\r\n Add screen from mentions in tweet\r\n :param tweet: Tweet object\r\n :param Users: Users table\r\n :return:\r\n \"\"\"\r\n for s in tweet.mentions:\r\n if not Users.exist_user_by_screen(s):\r\n self.add_by_screen(s)\r\n\r\n\r\n def __get_free_screen(self):\r\n \"\"\"\r\n Get a unlocked (inuse = 0) user\r\n :return:\r\n \"\"\"\r\n entry = self.__table.select(self.__table.c.inuse == 0).execute().fetchone()\r\n if entry is None:\r\n return None\r\n else:\r\n return entry['screen']\r\n\r\n\r\n\r\nclass Users:\r\n \"\"\"\r\n Operations on Users table\r\n \"\"\"\r\n def __init__(self, table=None):\r\n \"\"\"\r\n\r\n :param table: Name of Users table\r\n :return:\r\n \"\"\"\r\n if table is None:\r\n name = config.Users\r\n else:\r\n name = table\r\n self.__table = get_table(name, engine_connection())\r\n\r\n def exist_user_by_screen(self, screen):\r\n \"\"\"\r\n Whether a user exits in table Users identified by screen name.\r\n :param screen: the screen name\r\n :return: True if exist, False otherwise\r\n \"\"\"\r\n current_user = self.__table.select(self.__table.c.screen == screen)\\\r\n .execute().fetchone()\r\n if current_user is not None:\r\n return True\r\n else:\r\n return False\r\n\r\n def update_followers(self, user):\r\n \"\"\"\r\n Update the number of followers of user with user.followers\r\n :param user:\r\n :return: None\r\n \"\"\"\r\n pass\r\n\r\n def __add_user(self, user):\r\n \"\"\"\r\n\r\n :param user: user of User class\r\n :return:\r\n \"\"\"\r\n self.__table.insert().execute(id=user.id,\r\n name=user.name,\r\n screen=user.screen,\r\n follower=user.followers,\r\n last_update=user.last_update)\r\n\r\n def add_user(self, user):\r\n \"\"\"\r\n Add user if not exists\r\n :param user:\r\n :return:\r\n \"\"\"\r\n try:\r\n self.__add_user(user)\r\n log(user.screen)\r\n except Exception as e:\r\n log(str(e))\r\n\r\n\r\nclass Tweets:\r\n \"\"\"\r\n Table of Tweets\r\n \"\"\"\r\n def __init__(self, table=None):\r\n \"\"\"\r\n\r\n :param table: name of tweets table\r\n :return:\r\n \"\"\"\r\n if table is None:\r\n name = config.Tweets\r\n else:\r\n name = table\r\n self.__table = get_table(name, engine_connection())\r\n\r\n def __add_tweet(self, tweet):\r\n \"\"\"\r\n\r\n :param tweet: tweet of Tweet class\r\n :return:\r\n \"\"\"\r\n self.__table.insert().execute(id=tweet.id,\r\n uid=tweet.uid,\r\n text=tweet.text,\r\n timestamp=tweet.timestamp,\r\n date=tweet.date,\r\n time=tweet.time,\r\n retweets=tweet.retweets,\r\n favorite=tweet.favorite)\r\n\r\n def add_tweet(self, tweet):\r\n \"\"\"\r\n\r\n :param tweet: Tweet object\r\n :return:\r\n \"\"\"\r\n try:\r\n self.__add_tweet(tweet)\r\n log(tweet.id)\r\n except Exception as e:\r\n log(str(e))\r\n\r\n\r\nclass Mentions:\r\n \"\"\"\r\n Table of Tweet_Mentions\r\n \"\"\"\r\n def __init__(self, table=None):\r\n if table is None:\r\n name = config.Tweet_Mentions\r\n else:\r\n name = table\r\n self.__table = get_table(name, engine_connection())\r\n\r\n def __add_mention(self, tweet_id, screen):\r\n \"\"\"\r\n Add a pair tweet_id and mention\r\n :param tweet_id:\r\n :param screen: is a user screen\r\n :return:\r\n \"\"\"\r\n self.__table.insert().execute(id=tweet_id, screen=screen)\r\n\r\n def __add_mentions(self, tweet):\r\n \"\"\"\r\n Add all mentions in tweet\r\n :param tweet: Tweet object\r\n :return:\r\n \"\"\"\r\n for s in tweet.mentions:\r\n self.__add_mention(tweet.id, s)\r\n\r\n def add_mentions(self, tweet):\r\n \"\"\"\r\n\r\n :param tweet:\r\n :return:\r\n \"\"\"\r\n try:\r\n self.__add_mentions(tweet)\r\n log(tweet.id)\r\n except Exception as e:\r\n log(str(e), str(tweet.id), ' '.join(tweet.mentions))\r\n\r\n\r\nclass Tags:\r\n \"\"\"\r\n Table of Tweet_Tags\r\n \"\"\"\r\n def __init__(self, table=None):\r\n \"\"\"\r\n\r\n :param table: table name of Tweet_Tags\r\n :return:\r\n \"\"\"\r\n if table is None:\r\n name = config.Tweet_Tags\r\n else:\r\n name = table\r\n self.__table = get_table(name, engine_connection())\r\n\r\n def __add_tag(self, tweet_id, tag):\r\n \"\"\"\r\n Add a pair tweet_id and tag\r\n :param tweet_id:\r\n :param tag:\r\n :return:\r\n \"\"\"\r\n self.__table.insert().execute(id=tweet_id, tag=tag)\r\n\r\n def __add_tags(self, tweet):\r\n \"\"\"\r\n\r\n :param tweet: Tweet object\r\n :return:\r\n \"\"\"\r\n for t in tweet.tags:\r\n self.__add_tag(tweet.id, t)\r\n\r\n def add_tags(self, tweet):\r\n \"\"\"\r\n\r\n :param tweet:\r\n :return:\r\n \"\"\"\r\n try:\r\n self.__add_tags(tweet)\r\n log(tweet.id)\r\n except Exception as e:\r\n log(str(e), str(tweet.id), ' '.join(tweet.tags))\r\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":8589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"340781718","text":"import time\nimport random\nfrom Bots.Functions.API import login\n\n\ntry:\n api = login.login()\n print(\"Logged in.\\n\")\nexcept:\n api=login.login()\n\nunf_list = open(\"unf.txt\", \"a\")\n\n\ndef get_list(username):\n name = api.username_info(username)\n id = name[\"user\"][\"pk\"]\n rank_token = api.generate_uuid()\n f_list = api.user_following(id, rank_token)\n\n return f_list\n\n\ndef unfollow_script(username, no_check):\n list = get_list(username)\n self_time = api.username_feed(username)[\"items\"][0][\"taken_at\"]\n count=0\n month_sec = 2628000.0\n\n\n for i in range(len(list[\"users\"])):\n rand = random.randint(1, 10)\n o_user = list[\"users\"][i][\"username\"]\n o_user_id = list[\"users\"][i][\"pk\"]\n if len(api.username_feed(o_user)[\"items\"]) > 0:\n last_post = api.username_feed(o_user)[\"items\"][0]\n o_time=last_post[\"taken_at\"]\n if (self_time-o_time) >= month_sec and o_user not in no_check:\n api.friendships_destroy(o_user_id)\n print(\"Unfollowed {}.\".format(o_user))\n unf_list.write(o_user)\n count+=1\n else:\n print(\"{} is fine.\".format(o_user))\n else:\n print(\"{} is fine.\".format(o_user))\n time.sleep(rand/10)\n print(\"Unfollowed {} users.\".format(count))\n\n","sub_path":"Bots/unfollow_inactives.py","file_name":"unfollow_inactives.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"518502704","text":"import socket\nimport PyQt5\nfrom PyQt5 import QtCore\nimport threading\nimport time\nimport pickle\nimport query_struct_class as qs\nimport sys\nfrom PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QApplication, QLabel, QPlainTextEdit, QLineEdit, QGridLayout, QComboBox\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtWidgets import QGroupBox, QVBoxLayout, QHBoxLayout, QCheckBox, QSpinBox, QMessageBox\nfrom PyQt5.QtChart import QChart, QChartView, QLineSeries\nfrom PyQt5.QtGui import QPolygonF, QPainter, QPen, QBrush, QColor, QTextCursor\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtChart import QScatterSeries, QChartView, QLegend\n\n\n########################################################################################\n############################### INTERFACE CLASS ######################################\n########################################################################################\nclass Interface(QMainWindow):\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(Interface, self).__init__()\n\t\tglobal g_server_message\n\t\tself.__ax = 100\n\t\tself.__ay = 60\n\t\tself.__aw = 1000\n\t\tself.__ah = 600\n\t\tself.__margin = 30\n\t\tself.__wid = QWidget(self)\n\t\tself.setCentralWidget(self.__wid)\n\t\tself.__layout = QGridLayout()\n\t\tself.__layout.setSpacing(5)\n\t\tself.__data1 = []\n\t\tself.__data2 = []\n\t\tself.start = False\n\t\tself.stop = False\n\t\tself.__cl = client(\"192.168.30.101\", 10001, self)\n\t\tself.__cl.data_come_pareto.connect(self.on_data_come_pareto)\n\t\tself.__cl.data_come_times.connect(self.on_data_come_times)\n\t\tself.initUI()\n\t\tthreading.Thread(target = self.__cl.start).start()\n\t\n\tdef on_data_come_pareto(self, data):\n\t\tself.drawParetoChart(data)\n\n\tdef on_data_come_times(self, data1, data2):\n\t\tself.writeTimeLog(data1, data2)\n\t\tself.drawComparisonChart(data1, data2)\n\n\tdef __setWindowProperties(self, parrent):\n\t\tself.setWindowTitle(\"Title\") #название окна\n\t\tself.__setWindowSize(self.__ax, self.__ay, self.__aw, self.__ah)\n\n\tdef __setWindowSize(self, ax, ay, aw, ah):\n\t\tself.setGeometry(ax, ay, aw, ah) #размеры окна\n\n\tdef drawParetoChart(self, data):\n\t\tself.__pareto_chart.removeAllSeries()\n\t\tfor i in data[\"database_clients\"]:\n\t\t\tseries = QScatterSeries()\n\t\t\tseries.setName(\"database_client\")\n\t\t\tseries.setMarkerShape(QScatterSeries.MarkerShapeCircle)\n\t\t\tseries.setMarkerSize(5)\n\t\t\tseries.append(i[0],i[1])\n\t\t\tseries.setBrush(QColor(Qt.red))\n\t\t\tself.__pareto_chart.addSeries(series)\n\t\tseries = QScatterSeries()\n\t\tseries.setName(\"optimal_client\")\n\t\tseries.setMarkerShape(QScatterSeries.MarkerShapeCircle)\n\t\tseries.setMarkerSize(7)\n\t\tseries.append(data[\"optimal_client\"][0], data[\"optimal_client\"][1])\n\t\tself.__pareto_chart.addSeries(series)\n\t\tseries = QScatterSeries()\n\t\tseries.setName(\"utopian_point\")\n\t\tseries.setMarkerShape(QScatterSeries.MarkerShapeCircle)\n\t\tseries.setMarkerSize(10)\n\t\tseries.append(data[\"utopian_point\"][0], data[\"utopian_point\"][1])\n\t\tself.__pareto_chart.addSeries(series)\n\t\tself.__pareto_chart.createDefaultAxes()\n\n\tdef __createOptimisationChartGroupBox(self):\n\t\tgroupBox = QGroupBox(\"Optimisation Chart\")\n\t\tlayout = QGridLayout()\n\t\tlayout.setSpacing(0)\n\t\t\n\t\tself.__pareto_chart = QChart()\n\t\tself.__pareto_chart_series = []\n\t\t# self.__pareto_chart.createDefaultAxes()\n\t\t# legend = QLegend()\n\t\t# chart.legend.setMarkerShape(QLegend.MarkerShapeFromSeries)\n\t\tview = QChartView(self.__pareto_chart)\n\t\tlayout.addWidget(view)\n\t\tgroupBox.setLayout(layout)\n\t\treturn groupBox\n\n\tdef __createButtonsGroupBox(self):\n\t\tgroupBox = QGroupBox(\"Buttons\")\n\t\thbox = QHBoxLayout()\n\t\tself.__btn_start = QPushButton(\"Start\", self) #создание кнопки\n\t\tself.__btn_stop = QPushButton(\"Stop\", self)\n\t\thbox.addWidget(self.__btn_start)\n\t\thbox.addWidget(self.__btn_stop)\n\t\tgroupBox.setLayout(hbox)\n\t\treturn groupBox\n\n\tdef __createQueryParametersGroupBox(self):\n\t\tgroupBox = QGroupBox(\"Query Parameters\")\n\t\tlayout = QGridLayout()\n\t\tlayout.setSpacing(5)\n\t\tlabel_query_count = QLabel(\"Query Count: \")\n\t\tself.spinbox_query_count = QSpinBox()\n\t\tself.spinbox_query_count.setMinimum(100)\n\t\tself.spinbox_query_count.setMaximum(1000)\n\t\tlayout.addWidget(label_query_count, 1, 1, 1, 1)\n\t\tlayout.addWidget(self.spinbox_query_count, 1, 2, 1, 3)\n\t\tlabel_package_size = QLabel(\"Package Size: \")\n\t\tgroupBox.setLayout(layout)\n\t\treturn groupBox\n\n\tdef writeTimeLog(self, data1, data2):\n\t\tself.__plainTextEdit_time_logs.moveCursor(QTextCursor.End)\n\t\tself.__plainTextEdit_time_logs.insertPlainText(str(\"optimal:\" + str(data1[0]) + '\\n'))\n\t\tself.__plainTextEdit_time_logs.insertPlainText(str(\"drugoi:\" + str(data2[0]) + '\\n'))\n\t\tself.__plainTextEdit_time_logs.moveCursor(QTextCursor.End)\n\n\tdef __createLogGroupBox(self):\n\t\tgroupBox = QGroupBox(\"Time Logs\")\n\t\tself.__plainTextEdit_time_logs = QPlainTextEdit(\"\")\n\t\tvbox = QVBoxLayout()\n\t\tvbox.addWidget(self.__plainTextEdit_time_logs)\n\t\tvbox.addStretch(1)\n\t\tgroupBox.setLayout(vbox)\n\t\treturn groupBox\n\n\tdef drawComparisonChart(self, data1, data2):\n\t\tself.__comparison_chart.removeAllSeries()\n\t\t#for i in self.__comparison_chart_series:\n\t\t#\tself.__comparison_chart.removeSeries(i)\n\t\t#\tdel i\n\t\tseries1 = QLineSeries()\n\t\tseries1.setName(\"optimal\")\n\t\tseries2 = QLineSeries()\n\t\tseries2.setName(\"drugoi\")\n\t\tprint(\"[drawComparisonChart]: \", data1, data2)\n\t\ttemp1 = {}\n\t\ttemp1[\"time\"] = data1[0]\n\t\ttemp1[\"count\"] = data1[1]\n\t\ttemp2 = {}\n\t\ttemp2[\"time\"] = data2[0]\n\t\ttemp2[\"count\"] = data2[1]\n\t\tif self.__data1:\n\t\t\ttemp1[\"count\"] += self.__data1[len(self.__data1) - 1][\"count\"]\n\t\t\ttemp1[\"time\"] += self.__data1[len(self.__data1) - 1][\"time\"]\n\t\tif self.__data2:\n\t\t\ttemp2[\"count\"] += self.__data2[len(self.__data2) - 1][\"count\"]\n\t\t\ttemp2[\"time\"] += self.__data2[len(self.__data2) - 1][\"time\"]\n\t\tself.__data1.append(temp1)\n\t\tself.__data2.append(temp2)\n\t\tprint(\"[drawComparisonChart]: \", self.__data1, self.__data2)\n\n\t\tfor i in self.__data1:\n\t\t\tseries1.append(i[\"time\"], i[\"count\"])\n\t\tfor i in self.__data2:\n\t\t\tseries2.append(i[\"time\"], i[\"count\"])\n\n\t\tself.__comparison_chart.addSeries(series1)\n\t\t#self.__comparison_chart_series.append(series1)\n\t\tself.__comparison_chart.addSeries(series2)\n\t\t#self.__comparison_chart_series.append(series2)\n\t\tself.__comparison_chart.createDefaultAxes()\n\n\tdef __createComparisonChartGroupBox(self):\n\t\tgroupBox = QGroupBox(\"Comparison Chart\")\n\t\tlayout = QGridLayout()\n\t\tlayout.setSpacing(0)\n\t\tself.__comparison_chart = QChart()\n\t\tself.__comparison_chart_series = []\n\t\tself.__comparison_view = QChartView(self.__comparison_chart)\n\t\tlayout.addWidget(self.__comparison_view)\n\t\tgroupBox.setLayout(layout)\n\t\treturn groupBox\n\n\tdef __start_btn_clicked(self):\n\t\tprint(\"[init]: start\")\n\t\tthreading.Thread(target = self.__cl.start2).start()\n\n\tdef initUI(self):\n\t\tself.__layout.addWidget(self.__createOptimisationChartGroupBox(), 1, 1, 8, 5)\n\t\tself.__layout.addWidget(self.__createLogGroupBox(), 9, 1, 2, 5)\n\t\tself.__layout.addWidget(self.__createButtonsGroupBox(), 1, 6, 1, 5)\n\t\tself.__layout.addWidget(self.__createQueryParametersGroupBox(), 2, 6, 2, 5)\n\t\tself.__layout.addWidget(self.__createComparisonChartGroupBox(), 4, 6, 7, 5)\n\t\tself.__wid.setLayout(self.__layout)\n\t\tself.__btn_start.clicked.connect(self.__start_btn_clicked)\n\t\tself.__btn_stop.clicked.connect(self.__cl.stop2)\n\t\tself.__setWindowProperties(self)\n\t\tself.show()\n\n\tdef closeEvent(self, event): #событие закрытия окна\n\t\treply = QMessageBox.question(self, 'Message',\n\t\t\t\"Are you sure to quit?\", QMessageBox.Yes |\n\t\t\tQMessageBox.No, QMessageBox.No)\n\t\tif reply == QMessageBox.Yes:\n\t\t\tevent.accept()\n\t\telse:\n\t\t\tevent.ignore()\n\n########################################################################################\n################################# CLIENT CLASS #######################################\n########################################################################################\nclass client(QObject):\n\tdata_come_pareto = QtCore.pyqtSignal(dict)\n\tdata_come_times = QtCore.pyqtSignal(list, list)\n\n\tdef __init__(self, server_ip, server_port, inter):\n\t\tsuper(client, self).__init__()\n\t\ttry:\n\t\t\tself.__connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\t\tself.__server_address = (server_ip, server_port)\n\t\t\tself.__connection.connect(self.__server_address)\n\t\t\tself.__interface = inter\n\t\texcept:\n\t\t\tprint(\"[__init__]: Connection error.\")\n\n\tdef start2(self):\n\t\tprint(\"start2\")\n\t\twhile True:\n\t\t\ttime.sleep(1)\n\t\t\tmessage = pickle.dumps({\"command\": 98})\n\t\t\tself.__connection.send(message)\n\t\t\tself.comparisonCommand() #vremya ne 1 sec, a kak tol'ko pridet otvet\n\n\tdef stop2(self):\n\t\tprint(\"stop\")\n##////////////////////////////////////////////////////////////////////////////////////##\n\tdef start(self):\n\t\tself.__working = True\n\t\ttry:\n\t\t\ttemp_message = {}\n\t\t\ttemp_message[\"command\"] = -1\n\t\t\ttemp_message[\"client_type\"] = \"user\"\n\t\t\tmessage = pickle.dumps(temp_message)\n\t\t\tself.__connection.send(message)\n\t\t\tthreading.Thread(target = self.__listenServer).start()\n\t\t\twhile True:\n\t\t\t\ttime.sleep(100)\n\t\texcept (KeyboardInterrupt, SystemExit):\n\t\t\tprint(\"[__init__]: KeyboardInterrupt.\")\n\t\t\tself.__working = False\n\t\t\ttemp_message = {}\n\t\t\ttemp_message[\"command\"] = 0\n\t\t\tmessage = pickle.dumps(temp_message)\n\t\t\tself.__connection.send(message)\n\t\t\tself.__connection.close()\n##////////////////////////////////////////////////////////////////////////////////////##\n\tdef formServerAnswer(self):\n\t\tresult = \"\"\n\t\tprint(\"TYPE\", self.server_message)\n\t\tprint(self.server_message[\"command\"])\n\t\tprint(type(self.server_message[\"command\"]))\n\t\tprint(\"records number: \" + str(self.server_message[\"command\"]) + '\\n')\n\t\tfor i in self.server_message[\"query\"]:\n\t\t\tresult += str(i.getData()) + '\\n'\n\t\treturn result\n##////////////////////////////////////////////////////////////////////////////////////##\n\tdef __listenServer(self):\n\t\tprint(\"[__listenServer]\")\n\t\twhile self.__working:\n\t\t\ttry:\n\t\t\t\tif self.__connection:\n\t\t\t\t\tserver_message = pickle.loads(self.__connection.recv(4096))\n\t\t\t\t\tprint(\"[__listenServer]: \", server_message)\n\t\t\t\t\tif server_message[\"command\"] == 0:\n\t\t\t\t\t\tprint(\"[__listenServer]: server is off.\")\n\t\t\t\t\t\tself.__working = False\n\t\t\t\t\t\tself.__connection.close()\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.server_message = server_message\n\t\t\t\t\t\tprint(\"TYPE:\", type(self.server_message))\n\t\t\t\t\t\tprint(\"[__listenServer]: server message:\", server_message)\n\t\t\t\t\t\tif self.server_message[\"command\"] == 99:\n\t\t\t\t\t\t\tself.data_come_times.emit(server_message[\"data1\"], server_message[\"data2\"])\n\t\t\t\t\t\tif self.server_message[\"command\"] == 98:\n\t\t\t\t\t\t\tself.data_come_pareto.emit(server_message)\n\t\t\texcept KeyboardInterrupt:\n\t\t\t\tprint(\"[__listenServer]: exception.\")\n\t\t\t\tself.__working = False\n\t\t\t\tbreak\n##////////////////////////////////////////////////////////////////////////////////////##\n\tdef comparisonCommand(self):\n\t\ttemp_message = {}\n\t\ttemp_message[\"command\"] = 99 #command\n\t\ttemp_message[\"count\"] = self.__interface.spinbox_query_count.value() #100 #records number\n\t\ttemp_message[\"type\"] = 0 #0 - read, 1 - write\n\t\ttemp_message[\"optimisation\"] = 2 #0 - without, 1 - with, 2 - both\n\t\tmessage = pickle.dumps(temp_message)\n\t\tself.__connection.send(message)\n\t\tprint(temp_message)\n##////////////////////////////////////////////////////////////////////////////////////##\n\n\n########################################################################################\ndef main():\n\tprint(\"START\")\n\tapp = QApplication(sys.argv)\n\tex = Interface()\n\tsys.exit(app.exec_())\n\t\n##////////////////////////////////////////////////////////////////////////////////////##\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"user_client.py","file_name":"user_client.py","file_ext":"py","file_size_in_byte":11414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"609099126","text":"#!/usr/bin/python3\n#encoding=utf-8\nimport sys, argparse\nfrom numpy import *\nfrom sklearn import mixture\nimport math\nimport time\nfrom scipy.stats import multivariate_normal\nfrom functools import reduce\n\ndef read_features(txt,cols=100):\n\tfeatures=[]\n\tf = open(txt)\n\tlines = f.readlines();\n\tfor line in lines:\n\t\tline_feature=[]\n\t\tvec = line.split(' ')\n\t\tif size(vec) != cols:\n\t\t\tprint (\"cols of input is wrong\")\n\t\telse:\n\t\t#print size(vec)\n\t\t\tfor v in vec:\n\t\t\t\ttry:\n\t\t\t\t\tline_feature.append(float32(v))\n\t\t\t\texcept ValueError:\n\t\t\t\t\tprint ('invalid input %s' %(v))\n\t\t\tfeatures.append(line_feature)\n\tf.close()\n\tfeatures = array(features)\n\treturn features\n\ndef dictionary(descriptors, N):\n\tgmm = mixture.GMM(n_components=N,covariance_type='full')\n\tgmm.fit(descriptors)\n\t#save(\"means.gmm\", gmm.means_)\n\t#save(\"covs.gmm\", gmm.covars_)\n\t#save(\"weights.gmm\", gmm.weights_)\n\treturn float32(gmm.means_),float32(gmm.covars_),float32(gmm.weights_)\n\ndef likelihood_moment(x, gaussians, weights, k, moment):\t\n\tx_moment = power(float32(x), moment) if moment > 0 else float32([1])\n\tprobabilities = map(lambda i: weights[i] * gaussians[i], range(0, len(weights)))\n\tytk = probabilities[k] / sum(probabilities)\n\treturn x_moment * ytk\n\ndef likelihood_statistics(samples, means, covs, weights):\n\ts0, s1,s2 = {}, {}, {}\n\tsamples = zip(range(0, len(samples)), samples)\n\tgaussians = {}\n\tg = [multivariate_normal(mean=means[k], cov=covs[k]) for k in range(0, len(weights)) ]\n\tfor i,x in samples:\n\t\tgaussians[i] = {k : g[k].pdf(x) for k in range(0, len(weights) ) }\n\n\tfor k in range(0, len(weights)):\n\t\t#s0[k] = reduce(lambda a, (i,x): a + likelihood_moment(x, gaussians[i], weights, k, 0), samples, 0)\n\t\t#s1[k] = reduce(lambda a, (i,x): a + likelihood_moment(x, gaussians[i], weights, k, 1), samples, 0)\n\t\t#s2[k] = reduce(lambda a, (i,x): a + likelihood_moment(x, gaussians[i], weights, k, 2), samples, 0)\n\t\ts0[k] = reduce(lambda a, i,x: a + likelihood_moment(x, gaussians[i], weights, k, 0), samples, 0)\n\t\ts1[k] = reduce(lambda a, i,x: a + likelihood_moment(x, gaussians[i], weights, k, 1), samples, 0)\n\t\ts2[k] = reduce(lambda a, i,x: a + likelihood_moment(x, gaussians[i], weights, k, 2), samples, 0)\n\treturn s0, s1, s2\n\ndef fisher_vector_weights(s0, s1, s2, means, covs, w, T):\n\treturn float32([((s0[k] - T * w[k]) / sqrt(w[k]) ) for k in range(0, len(w))])\n\ndef fisher_vector_means(s0, s1, s2, means, sigma, w, T):\n\treturn float32([(s1[k] - means[k] * s0[k]) / (sqrt(w[k] * sigma[k])) for k in range(0, len(w))])\n\ndef fisher_vector_sigma(s0, s1, s2, means, sigma, w, T):\n\treturn float32([(s2[k] - 2 * means[k]*s1[k] + (means[k]*means[k] - sigma[k]) * s0[k]) / (sqrt(2*w[k])*sigma[k]) for k in range(0, len(w))])\n\ndef normalize(fisher_vector):\n\tv = sqrt(abs(fisher_vector)) * sign(fisher_vector)\n\treturn v / max(1,sqrt(dot(v, v)))\n\n\n\"\"\"\n************************Interface*****************************************\n\"\"\"\n\n\ndef generate_gmm(gmm_folder,descriptors, N):\n\t'''\n\tInterface\n\tgmm_folder\n\tdescriptors, (Train data) ,numpy.array, matrix, each row is one sample\n\tN, int ,the number of cluster center\n\t'''\n\tmeans,covs,weights = dictionary(descriptors,N)\n\tsave(gmm_folder+ '/'+ \"means.gmm\", means)\n\tsave(gmm_folder+ '/'+ \"covs.gmm\", covs)\n\tsave(gmm_folder+ '/'+ \"weights.gmm\", weights)\n\treturn means, covs, weights\t\n\ndef load_gmm(folder = \".\"):\n\t'''\n\tInterface\n\t'''\n\tfiles = [\"means.gmm.npy\", \"covs.gmm.npy\", \"weights.gmm.npy\"]\n\treturn map(lambda file: load(open(file,'rb')), map(lambda s : folder + \"/\" + s , files))\n\ndef fisher_vector(samples, means, covs, w):\n\t'''\n\tInterface: \n\tsamples: (to be encoded ),numpy.array , matrix, each row is a sample\n\tmeans: gmm.means_\n\tcovs: gmm.covars_\n\tw: gmm.weights_\n\t'''\n\ts0, s1, s2 = likelihood_statistics(samples, means, covs, w)\n\tT = samples.shape[0]\n\tcovs = float32([diagonal(covs[k]) for k in range(0, covs.shape[0])])\n\ta = fisher_vector_weights(s0, s1, s2, means, covs, w, T)\n\ta = normalize(a)\n\tb = concatenate(fisher_vector_means(s0, s1, s2, means, covs, w, T))\n\tb = normalize(b)\n\tc = concatenate(fisher_vector_sigma(s0, s1, s2, means, covs, w, T))\n\tc = normalize(c)\n\tfv = concatenate([a,b,c])\n\t#fv = concatenate([concatenate(a), concatenate(b), concatenate(c)])\n\t#fv = normalize(fv)\n\treturn fv\n\n\n\n","sub_path":"Fisher-Vector-master/fv_py3.py","file_name":"fv_py3.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"302510936","text":"#!/usr/bin/env python3\nfrom flask.ext.script import Manager\nfrom sqlalchemy_utils import create_database, database_exists, drop_database\n\nfrom scrapper import create_app\n\nmanager = Manager(create_app)\n\n@manager.command\ndef init_db():\n '''\n Initialize database. Should be run before runserver command. Database details\n can be found (and changed) on scrapper/config/server.py\n '''\n from scrapper.config.default import SQLALCHEMY_DATABASE_URI as db_url\n from scrapper import db\n\n if not database_exists(db_url):\n create_database(db_url)\n db.create_all()\n print(\"Done\")\n else:\n print(\"Database already exists\")\n exit(1)\n\n@manager.command\ndef drop_db():\n '''\n Drops database according to scrapper/config/server.py.\n '''\n from scrapper.config.default import SQLALCHEMY_DATABASE_URI as db_url\n\n if database_exists(db_url):\n drop_database(db_url)\n print(\"Done\")\n else:\n print(\"Database doesn't exist\")\n exit(1)\n\nif __name__==\"__main__\":\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"47350369","text":"'''\nCreated on May 30, 2013\n\n@package: ally core http\n@copyright: 2011 Sourcefabric o.p.s.\n@license: http://www.gnu.org/licenses/gpl-3.0.txt\n@author: Gabriel Nistor\n\nProvides the paths adjustments for update invokers.\n'''\n\nfrom ally.api.operator.type import TypeModel, TypeProperty\nfrom ally.design.processor.attribute import requires, defines\nfrom ally.design.processor.context import Context\nfrom ally.design.processor.execution import Abort\nfrom ally.design.processor.handler import HandlerProcessor\nfrom ally.http.spec.server import HTTP_PUT\nimport logging\n\n# --------------------------------------------------------------------\n\nlog = logging.getLogger(__name__)\n\n# --------------------------------------------------------------------\n\nclass Register(Context):\n '''\n The register context.\n '''\n # ---------------------------------------------------------------- Required\n invokers = requires(list)\n \nclass Invoker(Context):\n '''\n The invoker context.\n '''\n # ---------------------------------------------------------------- Defined\n path = defines(list)\n # ---------------------------------------------------------------- Required\n methodHTTP = requires(str)\n target = requires(TypeModel)\n location = requires(str)\n \nclass ElementUpdate(Context):\n '''\n The element context.\n '''\n # ---------------------------------------------------------------- Defined\n name = defines(str)\n property = defines(TypeProperty)\n isInjected = defines(bool, doc='''\n @rtype: boolean\n If True indicates that the path element is actually to be injected inside a model entity.\n ''')\n # ---------------------------------------------------------------- Required\n model = requires(TypeModel)\n \n# --------------------------------------------------------------------\n\nclass PathUpdateHandler(HandlerProcessor):\n '''\n Implementation for a processor that provides the invoker adjustments for updates.\n '''\n \n def __init__(self):\n super().__init__(Invoker=Invoker)\n\n def process(self, chain, register:Register, Element:ElementUpdate, **keyargs):\n '''\n @see: HandlerProcessor.process\n \n Provides the paths adjustments based on target models.\n '''\n assert isinstance(register, Register), 'Invalid register %s' % register\n assert issubclass(Element, ElementUpdate), 'Invalid element %s' % Element\n if not register.invokers: return\n\n aborted = []\n for invoker in register.invokers:\n assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\n if invoker.methodHTTP != HTTP_PUT: continue\n if not invoker.target: continue\n assert isinstance(invoker.target, TypeModel), 'Invalid target %s' % invoker.target\n if not invoker.target.propertyId: continue\n \n if invoker.path is None: invoker.path = []\n for el in invoker.path:\n assert isinstance(el, ElementUpdate), 'Invalid element %s' % el\n if el.model == invoker.target:\n log.error('Cannot use for update because the %s is already present as input, at:%s',\n invoker.target, invoker.location)\n aborted.append(invoker)\n break\n else:\n invoker.path.append(Element(name=invoker.target.name, model=invoker.target))\n invoker.path.append(Element(property=invoker.target.propertyId, isInjected=True))\n\n if aborted: raise Abort(*aborted)\n \n","sub_path":"components/ally-core-http/ally/core/http/impl/processor/assembler/path_for_update.py","file_name":"path_for_update.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"523218819","text":"import httplib2\nimport os\n\nfrom bs4 import BeautifulSoup as soup\n# import requests\nimport re\n\nimport pytz\nfrom datetime import datetime as dt\nfrom datetime import timedelta\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\n\nfrom googleapiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\nSCOPES = 'https://www.googleapis.com/auth/calendar'\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'UKY Schedule Webscrape'\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'uky-web-scrape-calendar.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\neventIdList = []\ncalendarId = 'primary'\n# calendarId = 'un1nmhba2l7vfm5vvie66m6nrk@group.calendar.google.com'\n\ndef getService():\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n return discovery.build('calendar', 'v3', http=http)\n\ndef main():\n choiceText = \"\\n1. Add\\n2. Delete\\n3. Exit\\nChoice: \"\n choice = int(input(choiceText))\n\n while choice == 1 or choice == 2:\n if choice == 1:\n add()\n # elif choice == 2:\n # delete()\n choice = int(input(choiceText))\n\n exit()\n\ndef add():\n # url = 'https://myuk.uky.edu/zAPPS/CourseCatalog/Schedule/Print/2018/010'\n # res = requests.get(url)\n # page_html = res.text\n # page_soup = soup(page_html, \"html.parser\")\n # print(page_soup)\n\n fileName = \"calendar.html\"\n page_html = open(fileName, 'r').read()\n page_soup = soup(page_html, \"html.parser\")\n\n # httplib2.debuglevel = 4\n service = getService()\n\n six_months = date.today() + relativedelta(months=+6)\n year = str(six_months.year)\n\n timeZone = \"America/New_York\"\n\n courses = page_soup.findAll(\"div\", {\"class\": \"table-thin-row small\"})\n\n for course in courses:\n title = \" \".join(course.find(\"strong\", {\"class\": \"text-dark\"}).text.split())\n section = course.findAll(\"div\")[4].text\n courseType = course.findAll(\"div\")[5].text.strip()\n\n p = re.compile(r'Section ')\n newSection = p.sub(\"\", section)\n summary = title + \" - \" + newSection\n\n weekdays = course.findAll(\"div\")[7].text\n if weekdays == \"TBD\": # for online classes that do not have a time or location\n continue\n\n hour = course.findAll(\"div\")[8].text\n dates = course.findAll(\"div\")[9].text.strip()\n\n hourList = hour.split(\" - \")\n datesList = dates.split(\"-\")\n googleDateTimeList = []\n for i in range(0, len(datesList)):\n h = ''.join(hourList[i].split(\" \"))\n new_time = dt.strptime(h, '%I:%M%p').strftime(\"%H:%M\")\n new_time += \":00\"\n unformattedTime = datesList[0] + \" \" + year + \" \" + new_time\n naive = dt.strptime(unformattedTime, '%b %d %Y %H:%M:%S')\n local = pytz.timezone(timeZone)\n local_dt = local.localize(naive, is_dst=None)\n googleDateTimeList.append(local_dt.strftime(\"%Y-%m-%d\"+\"T\"+\"%H:%M:%S\"+\"-05:00\"))\n googleDateTimeStart = googleDateTimeList[0]\n googleDateTimeEnd = googleDateTimeList[1]\n\n classEndTime = ''.join(hourList[1].split(\" \"))\n new_time = dt.strptime(classEndTime, '%I:%M%p').strftime(\"%H:%M\")\n new_time += \":00\"\n unformattedTime = datesList[1] + \" \" + year + \" \" + new_time\n naive = dt.strptime(unformattedTime, '%b %d %Y %H:%M:%S')\n naive += timedelta(hours=48) # make two days ahead because recurrence is inclusive of end time\n local = pytz.timezone(timeZone)\n local_dt = local.localize(naive, is_dst=None)\n until = local_dt.strftime(\"%Y%m%d\"+\"T\"+\"%H%M%S\"+\"Z\")\n\n weekdays = list(weekdays)\n days = \"\"\n for char in weekdays:\n if char == 'M': days += \"MO\"\n elif char == 'T': days += \"TU\"\n elif char == 'W': days += \"WE\"\n elif char == 'R': days += \"TH\"\n else: days += \"FR\"\n days += \",\"\n days = days[:-1] # remove last comma\n\n recurrence = \"RRULE:FREQ=WEEKLY;UNTIL={};BYDAY={}\".format(until, days)\n\n building = course.findAll(\"div\")[11].text\n room = course.findAll(\"div\")[12].text\n location = building + \" \" + room\n\n instuctor = course.findAll(\"div\")[13].text.strip()\n\n description = courseType + \"\\n\" + instuctor\n\n event = {\n 'summary': summary,\n 'location': location,\n 'description': description,\n 'start': {\n 'dateTime': googleDateTimeStart,\n 'timeZone': timeZone,\n },\n 'end': {\n 'dateTime': googleDateTimeEnd,\n 'timeZone': timeZone,\n },\n 'recurrence': [\n recurrence\n ]\n }\n event = service.events().insert(calendarId=calendarId, body=event).execute()\n print('Event created for {}: {}'.format(title, event.get('htmlLink')))\n\n # eventURL = event.get('htmlLink')\n # eventIdIndex = eventURL.rfind(\"=\")\n # eventId = eventURL[eventIdIndex+1:]\n # eventIdList.append(eventId)\n\n# def delete():\n# service = getService()\n# for id in eventIdList:\n# event = service.events().delete(calendarId=calendarId, eventId=id).execute()\n# print(event)\n\nif __name__ == '__main__':\n main()\n","sub_path":"ws.py","file_name":"ws.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"172967969","text":"\n\nfrom ui.equip_ui import *\n\n\nclass Equip3(Equip_UI):\n\n def __init__(self,parent=None):\n super(Equip3,self).__init__(parent)\n paths = gol.get_value('monitor_filepath', \"E:\\\\DR\\\\\")\n self.watcher=QFileSystemWatcher()\n if isinstance(paths,list):\n self.watcher.addPaths(paths)\n else :\n self.watcher.addPath(paths)\n\n self.watcher.directoryChanged.connect(self.mes)\n # self.filemonitor.directoryChanged.connect(self.newfile)\n\n\n def mes(self,p_str):\n print(p_str)\n print(self.watcher.files())\n print(self.watcher.directories())\n\n\n\n\n\nif __name__ == '__main__':\n from utils.envir import *\n set_env()\n from ui.tj_main_ui import *\n app = QApplication(sys.argv)\n ui = Equip3()\n ui.show()\n #ui.showFullScreen()\n app.exec_()","sub_path":"filemonitor.py","file_name":"filemonitor.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"515174037","text":"from __future__ import print_function\nimport os\nimport pandas as pd\nimport xgboost as xgb\nimport time\n\nimport shutil\nfrom sklearn import preprocessing\nfrom sklearn.cross_validation import train_test_split\nimport numpy as np\nfrom sklearn.utils import shuffle\nfrom sklearn import metrics\ndef archive_results(filename,results,algo,script):\n \"\"\"\n :type algo: basestring\n :type script: basestring\n :type results: DataFrame\n \"\"\"\n #assert results == pd.DataFrame\n now=time.localtime()[0:5]\n dirname='../archive'\n subdirfmt='%4d-%02d-%02d-%02d-%02d'\n subdir=subdirfmt %now\n if not os.path.exists(os.path.join(dirname,str(algo))):\n os.mkdir(os.path.join(dirname,str(algo)))\n dir_to_create=os.path.join(dirname,str(algo),subdir)\n if not os.path.exists(dir_to_create):\n os.mkdir(dir_to_create)\n os.chdir(dir_to_create)\n\n results.to_csv(filename,index=False,float_format='%.6f')\n shutil.copy2(script,'.')\n\n return\n\n###############################################################################################\n\ndef preprocess_data(train,test):\n id_test=test['patient_id']\n\n train=train.drop(['patient_id'],axis=1)\n test=test.drop(['patient_id'],axis=1)\n #train=train.drop_duplicates()\n y=train['is_screener']\n train=train.drop(['is_screener'],axis=1)\n\n\n for f in train.columns:\n if train[f].dtype == 'object':\n print(f)\n lbl = preprocessing.LabelEncoder()\n lbl.fit(list(train[f].values) + list(test[f].values))\n train[f] = lbl.transform(list(train[f].values))\n test[f] = lbl.transform(list(test[f].values))\n\n return id_test,test,train,y\n\nos.chdir(os.getcwd())\ntrainfile=('../input/patients_train.csv.gz')\ntestfile=('../input/patients_test.csv.gz')\nsurgical_file=('../input/surgical_selected_last.csv.gz')\nactivity_file=('../input/activity_selected_last.csv.gz')\ndiagnosis_file=('../input/diagnosis_selected_last.csv.gz')\nprocedure_file=('../input/procedure_selected_last.csv.gz')\nprescription_file=('../input/prescription_selected_last.csv.gz')\nphysicians_file=('../input/physicians.csv.gz')\ndrugs_file=('../input/drugs.csv.gz')\n\ntrain=pd.read_csv(trainfile,low_memory=False )\ntest=pd.read_csv(testfile,low_memory=False )\n\n##prepare a sparse matrix#\ntrain_ex_file=('../input/train_patients_to_exclude.csv.gz')\ntrain_ex=pd.read_csv(train_ex_file,low_memory=False)\ntrain=train[train.patient_id.isin(train_ex.patient_id)==False]\ntest_ex_file=('../input/test_patients_to_exclude.csv.gz')\ntest_ex=pd.read_csv(test_ex_file,low_memory=False)\ntest=test[test.patient_id.isin(test_ex.patient_id)==False]\nprint(train.shape,test.shape)\n\nsurgical=pd.read_csv(surgical_file )\ntrain=pd.merge(train,surgical, on='patient_id',how='left')\ntest=pd.merge(test,surgical, on='patient_id',how='left')\nprint('after merging surgical')\nprint(train.shape,test.shape)\n\nactivity=pd.read_csv(activity_file )\ntrain=pd.merge(train,activity, on='patient_id',how='left')\ntest=pd.merge(test,activity, on='patient_id',how='left')\nprint('after merging activity')\nprint(train.shape,test.shape)\nprescription=pd.read_csv(prescription_file)\ndrugs=pd.read_csv(drugs_file)\nphysicians=pd.read_csv(physicians_file)\nprescription=pd.merge(prescription,drugs, left_on='patient_id',right_on='drug_id',how='left')\nprescription=pd.merge(prescription,physicians, left_on='patient_id',right_on='practitioner_id',how='left')\ntrain=pd.merge(train,prescription,on='patient_id',how='left')\ntest=pd.merge(test,prescription,on='patient_id',how='left')\nprint('after merging prescription ')\nprint(train.shape,test.shape)\n\nprocedure=pd.read_csv(procedure_file )\ndiagnosis=pd.read_csv(diagnosis_file)\ntrain=pd.merge(train,procedure,on='patient_id',how='left')\ntest=pd.merge(test,procedure,on='patient_id',how='left')\nprint('after merging procedure')\nprint(train.shape,test.shape)\ntrain=pd.merge(train,diagnosis, on='patient_id',how='left')\ntest=pd.merge(test,diagnosis, on='patient_id',how='left')\nprint('after merging diagnosis ')\nprint(train.shape,test.shape)\n\n\ntrain=train.fillna(0)\ntest=test.fillna(0)\n\nid_test,test,train,y=preprocess_data(train,test)\nprint(train.shape,test.shape)\n#print(train.columns)\n\nX=np.asarray(train)\ny=np.asarray(y)\nX_test=np.asarray(test)\nX,y=shuffle(X,y,random_state=9)\nX_train,X_val0,y_train,y_val0 = train_test_split(X,y,test_size=0.1,random_state=17)\nX_train,X_val,y_train,y_val = train_test_split(X_train,y_train,test_size=0.1,random_state=77)\n\n#from sklearn import preprocessing,decomposition\n#scl=decomposition.PCA(n_components=None,whiten=False)\n#scl=preprocessing.RobustScaler()\n#X_train=scl.fit_transform(X_train)\n#X_val=scl.transform(X_val)\n#X_test=scl.transform(X_test)\n#X_val0=scl.transform(X_val0)\n\ndval=xgb.DMatrix(data=X_val,label=y_val)\ndtrain=xgb.DMatrix(data=X_train,label=y_train)\nDTest=xgb.DMatrix(data=X_test)\nDval0=xgb.DMatrix(data=X_val0)\nwatchlist = [(dval,'eval'), (dtrain,'train')]\n\nparams = {\"objective\": \"binary:logistic\",\n \"eta\": 0.023,\n \"eta_decay\":0.5,\n \"max_depth\": 6,\n \"silent\":1,\n \"subsample\": 0.9,\n \"colsample_bytree\": 0.65,\n \"seed\": 1193,\n \"booster\": \"gbtree\",\n \"nthread\":6,\n \"eval_metric\":'auc'\n }\n#\nclf = xgb.train(params, dtrain, num_boost_round=1000, evals=watchlist, early_stopping_rounds=30,verbose_eval=True,\n maximize= True)\n\npredictions=clf.predict(DTest)\nscore=clf.best_score\nprint('best score:%s'%score)\ny_pred=clf.predict(Dval0)\n\nscore=metrics.roc_auc_score(y_val0, y_pred)\nprint('score on extra set:%s' %score)\nmodel='XGBOOST_onselected'\n#\n# predict on test set\nsubmission='%s_score_%03f.csv' %(model,score)\n# create submission file\n\npreds = pd.DataFrame({\"patient_id\": id_test, 'predict_screener': predictions})\nresults=preds.groupby(['patient_id'])['predict_screener'].mean()\nidx=preds.groupby(['patient_id'])['patient_id'].mean().astype(int)\ntest_ex['predict_screener']=0.0\n\n# Create your first submission file\nxgb_preds0 = pd.DataFrame({\"patient_id\": idx, \"predict_screener\": results})\nxgb_preds=pd.concat([xgb_preds0,test_ex],axis=0)\nxgb_preds.to_csv('../output/'+submission,index=False)\nscript=os.path.abspath(__file__)\nprint (script)\nranking=0.75\nprint ('score= %03f'%score)\nif score>ranking:\n print('score is higher than %s'%ranking)\n archive_results(submission,xgb_preds,model,script)\n","sub_path":"cervical-cancer-screening/models/src/XGBFull-selected.py","file_name":"XGBFull-selected.py","file_ext":"py","file_size_in_byte":6372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"97202044","text":"import mysql.connector\nimport csv\nimport time\nimport sys\nimport logging\n\nformat = \"%(asctime)s: %(levelname)s: %(funcName)s Line:%(lineno)d %(message)s\"\nlogging.basicConfig(filename=\"log_Py.log\", level=logging.INFO, filemode=\"a\", format=format)\n'''logger = logging.getLogger(\"meinLogger\")\nlogger.setLevel(logging.DEBUG)\nfileh = logging.FileHandler(\"log.txt\")\nform = logging.Formatter('%(name)s - %(levelname)s : %(asctime)s - %(message)s')\nfileh.setFormatter(form)\nlogger.addHandler(fileh)\nlogger.debug(\"debugging\")'''\n\ndef time_fun(sec):\n time.sleep(sec)\n\n\ndef help_function():\n print(\"You need help? Hear is my support :)\")\n print(\"You can always write a word or a sentence, what describe your intention. For example delete column or make a new table.\")\n logging.info(\"Help function was activated\")\n\n\ndef Server_connection():\n print(\"Please enter the connection data:\")\n logging.info(\"Rhe user try to connect to the server\")\n\n global connection\n condition = True\n while condition:\n try:\n host = input(\"Please input the host name: \")\n user = input(\"Please input the user name: \")\n password = input(\"Please input the password: \")\n # database = input(\"Please input the database name: \")\n\n stop_to_repeat = True\n\n while stop_to_repeat:\n\n connection = mysql.connector.connect(host=host,\n user=user,\n password=password\n )\n global mycursor\n mycursor = connection.cursor(buffered=True)\n\n print(\"\")\n mycursor.execute(\"SHOW DATABASES\")\n print(\"Databases: \")\n for db in mycursor:\n print(db)\n\n print(\"\")\n\n num = True\n while num:\n try:\n print(\"1. Connect with a database\\n\"\n \"2. Make a new database\")\n answer = int(input(\"Please answer with 1 or 2: \"))\n if answer == 1 or answer == 2:\n if answer == 2:\n name_of_databse = input(\"Name of the new database: \")\n\n sqlform = \"CREATE DATABASE \" + name_of_databse\n mycursor.execute(sqlform)\n else:\n database = input(\"Please enter the database name: \")\n connection = mysql.connector.connect(host=host,\n user=user,\n password=password,\n database=database)\n mycursor = connection.cursor(buffered=True)\n stop_to_repeat = False\n\n num = False\n\n except:\n print(\"Please answer with a number 1 or 2!\")\n logging.error(\"An error with number input\")\n\n if (connection):\n print(\"Connection successful\")\n condition = False\n time_fun(1)\n\n except:\n print(\"Not connected\")\n logging.critical(\"The logging information was not correct\")\n\n\ndef table_make():\n condition = True\n print(\"Not forget, your table must have at least 1 column\")\n\n while condition:\n try:\n tableN = input(\"Please enter the name of the new table: \")\n columns = int(input(\"How many columns do you want to make: \"))\n i = 0\n\n while i < columns:\n columnsN = input(\"Please enter the columns name: \")\n columnsT = input(\"Please enter the columns type: \")\n i = i + 1\n\n if i == 1:\n sqlform = \"CREATE TABLE \" + tableN + \"(\" + columnsN + \" \" + columnsT + \")\"\n else:\n sqlform = \"ALTER TABLE \" + tableN + \" ADD \" + columnsN + \" \" + columnsT\n\n mycursor.execute(sqlform)\n if i == columns:\n condition = False\n\n except:\n print(\"Please try again!\")\n\n\ndef table_delete():\n try:\n tableN = input(\"Please enter the table name: \")\n\n sqlform = \"DROP TABLE \" + tableN\n\n mycursor.execute(sqlform)\n except:\n print(\"Please check if the table really exist!\")\n\n\ndef show_table():\n sqlformp = \"SHOW TABLES\"\n mycursor.execute(sqlformp)\n\n for tb in mycursor:\n print(tb)\n\n\ndef columns_make():\n try:\n tableN = input(\"Please enter the table name:\")\n\n columns = int(input(\"How many columns do you want to make: \"))\n i = 0\n\n while i < columns:\n columnsN = input(\"Please enter the columns name: \")\n columnsT = input(\"Please enter the columns type: \")\n\n sqlform = \"ALTER TABLE \" + tableN + \" ADD \" + columnsN + \" \" + columnsT\n\n mycursor.execute(sqlform)\n i = + 1\n except:\n print(\"Please make sure that you gave the correct input!\")\n\n\ndef columns_drop():\n try:\n tableN = input(\"Please input the name of the table:\")\n columnN = input(\"Please enter the name of the column you want to delete: \")\n\n sqlform = \"ALTER TABLE \" + tableN + \" DROP COLUMN \" + columnN\n\n mycursor.execute(sqlform)\n except:\n print(\"Please make sure that you gave correct input or if the column exist!\")\n\n\ndef show_columns():\n try:\n tableN = input(\"Please enter the table name: \")\n\n sqlform = \"SHOW COLUMNS FROM \" + tableN\n\n mycursor.execute(sqlform)\n\n for tb in mycursor:\n print(tb)\n except:\n print(\"Please make sure that the input is correct!\")\n\n\ndef addition_to_table():\n try:\n tableN = input(\"Please enter the name of the table:\")\n sqlform = \"SHOW COLUMNS FROM \" + tableN\n mycursor.execute(sqlform)\n\n columnN = input(\"Please enter the name of the column, which you want to add the information: \")\n\n addition_text = input(\"Pleas enter what you want to add to the \" + columnN + \": \")\n\n if addition_text.isdigit():\n sqlform = \"INSERT INTO \" + tableN + \" (\" + columnN + \")\" + \"VALUES\" + \"(\" + addition_text + \")\"\n else:\n sqlform = \"INSERT INTO \" + tableN + \" (\" + columnN + \")\" + \"VALUES\" + \"(\\\"\" + addition_text + \"\\\")\"\n\n mycursor.execute(sqlform)\n connection.commit()\n\n except:\n print(\"Please make sure that the input is correct!\")\n\n ''' i = 0\n for tb in mycursor:\n print(tb)\n i = +1\n '''\n\n ''' t = 0\n b = 0\n more = True\n\n while more:\n while t < i - 1:\n more_info = input(\n \"Do you want to add information to another column in the same row? you can write the column name or 0 for no: \")\n\n more = False\n else:\n column_2 = input(\"Pleas enter the column name: \")\n b =+ 1\n '''\n\n ''' \n if b == 1:\n addition_text_one = input(\"Pleas enter what you want to add to the \" + columnN + \": \")\n addition_text_tow = input(\"Pleas enter what you want to add to the \" + columnN + \": \")\n \n if addition_text_one.isdigit():\n sqlform = \"INSERT INTO \" + tableN + \" (\" + columnN + \")\" + \"VALUES\" + \"(\" + addition_text + \")\"\n else:\n sqlform = \"INSERT INTO \" + tableN + \" (\" + columnN + \")\" + \"VALUES\" + \"(\\\"\" + addition_text + \"\\\")\"\n\n '''\n\n\ndef alter_some_inTable():\n tableN = input(\"Please enter the name of the table: \")\n sqlform = \"SHOW COLUMNS FROM \" + tableN\n mycursor.execute(sqlform)\n\n columnN = input(\"Please enter the name of the column, which you want to add information: \")\n add_to_column = input(\"Pleas enter what you want to add: \")\n\n columnC = input(\"Please enter the name of the column for the condition: \")\n condition_text = input(\"Please enter the condition: \")\n\n sqlform = \"UPDATE \" + tableN + \" SET \" + columnN + \"= %s WHERE \" + columnC + \"= %s\"\n values = (add_to_column, condition_text)\n\n mycursor.execute(sqlform, values)\n connection.commit()\n\n\ndef delete_from_table():\n try:\n tableN = input(\"Please input the name of the table:\")\n columnN = input(\"Please enter the name of the column: \")\n delete_item = input(\"Pleas enter what you want to delete: \")\n\n sqlform = \"DELETE FROM \" + tableN + \" WHERE \" + columnN + \"=\" + delete_item\n mycursor.execute(sqlform)\n connection.commit()\n except:\n print(\"Please make sure that the input is correct!\")\n\n\ndef show_data():\n global tableNS\n tableNS = input(\"Please enter tne table name: \")\n\n sqlform = \"SELECT * FROM \" + tableNS\n\n mycursor.execute(sqlform)\n\n global res\n res = mycursor.fetchall()\n\n for row in res:\n print(row)\n\n\ndef save_data():\n with open(\"mydata.txt\", \"a\") as file:\n file.write(\"The table \" + tableNS + \"H has: \\n\")\n for row in res:\n csv.writer(file).writerow(row)\n\n\ndef end_fun():\n print(\"That was fun with you :). I hope i see you again.\")\n sys.exit(0)\n\n\ndef switch_function(num):\n if num == \"0\" or num == \"end\" or num == \"exit\":\n end_fun()\n if num == \"1\" or num == \"show the tables\" or num == \"tables\" or num == \"tables show\":\n show_table()\n elif num == \"2\" or num == \"make a table\" or num == \"table make\" or num == \"make a new table\":\n table_make()\n elif num == \"3\" or num == \"delete a table\" or num == \"table delete\":\n table_delete()\n\n elif num == \"4\" or num == \"show the columns\" or num == \"columns\" or num == \"columns show\":\n show_columns()\n elif num == \"5\" or num == \"make a column\" or num == \"column make\" or num == \"make a new column\":\n columns_make()\n elif num == \"6\" or num == \"delete a column\" or num == \"column delete\":\n columns_drop()\n\n elif num == \"7\" or num == \"show the data\" or num == \"data\" or num == \"data show\":\n show_data()\n save_data()\n elif num == \"8\" or num == \"add\" or num == \"add something\" or num == \"something add\":\n addition_to_table()\n elif num == \"9\":\n alter_some_inTable()\n elif num == \"10\" or num == \"delete something\" or num == \"something delete\":\n delete_from_table()\n\n elif num == \"11\" or num == \"help\" or num == \"help me\" or num == \"-help\" or num == \"--help\":\n help_function()\n","sub_path":"py_Main_Programm/py_Programm_Classes.py","file_name":"py_Programm_Classes.py","file_ext":"py","file_size_in_byte":10819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"98815417","text":"def is_palindrome(value):\n middle_value = len(value)//2\n\n match = 0\n\n for i in range(0, middle_value):\n for j in range(-1, -middle_value-1, -1):\n if value[i] == value[j]:\n match += 1\n\n if match == len(value)//2:\n return True\n\n else:\n return False\n\n\ndef get_chinese_zodiac():\n zodiac_reference = {1: \"Rat\", 2: \"Ox\", 3: \"Tiger\", 4: \"Rabbit\", 5: \"Dragon\", 6: \"Snake\",\n 7: \"Horse\", 8: \"Goat\", 9: \"Monkey\", 10: \"Rooster\", 11: \"Dog\", 12: \"Pig\"}\n\n return [[i, zodiac_reference[(i%12)+1]] for i in range(1900, 2021)]\n\nif __name__ == \"__main__\":\n print(get_chinese_zodiac())\n","sub_path":"csc_336_data_structures/exercises/01_27_exercises.py","file_name":"01_27_exercises.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"455498172","text":"\"\"\"Plot the spanwise-averaged z-vorticity at saved time steps.\"\"\"\n\nfrom matplotlib import pyplot\nimport numpy\nimport pathlib\nimport yaml\n\nimport petibmpy\n\n\nsimudir = pathlib.Path(__file__).absolute().parents[1]\ndatadir = simudir / 'output' / 'postprocessing' / 'wz_avg'\n\n# Read the gridline coordinates from file.\nfilepath = datadir / 'grid.h5'\nx, y = petibmpy.read_grid_hdf5(filepath, 'wz-avg')\n\n# Read the boundary coordinates from file.\nfilepath = simudir / 'snake3d35.body'\nxb, yb, zb = petibmpy.read_body(filepath, skiprows=1)\n# Keep only a 2D cross-section.\nn = len(numpy.where(zb == zb[0])[0])\nxb, yb = xb[:n], yb[:n]\n\n# Get temporal parameters.\nfilepath = simudir / 'config.yaml'\nwith open(filepath, 'r') as infile:\n config = yaml.load(infile, Loader=yaml.FullLoader)['parameters']\ndt, nstart, nt, nsave = (config[k] for k in ['dt', 'startStep', 'nt', 'nsave'])\ntimesteps = list(range(nstart, nstart + nt + 1, nsave))\n\n# Create the directory to save the figures.\nfigdir = simudir / 'figures'\nfigdir.mkdir(parents=True, exist_ok=True)\n\n# Initialize the figure and axis.\npyplot.rc('font', family='serif', size=16)\nfig, ax = pyplot.subplots(figsize=(8.0, 4.0))\nax.set_xlabel('x')\nax.set_ylabel('y')\ntext = ax.text(-0.5, 0.8, '',\n bbox=dict(facecolor='white', edgecolor='white'), zorder=5)\nax.fill(xb, yb, color='black', zorder=10)\nlevels = numpy.linspace(-5.0, 5.0, num=50)\ncont = None\nax.axis('scaled', adjustable='box')\nax.set_xlim(-0.6, 4.5)\nax.set_ylim(-1.0, 1.0)\nfig.tight_layout()\n\n# Generate the filled contour at each saved time step.\nfor timestep in timesteps:\n print('[time step {:0>7}] Generating the figure...'.format(timestep))\n filepath = datadir / '{:0>7}.h5'.format(timestep)\n wz = petibmpy.read_field_hdf5(filepath, 'wz-avg')\n text.set_text('t = {}'.format(timestep * dt))\n if cont is not None:\n for collection in cont.collections:\n fig.gca().collections.remove(collection)\n cont = ax.contourf(x, y, wz, levels=levels, extend='both', zorder=0)\n filepath = figdir / 'wz_avg_wake2d_{:0>7}.png'.format(timestep)\n fig.savefig(filepath)\n","sub_path":"runs/snake/3d/1k35/scripts/plot_wz_avg_wake2d_pyplot.py","file_name":"plot_wz_avg_wake2d_pyplot.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"609436098","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def oddEvenList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head == None:\n return head\n ou_head = head.next\n ji_zhi = head\n ou_zhi = head.next\n while ji_zhi or ou_zhi:\n if ou_zhi==None or ou_zhi.next==None:\n ji_zhi.next = ou_head\n return head\n ji_zhi.next = ou_zhi.next\n ji_zhi = ji_zhi.next\n ou_zhi.next = ji_zhi.next\n ou_zhi = ou_zhi.next\n","sub_path":"算法面试题汇总/4链表/8奇偶链表-第一版.py","file_name":"8奇偶链表-第一版.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"89761717","text":"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ncols = ['LSTAT', 'PTRATIO', 'RM', 'MEDV'] # housing price dataset\ncm = np.corrcoef(data[cols].values.T)\nsns.set(font_scale=1.5)\nhm = sns.heatmap(cm,\n cbar=True,\n annot=True,\n square=True,\n fmt='.2f',\n annot_kws={'size': 15},\n yticklabels=cols,\n xticklabels=cols)\n\nplt.show()\n","sub_path":"lessons/snippets/heat_map.py","file_name":"heat_map.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"411070712","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nimport collections\nfrom typing import List\n\n\nclass Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n\n n = len(nums)\n indices = collections.defaultdict(list)\n xMin, xMax = 10 ** 9, -10 ** 9\n for i, vec in enumerate(nums):\n for x in vec:\n indices[x].append(i)\n xMin = min(xMin, *vec)\n xMax = max(xMax, *vec)\n\n # 记录频次\n freq = [0] * n\n\n inside = 0\n left, right = xMin, xMin - 1\n bestLeft, bestRight = xMin, xMax\n\n while right < xMax:\n right += 1\n if right in indices:\n for x in indices[right]:\n freq[x] += 1\n if freq[x] == 1:\n inside += 1\n while inside == n:\n if right - left < bestRight - bestLeft:\n bestLeft, bestRight = left, right\n if left in indices:\n for x in indices[left]:\n freq[x] -= 1\n if freq[x] == 0:\n inside -= 1\n left += 1\n\n return [bestLeft, bestRight]\n\n\nif __name__ == '__main__':\n s = Solution()\n nums = [[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]]\n print(s.smallestRange(nums))\n","sub_path":"备考/632.py","file_name":"632.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"142745232","text":"import socket\n\nBUFSIZE = 1024\nip_port = ('127.0.0.1', 8011)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nres = s.connect_ex(ip_port)\n\ns.send('hello'.encode('utf-8'))\ns.send('feng'.encode('utf-8'))\n","sub_path":"project/python_fullstack/day19/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"544630916","text":"import pygame, math\nfrom pygame.sprite import Sprite\nfrom pygame.locals import *\n\nclass Ship(Sprite):\n def __init__(self, contenedor):\n Sprite.__init__(self)\n self.angulo = 0\n self.puntos = 0\n self.vida = 100\n self.vel = [0,0]\n self.contenedor = contenedor\n self.base_image = pygame.image.load(\"imagenes/ship.png\")\n self.image = self.base_image\n self.rect = self.image.get_rect()\n self.rect.move_ip(contenedor[0]/2, contenedor[1]/2)\n \n def update(self):\n teclas = pygame.key.get_pressed()\n if teclas[K_LEFT]:\n self.rotar(2)\n elif teclas[K_RIGHT]:\n self.rotar(-2)\n elif teclas[K_UP]:\n self.acelerar()\n elif teclas[K_DOWN]:\n pass\n \n self.vel[0] *= 0.99\n self.vel[1] *= 0.99\n self.rect = self.rect.move(self.vel)\n self.rect.x = self.rect.x % self.contenedor[0]\n self.rect.y = self.rect.y % self.contenedor[1]\n \n def acelerar(self):\n self.vel[0] += math.cos(math.radians((self.angulo)%360))\n self.vel[1] -= math.sin(math.radians((self.angulo)%360))\n\n def rotar(self, angulo):\n self.angulo += angulo\n centerx = self.rect.centerx\n centery = self.rect.centery\n self.image = pygame.transform.rotate(self.base_image, self.angulo)\n self.rect = self.image.get_rect() \n self.rect.centerx = centerx\n self.rect.centery = centery\n","sub_path":"ejercicio05/asteroids_002/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"553205580","text":"import pygame\r\nimport random\r\nimport animation \r\nclass Monster(animation.AnimateSprite):\r\n def __init__(self,game, name,size, offset=0):\r\n super().__init__(name,size)\r\n self.game = game\r\n self.health = 100\r\n self.max_health = 100\r\n self.attack = 0.3\r\n self.rect = self.image.get_rect()\r\n self.rect.x = 1000 + random.randint(0,300)\r\n self.rect.y = 500 - offset\r\n self.velocity = random.randint(1,2)\r\n self.start_animation()\r\n self.loot_amount = 10\r\n\r\n def set_loot_amount(self,amount):\r\n self.loot_amount = amount\r\n\r\n def set_speed(self, speed):\r\n self.default_speed = speed\r\n self.velocity = random.randint(1,3)\r\n\r\n def damage(self,amount):\r\n #infliger les degats\r\n self.health -= amount\r\n #vérifier si le nb de points de vie est inférieur ou égal à 0\r\n if self.health <= 0:\r\n self.rect.x = 1000 + random.randint(0,300)\r\n self.velocity = random.randint(1,self.default_speed)\r\n self.health = self.max_health\r\n #incrementer le score\r\n self.game.add_score(20)\r\n\r\n #si la barre d'event est chargé à son maxi on ne fait pas repop les monstres\r\n if self.game.comet_event.is_full_loaded():\r\n #retirer du jeu\r\n self.game.all_monsters.remove(self)\r\n\r\n #appel de la méthode pour essayer de déclencher la pluie de cometes\r\n self.game.comet_event.attempt_fall()\r\n\r\n def update_health_bar(self,surface):\r\n #définir une couleur pour une jauge de vie\r\n bar_color = (111,210,46)\r\n #définir une couleur pour l'arriere plan de la jauge (gris foncé)\r\n back_bar_color = (60, 63, 60)\r\n\r\n #definir la position de notre jauge de vie ainsi que sa largeur et son épaisseur\r\n bar_position = [self.rect.x + 10, self.rect.y - 20, self.health, 5]\r\n\r\n #definir la position de l'arrière plan de notre jauge de vie \r\n back_bar_position = [self.rect.x + 10, self.rect.y - 20, self.max_health, 5]\r\n\r\n # dessiner notre barre de vie\r\n pygame.draw.rect(surface, back_bar_color, back_bar_position)\r\n pygame.draw.rect(surface, bar_color, bar_position)\r\n\r\n def update_animation(self):\r\n self.animate(loop=True)\r\n \r\n def forward(self):\r\n #le deplacement ne se fait que si il ny'a pas de collision avec un groupe de joueur\r\n if not self.game.check_collision(self, self.game.all_players):\r\n self.rect.x -= self.velocity\r\n #si le monstre est en collision avec le joueur\r\n else:\r\n #infliger des degats\r\n self.game.player.damage(self.attack)\r\n\r\n#définir une class pour les mobs\r\nclass BadWorm(Monster):\r\n def __init__(self,game):\r\n super().__init__(game,\"bad_worms\", (130,130))\r\n self.set_speed(3)\r\n self.set_loot_amount(20)\r\n#définir une class pour le boss\r\nclass Boss(Monster):\r\n def __init__(self,game):\r\n super().__init__(game,\"boss\", (300,300), 130)\r\n self.health = 250\r\n self.max_health = 250\r\n self.attack = 0.8\r\n self.set_speed(1)\r\n self.set_loot_amount(50)\r\n\r\n","sub_path":"monster.py","file_name":"monster.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"165743701","text":"import argparse\nimport os\nimport shutil\nimport sys\n\nimport yaml\n\ntry:\n sys.path.append(os.getcwd())\n from src.log import log\n from src.patch.updater import Updater\n from src.utils import Util\nexcept ModuleNotFoundError as e:\n raise e\n\n\ndef save_file(path, config):\n try:\n yaml_dumper = yaml.CDumper\n except Exception:\n yaml_dumper = yaml.Dumper\n with open(path, 'wb') as f:\n f.write(yaml.dump(config, Dumper=yaml_dumper, encoding='utf-8', allow_unicode=True))\n\n\ndef main():\n parser = argparse.ArgumentParser(description='WalBot config patcher', formatter_class=argparse.RawTextHelpFormatter)\n files = [\n \"config.yaml\",\n \"markov.yaml\",\n \"secret.yaml\",\n ]\n parser.add_argument(\"file\",\n choices=[\n \"all\",\n *files,\n ],\n nargs='?',\n default=\"all\",\n help='Config file to patch')\n args = parser.parse_args()\n if args.file != \"all\":\n files = [args.file]\n for file in files:\n config = Util.read_config_file(file)\n if config is None:\n log.error(\"File '{}' does not exist\".format(file))\n sys.exit(1)\n if not hasattr(config, \"version\"):\n log.error(\"{} does not have 'version' field\".format(file))\n sys.exit(1)\n version = config.version\n log.info(\"WalBot config patch tool: {}@{}\".format(file, version))\n if Updater(file, config).result():\n if not os.path.exists(\"backup\"):\n os.makedirs(\"backup\")\n shutil.copyfile(file, \"backup/\" + file + \".bak.\" + version)\n save_file(file, config)\n log.info(\"Successfully saved file: {}\".format(config.version))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"558753764","text":"import json\nfrom azure_resource_broker import AzureResourceBroker\nfrom config import AzureConfig\n\nvm_entity_sublist = []\nfor sub_name, sub_id in AzureConfig.AZURE_SUBSCRIPTION_ID_MAP.items():\n print (\"Fetching VMs from subscription\", sub_name)\n broker = AzureResourceBroker(sub_id)\n broker.load_resources()\n\n vm_names = broker.get_virtual_machine_names()\n for vm_name in vm_names:\n vm_entity_sublist.append({\n \"canonicalForm\": vm_name,\n \"list\": []\n })\n\nwith open(\"vm_entity_sublist.json\", 'w') as f:\n json.dump(vm_entity_sublist, f, indent=4)\n","sub_path":"generate_vm_entity_sublist.py","file_name":"generate_vm_entity_sublist.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"162748004","text":"from flask import Flask, request, Response, jsonify\n\nfrom db import WorkedWatcher, TaskPersist\n\nimport properties_rest\nimport json\n\nfrom queue import RedisTaskQueue, PAUSE, STOP, WORK, ERROR\n\n__author__ = 'alesha'\n\napp = Flask(__name__, static_url_path=\"\")\nlog = app.logger\n\n\nrtq = RedisTaskQueue(use_deferred_handler=False)\ntp = TaskPersist()\n\n\n@app.route(\"/tasks\", methods=[\"PUT\"])\ndef add_task():\n task_data_raw = request.data\n task_data = json.loads(task_data_raw)\n if not task_data.get('q'):\n return jsonify(**{'error': True, 'details': 'q field not passed'}), 400\n\n log.info(\"added new task: [%s] \\n%s\" % (task_data.get(\"q\"), task_data))\n task_id = rtq.add_task(q=task_data.get('q'),\n since_id=task_data.get('since_id'),\n project_id=task_data.get('project_id')\n )\n task_id = task_id\n task_data['task_id'] = task_id\n\n tp.save_task_info(task_id, task_data)\n\n return jsonify(**{'ok': True, 'id': str(task_id)})\n\n\n@app.route(\"/tasks\", methods=['GET'])\ndef show():\n state = request.args.get('state')\n tasks = rtq.get_tasks_states(state=state)\n return jsonify(**tasks)\n\n\n@app.route(\"/tasks/\", methods=['GET'])\ndef show_task(task_id):\n task_info = rtq.get_task_info(task_id)\n human_task_info = tp.get_task_info(task_id)\n if human_task_info:\n del human_task_info['_id']\n task_info.update(human_task_info)\n\n return jsonify(**task_info)\n\n\n@app.route(\"/tasks/\", methods=['POST'])\ndef change_task_status(task_id):\n change_info_raw = request.data\n change_info = json.loads(change_info_raw)\n new_status = change_info.get('status')\n if not new_status:\n return jsonify(**{'error': True, 'details': 'status field not passed'}), 400\n if new_status not in [PAUSE, STOP, WORK]:\n return jsonify(**{'error': True, 'details': 'status not supported'}), 400\n\n rtq.set_task_state(task_id, new_status)\n return jsonify(**{\"ok\": True, \"info\": \"status changed\"})\n\n\nww = WorkedWatcher()\n\n\n@app.route(\"/info\", methods=['GET'])\ndef info():\n work, error = ww.is_work()\n return jsonify(**{\"is_work\": work, \"error\": error})\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=properties_rest.ui_port, )\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"114248637","text":"from tkinter import *\r\nimport tkinter as tk\r\nfrom tkinter import filedialog, messagebox\r\nfrom tkinter import ttk\r\nfrom tkinter.font import Font\r\nimport pyautogui\r\nimport time\r\nimport os\r\nimport math\r\nimport subprocess\r\nfrom Thumbnail import create_thumbnail\r\nfrom Video import create_video\r\nfrom Upload import upload_video\r\nfrom tkinter.scrolledtext import ScrolledText\r\nfrom tkcalendar import *\r\nimport datetime\r\n\r\naudio = \"\"\r\nphotos = []\r\nphotos_thumb = []\r\nfolder_selected = \"\"\r\ninfo = \"\"\r\nartists = \"\"\r\ncredit = \"\"\r\ndate = \"\"\r\ntime_hr = 0\r\ntime_min = 0\r\n\r\ndef open_file_pics():\r\n global photos\r\n photos = filedialog.askopenfilenames(title=\"Select files\")\r\n\r\ndef open_file_pics_thumb():\r\n global photos_thumb\r\n photos_thumb = filedialog.askopenfilenames(title=\"Select files\") \r\n \r\ndef open_file_audio():\r\n global audio\r\n audio = filedialog.askopenfilename(title=\"Select file\")\r\n\r\ndef open_file_folder():\r\n global folder_selected\r\n folder_selected = filedialog.askdirectory() \r\n\r\ndef submit():\r\n global info, artists, credit, entry_box2, entry_box, entry_box3, photos, photos_thumb, audio, folder_selected\r\n info = entry_box.get('1.0', 'end-1c')\r\n artists = entry_box2.get('1.0', 'end-1c')\r\n credit = entry_box3.get('1.0', 'end-1c')\r\n global time_hr, time_min\r\n try:\r\n time_hr = int(entry_box4.get())\r\n time_min = int(entry_box5.get()) \r\n except:\r\n messagebox.showerror(title='Upload Time', message='Please provide the proper time for upload')\r\n\r\n global date\r\n date = cal.get_date()\r\n\r\n if photos == []:\r\n messagebox.showerror(title='Video', message='Please provide the path for all the pictures in the Video')\r\n\r\n elif photos_thumb == []:\r\n messagebox.showerror(title='Thumbnail', message='Please provide the path for all the pictures in the Thumbnail')\r\n\r\n elif folder_selected == '':\r\n messagebox.showerror(title='Resultant Folder', message='Please provide the path of the resultant folder') \r\n\r\n elif audio == '':\r\n messagebox.showerror(title='Audio', message='Please provide the audio path')\r\n\r\n elif info == '':\r\n messagebox.showerror(title='Basic Info', message='Please provide the info of the song')\r\n\r\n elif artists == '':\r\n messagebox.showerror(title='Artists', message='Please provide all the Artists')\r\n\r\n elif time_hr == 0 or time_hr >= 24:\r\n messagebox.showerror(title='Time Hour', message='Please provide the proper time for upload') \r\n\r\n elif time_min == 0 or time_min >= 60:\r\n messagebox.showerror(title='Time Min', message='Please provide the proper time for upload')\r\n\r\n else:\r\n artist = []\r\n for line in artists.splitlines():\r\n artist.append(line)\r\n i = 0\r\n try:\r\n main_artist = artist[0][0:artist[0].index('-')].strip()\r\n except Exception as e:\r\n i+=1\r\n messagebox.showerror(title='Artist', message='Please use \\\"-\\\"')\r\n\r\n if i == 0: \r\n root.destroy() \r\n\r\nroot = tk.Tk()\r\nroot.title(\"Video Creator\")\r\nroot.iconbitmap('logo.ico')\r\nmyFont = Font(family=\"Times New Roman\", size=12)\r\nroot.grid_columnconfigure(0, weight=1)\r\nroot.grid_rowconfigure(0, weight=1)\r\n\r\nprocess = 'ffmpeg'\r\ntry:\r\n p = subprocess.call(process, shell=True)\r\nexcept:\r\n messagebox.showerror(title='Error', message='Please install ffmpeg to continue')\r\n\r\ntext1 = tk.Text(root,height=1)\r\ntext1.insert(tk.INSERT , \"Select the pictures for the Video\")\r\ntext1.config(state=\"disabled\")\r\ntext1.configure(font=myFont)\r\ntext1.grid(row=0,column=0, sticky=N+S+E+W)\r\nbutton1 = Button(root,text=\"Open Pictures\", command=open_file_pics)\r\nbutton1.grid(row=1,column=0)\r\n\r\ntext4 = tk.Text(root,height=1)\r\ntext4.insert(tk.INSERT , \"Select the pictures for the Photos\")\r\ntext4.config(state=\"disabled\")\r\ntext4.configure(font=myFont)\r\ntext4.grid(row=2,column=0, columnspan=4, sticky=N+S+E+W)\r\nbutton4 = Button(root,text=\"Open Pictures\", command=open_file_pics_thumb)\r\nbutton4.grid(row=3,column=0)\r\n\r\ntext2 = tk.Text(root,height=1)\r\ntext2.insert(tk.INSERT, \"Select the audio file\")\r\ntext2.config(state=\"disabled\")\r\ntext2.configure(font=myFont)\r\ntext2.grid(row=4,column=0, columnspan=4, sticky=N+S+E+W)\r\nbutton2 = Button(root,text=\"Open Audio\", command=open_file_audio)\r\nbutton2.grid(row=5,column=0)\r\n\r\ntext3 = tk.Text(root,height=1)\r\ntext3.insert(tk.INSERT, \"Select the resultant folder\")\r\ntext3.config(state=\"disabled\")\r\ntext3.configure(font=myFont)\r\ntext3.grid(row=6,column=0, columnspan=4, sticky=N+S+E+W)\r\nbutton3 = Button(root,text=\"Select a folder\", command=open_file_folder)\r\nbutton3.grid(row=7,column=0)\r\n\r\nlabel1 = Label(root, text=\"Basic Info\", font=myFont)\r\nlabel1.grid(row=8,column=0, columnspan=4, sticky=N+S+E+W)\r\n#name=StringVar()\r\n#entry_box = Entry(root, textvariable=name, width=25)\r\n#entry_box.grid(row=9)\r\nentry_box = ScrolledText(root, width=50, height=2, font=myFont)\r\nentry_box.grid(row=9, columnspan=4, sticky=N+S+E+W)\r\n\r\nlabel2 = Label(root, text=\"Artists\", font=myFont)\r\nlabel2.grid(row=11,column=0, columnspan=4, sticky=N+S+E+W)\r\n#name1=StringVar()\r\n#entry_box2 = Entry(root, textvariable=name1, width=25).grid(row=11)\r\nentry_box2 = ScrolledText(root, width=50, height=2, font=myFont)\r\nentry_box2.grid(row=12, columnspan=4, sticky=N+S+E+W)\r\n\r\nlabel3 = Label(root, text=\"Credits\", font=myFont)\r\nlabel3.grid(row=13,column=0, columnspan=4, sticky=N+S+E+W)\r\n#name2=StringVar()\r\n#entry_box3 = Entry(root, textvariable=name2, width=25).grid(row=13)\r\nentry_box3 = ScrolledText(root, width=50, height=2, font=myFont)\r\nentry_box3.grid(row=14, columnspan=4, sticky=N+S+E+W)\r\n\r\ntext215 = tk.Text(root,height=1)\r\ntext215.insert(tk.INSERT, \"Select the Upload Date\")\r\ntext215.config(state=\"disabled\")\r\ntext215.configure(font=myFont)\r\ntext215.grid(row=15,column=0, columnspan=4, sticky=N+S+E+W)\r\n\r\ncal = DateEntry(root, selectmode=\"day\", year=datetime.date.today().year,\r\n month=datetime.date.today().month, day=datetime.date.today().day)\r\ncal.grid(row=16, column=0) \r\n\r\ntext216 = tk.Text(root,height=1)\r\ntext216.insert(tk.INSERT, \"Write the Upload Time\")\r\ntext216.config(state=\"disabled\")\r\ntext216.configure(font=myFont)\r\ntext216.grid(row=17,column=0, columnspan=4, sticky=N+S+E+W)\r\n\r\nentry_box4 = Entry(root, width=12, font=myFont)\r\nentry_box4.grid(row=18, column=0)\r\n\r\nentry_box5 = Entry(root, width=12, font=myFont)\r\nentry_box5.grid(row=19, column=0)\r\n\r\ntime = Button(root, text=\"Submit\", command=submit)\r\ntime.grid(row=20,column=0)\r\n\r\ndef on_closing():\r\n if messagebox.askokcancel(\"Quit\", \"Do you want to quit?\"):\r\n exit()\r\n\r\nroot.protocol(\"WM_DELETE_WINDOW\", on_closing)\r\n\r\n#root.geometry(\"800x705\")\r\nroot.resizable(width=False, height=False)\r\nroot.mainloop()\r\n\r\nphotos = [w.replace('/', '\\\\') for w in photos]\r\nphotos_thumb = [w.replace('/', '\\\\') for w in photos_thumb]\r\naudio = audio.replace('/', '\\\\')\r\nfolder_selected = folder_selected.replace('/','\\\\')\r\n\r\ni = 0\r\nsong = ''\r\nfor line in info.splitlines():\r\n if i == 0:\r\n song = line\r\n i += 1\r\n\r\nartist = []\r\nfor line in artists.splitlines():\r\n artist.append(line)\r\n\r\ntry:\r\n main_artist = artist[0][0:artist[0].index('-')].strip()\r\nexcept Exception as e:\r\n messagebox.showerror(title='Artist', message='Please use \\\"-\\\"')\r\n exit()\r\ntitle = f'{song} | {main_artist} | Carnatic Fever'\r\ndescription = f'{info}\\n\\nArtists:\\n{artists}\\n\\n{credit}'\r\n\r\nartist.append(song)\r\nartist.append('Carnatic Music')\r\nartist.append('Carnatic Fever')\r\nartist.append('Music')\r\nartist.append('Carnatic')\r\n\r\ndate_time = datetime.datetime(date.year, date.month, date.day, time_hr, time_min, 0).isoformat() + '.000Z'\r\n\r\ncreate_thumbnail(photos_thumb, song, folder_selected)\r\ncreate_video(photos, folder_selected, audio)\r\nupload_video(folder_selected, title, description, artist, date_time)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"307734004","text":"from Node import Node\n\nclass Topo:\n def __init__(self):\n self.nodes = {}\n self.links = []\n self.rootNode = None\n self.rootPaths = []\n\n def addNode(self, name, isRoot=False):\n node = Node(name)\n self.nodes[name] = node\n if isRoot:\n self.rootNode = node\n\n def addLink(self, src, dst, isRootPath=False):\n srcNode = self.nodes[src]\n dstNode = self.nodes[dst]\n srcNode.addLink(dstNode)\n dstNode.addLink(srcNode)\n\n self.links.append((srcNode, dstNode))\n if isRootPath:\n self.rootPaths.append((srcNode, dstNode))\n","sub_path":"Topo.py","file_name":"Topo.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"210485602","text":"#\n# @lc app=leetcode.cn id=49 lang=python3\n#\n# [49] 字母异位词分组\n#\n\n# @lc code=start\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n if not strs: return []\n\n def way1():\n # sort 时间复杂度 O(K * NlogN),空间复杂度 O(K); easy to recall\n mem = defaultdict(list)\n for word in strs:\n t = ''.join(sorted(word))\n mem[t].append(word)\n return [v for v in mem.values()]\n\n def way2():\n # array 时间复杂度 O(K * N), slow in string key construct \n mem = defaultdict(list)\n ch_int = {chr(k): k for k in range(97, 123)}\n for word in strs:\n array = [0] * 26\n for c in word:\n array[ch_int[c]-ch_int['a']] += 1\n key = '#'.join([str(m) for m in array])\n mem[key].append(word)\n return [v for v in mem.values()]\n\n def way3():\n # use prime to construct key; improved on way2\n primes = [2, 3, 5, 7, 11 ,13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]\n ch_int = {chr(k): k for k in range(97, 123)}\n mem = defaultdict(list)\n for word in strs:\n key = 1\n for c in word:\n key *= primes[ch_int[c] - ch_int['a']]\n mem[key].append(word)\n return [v for v in mem.values()]\n\n return way1()\n# @lc code=end\n\n","sub_path":"Week_02/49_字母异位分组.py","file_name":"49_字母异位分组.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"42472120","text":"from models import Order, db, User, Admin, Deliver, Product, Man, Car, Info, Alert\nfrom flask import render_template, session, redirect, url_for\nimport random, time\n\n\ndef show_user_orders():\n uid = session.get('uid')\n if not uid:\n return redirect(url_for('error', msg='未登录', info='不登录怎么知道你有什么订单呢', link='user%2flogin'))\n\n orders = Order.query.filter_by(uid=uid).all()\n\n return render_template('test.html', data=orders)\n\n\ndef show_a_orders():\n aid = session.get('aid')\n if not aid:\n return redirect(url_for('error', msg='未登录', info='不登录怎么知道你有什么订单呢', link='admin%2flogin'))\n\n orders = Order.query.filter_by(aid=aid).all()\n\n return render_template('test.html', data=orders)\n\n\ndef get_admin_name(aid):\n admin = Admin.query.filter_by(aid=aid).first()\n return admin.a_name\n\n\ndef get_user_name(uid):\n user = User.query.filter_by(uid=uid).first()\n return user.user_name\n\n\ndef order_page(oid):\n if not session.get('uid') and not session.get('aid'):\n return redirect(url_for('error', msg='请先登录', info='未登录不可查询订单', link='home'))\n order = Order.query.filter_by(oid=oid).first()\n\n if not order:\n if session.get('uid'):\n return redirect(url_for('error', msg='查无此单', info='请仔细检查订单号码', link='user'))\n if session.get('aid'):\n return redirect(url_for('error', msg='查无此单', info='请仔细检查订单号码', link='admin%2fbackstage'))\n\n user = User.query.filter_by(uid=order.uid).first()\n admin = Admin.query.filter_by(aid=order.aid).first()\n\n if session.get('uid') != order.uid and not session.get('aid'):\n return redirect(url_for('error', msg='请求错误', info='只能查询和自己相关的订单', link='home'))\n\n name = ''\n\n if session.get('uid'):\n name = get_user_name(session.get('uid'))\n else:\n name = get_admin_name(session.get('aid'))\n\n product = Product.query.filter_by(pid=order.pid).first()\n\n delivers = None\n info = None\n\n if order.status == 0:\n pass\n else:\n delivers = db.session.query(\n Deliver.did,\n Deliver.status,\n Car.cplace,\n Car.cnumber,\n Man.name,\n Man.tel,\n Deliver.created_at\n ).filter(\n Deliver.oid == order.oid,\n Deliver.cid == Car.cid,\n Car.mid == Man.mid\n ).order_by(\n Deliver.updated_at.desc()\n ).all()\n\n info = Info.query.filter_by(oid=oid).order_by(Info.created_at.desc()).all()\n\n\n data = {}\n data['user'] = {'name': name}\n\n data['order'] = {\n 'oid': oid,\n 'product': product.pname,\n 'pid': product.pid,\n 'price': (product.price * order.sum) / 100,\n 'sum': order.sum,\n 'o_price': product.price,\n 'created_at': order.created_at,\n 'addr': order.addr,\n 'tel': user.tel,\n 'status': order.status,\n 'updated_at': order.updated_at,\n }\n\n if order.status:\n data['delivers'] = list(delivers)\n data['info'] = info\n data['len1'] = len(list(delivers))\n data['len2'] = len(list(info))\n else:\n data['delivers'] = None\n data['info'] = None\n data['len1'] = 0\n data['len2'] = 0\n\n return render_template('order.html', data=data)\n\n\ndef show_orders():\n aid = session.get('aid')\n if not aid:\n return redirect(url_for('error', msg='请登录', info='这是管理员才能查看的页面', link='admin%2flogin'))\n\n send_orders = db.session.query(\n Order.oid,\n Product.pname,\n Order.sum,\n Product.price,\n User.user_name,\n User.tel,\n Order.addr,\n Order.status,\n Info,\n Deliver,\n Car,\n Man,\n Order.alevel,\n ).filter(\n Order.did == Deliver.did,\n Order.iid == Info.iid,\n User.uid == Order.uid,\n Car.cid == Deliver.cid,\n Man.mid == Car.mid,\n Order.pid == Product.pid\n ).order_by(Order.created_at.desc()).all()\n\n unsend_orders = db.session.query(\n Order.oid,\n Product.pname,\n Order.sum,\n Product.price,\n User.user_name,\n User.tel,\n Order.addr\n ).filter(\n User.uid == Order.uid,\n Order.status == 0,\n Product.pid == Order.pid\n ).order_by(Order.created_at.desc()).all()\n\n if Alert.query.filter_by(toid=aid, msgfor=2, level=3, valid=1).count() > 0: # 顶级\n level = 4\n elif Alert.query.filter_by(toid=aid, msgfor=2, level=2, valid=1).count() > 0:\n level = 3\n elif Alert.query.filter_by(toid=aid, msgfor=2, level=1, valid=1).count() > 0: # 开始弹窗\n level = 2\n elif Alert.query.filter_by(toid=aid, msgfor=2, level=0, valid=1).count() > 0:\n level = 1\n else: # 无事\n level = 0\n\n data = {}\n data['name'] = Admin.query.filter_by(aid=aid).first().a_name\n data['send'] = send_orders\n data['unsend'] = unsend_orders\n data['alert_num'] = Alert.query.filter_by(msgfor=2, toid=aid, valid=1).count()\n data['level'] = level\n\n data['send_len'] = len(send_orders)\n data['send_row_len'] = data['send_len'] // 3\n if data['send_len'] % 3 != 0:\n data['send_row_len'] += 1\n data['unsend_len'] = len(unsend_orders)\n data['unsend_row_len'] = data['unsend_len'] // 3\n if data['unsend_len'] % 3 != 0:\n data['unsend_row_len'] += 1\n data['all_len'] = len(send_orders) + len(unsend_orders)\n data['all_row_len'] = data['send_row_len'] + data['unsend_row_len']\n\n\n lenlen = 0\n for i in send_orders:\n if i[7] == 2:\n lenlen += 1\n\n data['end_len'] = lenlen\n data['end_row_len'] = data['end_len'] // 3\n if data['end_len'] % 3 != 0:\n data['end_row_len'] += 1\n\n return render_template('orders.html', data=data)\n\n\ndef admin_delivers():\n data = {}\n aid = session.get('aid')\n if not aid:\n return redirect(url_for('error', msg='请登录', info='这是管理员才能查看的页面', link='admin%2flogin'))\n\n data['alert_num'] = Alert.query.filter_by(msgfor=2, toid=aid, valid=1).count()\n if Alert.query.filter_by(toid=aid, msgfor=2, level=3, valid=1).count() > 0: # 顶级\n level = 4\n elif Alert.query.filter_by(toid=aid, msgfor=2, level=2, valid=1).count() > 0:\n level = 3\n elif Alert.query.filter_by(toid=aid, msgfor=2, level=1, valid=1).count() > 0: # 开始弹窗\n level = 2\n elif Alert.query.filter_by(toid=aid, msgfor=2, level=0, valid=1).count() > 0:\n level = 1\n else: # 无事\n level = 0\n data['level'] = level\n\n cars = db.session.query(\n Car.cplace,\n Car.cnumber,\n Man.name,\n Man.tel,\n Car.status,\n Car.active,\n Car.cid,\n ).filter(Car.mid == Man.mid).order_by(Car.active.desc()).all()\n\n delivers = []\n for i in cars:\n deliver = Deliver.query.filter_by(cid=i[6]).order_by(Deliver.created_at.desc()).all()\n delivers.append(deliver)\n data['delivers'] = delivers\n data['car_len'] = len(cars)\n data['cars'] = cars\n\n return render_template('delivers.html', data=data)","sub_path":"orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"229057060","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('poster', '0005_auto_20160228_1928'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='plant',\n name='state',\n field=models.CharField(max_length=15, choices=[(b'upcoming', b'upcoming'), (b'pending', b'pending'), (b'proposed', b'proposed'), (b'rejected', b'rejected')]),\n ),\n ]\n","sub_path":"poster/migrations/0006_auto_20160228_1947.py","file_name":"0006_auto_20160228_1947.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"564837848","text":"from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta\nfrom typing import TYPE_CHECKING\n\nfrom users.settings import JWT_EXPIRES_AFTER_IN_MINUTES\n\nif TYPE_CHECKING:\n from users.domain.entities import Credential, User # noqa\n\n\ndef get_jwt_metadata() -> dict:\n utcnow = datetime.utcnow()\n\n return {\n \"exp\": utcnow + timedelta(minutes=JWT_EXPIRES_AFTER_IN_MINUTES),\n \"iat\": utcnow,\n }\n\n\n@dataclass\nclass JWTToken:\n id: str\n email: str\n name: str\n credentials: list[\"Credential\"]\n exp: datetime\n iat: datetime\n aud: str = \"auth\"\n\n @classmethod\n def from_user(cls, user: \"User\") -> JWTToken:\n return cls(\n id=user.id,\n email=user.email,\n name=user.name,\n credentials=user.credentials.scopes,\n **get_jwt_metadata()\n )\n\n @classmethod\n def from_payload(cls, payload: dict) -> JWTToken:\n return cls(\n id=payload[\"id\"],\n email=payload[\"email\"],\n name=payload[\"name\"],\n credentials=payload[\"credentials\"],\n exp=payload[\"exp\"],\n iat=payload[\"iat\"],\n )\n","sub_path":"users/users/auth/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84385600","text":"import os\nimport regex\nfrom doc_curation.md_helper import MdFile\n\n\ndef get_adhyaaya_md_files(md_file_path):\n md_files = MdFile.get_md_files_from_path(dir_path=md_file_path, file_pattern=\"**/*.md\", file_name_filter=lambda x: len(regex.findall(\"\\\\d\\\\d\\\\d\", os.path.basename(x))) > 0)\n return md_files\n\n\ndef get_parva_adhyaaya(md_file):\n parva = regex.findall(\"/\\\\d\\\\d-\", str(md_file.file_path))[0].replace(\"/\", \"\").replace(\"-\", \"\")\n adhyaaya = regex.findall(\"\\\\d\\\\d\\\\d\", str(md_file.file_path))[-1]\n return (parva, adhyaaya)\n\n\ndef get_adhyaaya_id(md_file):\n (parva, adhyaaya) = get_parva_adhyaaya(md_file=md_file)\n return \"%03d-%03d\" % (int(parva), int(adhyaaya))\n\n\ndef get_adhyaaya_to_source_file_map():\n md_files = get_adhyaaya_md_files(md_file_path=\"/home/vvasuki/sanskrit/raw_etexts/purANa/mahAbhArata/kumbhakonam\")\n final_map = {}\n for md_file in md_files:\n parva = regex.findall(\"/\\\\d\\\\d/\", str(md_file.file_path))[0].replace(\"/\", \"\")\n adhyaaya = regex.findall(\"\\\\d\\\\d\\\\d\", str(md_file.file_path))[0]\n adhyaaya_id = \"%s-%s\" % (parva, adhyaaya)\n final_map[adhyaaya_id] = md_file\n return final_map\n\n\n\n\n\n","sub_path":"curation_projects/mahaabhaarata/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"343759650","text":"from PyQt5 import QtWidgets, uic\nfrom pyqtgraph import PlotWidget, plot\nimport pyqtgraph as pg\nimport sys # We need sys so that we can pass argv to QApplication\nimport os\nfrom PyQt5 import QtCore\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n\n self.graphWidget = pg.PlotWidget()\n self.setCentralWidget(self.graphWidget)\n\n x = [1,2,3,4,5,6,7,8,9,10]\n y = [30,32,34,32,33,31,29,32,35,45]\n\n self.graphWidget.setTitle(\"Your Title Here\")\n self.graphWidget.setLabel('left', \"Temperature (°C)\")\n self.graphWidget.setLabel('bottom', \"Hour (H)\")\n\n self.graphWidget.setBackground('w')\n pen = pg.mkPen(color=(255, 0, 0), width=15, style=QtCore.Qt.DashDotLine)\n self.graphWidget.plot(x, y, pen=pen, symbol='+', symbolSize=30, symbolBrush=('b'))\n self.graphWidget.setXRange(-5, 12, padding=0)\n self.graphWidget.setYRange(25, 50, padding=0)\n self.graphWidget.showGrid(x=True, y=True)\n\n\ndef main():\n app = QtWidgets.QApplication(sys.argv)\n main = MainWindow()\n main.show()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()","sub_path":"part-2/level-2.py","file_name":"level-2.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"269306379","text":"import tensorflow as tf\nfrom .solver_base import solver_base\nfrom ...utils.log import log_message\n\nclass solver_gan(solver_base):\n def __init__(self):\n solver_base.__init__(self)\n\n def build_graph(self, **kwargs):\n cfg_args = kwargs['cfg_args']\n loss_list = kwargs['loss']\n var_prefix = kwargs['var_prefix']\n\n log_message('solver_gan', '---Graph Solver..---')\n\n gpu_list = cfg_args.gpu_list\n\n tf_vars = tf.trainable_variables()\n var_g = [var for var in tf_vars if 'gen_' in var.name]\n var_d = [var for var in tf_vars if 'dis_' in var.name]\n\n loss_g_full_list = loss.public_ops['loss_g']\n loss_d_full_list = []\n for g_id in range(0, len(gpu_list)):\n with tf.device('/gpu:{}'.format(g_id)):\n _loss_d = loss.public_ops['loss_d'][g_id]\n if('loss_gp' in loss.public_ops):\n _loss_d += loss.public_ops['loss_gp'][g_id]\n\n loss_d_full_list.append(_loss_d)\n\n train_op_g = self.construct_solver(loss_g_full_list, var_g, cfg_args.param)\n train_op_d = self.construct_solver(loss_d_full_list, var_d, cfg_args.param)\n\n self.public_ops['train_op_g'] = train_op_g\n self.public_ops['train_op_d'] = train_op_d\n\nclass solver_classifier(solver_base):\n def __init__(self):\n solver_base.__init__(self)\n\n def build_graph(self, **kwargs):\n cfg_args = kwargs['cfg_args']\n phase = kwargs['phase']\n loss = kwargs['loss']\n global_data_dict = kwargs['global_data_dict']\n\n log_message('solver_classifier', '---Graph Solver..---')\n\n gpu_list = cfg_args.gpu_list\n\n tf_vars = tf.trainable_variables()\n var_ = [var for var in tf_vars if 'classifier_' in var.name]\n\n loss_full_list = loss.public_ops['loss_full']\n train_op = self.construct_solver(loss_full_list, var_, cfg_args.param)\n self.public_ops['loss_full'] = loss_full_list\n self.public_ops['train_op'] = train_op","sub_path":"framework/modules/solver/mp_gan.py","file_name":"mp_gan.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"23126095","text":"#system\nimport os\nimport time \n\n# spartan\nimport spartan.manipulation.grasp_supervisor\nimport spartan.manipulation.background_subtraction\nimport spartan.calibration.handeyecalibration\nimport spartan.utils.utils as spartanUtils\n\n\nfrom spartan.utils.taskrunner import TaskRunner\n\n# ros\nimport tf2_ros\n\n\nclass TFWrapper(object):\n\n def __init__(self):\n self.tfBuffer = None\n self.tfListener = None\n self.taskRunner = TaskRunner()\n self.taskRunner.callOnThread(self.setup)\n\n def setup(self):\n self.tfBuffer = tf2_ros.Buffer()\n self.tfListener = tf2_ros.TransformListener(self.tfBuffer)\n\n def getBuffer(self):\n while self.tfBuffer is None:\n time.sleep(0.1)\n\n return self.tfBuffer\n\n\ndef setupRLGDirector(globalsDict=None):\n\n tfWrapper = TFWrapper()\n tfBuffer = tfWrapper.getBuffer()\n\n graspSupervisor = spartan.manipulation.grasp_supervisor.GraspSupervisor.makeDefault(tfBuffer=tfBuffer)\n graspSupervisor.robotSystem = globalsDict['robotSystem'] # for visualization\n globalsDict['graspSupervisor'] = graspSupervisor\n\n \n backgroundSubtraction = spartan.manipulation.background_subtraction.BackgroundSubtractionDataCapture.makeDefault(tfBuffer=tfBuffer)\n globalsDict['backgroundSubtraction'] = backgroundSubtraction\n\n\n\n spartanSourceDir = spartanUtils.getSpartanSourceDir()\n handEyeCalibrationConfigFilename = os.path.join(spartanSourceDir, \"src/catkin_projects/station_config/RLG_iiwa_1/hand_eye_calibration/carmine_1.yaml\")\n\n\n cal = spartan.calibration.handeyecalibration.HandEyeCalibration(globalsDict['robotSystem'], configFilename=handEyeCalibrationConfigFilename)\n cal.loadConfigFromFile()\n globalsDict['cal'] = cal\n\n # set rate limit on RemoteTreeViewer\n # fix for https://github.com/RobotLocomotion/spartan/issues/244\n globalsDict['treeViewer'].subscriber.setSpeedLimit(5)","sub_path":"modules/spartan/director/iiwamanipdev.py","file_name":"iiwamanipdev.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"511735198","text":"#!/ usr/bin/env\n# coding=utf-8\n#\n# Copyright 2019 ztosec & https://sec.zto.com/\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"\nauthor: b5mali4\nTo use:\n>>> sq = Square(3)\n>>> sq.area \n\"\"\"\nimport os\nimport signal\nimport json\nimport time\nimport subprocess\nfrom sys import version_info\nfrom common import log\nfrom subprocess import Popen\nfrom common.http_util import header_to_lowercase\nfrom common.http_util import header_to_str\nfrom common.http_util import json_to_urlencoded\nfrom common.plugins_util import load_default_checkers, modify_default_checkers\nfrom common.settings import DEFAULT_CONTENT_TYPE\nfrom common.settings import FORM_DATA_CONTENT_TYPE\nfrom common.settings import JSON_TEXT_CONTENT_TYPE\nfrom plugins.base.vuln_enum import PluginSwith\nfrom common.plugin_config.localfile_plugin_config import LocalFilePluginConfig\nfrom argparse import Namespace\n\nif version_info < (3, 0):\n IS_WIN = subprocess.mswindows\nelse:\n IS_WIN = subprocess._mswindows\n\nlogger = log.get_default_logger()\n\n\ndef modify_checker(broadcast):\n \"\"\"\n 修改本地插件配置信息,只修改本地配置文件\n\n {\"type\": \"plugin\", \"action\": \"modify\", \"data\": {\"name\": checker_name, \"switch\": PluginSwith.ON}\n :param broadcast: \n :return: \n \"\"\"\n checker_name = broadcast[\"data\"][\"name\"]\n switch = broadcast[\"data\"][\"switch\"]\n checkers_dict = load_default_checkers()\n if checker_name in checkers_dict:\n logger.info('接收到修改插件{}状态为{}的请求'.format(checker_name, switch))\n LocalFilePluginConfig().modify_plugin_config(checker_name, \"useable\", switch)\n modify_default_checkers()\n\n\ndef scan(package, task_id, create_user, status):\n \"\"\"\n :param package: \n :param task_id: \n :param create_user: \n :param status: \n :return: \n \"\"\"\n logger.info(\"hunter task has started\")\n # 加载插件,只有一个插件\n checkers = load_default_checkers()\n logger.info('loading package success')\n logger.info('loading plugin success')\n try:\n if checkers[\"sqlmap\"].useable == PluginSwith.ON:\n sqlmap_process = SqlmapProcess(package, task_id)\n sqlmap_process.engine_start()\n while not sqlmap_process.engine_has_terminated() and sqlmap_process.process is not None:\n logger.info(\"sqlmap program is runing\")\n time.sleep(5)\n sqlmap_process.engine_kill()\n logger.warn(\"sqlmap program runs to completion\")\n except KeyboardInterrupt as e:\n logger.exception(\"scan error\")\n finally:\n logger.info(\"hunter task has done\")\n\n\nclass SqlmapProcess():\n def __init__(self, package, task_id):\n self.process = None\n self.package = package\n self.task_id = task_id\n\n def parse_package(self):\n \"\"\"\n 将从mq中获得的数据解析 ,sqlmap会自动解析参数,json还是普通data\n :return: \n \"\"\"\n header = None\n cookie = None\n url = self.package['url'] if \"url\" in self.package else None\n\n if \"headers\" in self.package:\n header = header_to_lowercase(json.loads(self.package[\"headers\"]))\n if \"Cookie\" in json.loads(self.package[\"headers\"]):\n cookie = json.loads(self.package[\"headers\"])['Cookie']\n if header:\n header = header_to_str(header)\n data = self.parse_data(self.package, header)\n return url, data, cookie, header\n\n def parse_data(self, package, header):\n \"\"\"\n 根据请求头解析数据\n :param package: \n :param header: \n :return: \n \"\"\"\n\n result = None\n\n if \"data\" not in package or package[\"data\"] == \"\":\n return result\n\n if header and \"content-type\" in header:\n if FORM_DATA_CONTENT_TYPE in header[\"content-type\"] or DEFAULT_CONTENT_TYPE in header[\"content-type\"]:\n return json_to_urlencoded(json.loads(package['data']))\n elif JSON_TEXT_CONTENT_TYPE in header[\"content-type\"]:\n return str(json.loads(package[\"data\"]))\n return json_to_urlencoded(json.loads(package['data']))\n\n def get_command(self):\n \"\"\"\n 根据数据的得到命令,超时重联3次\n :return: \n \"\"\"\n command = self.init_command_by_path()\n # status = True\n # 表示不正常,比如一个数据包中没有url\n url, data, cookie, headers = self.parse_package()\n if url is None or url == \"\":\n return False, command\n command += [\"--url\", \"{}\".format(url)]\n if data is not None and data != \"\":\n command += [\"--data\", \"{}\".format(data)]\n if cookie is not None and cookie != \"\":\n command += [\"--cookie\", \"{}\".format(cookie)]\n if headers is not None and headers != \"\":\n command += [\"--headers\", \"{}\".format(headers)]\n command += [\"--batch\"]\n command += [\"--purge-output\"]\n # print (\" \".join(command))\n return True, command\n\n def init_command_by_path(self):\n \"\"\"\n 根据路径\n :return: \n \"\"\"\n from common.path import SQLMAP_SCRIPT_PATH\n command = [\"python2\", SQLMAP_SCRIPT_PATH]\n command += [\"--celery\", \"{}\".format(self.task_id)]\n return command\n\n def engine_start(self):\n \"\"\"开始命令\"\"\"\n status, command = self.get_command()\n # print status, command\n if status:\n self.process = Popen(command, shell=False, close_fds=not IS_WIN)\n\n def engine_stop(self):\n \"\"\"\n 结束\n :return: \n \"\"\"\n if self.process:\n self.process.terminate()\n return self.process.wait()\n else:\n return None\n\n def engine_process(self):\n return self.process\n\n def engine_kill(self):\n \"\"\"\n 强制kill,删除SQLMAP扫描缓存记录\n :return: \n \"\"\"\n if self.process:\n try:\n self.process.kill()\n os.killpg(self._process.pid, signal.SIGTERM)\n return self.process.wait()\n except:\n pass\n return None\n\n def engine_get_id(self):\n \"\"\"\n 获得进程模块\n :return: \n \"\"\"\n if self.process:\n return self.process.pid\n else:\n return None\n\n def engine_get_returncode(self):\n \"\"\"\n 如果为None表示命令还在执行中,为0表示已经执行完成并退出\n :return: \n \"\"\"\n if self.process:\n self.process.poll()\n return self.process.returncode\n else:\n return None\n\n def engine_has_terminated(self):\n return isinstance(self.engine_get_returncode(), int)\n","sub_path":"SqlmapCelery/taskschedule/task_schedule.py","file_name":"task_schedule.py","file_ext":"py","file_size_in_byte":7288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"121580679","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', 'core.views.main', name='main'), \n url(r'^(?P\\d+)/?$', 'core.views.expense', name='expense'),\n url(r'^register/?$', 'core.views.register', name='register'),\n url(r'^overview/(?P\\d*)/?$', 'core.views.overview', name='overview'),\n url(r'^login/?$', 'core.views.login_view'),\n url(r'^logout/?$', 'core.views.logout_view'),\n\n # Api\n url(r'^api/user/?$', 'core.views.api_user', name='api_user'),\n url(r'^api/userbar/?$', 'core.views.api_userbar', name='userbar'),\n url(r'^api/add_friend/?$', 'core.views.api_add_friend', name='api_add_friend'),\n url(r'^api/expense/(?P\\d*)/?$', 'core.views.api_expense', name='api_expense'),\n url(r'^api/item/(?P\\d*)/?$', 'core.views.api_item', name='api_item'),\n)\n","sub_path":"debthing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"612544298","text":"import os,sys\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport random\nimport ipdb\nimport glob\nfrom scipy.ndimage.filters import gaussian_filter1d\nfrom scipy.interpolate import griddata\nfrom sklearn.externals import joblib\n\ndir_of_this_script = os.path.dirname(os.path.realpath(__file__))\ndemonstration_dir = os.path.join(dir_of_this_script, '..', 'datasets', 'pick_20190228')\ndemo_path_list = glob.glob(os.path.join(demonstration_dir,'*.npy'))\ndemo_path_list = sorted(demo_path_list)\nsigma = 5\n\nlen_norm=101\ndatasets_raw = []\ndatasets_filtered = []\ndatasets_norm = []\nfig = plt.figure(0)\nax = fig.gca(projection='3d')\nfor demo_path in demo_path_list:\n raw_demo = np.load(demo_path, 'r')\n filtered_demo = gaussian_filter1d(raw_demo.T, sigma=sigma).T\n grid = np.linspace(0, 2, len_norm)\n time_stamp = np.linspace(0, 2, len(raw_demo))\n norm_demo = griddata(time_stamp, filtered_demo, grid, method='linear')\n datasets_raw.append(raw_demo)\n datasets_filtered.append(datasets_raw)\n datasets_norm.append(datasets_norm)\n# ax.plot(norm_demo[:,0],norm_demo[:,1],norm_demo[:,2])\n# plt.show()\npkl_dir = os.path.join(demonstration_dir,\"pkl\")\nprint('Saving the datasets as pkl ...')\njoblib.dump(datasets_raw, os.path.join(pkl_dir, 'datasets_raw.pkl'))\njoblib.dump(datasets_filtered, os.path.join(pkl_dir, 'datasets_filtered.pkl'))\njoblib.dump(datasets_norm, os.path.join(pkl_dir, 'datasets_norm.pkl'))\nprint('Loaded, filtered, normalized, preprocessed and saved the datasets successfully!!!')\n\n\n \n\n\n","sub_path":"data_process/load_pick_trainig_data.py","file_name":"load_pick_trainig_data.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"177396758","text":"import json\nfrom pycircuit.circuit import Node\nfrom pycircuit.pcb import Pcb\nfrom pycircuit.formats import extends\n\n@extends(Node)\ndef to_pcpl(self):\n assert(self.footprint)\n width, height = self.footprint.package.size()\n return {\n 'id': self.id,\n 'width': width,\n 'height': height,\n }\n\n\n@extends(Pcb)\ndef to_pcpl(self, filename):\n nodes = []\n for node in self.circuit.iter_nodes():\n nodes.append(node.to_pcpl())\n with open(filename, 'w') as f:\n print(json.dumps(nodes), file=f)\n\n\n@extends(Pcb)\ndef from_pcpl(self, filename):\n with open(filename) as f:\n for node in json.loads(f.read()):\n self.circuit.node_by_id(node['id']).place(node['x'], node['y'])\n","sub_path":"pycircuit/formats/pcpl.py","file_name":"pcpl.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"298895973","text":"#!/usr/bin/env python\n#\n# Jiao Lin \n\nimport numpy as np, histogram as H, histogram.hdf as hh, os\n\n\nclass EnergyAxisMissingBinCenterAtZero(Exception): pass\n\n\ndef sqe2dos(sqe, T, Ecutoff, elastic_E_cutoff, M, initdos=None, update_weights=None):\n \"\"\"\n Given a single-phonon SQE, compute DOS\n\n The basic procedure is\n * construct an initial guess of DOS\n * use this DOS to compute 1-phonon SQE\n * for both exp and sim SQE, integrate along Q to obtain S(E)\n * scale the initial guess DOS by the S(E) ratio\n * optionally we can do this again\n\n Parameters\n ----------\n sqe:histogram\n S(Q,E)\n\n T:float\n Temperature (kelvin)\n\n Ecutoff:float\n Cutoff energy beyond which DOS must be zero\n \n Elastic_E_cutoff: 2-tuple of floats\n Cutoff energy bracket for removing the elastic line (unit: meV)\n \n M:float\n Atomic mass\n \n initdos:histogram\n initial guess of DOS\n\n update_weights:2-tuple of floats\n weights for DOS update strategies (continuity, area conservation)\n\n \"\"\"\n # create initial guess of dos\n Efull = sqe.E\n dE = sqe.E[1] - sqe.E[0]\n assert dE > 0, \"Energy axis must be incremental\"\n Eplus = Efull[Efull > -dE / 2]\n if abs(Eplus[0]) > dE / 1e6:\n raise EnergyAxisMissingBinCenterAtZero('\"0\" must be one of the bin centers of the energy axis')\n Eplus[0] = 0.\n if initdos is None:\n initdos = guess_init_dos(Eplus, Ecutoff)\n else:\n # make sure the energy axis is compatible with sqe\n dos_Eaxis_part1 = initdos[(Eplus[0], Eplus[-1])].E\n if dos_Eaxis_part1.size != Eplus.size or not np.allclose(dos_Eaxis_part1, Eplus):\n raise RuntimeError(\"Incompatible energy axis. DOS: %s, SQE: %s\" % (dos_Eaxis_part1, Eplus))\n pass\n # compute sqe from dos\n from ..forward.phonon import computeSQESet, kelvin2mev\n Q = sqe.Q\n dQ = Q[1] - Q[0]\n E = sqe.E\n dE = E[1] - E[0]\n beta = 1. / (T * kelvin2mev)\n Q2, E2, sqeset = computeSQESet(1, Q, dQ, initdos.E, dE, M, initdos.I, beta)\n # compute S(E) from SQE\n # - experiment\n # -- only need the positive part\n expsqe = sqe.copy()\n expsqe_Epositive = expsqe[(), (dE / 10, None)].I\n expsqeE2_Epositive = expsqe[(), (dE / 10, None)].E2\n mask = expsqe_Epositive != expsqe_Epositive\n expsqe_Epositive[mask] = 0\n expsqeE2_Epositive[mask] = 0\n expse = expsqe_Epositive.sum(0)\n expse_E2 = expsqeE2_Epositive.sum(0)\n # - simulation\n simsqe_arr = sqeset[0]\n simsqe = H.histogram('simsqe', [('Q', Q2, '1./angstrom'), ('E', E2, 'meV')], simsqe_arr)\n simsqe_Epositive = simsqe[(), (Eplus[0], Eplus[-1])]\n simsqe_Epositive.I[mask] = 0\n simse = simsqe_Epositive.I.sum(0)\n # apply scale factor to dos\n # but only at the range of the measurement\n N_Eplus = Eplus.size\n dos_in_range = initdos[(Eplus[0], Eplus[-1])].copy()\n with np.errstate(divide='ignore', invalid='ignore'):\n dos_in_range.I *= expse / simse\n # remember the relative error of the dos\n dos_relative_error = expse_E2 ** .5 / expse\n # clean up bad values\n dos_in_range.I[dos_in_range.I != dos_in_range.I] = 0\n # clean up data near elastic line\n n_small_E = (Eplus < elastic_E_cutoff[1]).sum()\n dos_in_range.I[:n_small_E] = Eplus[:n_small_E] ** 2 * dos_in_range.I[n_small_E] / Eplus[n_small_E] ** 2\n # keep positive\n dos_in_range.I[dos_in_range.I < 0] = 0\n dos_in_range.E2[:] = (dos_in_range.I * dos_relative_error)**2\n # DOS range to update should be smaller than SQE E range, so we need to\n Emin = Eplus[0]; Emax = min(Eplus[-1], Ecutoff)\n dos_to_update = dos_in_range[(Emin, min(Eplus[-1], Emax*2))]\n # update\n return update_dos(initdos, dos_to_update, Emin, Emax, weights=update_weights)\n\n\ndef update_dos(original_dos_hist, new_dos_hist, Emin, Emax, weights=None):\n # only if the spectrum is nontrivial beyond Emax, we need rescale\n \"\"\" Parameters\n ----------\n original_dos_hist:histogram\n original phonon density of states\n\n new_dos_hist:histogram\n new phonon density of states\n\n Emin:float\n minimum value for energy transfer axis\n\n Emax:float \n maximum value for energy transfer axis\n \n weights:float \n weights for DOS update strategies (continuity, area conservation)\n\n \"\"\"\n from .stitch_dos import DOSStitcher\n stitch = DOSStitcher(weights)\n return stitch(original_dos_hist, new_dos_hist, Emin, Emax)\n\n\ndef guess_init_dos(E, cutoff):\n \"\"\"return an initial DOS\n\n It is x^2 near E=0, and flat after that, until it reaches\n maximum E.\n \"\"\"\n dos = np.ones(E.size, dtype=float)\n dos[E > cutoff] = 0.\n end_of_E2_zone = cutoff / 3.\n dos[E < end_of_E2_zone] = (E * E / end_of_E2_zone / end_of_E2_zone)[E < end_of_E2_zone]\n dE = E[1] - E[0]\n norm = np.sum(dos) * dE\n g = dos / norm\n Eaxis = H.axis(\"E\", E, 'meV')\n return H.histogram(\"DOS\", [Eaxis], data=g)\n\n\n# the following methods are obsolete\n\"\"\"\ndef update_dos_continuous(original_dos_hist, Emin, Emax, g, gerr):\n return update_dos_(original_dos_hist, Emin, Emax, g, gerr, compute_scalefactor_using_continuous_criteria)\n\ndef update_dos_keep_area(original_dos_hist, Emin, Emax, g, gerr):\n \"update the lower E portion of the dos by keeping the area of the updated portion intact\"\n return update_dos_(original_dos_hist, Emin, Emax, g, gerr, compute_scalefactor_using_area_criteria)\n\ndef update_dos_(original_dos_hist, Emin, Emax, g, gerr, compute_scalefactor):\n \"update the lower E portion of the dos by using a function to compute the scale factor\" \n scale = compute_scalefactor(original_dos_hist, Emin, Emax, g)\n g *= scale\n # compute error bar\n gerr *= scale\n # compute new DOS\n newdos = original_dos_hist.copy()\n # by updating only the front portion\n newdos[(Emin, Emax)].I[:] = g\n newdos[(Emin, Emax)].E2[:] = gerr**2\n # now renormalize\n norm = newdos.I.sum()\n newdos.I/=norm\n newdos.E2/=norm*norm\n return newdos\n\"\"\"\n\n# End of file\n","sub_path":"multiphonon/backward/singlephonon_sqe2dos.py","file_name":"singlephonon_sqe2dos.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"378440861","text":"import torch\nfrom torch import nn\n\n\nclass ESIM(nn.Module):\n def __init__(self,\n vocab_len,\n wordvc_dim,\n hidden_dim = 300,\n output_dim = 3,\n weight_matrix=None,\n pretrained=False,\n fine_tune=False,\n dropout=0.5):\n super(ESIM, self).__init__()\n self.word_embeddings = nn.Embedding(vocab_len, wordvc_dim)\n self.pretrained = pretrained\n self.weight_matrix = weight_matrix\n\n self.fine_tune = fine_tune\n\n self.encoder = nn.LSTM(input_size=wordvc_dim, hidden_size=hidden_dim, num_layers=1, bidirectional=True, batch_first=True)\n\n self.softmax_a = nn.Softmax(dim=-1)\n self.softmax_b = nn.Softmax(dim=-2)\n\n self.inference = nn.LSTM(input_size=2*hidden_dim, hidden_size=hidden_dim, num_layers=1, bidirectional=True, batch_first=True)\n\n self.mlp = nn.Linear(8*hidden_dim, output_dim)\n self.act = nn.Tanh()\n\n self.dropout = nn.Dropout(dropout)\n\n self.init_weights()\n\n def init_weights(self):\n if self.pretrained:\n self.word_embeddings.weight.data.copy_(self.weight_matrix)\n self.word_embeddings.requires_grad_(self.fine_tune)\n\n def forward(self, input_a, input_b):\n # batch first\n input_a = input_a.transpose(0, 1)\n input_b = input_b.transpose(0, 1)\n # Word embedding\n embeddings_a = self.word_embeddings(input_a) # [batch_size, seq_len_a, emb_size]\n embeddings_a = self.dropout(embeddings_a)\n embeddings_b = self.word_embeddings(input_b) # [batch_size, seq_len_b, emb_size]\n embeddings_b = self.dropout(embeddings_b)\n\n # Input encoding\n encoded_a, _ = self.encoder(embeddings_a) # [batch_size, seq_len_a, 2 * hidden_size]\n encoded_a = self.dropout(encoded_a)\n encoded_b, _ = self.encoder(embeddings_b) # [batch_size, seq_len_b, 2 * hidden_size]\n encoded_b = self.dropout(encoded_b)\n\n # Local inference modeling\n attentions = torch.matmul(encoded_a, encoded_b.transpose(-2, -1)) # [batch_size, seq_len_a, seq_len_b]\n # Local inference collected over sequences\n summation_a = self.softmax_a(attentions)\n summation_a = torch.matmul(summation_a, encoded_b) # [batch_size, seq_len_a, 2 * hidden_size]\n\n summation_b = self.softmax_b(attentions).transpose(-2, -1)\n summation_b = torch.matmul(summation_b, encoded_a) # [batch_size, seq_len_b, 2 * hidden_size]\n\n # Enhancement of local inference information\n # difference\n diff_a = torch.sub(encoded_a, summation_a) # [batch_size, seq_len_a, 2 * hidden_size]\n diff_b = torch.sub(encoded_b, summation_b) # [batch_size, seq_len_b, 2 * hidden_size]\n # element-wise produce\n ewp_a = torch.mul(encoded_a, summation_a) # [batch_size, seq_len_a, 2 * hidden_size]\n ewp_b = torch.mul(encoded_b, summation_b) # [batch_size, seq_len_b, 2 * hidden_size]\n # concatenate\n # [batch_size, 4 * seq_len_a, 2 * hidden_size]\n enhancement_a = torch.cat((encoded_a, summation_a, diff_a, ewp_a), dim=-2)\n # [batch_size, 4 * seq_len_b, 2 * hidden_size]\n enhancement_b = torch.cat((encoded_b, summation_b, diff_b, ewp_b), dim=-2)\n\n # Inference Composition\n val_a, _ = self.inference(enhancement_a) # [batch_size, 4 * seq_len_a, 2 * hidden_size]\n val_a = self.dropout(val_a)\n val_b, _ = self.inference(enhancement_b) # [batch_size, 4 * seq_len_b, 2 * hidden_size]\n val_b = self.dropout(val_b)\n\n mean_a = torch.mean(val_a, dim=-2)\n max_a, _ = torch.max(val_a, dim=-2)\n mean_b = torch.mean(val_b, dim=-2)\n max_b, _ = torch.max(val_b, dim=-2)\n\n val = torch.cat((mean_a, max_a, mean_b, max_b), dim=-1) # [batch_size, 4 * 2 * hidden_size]\n\n # predict\n output = self.mlp(val)\n output = self.dropout(output)\n output = self.act(output)\n\n return output\n\n\nif __name__ == '__main__':\n from data_helper import get_iter\n\n vector_path = 'F:/DATASET/Glove/glove.6B/glove.6B.300d.txt'\n torch_device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n (text_field, label_field), (train_iter, dev_iter, test_iter) = get_iter(vector_path=vector_path,\n train_path='./data/snli_1.0_train.csv',\n dev_path='./data/snli_1.0_dev.csv',\n test_path='./data/snli_1.0_test.csv',\n file_format='csv',\n batch_size=32,\n torch_device=torch_device)\n model = ESIM(vocab_len=len(text_field.vocab), wordvc_dim=300, hidden_dim=64, output_dim=3, fine_tune=True,\n weight_matrix=text_field.vocab.vectors, pretrained=True, dropout=0.5)\n model.to(torch_device)\n model.eval()\n\n for iter in dev_iter:\n # print(iter.sentence1.size())\n print(model(iter.sentence1, iter.sentence2))\n break\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"413212429","text":"# coding=utf-8\n\"\"\"cvTesseract.py: Class to interface Tesseract OCR API\"\"\"\n\nimport tesseract\nimport cv2\nimport cv2.cv as cv\n\nclass OCR():\n\tdef __init__(self):\n\t\tself.api = tesseract.TessBaseAPI()\n\t\tself.api.Init(\".\",\"eng\",tesseract.OEM_DEFAULT)\n\t\tself.api.SetVariable(\"tessedit_char_whitelist\", \"ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ0-123456789\")\n\t\t#self.api.SetPageSegMode(tesseract.PSM_SINGLE_CHAR)\n\t\tself.api.SetPageSegMode(tesseract.PSM_SINGLE_LINE)\n\t\t\n\tdef __del__(self):\n\t\tself.api.End()\n\t\t\n\tdef recognize(self, img):\n\t\t\n\t\t#add 20 pixel border to image before processing\n\t\timg1=cv2.copyMakeBorder(img, 20,20,20,20, cv2.BORDER_CONSTANT, value=(255,255,255))\n\t\t\n\t\t#convert to IPL image \n\t\th,w = img1.shape\n\t\tiplimage = cv.CreateImageHeader((w,h), cv.IPL_DEPTH_8U, 1)\n\t\tcv.SetData(iplimage, img1.tostring(),img1.dtype.itemsize * w)\n\t\t\n\t\t#try to recognize the text\n\t\ttesseract.SetCvImage(iplimage,self.api)\n\t\ttext=self.api.GetUTF8Text()\n\t\tconf=self.api.MeanTextConf()\n\t\t\n\t\treturn text.strip(), conf\n\n","sub_path":"cvTesseract.py","file_name":"cvTesseract.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"365114760","text":"#coding:utf-8\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.common.keys import Keys\nimport unittest,time,re\nclass Youdao(unittest.TestCase):\n def setUp(self):\n self.browser = webdriver.Chrome()\n self.browser.maximize_window()\n self.browser.implicitly_wait(29)\n self.base_url = 'http://www.youdao.com/'\n self.verificationErrors = []\n self.accept_next_alert = True\n #有道搜索的测试用例\n def testyoudao_search(self):\n '''有道搜索'''\n browser = self.browser\n browser.get(self.base_url)\n browser.find_element_by_xpath('//*[@id=\"translateContent\"]').send_keys('这可能就是生活吧')\n browser.find_element_by_xpath('//*[@id=\"form\"]/button').click()\n time.sleep(4)\n #释放\n def tearDown(self):\n self.browser.close()\n self.assertEqual([],self.verificationErrors)\n#测试\nif __name__ == '__main__':\n unittest.main()\n\n#youdao.py 文件中编写一条用例\n\n","sub_path":"youdao.py","file_name":"youdao.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"636208661","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport heapq\nclass Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n if not heightMap or not heightMap[0]: return 0\n m=len(heightMap)\n n=len(heightMap[0])\n heap=[]\n seen=set()\n for i in range(n):\n heapq.heappush(heap,(heightMap[0][i],0,i))\n heapq.heappush(heap,(heightMap[m-1][i],m-1,i))\n seen.add((0,i))\n seen.add((m-1,i))\n for j in range(m):\n heapq.heappush(heap,(heightMap[j][0],j,0))\n heapq.heappush(heap,(heightMap[j][n-1],j,n-1))\n seen.add((j,0))\n seen.add((j,n-1))\n ans=0\n while heap:\n d,x,y=heapq.heappop(heap)\n for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]:\n new_x,new_y=x+dx,y+dy\n if new_x>=0 and new_x=0 and new_y 0:\n ordered_items = [v[0] for v in sorted(local_d.items(), key=lambda p:p[1], reverse=True)]\n update_tree(ordered_items, ret_tree, header_table, count)\n return ret_tree, header_table\n\n\ndef update_tree(items, in_tree, header_table, count):\n if items[0] in in_tree.children:\n in_tree.children[items[0]].inc(count)\n else:\n in_tree.children[items[0]] = tree_node(items[0], count, in_tree)\n if header_table[items[0]][1] == None:\n header_table[items[0]][1] = in_tree.children[items[0]]\n else:\n update_header(header_table[items[0]][1], in_tree.children[items[0]])\n if len(items) > 1:\n update_tree(items[1::], in_tree.children[items[0]], header_table, count)\n\n\ndef update_header(node_to_test, target_node):\n #寻找最后面的node 链表\n while (node_to_test.node_link != None):\n node_to_test = node_to_test.node_link\n node_to_test.node_link = target_node\n\n\ndef ascend_tree(leaf_node, prefix_path):\n if leaf_node.parent != None:\n prefix_path.append(leaf_node.name)\n ascend_tree(leaf_node.parent, prefix_path)\n\n\ndef find_prefix_path(base_pat, tree_node):\n cond_pats = {}\n while tree_node != None:\n prefix_path = []\n ascend_tree(tree_node, prefix_path)\n if len(prefix_path) > 1:\n cond_pats[frozenset(prefix_path[1:])] = tree_node.count\n tree_node = tree_node.node_link\n return cond_pats\n\n\ndef mine_tree(in_tree, header_table, min_sup, prefix, freq_item_list):\n bigL = [v[0] for v in sorted(header_table.items(), key=lambda p: p[1][0])]\n for base_pat in bigL:\n new_freq_set = prefix.copy()\n new_freq_set.add(base_pat)\n freq_item_list.append(new_freq_set)\n cond_patt_bases = find_prefix_path(new_freq_set, header_table[base_pat][1])\n my_cond_tree, my_head = create_tree(cond_patt_bases, min_sup)\n if my_cond_tree != None:\n my_cond_tree.disp()\n if my_head != None:\n mine_tree(my_cond_tree, my_head, min_sup, new_freq_set, freq_item_list)\n\n\ndef loadSimpDat():\n simpDat = [['r', 'z', 'h', 'j', 'p'],\n ['z', 'y', 'x', 'w', 'v', 'u', 't', 's'],\n ['z'],\n ['r', 'x', 'n', 'o', 's'],\n ['y', 'r', 'x', 'z', 'q', 't', 'p'],\n ['y', 'z', 'x', 'e', 'q', 's', 't', 'm']]\n return simpDat\n\n\ndef createInitSet(dataSet):\n retDict = {}\n for trans in dataSet:\n retDict[frozenset(trans)] = 1\n return retDict\n\n\nif __name__ == '__main__':\n simp_dat = loadSimpDat()\n init_dat = createInitSet(simp_dat)\n tree, header_table = create_tree(init_dat, 3)\n freqItems = []\n mine_tree(tree, header_table, 3, set([]), freqItems)\n","sub_path":"Ch12/my_fp_growth.py","file_name":"my_fp_growth.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"218138790","text":"def DataManupulate(element):\n\tfilterArr = list(filter(lambda no: no % 2 == 0 ,element))\n\tprint(filterArr)\n\tsquareNums = list(map(lambda no:(no**2),filterArr))\n\tprint(squareNums)\n\tresult = reduce(lambda no1, no2 : (no1+no2),squareNums)\n\tprint(result)\n\n\n\n\nelements = []\nelementCount = int(input(\"Number of Elments : \\n\"))\nprint('Eneter Elements list : \\n')\nfor i in range(elementCount):\n\telements.append(int(input()))\nprint(elements)\n\n\n\n\n\n\n\n# elements = [5, 2, 3, 4, 3, 4, 1, 2, 8, 10]\nDataManupulate(elements)","sub_path":"PyCodes/Assignment4/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"316167242","text":"# /usr/local/bin/python3.8\n# -*- coding: utf-8 -*-\n# @Time : 2021-03-25 5:51 下午\n# @Author : 张晨旭\n# @IDE : PyCharm\n# @PROJECT : Test_Api\n# @File : test_conntact.py\nimport requests\n\n\ndef get_token():\n r = requests.get(\n \"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww491558834d2ff0a1&corpsecret=XifeGU1Ud2Sn8PQXIETGVOWAISwvyxNRjkzbcuU9xFA\")\n token = r.json()[\"access_token\"]\n return token\n\ndef test_get_member():\n get_member_url = f\"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={get_token()}&userid=a001\"\n r =requests.get(get_member_url)\n print(r)\n print(r.json())\n\ndef test_update_member():\n update_member_url = f\"https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token={get_token()}\"\n data = {\n \"userid\": \"a001\",\n \"name\": \"李四\",\n }\n r = requests.post(url=update_member_url, json=data)\n print(r.json())\n\ndef test_del_member():\n del_member_url = f\"https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token={get_token()}&userid=root\"\n r = requests.get(del_member_url)\n print(r.json())\n\ndef test_add_member():\n add_member_url = f\"https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={get_token()}\"\n data = {\n \"userid\": \"zhangsan\",\n \"name\": \"张三\",\n \"mobile\": \"13800000000\",\n \"department\": [1],\n }\n r = requests.post(url=add_member_url, json=data)\n print(r.json())","sub_path":"test_conntact/test_conntact.py","file_name":"test_conntact.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"57727316","text":"## ChapGPT, Lanchain\n#import openai\nfrom dotenv import load_dotenv\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.schema import HumanMessage\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi import FastAPI, WebSocket\n\n## ChapGPT, Lanchain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.schema import HumanMessage\n\n## SQlAlchemy to connect Postgres\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import text\n\nSQLALCHEMY_DATABASE_URL = \"postgresql://test_dev:jhinchak_2023#@127.0.0.1/test_dev\"\n\nengine = create_engine(SQLALCHEMY_DATABASE_URL);\n\nwith engine.connect() as conn:\n result = conn.execute(text(\"select * from first;\"))\n print(result.all())\n\n\n## Initiate openAI and langchain\nload_dotenv('.env')\nchat = ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0)\nmessages = []\n\napp = FastAPI()\n\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n\ntemplates = Jinja2Templates(directory=\"templates\")\n\n## https://stackoverflow.com/questions/63667466/video-streaming-app-using-fastapi-and-opencv#63667607\n\n@app.get(\"/\")\nasync def index(request: Request):\n print ('I am here')\n #return HTMLResponse(html)\n return templates.TemplateResponse(\"item.html\", {\"request\": request})\n\n@app.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n print ('I am here too')\n await websocket.accept()\n print ('I am here as well')\n while True:\n data = await websocket.receive_text()\n print ('I am here repeat')\n\n ## Reponse from chatGPT\n ## https://www.haihai.ai/langchain/\n message = data;\n usr_msg = HumanMessage(content=message)\n messages.append(usr_msg)\n ai_msg = chat(messages)\n print(ai_msg.content)\n messages.append(ai_msg)\n\n with engine.connect() as conn:\n ## insert user message\n result = conn.execute(text(\"CALL SP_Ins_chatcomment(:user_id, :session_id, :user_type, :user_comment );\"), {\"user_id\":'test_usr', \"session_id\":'sessionTetsum',\"user_type\":'user',\"user_comment\":message} );\n ## insert ai message ##WORKS!!!\n #result = conn.execute(text(\"CALL SP_Ins_chatcomment(:user_id, :session_id, :user_type, :user_comment );\"), {\"user_id\":'test_usr', \"session_id\":'sessionTetsum',\"user_type\":'chatGPT',\"user_comment\":ai_msg.content} );\n ## Use named parameters!!! insert ai message ##WORKS!!!\n result = conn.execute(text(\"CALL SP_Ins_chatcomment(p_user_id => :user_id, p_session_id => :session_id, p_user_type => :user_type, p_user_comment => :user_comment );\"), {\"user_id\":'test_usr', \"session_id\":'sessionTetsum',\"user_type\":'chatGPT',\"user_comment\":ai_msg.content} );\n conn.commit();\n\n #await websocket.send_text(f\"Message text was: {data}\")\n await websocket.send_text(f\"{ai_msg.content}\")\n\n","sub_path":"try/fastAPI/src/example_websocket6_ninja_chatGPT_Postgres/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"410570164","text":"\n\nfrom xai.brain.wordbase.nouns._sluggard import _SLUGGARD\n\n#calss header\nclass _SLUGGARDS(_SLUGGARD, ):\n\tdef __init__(self,): \n\t\t_SLUGGARD.__init__(self)\n\t\tself.name = \"SLUGGARDS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"sluggard\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_sluggards.py","file_name":"_sluggards.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"77641868","text":"#!/usr/bin/python\n\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import WebDriverException\nfrom time import sleep\nfrom urllib.parse import urlparse\nfrom ui.login.zbUILoginCore import Login\nfrom ui.zbUIShared import *\nfrom common.zbCommon import validateDataNotEmpty\nimport pdb, time\n\n# global CSS parameters for Policies/Alert > Notify page\nCSS_SELECTOR_CHIP_INPUT = \"input.md-input[type='search']\"\nCSS_SELECTOR_INPUT_OPTIONS_CHIPS = \"md-virtual-repeat-container > div.md-virtual-repeat-scroller > div.md-virtual-repeat-offsetter > ul > li\"\n\nCSS_NOTIFY_SELECT_SYSTEM = \"[md-search-text='notifyCtrl.systemText'][md-selected-item='notifyCtrl.selectedSystemItem'] [name=''][type='search']\"\nCSS_NOTIFY_SELECT_THREAT = \"[md-search-text='notifyCtrl.threatText'] [name=''][type='search']\"\nCSS_NOTIFY_SELECT = \"[type='search']\"\nCSS_NOTIFY_THREAT_SECTION = 'div.threat-section'\nCSS_NOTIFY_SYSTEM_SECTION = 'div.system-section'\nCSS_NOTIFY_USERS = \"md-autocomplete-parent-scope strong.ng-binding\"\nCSS_NOTIFY_USER_CHIP = \"md-chip.ng-scope\" #\"[ng-model='notifyCtrl.threatUserList'] md-chip[ng-repeat='$chip in $mdChipsCtrl.items']\" #'md-chips > * > md-chip'\nCSS_CHIP_REMOVE_BUTTON = 'button.md-chip-remove'\nCSS_NOTIFY_SAVE_BUTTON = 'button[ng-click=\"notifyCtrl.submitTenantNotificationSettings()\"]'\nCSS_BUTTON_WRAPPER = \"li.ng-scope\"\n\n\nclass Notify():\n def __init__(self, **kwargs):\n self.params = kwargs\n self.selenium = Login(**kwargs).login()\n\n\n def gotoNotify(self):\n # go to Policies/Alerts > Notify\n url = urlparse(self.params[\"url\"])\n rcode = self.selenium.getURL(url.scheme+'://'+url.netloc+'/policiesalerts/notifications')\n waitLoadProgressDone(self.selenium)\n\n\n def verifyThreatNotifications(self, **kwargs):\n self.gotoNotify()\n rcode = self.configAddThreatNotifications(**kwargs)\n return rcode\n\n\n def verifySystemNotifications(self, **kwargs): \n self.gotoNotify() \n rcode = self.configAddSystemNotifications(**kwargs)\n return rcode\n\n def configAddThreatNotifications(self, **kwargs):\n \n # set default user if none entered\n # Using 'aaa Zbat Automation' in list because other accounts could not be found in dropdown or due to the need to scroll down\n\n user = kwargs[\"user\"] if \"user\" in kwargs else [\"aaa Zbat Automation\"]\n user = [x.lower() for x in user]\n user = ''.join(user)\n\n # initialize by delete all pre-existing user first\n self.configDeleteNotifyUser(user)\n\n # configure threat notification\n params = {\"selector\": CSS_NOTIFY_THREAT_SECTION, \"waittype\":\"visibility\", \"timeout\":3}\n threat = self.selenium.findSingleCSS(**params)\n params = {\"selector\": CSS_NOTIFY_SELECT_THREAT, \"waittype\":\"visibility\", \"timeout\":3}\n threatNotify = self.selenium.findSingleCSS(**params)\n if not threatNotify:\n print(\"Notification Threats not able to find recipient fields.\")\n return False\n threatNotify.click()\n time.sleep(1)\n \n \n threatNotify.send_keys(\"aaa\")\n params = {\"selector\":CSS_NOTIFY_USERS, \"waittype\":\"located\", \"timeout\":3, \"err_msg\": \"Unable to find users again\"}\n rcode = self.selenium.findMultiCSS(**params)\n if not rcode:\n print(\"Notification not able to find any users for System recipient\")\n for index, item in enumerate(rcode):\n if item.text.strip().lower() in user:\n item.click()\n time.sleep(1)\n break\n\n threatNotify.click()\n threatNotify.send_keys(Keys.ESCAPE)\n time.sleep(1)\n\n params = {\"selector\": CSS_NOTIFY_SAVE_BUTTON, \"waittype\":\"visibility\", \"timeout\":3}\n rcode = self.selenium.click(**params)\n\n # make sure that it's properly added\n rcode = self.configCheckUserExist(user, usertype=\"threat\")\n \n return rcode\n\n\n def configAddSystemNotifications(self, **kwargs):\n # set default user if none entered\n # Using 'aaa Zbat Automation' in list because other accounts could not be found in dropdown or due to the need to scroll down\n user = kwargs[\"user\"] if \"user\" in kwargs else [\"aaa Zbat Automation\"]\n user = [x.lower() for x in user]\n\n # initialize by delete all pre-existing user first\n self.configDeleteNotifyUser(user)\n\n # configure System notification\n params = {\"selector\": CSS_NOTIFY_SYSTEM_SECTION, \"waittype\":\"visibility\", \"timeout\":3}\n system = self.selenium.findSingleCSS(**params)\n params = {\"selector\": CSS_NOTIFY_SELECT_SYSTEM, \"waittype\":\"located\", \"timeout\":3}\n systemNotify = self.selenium.findSingleCSS(**params)\n if not systemNotify:\n print(\"Notification System not able to find recipient fields.\")\n return False\n \n \n systemNotify.click()\n time.sleep(1)\n \n \n systemNotify.send_keys(\"aaa\")\n params = {\"selector\":CSS_NOTIFY_USERS, \"waittype\":\"located\", \"timeout\":3, \"err_msg\": \"Unable to find users again\"}\n rcode = self.selenium.findMultiCSS(**params)\n if not rcode:\n print(\"Notification not able to find any users for System recipient\")\n for index, item in enumerate(rcode):\n if item.text.strip().lower() in user:\n item.click()\n time.sleep(1)\n break\n\n systemNotify.click()\n systemNotify.send_keys(Keys.ESCAPE)\n time.sleep(1)\n waitLoadProgressDone(self.selenium)\n params = {\"selector\": CSS_NOTIFY_SAVE_BUTTON, \"waittype\":\"visibility\", \"timeout\":3}\n rcode = self.selenium.click(**params)\n\n # make sure that it's properly added\n rcode = self.configCheckUserExist(user, usertype=\"system\")\n return rcode\n\n\n def configDeleteNotifyUser(self, user):\n userlist = [user] if type(user) == str else user\n #userlist = [x.lower() for x in userlist]\n\n '''\n params = {\"selector\": CSS_NOTIFY_THREAT_SECTION, \"waittype\":\"visibility\", \"timeout\":3}\n section = self.selenium.findSingleCSS(**params)\n params = {\"browserobj\": section, \"selector\": CSS_NOTIFY_SELECT, \"waittype\":\"visibility\", \"timeout\":3}\n field = self.selenium.findSingleCSS(**params)\n if not field:\n print \"Notification field not able to find any recipient\"\n return False\n '''\n params = {\"selector\": CSS_NOTIFY_USER_CHIP, \"waittype\":\"located\", \"timeout\":5}\n \n chips = self.selenium.findMultiCSS(**params)\n \n if not chips:\n print(\"No chips found\")\n # if no chips found, then no need to delete, return True.\n return True\n for chip in chips:\n chiptext = chip.text.split('\\n')[0]\n if chiptext.strip().lower() in userlist:\n params = {\"browserobj\":chip, \"selector\":CSS_CHIP_REMOVE_BUTTON, \"waittype\":\"clickable\", \"timeout\":3}\n rcode = self.selenium.click(**params)\n #field.send_keys(Keys.ENTER)\n time.sleep(1)\n params = {\"selector\": CSS_NOTIFY_SAVE_BUTTON, \"waittype\":\"visibility\", \"timeout\":3}\n rcode = self.selenium.click(**params)\n return rcode\n\n\n\n def configCheckUserExist(self, userlist, usertype=\"threat\"):\n self.gotoNotify()\n\n #userlist = [x.lower() for x in userlist]\n print(userlist)\n\n # configure threat notification\n if usertype == \"threat\":\n params = {\"selector\": CSS_NOTIFY_THREAT_SECTION, \"waittype\":\"visibility\", \"timeout\":3}\n if usertype == \"system\":\n params = {\"selector\": CSS_NOTIFY_SYSTEM_SECTION, \"waittype\":\"visibility\", \"timeout\":3}\n\n section = self.selenium.findSingleCSS(**params)\n params = {\"browserobj\": section, \"selector\": CSS_NOTIFY_SELECT, \"waittype\":\"visibility\", \"timeout\":3}\n field = self.selenium.findSingleCSS(**params)\n if not field:\n return False\n params = {\"browserobj\": section, \"selector\": CSS_NOTIFY_USER_CHIP, \"waittype\":\"visibility\", \"timeout\":5}\n chips = self.selenium.findMultiCSS(**params)\n\n if not chips:\n print(\"no matching user chip found\")\n return False\n for chip in chips:\n chiptext = chip.text.split('\\n')[0]\n if chiptext.strip().lower() in userlist:\n # found user match\n return True\n return False\n\n def close(self):\n if self.selenium:\n self.selenium.quit()\n","sub_path":"lib/ui/zbUINotify.py","file_name":"zbUINotify.py","file_ext":"py","file_size_in_byte":8642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"246247953","text":"#coding:utf-8\n\nimport numpy as np\nimport os\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\nimport cv2\n\nfrom collections import defaultdict\nfrom io import StringIO\n# from matplotlib import pyplot as plt\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nsys.path.append(\"..\")\nfrom object_detection.utils import ops as utils_ops\nfrom utils import label_map_util\nfrom utils import visualization_utils as vis_util\n\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\n# MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'\n# MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'\nMODEL_NAME = 'mask_rcnn_inception_v2_coco_2018_01_28'\nMODEL_FILE = MODEL_NAME + '.tar.gz'\nDOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\nPATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')\nNUM_CLASSES = 90\n\n# Mamually Install\n# opener = urllib.request.URLopener()\n# opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\n\n# Load a Tensorflow mode into memory\ndef load_frozenmodel():\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n return detection_graph\n\ndef load_labelmap():\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n return category_index\n\nclass ObjectDetection(object):\n def __init__(self, detection_graph, category_index):\n self.image_sub = rospy.Subscriber(\"/usb_cam/image_raw\", Image, self.imageCallback, queue_size=10)\n self.image_pub = rospy.Publisher(\"/object_detection/image\", Image, queue_size=10)\n self.detection_graph = detection_graph\n self.category_index = category_index\n\n def imageCallback(self, image_msg):\n try:\n self.cv_image = CvBridge().imgmsg_to_cv2(image_msg, \"bgr8\")\n except CvBridgeError as e:\n print (e)\n\n def main(self):\n rospy.init_node(\"object_detection_ros\")\n rate = rospy.Rate(30)\n with self.detection_graph.as_default():\n with tf.Session(graph=self.detection_graph) as sess:\n while not rospy.is_shutdown():\n image_np = self.cv_image\n image_np_expanded = np.expand_dims(image_np, axis=0)\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in [\n 'num_detections', 'detection_boxes', 'detection_scores',\n 'detection_classes', 'detection_masks'\n ]:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n tensor_name)\n if 'detection_masks' in tensor_dict:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image_np.shape[0], image_np.shape[1])\n detection_masks_reframed = tf.cast(\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict['detection_masks'] = tf.expand_dims(\n detection_masks_reframed, 0)\n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n # Run inference\n output_dict = sess.run(tensor_dict,\n feed_dict={image_tensor: np.expand_dims(image_np, 0)})\n\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict[\n 'detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\n \n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n self.category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=8)\n \n image_height = self.cv_image.shape[0]\n image_width = self.cv_image.shape[1]\n resize_image = cv2.resize(image_np, (image_width, image_height))\n pub_image = CvBridge().cv2_to_imgmsg(resize_image, \"bgr8\")\n self.image_pub.publish(pub_image)\n\ndef main():\n # Load \n category = load_labelmap()\n graph = load_frozenmodel()\n # Detection\n detection = ObjectDetection(graph, category)\n detection.main()\n\nif __name__ == '__main__':\n print(\"start\")\n main()\n","sub_path":"object_detection/mask_rcnn_ros.py","file_name":"mask_rcnn_ros.py","file_ext":"py","file_size_in_byte":6654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"106638282","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport pygame\nfrom ondas import *\nfrom circulo import *\nfrom pygame.locals import *\n\ndef eventos():\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\texit()\n\t\tif event.type == pygame.KEYDOWN:\n\t\t\tif event.key == K_ESCAPE:\n\t\t\t\texit()\n\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\tif pygame.mouse.get_pressed()[0]:\n\t\t\t\tlistado.put(circulo(2,2,pygame.mouse.get_pos(),[0,0,255]))\n\npygame.init()\nscreen = pygame.display.set_mode((1366,768))\ntimer = pygame.time.Clock()\nlistado = ondas()\n#c1 = circulo(200,2,[320,240])\n#listado.put(c1)\nlistado.test()\nwhile True:\n\teventos()\n\n\tlistado.pintar(screen)\n\tlistado.avance()\n\tpygame.display.flip()\n\ttimer.tick(100)\n","sub_path":"4- Efects/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"234174292","text":"\"\"\"\nVisualizador.\n\"\"\"\n\nimport glfw\nfrom OpenGL.GL import *\nimport numpy as np\nimport sys\n\nimport transformations2 as tr2\nimport easy_shaders as es\n\nfrom model import Tpose, Axis\nfrom controller import Controller\n\nif __name__ == '__main__':\n\n # Initialize glfw\n if not glfw.init():\n sys.exit()\n\n width = 600\n height = 600\n\n window = glfw.create_window(width, height, 'TPOSE EPIC', None, None)\n\n if not window:\n glfw.terminate()\n sys.exit()\n\n glfw.make_context_current(window)\n\n # Creamos el controlador\n controller = Controller()\n\n # Connecting the callback function 'on_key' to handle keyboard events\n glfw.set_key_callback(window, controller.on_key)\n\n # Creating shader programs for textures and for colores\n textureShaderProgram = es.SimpleTextureModelViewProjectionShaderProgram()\n colorShaderProgram = es.SimpleModelViewProjectionShaderProgram()\n\n # Setting up the clear screen color\n glClearColor(0.15, 0.15, 0.15, 1.0)\n\n # As we work in 3D, we need to check which part is in front,\n # and which one is at the back\n glEnable(GL_DEPTH_TEST)\n\n # Creamos los objetos\n axis = Axis()\n tpose = Tpose('img/ricardo.png', 'img/sad.png', 'img/mememan.png')\n # ricardo = feliz\n # sad = triste\n # mememan = neutral\n\n controller.set_toggle(tpose, 'face')\n controller.set_toggle(axis, 'axis')\n\n # Creamos la camara y la proyección\n projection = tr2.ortho(-1, 1, -1, 1, 0.1, 100)\n view = tr2.lookAt(\n np.array([10, 10, 5]), # Donde está parada la cámara\n np.array([0, 0, 0]), # Donde estoy mirando\n np.array([0, 0, 1]) # Cual es vector UP\n )\n\n while not glfw.window_should_close(window):\n\n # Using GLFW to check for input events\n glfw.poll_events()\n\n # Filling or not the shapes depending on the controller state\n if controller.fill_polygon:\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)\n else:\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)\n\n # Clearing the screen in both, color and depth\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n # Dibujamos\n axis.draw(colorShaderProgram, projection, view)\n tpose.draw(colorShaderProgram, textureShaderProgram, projection, view)\n\n # Once the drawing is rendered, buffers are swap so an uncomplete drawing is never seen.\n glfw.swap_buffers(window)\n\n glfw.terminate()\n","sub_path":"décimas/decima5/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"643186082","text":"\nimport pandas as pd\nimport numpy as np\nimport json\nimport itertools\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport sys\n\nn = len(sys.argv)\nif n < 2:\n print(\"Please input an anime name\")\n sys.exit()\n\npath_in_str = 'data/anime_list_final_231.json'\njson_file = open(path_in_str)\ndata = json.load(json_file)\nanime_df_raw = pd.DataFrame.from_dict(data, orient='index')\nanime_df_raw = anime_df_raw[anime_df_raw['error'] != 'not_found']\nanime_df = anime_df_raw[['id', 'title', 'mean', 'genres', 'statistics', 'num_episodes', 'synopsis']]\nanime_df = anime_df.dropna()\n\n\nanime_df['genres_name'] = anime_df['genres'].apply(lambda x : [a['name'] for a in x])\nanime_df['genres_id'] = anime_df['genres'].apply(lambda x : [a['id'] for a in x])\n\n\nanime_df['watching'] = anime_df['statistics'].apply(lambda x : x['status']['watching'])\nanime_df['num_list_users'] = anime_df['statistics'].apply(lambda x : x['num_list_users'])\nanime_df['completed'] = anime_df['statistics'].apply(lambda x : x['status']['completed'])\nanime_df['plan_to_watch'] = anime_df['statistics'].apply(lambda x : x['status']['plan_to_watch'])\nanime_df['dropped'] = anime_df['statistics'].apply(lambda x : x['status']['dropped'])\nanime_df['on_hold'] = anime_df['statistics'].apply(lambda x : x['status']['on_hold'])\n\n\nanime_df.drop(['genres', 'statistics'], axis=1, inplace=True)\n\n\nanime_df.rename({'id': 'anime_id'}, axis=1, inplace=True)\n\nnltk.download('wordnet', quiet = True)\nnltk.download('stopwords', quiet = True)\nnltk.download('averaged_perceptron_tagger', quiet = True)\nnltk.download('punkt', quiet = True)\n \n \n \nstop_words = set(stopwords.words('english'))\n\nlemmatizer = WordNetLemmatizer()\n\nverbs = {'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'}\n\n\ndef extract_tokens(text):\n text = text.lower()\n\n sentence =[]\n tokens = nltk.word_tokenize(text)\n tags = nltk.pos_tag(tokens)\n\n i = 0\n for token in tokens:\n if tags[i][1] not in verbs: \n lemma_tag = lemmatizer.lemmatize(token)\n else:\n lemma_tag = lemmatizer.lemmatize(token, 'v')\n\n\n if lemma_tag not in stop_words:\n if lemma_tag.isalpha():\n sentence.append(lemma_tag)\n i = i+1\n \n lemma_sentence = ' '.join(sentence)\n lemma_sentence = lemma_sentence.replace(\"'s\", \" is\")\n lemma_sentence = lemma_sentence.replace(\"'ve\", \" have\")\n lemma_sentence = lemma_sentence.replace(\"'ll\", \" will\")\n lemma_sentence = lemma_sentence.replace(\"'m\", \" am\")\n lemma_sentence = lemma_sentence.replace(\"n't\", \" not\")\n lemma_sentence = lemma_sentence.replace(\"'d\", \" would\")\n lemma_sentence = lemma_sentence.replace(\"'re\", \" are\")\n return lemma_sentence\n \nanime_df[\"lemma_synopsis\"]= anime_df[\"synopsis\"].apply(extract_tokens)\n\ntf_idf_vectorizer = TfidfVectorizer()\ntf_idf_anime_id = tf_idf_vectorizer.fit_transform((anime_df[\"lemma_synopsis\"]))\n \ncos_sim = cosine_similarity(tf_idf_anime_id, tf_idf_anime_id)\ntf_idf_vectorizer.get_feature_names_out().shape\n\n\n\n\ndef genre_agg(genres):\n return [genre for i in range(1, 6) for genre in itertools.combinations(genres, r=i)]\n\ntf_genre_vec = TfidfVectorizer(analyzer=genre_agg)\ntf_idf_genre = tf_genre_vec.fit_transform(anime_df['genres_name'])\ncos_sim_genre = cosine_similarity(tf_idf_genre, tf_idf_genre)\n\n\n\nanime_df['anime_id'] = anime_df['anime_id'].astype(int)\nanime_names = pd.Series(np.array(anime_df['title']))\n \ndef recommend_anime(title, max_reco = 10, cosine_sim = cos_sim, cosine_sim_genre = cos_sim_genre):\n recommended_animes = []\n index = anime_names[anime_names == title].index[0]\n # print(index)\n # print(anime_df.iloc[index])\n \n similar_scores = pd.Series(cosine_sim[index])\n similar_scores_genre = pd.Series(cosine_sim_genre[index])\n\n similar_scores_mul = similar_scores.mul(similar_scores_genre)\n similar_scores_mul = similar_scores_mul.sort_values(ascending=False)\n\n top_animes = list(similar_scores_mul.iloc[1:max_reco+1].index)\n for anime_index in top_animes:\n anime_row = anime_df.iloc[anime_index]\n anime_name = anime_row['title']\n recommended_animes.append(anime_name)\n return recommended_animes\n\n\n\nfor i in range(1, n):\n print(\"Anime recommendations for: \"+sys.argv[i])\n\n try:\n print(recommend_anime(sys.argv[i]))\n except:\n print(\"Invalid anime name according to MyAnimeList, please enter a valid name\")\n","sub_path":"tf_idf_syn_genre_recommender.py","file_name":"tf_idf_syn_genre_recommender.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"424843139","text":"import re\nimport htmlentitydefs\n\n##\n# From http://effbot.org/zone/re-sub.htm#unescape-html\n# Removes HTML or XML character references and entities from a text string.\n#\n# @param text The HTML (or XML) source text.\n# @return The plain text, as a Unicode string, if necessary.\n\ndef unescape(text):\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&#\":\n # character reference\n try:\n if text[:3] == \"&#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except ValueError:\n pass\n else:\n # named entity\n try:\n text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])\n except KeyError:\n pass\n return text # leave as is\n return re.sub(\"&#?\\w+;\", fixup, text)\n\ndef remove_quote(text, replacement=u\"\", quote_prefix=u\">\"):\n lines = []\n put_replacement = True\n for line in text.splitlines():\n if line.strip().startswith(quote_prefix):\n if put_replacement:\n lines.append(replacement)\n put_replacement = False\n else:\n lines.append(line)\n put_replacement = True\n return u\"\\n\".join(lines)\n\ndef remove_signature(text, dividers=[re.compile(r'^--\\s+')]):\n lines = []\n found = False\n for line in text.splitlines():\n for divider in dividers:\n if divider.match(line) is not None:\n found = True\n break\n if found:\n break\n lines.append(line)\n return u\"\\n\".join(lines)\n\nEMAIL_NAME_RE = re.compile(r'[,:]? \"?.*?\"? <[^@]+@[^>]+>')\n\ndef replace_email_name(text, replacement=u\"\"):\n return EMAIL_NAME_RE.sub(replacement, text)\n\nEMAIL_RE = re.compile(r'[^\\s]+@[^\\s]+')\n\ndef replace_email(text, replacement=u\"\"):\n return EMAIL_RE.sub(replacement, text)\n","sub_path":"froide/helper/text_utils.py","file_name":"text_utils.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"349343554","text":"# Import libraries\nimport math\nfrom src import *\nimport Space_Object\n\nclass Ship(Space_Object):\n # keys are passed as dictionary\n # {\"up\":, \"left\":, \"right\":, \"shoot\":}\n def __init__(self, pos, vel, rad, rot, ang, img, siz, cen, sca, sid, keys):\n Space_Object.__init__(self, pos, vel, rad, rot, ang, img, siz, cen, sca)\n self.sid = sid\n self.keys = keys\n self.lives = 3\n self.score = 0\n self.health = 100\n self.sheild = 100\n self.float_count = 0\n\n def update(self, game):\n # Get key presses\n key_U = (game.key_map.get(simplegui.KEY_MAP[self.keys[\"up\"]]) == True)\n key_L = (game.key_map.get(simplegui.KEY_MAP[self.keys[\"left\"]]) == True)\n key_R = (game.key_map.get(simplegui.KEY_MAP[self.keys[\"right\"]]) == True)\n\n # Check forward movement\n if (key_U):\n self.vel.x += math.cos(self.rot - (math.pi / 2)) * game.SHIP_FORWARD_THRUST\n self.vel.y += math.sin(self.rot - (math.pi / 2)) * game.SHIP_FORWARD_THRUST\n self.cen = [255,85]\n else:\n self.vel.x *= game.SHIP_BACKWARDS_DRAG\n self.vel.y *= game.SHIP_BACKWARDS_DRAG\n self.cen = [85,85]\n\n # Check rotation\n if (key_L and key_R):\n self.ang = 0\n self.cen = [255,85]\n elif (key_L):\n self.ang = -game.SHIP_ROTATION_SPEED\n self.cen = [595,85]\n elif (key_R):\n self.ang = game.SHIP_ROTATION_SPEED\n self.cen = [425,85]\n else:\n self.ang = 0\n\n # If no thrusters on, then drift slowly\n self.float_count += 1 \t\n if ((not key_U) and (not key_L) and (not key_R) and self.float_count % 5 == 0):\n self.pos.x += random.randint(-1, 1)\n self.pos.y += random.randint(-1, 1)\n\n Space_Object.update(self, game)\n \n \n def draw(self, game, canvas):\n # Draw ship stats\n if self.sid == \"L\":\n canvas.draw_text('Score: 0', (10,20), 20, COLOR, 'monospace')\n canvas.draw_line([10,35],[210,35], 10, \"Red\")\n canvas.draw_line([10,50],[210,50], 10, \"Blue\")\n else:\n canvas.draw_text('Score: 0', (game.CANVAS_W-210,20), 20, game.COLOR, 'monospace')\n canvas.draw_line([game.CANVAS_W-10,35],[game.CANVAS_W-210,35], 10, \"Red\")\n canvas.draw_line([game.CANVAS_W-10,50],[game.CANVAS_W-210,50], 10, \"Blue\")\n\n Space_Object.draw(self, canvas)","sub_path":"Asteroids/src/Ship.py","file_name":"Ship.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"512289067","text":"#!/usr/bin/env python\n#\n# Build dynamic library with JNI using user-provided arguments and place it to resources directory\n# of Maven package\n#\n# NOTE: this script must be python2/3 compatible\n#\n# How to use: build_native_for_maven.py []\n#\n\n\nfrom __future__ import absolute_import, print_function\n\nimport contextlib\nimport errno\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport zipfile\n\n\n@contextlib.contextmanager\ndef _tempdir(prefix=None):\n tmp_dir = tempfile.mkdtemp(prefix=prefix)\n yield tmp_dir\n # TODO(yazevnul): log error\n shutil.rmtree(tmp_dir, ignore_errors=True)\n\n\ndef _get_platform():\n if sys.platform.startswith('linux'):\n return 'linux'\n return sys.platform\n\ndef _get_arch():\n machine = platform.machine()\n if machine.lower() == 'amd64':\n return 'x86_64'\n return machine\n\n\ndef _get_arcadia_root():\n arcadia_root = None\n path = os.path.dirname(os.path.abspath(sys.argv[0]))\n while True:\n if os.path.isfile(os.path.join(path, '.arcadia.root')):\n arcadia_root = path\n break\n\n if path == os.path.dirname(path):\n break\n\n path = os.path.dirname(path)\n\n assert arcadia_root is not None, 'you are probably trying to use this script with repository being checkout not from the root'\n return arcadia_root\n\n\ndef _get_ya_path():\n ya_path = os.path.join(_get_arcadia_root(), 'ya')\n assert os.path.isfile(ya_path), 'no `ya` in arcadia root'\n assert os.access(ya_path, os.X_OK), '`ya` must be executable'\n return ya_path\n\n\ndef _get_package_resources_dir(base_dir):\n return os.path.join(base_dir, 'src', 'main', 'resources')\n\n\ndef _get_native_lib_dir(root_dir, package_arcadia_path):\n return os.path.join(root_dir, package_arcadia_path, 'src', 'native_impl')\n\n\ndef _ensure_dir_exists(path):\n try:\n os.makedirs(path)\n except OSError as e:\n import errno\n if e.errno != errno.EEXIST:\n raise\n\n\ndef _get_current_machine_resources_dir():\n return ''.join((_get_platform(), '-', _get_arch()))\n\n\ndef _extract_classes_from_jar(jar_file, dst_dir):\n with zipfile.ZipFile(jar_file, 'r') as zf:\n for member_name in zf.namelist():\n if member_name.endswith('.class'):\n zf.extract(member_name, dst_dir)\n\n\ndef _main():\n if len(sys.argv) < 3:\n raise Exception('Required basedir and library_name arguments is not specified')\n\n base_dir = sys.argv[1]\n lib_name = sys.argv[2]\n package_name = os.path.basename(os.path.abspath(base_dir))\n package_arcadia_path = os.path.relpath(base_dir, _get_arcadia_root())\n ya_path = _get_ya_path()\n resources_dir = _get_package_resources_dir(base_dir)\n _ensure_dir_exists(resources_dir)\n shared_lib_dir = os.path.join(\n resources_dir,\n _get_current_machine_resources_dir(),\n 'lib')\n _ensure_dir_exists(shared_lib_dir)\n native_lib_dir = _get_native_lib_dir(_get_arcadia_root(), package_arcadia_path)\n env = os.environ.copy()\n\n print('building dynamic library with `ya`', file=sys.stderr)\n sys.stderr.flush()\n\n with _tempdir(prefix='catboost_build-') as build_output_dir:\n ya_make = ([sys.executable, ya_path, 'make', native_lib_dir]\n + ['--output', build_output_dir]\n + ['-D', 'CATBOOST_OPENSOURCE=yes']\n + ['-D', 'CFLAGS=-DCATBOOST_OPENSOURCE=yes']\n + sys.argv[3:])\n print (' '.join(ya_make))\n subprocess.check_call(\n ya_make,\n env=env,\n stdout=sys.stdout,\n stderr=sys.stderr)\n\n native_lib_build_dir = _get_native_lib_dir(build_output_dir, package_arcadia_path)\n jar_name = lib_name + '.jar'\n jar_src_path = os.path.join(native_lib_build_dir, jar_name)\n if os.path.exists(jar_src_path):\n \"\"\"\n Ya Make's DLL_JAVA packs classes generated by SWIG into it's own jar,\n put these classes into resource dir to be added in main package's jar.\n \"\"\"\n\n print('extract classes from jar to resources', file=sys.stderr)\n _extract_classes_from_jar(jar_src_path, resources_dir)\n\n \"\"\"\n Copy jar with sources to target dir (needed for documentation generators)\n \"\"\"\n print('copy sources jar to target', file=sys.stderr)\n\n target_dir = os.path.join(base_dir, 'target')\n \"\"\"\n ensure that target directory exists, can't use exist_ok flag because it is unavailable in\n python 2.7\n \"\"\"\n try:\n os.makedirs(target_dir)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n shutil.copy(os.path.join(native_lib_build_dir, lib_name + '-sources.jar'), target_dir)\n\n native_lib_name = {\n 'darwin': 'lib{}.dylib',\n 'win32': '{}.dll',\n 'linux': 'lib{}.so',\n }[_get_platform()].format(lib_name)\n\n print('copying dynamic library to resources/lib', file=sys.stderr)\n shutil.copy(\n os.path.join(_get_native_lib_dir(build_output_dir, package_arcadia_path), native_lib_name),\n shared_lib_dir)\n\n\nif '__main__' == __name__:\n _main()\n","sub_path":"catboost/jvm-packages/tools/build_native_for_maven.py","file_name":"build_native_for_maven.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"320334986","text":"#coding: utf-8\r\n#-----------------------------\r\n# 安装脚本\r\n#-----------------------------\r\nimport sys,os,shutil\r\npanelPath = os.getenv('BT_PANEL')\r\nos.chdir(panelPath)\r\nsys.path.append(\"class/\")\r\nimport public,tarfile,time,re\r\n\r\nclass panel_nginx:\r\n _name = 'nginx'\r\n _version = None\r\n _setup_path = None\r\n\r\n def __init__(self,name,version,setup_path):\r\n self._name = name\r\n self._version = version\r\n self._setup_path = setup_path\r\n \r\n def install_soft(self,downurl): \r\n status = public.get_server_status('W3SVC')\r\n if status >=0:\r\n public.bt_print('准备卸载IIS..')\r\n os.system(\"iisreset /stop\") \r\n public.change_server_start_type('W3SVC',-1)\r\n\r\n if public.get_server_status(self._name) >= 0: \r\n public.delete_server(self._name)\r\n\r\n path = self._setup_path \r\n temp = self._setup_path + '/temp/' + self._name + self._version +'.rar'\r\n\r\n #配置PHP上传路径\r\n public.bt_print('正在更改PHP上传路径...')\r\n self.set_php_upload_path()\r\n\r\n public.bt_print('��在下载安装包...') \r\n public.downloadFile(downurl + '/win/nginx_new/'+ self._name + '.rar',temp)\r\n if not os.path.exists(temp): return public.returnMsg(False,'文件下载失败,请检查网络!');\r\n\r\n public.bt_print('正在解压...')\r\n from unrar import rarfile\r\n try: \r\n rar = rarfile.RarFile(temp) \r\n rar.extractall(path)\r\n except :\r\n time.sleep(1)\r\n rar = rarfile.RarFile(temp) \r\n rar.extractall(path)\r\n\r\n #设置启动权限\r\n public.bt_print('正在配置目录权限...')\r\n self.set_webserver_access()\r\n\r\n public.bt_print('正在配置' + self._name + '...')\r\n phps = self.get_php_versions()\r\n public.bt_print(phps)\r\n phps_str = ','.join(phps)\r\n \r\n import psutil\r\n cpuCount = psutil.cpu_count() / 2\r\n if cpuCount < 2: cpuCount = 2\r\n if cpuCount > 6: cpuCount = 6\r\n cpuCount = int(cpuCount)\r\n\r\n iniPath = self._setup_path + '/' + self._name + '/config.ini'\r\n conf = public.readFile(iniPath)\r\n conf = re.sub('path\\s?=.+','path = ' + public.format_path(self._setup_path),conf);\r\n conf = re.sub('php_versions\\s?=.+','php_versions = ' + phps_str,conf);\r\n conf = re.sub('php_cgi_thread\\s?=.+','php_cgi_thread = ' + str(cpuCount),conf);\r\n public.writeFile(iniPath,conf)\r\n\r\n public.bt_print('正在安装' + self._name + '服务...')\r\n password = public.readFile('data/www')\r\n if os.path.exists(self._setup_path + '/' + self._name + '/version.pl'): os.remove(self._setup_path + '/' + self._name + '/version.pl') \r\n\r\n #zend需要授权c:/Windows目录,无法www用户无法授权\r\n rRet = public.create_server(self._name,self._name,self._setup_path + '/' + self._name + '/nginx_server.exe','',\"nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行\")\r\n time.sleep(1);\r\n if public.get_server_status(self._name) >= 0:\r\n public.M('config').where(\"id=?\",('1',)).setField('webserver','nginx')\r\n if public.set_server_status(self._name,'start'):\r\n public.bt_print('安装成功.')\r\n return public.returnMsg(True,self._name + '安装成功')\r\n else:\r\n return public.returnMsg(False,'启动失败,请检查配置文件是否错误!') \r\n return rRet; \r\n\r\n def uninstall_soft(self):\r\n try:\r\n if os.path.exists(self._setup_path + '/phpmyadmin'): shutil.rmtree(self._setup_path + '/phpmyadmin')\r\n except :\r\n pass\r\n if public.get_server_status(self._name) >= 0: \r\n public.delete_server(self._name) \r\n time.sleep(2)\r\n shutil.rmtree(self._setup_path + '/' + self._name)\r\n\r\n return public.returnMsg(True,'卸载成功!');\r\n\r\n #更新软件\r\n def update_soft(self,downurl):\r\n files = ['config.ini','config/nginx.conf']\r\n for filename in files:\r\n filepath = self._setup_path + '/' + self._name + '/' + filename\r\n if os.path.exists(filepath): shutil.copy(filepath,filepath + '.backup');\r\n rRet = self.install_soft(downurl)\r\n if not rRet['status'] : rRet;\r\n \r\n for filename in files:\r\n filepath = self._setup_path + '/' + self._name + '/' + filename + '.backup'\r\n if os.path.exists(filepath): \r\n shutil.copy(filepath,filepath.replace('.backup',''));\r\n os.remove(filepath)\r\n \r\n return public.returnMsg(True,'更新成功!');\r\n\r\n #获取所有php版本\r\n def get_php_versions(self):\r\n phpPath = self._setup_path + '/php'\r\n phps = []\r\n if os.path.exists(phpPath): \r\n for filename in os.listdir(phpPath): \r\n if os.path.isdir(phpPath + '/' + filename):\r\n try: \r\n version = int(filename)\r\n phps.append(filename)\r\n except :\r\n pass\r\n return phps;\r\n\r\n #由于C:/Windows无法增加www权限,故修改上传目录到C:/Temp\r\n def set_php_upload_path(self): \r\n phps = self.get_php_versions()\r\n for version in phps:\r\n iniPath = self._setup_path + '/php' + '/' + version + '/php.ini'\r\n \r\n if os.path.exists(iniPath):\r\n conf = public.readFile(iniPath) \r\n conf = re.sub(';?upload_tmp_dir.+','upload_tmp_dir=\"C:/Temp\"',conf);\r\n public.writeFile(iniPath,conf)\r\n return True\r\n\r\n\r\n #恢复网站权限(仅适配nginx下www权限)\r\n def set_webserver_access(self):\r\n if not os.path.exists('C:/Temp'): os.makedirs('C:/Temp') \r\n public.set_file_access(\"C:/Temp\",\"IIS_IUSRS\",public.file_all,False)\r\n user = 'www'\r\n data = public.M('config').where(\"id=?\",('1',)).field('sites_path').find();\r\n\r\n if data['sites_path'].find('/www/') >=0 :\r\n wwwroot = os.getenv(\"BT_SETUP\")[:2] + '/wwwroot'\r\n if not os.path.exists(wwwroot): os.makedirs(wwwroot)\r\n\r\n backup_path = os.getenv(\"BT_SETUP\")[:2] + '/backup'\r\n if not os.path.exists(backup_path): os.makedirs(backup_path)\r\n \r\n public.M('config').where('id=?',(1,)).setField('backup_path',backup_path)\r\n public.M('config').where('id=?',(1,)).setField('sites_path',wwwroot)\r\n\r\n data = public.M('config').where(\"id=?\",('1',)).field('sites_path').find();\r\n\r\n #完全控制权限\r\n paths = [\"C:/Temp\", public.GetConfigValue('logs_path'), public.GetConfigValue('setup_path') + '/nginx' ,data['sites_path'] ] \r\n\r\n #只读权限\r\n flist = []\r\n for x in paths: public.get_paths(x,flist) \r\n #批量设置上层目录只读权限 \r\n for f in flist:\r\n print(\"正在设置 %s 权限\" % f)\r\n public.set_file_access(f,user,public.file_read,False)\r\n\r\n for f in paths: \r\n print(\"正在设置 %s 权限\" % f)\r\n public.set_file_access(f,user,public.file_all,False)\r\n\r\n public.set_file_access(os.getenv(\"BT_SETUP\") + '/nginx',user,public.file_all)\r\n\r\n return public.returnMsg(True,'权限恢复成功,当前仅恢复Nginx启动所需权限,网站权限需要手动恢复!')\r\n","sub_path":"PxZwlELmqyK1QsaW/c3233f6bd265232b643092f144354752a9ff24e1.py","file_name":"c3233f6bd265232b643092f144354752a9ff24e1.py","file_ext":"py","file_size_in_byte":7728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"633239715","text":"try:\n from os import scandir\nexcept ImportError:\n from scandir import scandir # use scandir PyPI module on Python < 3.5\n\ndef scantree(path):\n \"\"\"Recursively yield DirEntry objects for given directory.\"\"\"\n for entry in scandir(path):\n if entry.is_dir(follow_symlinks=False):\n yield from scantree(entry.path) # see below for Python 2.x\n else:\n yield entry\n\nif __name__ == '__main__':\n import sys\n mypath = '/Users/anandihalli/Documents/01_Work/brazil'\n for entry in scantree(mypath):\n if(entry.name != '.DS_Store'):\n print(entry.name)\n","sub_path":"Pyhton/Tests and genral scripts/test_2.py","file_name":"test_2.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"294614633","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/fynance/dev/set_neuralnetwork_tools.py\n# Compiled at: 2019-02-12 11:42:02\n# Size of source mod 2**32: 4877 bytes\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.optimizers import Adam\nfrom keras import regularizers, initializers, constraints\n__all__ = [\n 'incr_seed', 'set_layer', 'set_nn_model']\n\ndef incr_seed(SEED, incr=1):\n \"\"\" Increment seed \"\"\"\n if SEED is None:\n return\n return SEED + incr\n\n\ndef set_layer(nn, n_neurons, layer=Dense, dropout=None, SEED_dropout=None, **kwargs):\n \"\"\" Set `Dense` layers \n \n Parameters\n ----------\n :nn: keras.Model\n An initilized neural network (cf `Input` keras documation).\n :n_neurons: int\n Number of neurons to set in this layer.\n :layer: keras.layer\n Kind of layers to use.\n :dropout: float\n At each iteration an part of variables is dropout. cf keras doc.\n :SEED: int\n A number to set the random weights.\n :kwargs: any parameters of `Dense` \n cf keras documentation.\n \n Returns\n -------\n :nn: keras.Model\n Neural network with one more layer.\n \n \"\"\"\n if dropout is None:\n return layer(n_neurons, **kwargs)(nn)\n nn = layer(n_neurons, **kwargs)(nn)\n return Dropout(dropout, seed=SEED_dropout)(nn)\n\n\ndef set_nn_model(X, neurons_list=[], layer=Dense, SEED=None, SEED_dropout=None, l1=0.01, l2=0.01, dropout=None, lr=0.01, b_1=0.99, b_2=0.999, decay=0.0, name=None, loss='mse', metrics=['accuracy'], l1_bias=0.01, l2_bias=0.01, l1_acti=0.01, l2_acti=0.01, m=0.0, std=1.0, **kwargs):\n \"\"\" Set a very basic neural network with `Dense` layers.\n \n Parameters\n ----------\n :X: np.ndarray[ndim=2, dtype=np.float32]\n Matrix of features of shape (T, N) with T is the number of \n observations and N the number of features.\n :neurons_list: list of int\n Each number correspond at the number of neurons in corrsponding layers.\n :layer: keras.layer\n Kind of layers to use.\n :dropout: float\n At each iteration an part of variables is dropout. cf keras doc.\n :SEED: int\n A number to set the random weights.\n For other parameters cf Keras documentation.\n \n Returns\n -------\n :model: Keras.model\n A Neural Network ready to be train !\n \n \"\"\"\n T, N = X.shape\n KERN_REG = regularizers.l1_l2(l1=l1, l2=l2)\n BIAS_REG = regularizers.l1_l2(l1=l1_bias, l2=l2_bias)\n ACTIV_REG = regularizers.l1_l2(l1=l1_acti, l2=l2_acti)\n KERN_CONS = constraints.MinMaxNorm(min_value=(-2.0),\n max_value=2.0,\n rate=1.0,\n axis=0)\n BIAS_CONS = constraints.MinMaxNorm(min_value=(-2.0),\n max_value=2.0,\n rate=1.0,\n axis=0)\n inputs = Input(shape=(N,), sparse=False)\n kern_init = initializers.RandomNormal(mean=m, stddev=std, seed=SEED)\n SEED = incr_seed(SEED, incr=1)\n nn = set_layer(\n inputs, neurons_list[0], dropout=dropout, kernel_regularizer=KERN_REG, SEED_dropout=SEED_dropout, \n bias_regularizer=BIAS_REG, activity_regularizer=ACTIV_REG, \n kernel_initializer=kern_init, kernel_constraint=KERN_CONS, \n bias_constraint=BIAS_CONS, **kwargs)\n SEED_dropout = incr_seed(SEED_dropout, incr=1)\n for n_neurons in neurons_list[1:]:\n kern_init = initializers.RandomNormal(mean=m, stddev=std, seed=SEED)\n SEED = incr_seed(SEED, incr=1)\n nn = set_layer(\n nn, n_neurons, layer=layer, dropout=dropout, SEED_dropout=SEED_dropout, \n kernel_regularizer=KERN_REG, kernel_initializer=kern_init, \n bias_regularizer=BIAS_REG, activity_regularizer=ACTIV_REG, \n kernel_constraint=KERN_CONS, bias_constraint=BIAS_CONS, **kwargs)\n SEED_dropout = incr_seed(SEED_dropout, incr=1)\n\n kern_init = initializers.RandomNormal(mean=m, stddev=std, seed=SEED)\n SEED = incr_seed(SEED, incr=1)\n outputs = set_layer(\n nn, 1, dropout=dropout, SEED_dropout=SEED_dropout, kernel_regularizer=KERN_REG, \n bias_regularizer=BIAS_REG, activity_regularizer=ACTIV_REG, \n kernel_initializer=kern_init, kernel_constraint=KERN_CONS, \n bias_constraint=BIAS_CONS, **kwargs)\n SEED_dropout = incr_seed(SEED_dropout, incr=1)\n model = Model(inputs=inputs, outputs=outputs)\n model.name = name\n model.compile(optimizer=Adam(lr=lr,\n beta_1=b_1,\n beta_2=b_2,\n decay=decay,\n amsgrad=True),\n loss=loss,\n metrics=metrics)\n return model","sub_path":"pycfiles/fynance-1.0.8-py3.7-linux-x86_64/set_neuralnetwork_tools.cpython-37.py","file_name":"set_neuralnetwork_tools.cpython-37.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"284020453","text":"import json\nimport os\nimport sys\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import dates\n\n\ndef get_struct(file_name):\n with open(file_name,'r') as f:\n DATA_FULL=json.load(f)\n return DATA_FULL\n\n\ndef main():\n plt.rcParams['pdf.fonttype'] = 42\n plt.rcParams['font.family'] = 'Calibri'\n sis = sys.platform\n if sis == 'win32':\n file_name = os.getcwd() + '\\\\GES_DATA.json'\n else:\n file_name = os.getcwd() + '/GES_DATA.json'\n DATA=get_struct(file_name)\n WHAT_GRAF=\"Level\"\n #for name in DATA:\n for name in DATA:\n date=[]\n levels=[]\n for datem in DATA[name]:\n date.append(dates.date2num(datetime.strptime(datem[:-9],'%Y-%m-%d')))\n levels.append(DATA[name][datem][WHAT_GRAF])\n plt.figure()\n axes = plt.subplot(1, 1, 1)\n axes.xaxis.set_major_formatter (dates.DateFormatter(\"%d.%m.%y\"))\n plt.plot(date,levels)\n plt.grid()\n figname=name+\"_\"+WHAT_GRAF+\".png\"\n plt.savefig(figname, bbox_inches='tight')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Grafiki_Ischod.py","file_name":"Grafiki_Ischod.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"75178214","text":"import os\nimport logging\nfrom operator import mul\nfrom functools import reduce\nfrom discord.ext import commands\nfrom datetime import datetime as dt\n\nlogging.basicConfig(level=logging.INFO)\nbot = commands.Bot(command_prefix=commands.when_mentioned_or('/'), help_command=None)\nconfig = {\n 'daug': {\n 'guild_id': 494911447420108820,\n 'guild_logs_id': 674500858054180874,\n 'role_member_id': 579591779364372511,\n 'role_contributor_id': 631299456037289984,\n 'channel_tips_id': 693388545628438538,\n 'category_issues_id': 601219955035209729,\n 'category_open_id': 575935336765456394,\n 'category_closed_id': 640090897417240576,\n 'category_archive_id': 689447835590066212,\n },\n}\n\n\n@bot.event\nasync def on_ready():\n ID = reduce(mul, (2, 7, 11, 33637, 223253, 434803))\n await bot.get_channel(ID).send(dt.now().strftime(\"%Y/%m/%d %H:%M:%S\"))\n\n\nif __name__ == '__main__':\n bot.config = config\n bot.load_extension('jishaku')\n bot.load_extension('dispander')\n bot.load_extension('daug.extension')\n bot.load_extension('cogs.admin')\n bot.load_extension('cogs.database')\n bot.load_extension('cogs.public')\n bot.load_extension('cogs.werewolf')\n bot.run(os.environ['DISCORD_BOT_TOKEN'])\n","sub_path":"src/discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"228672357","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2019 Roberto Riggio\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"API Manager (REST Northbound Interface).\"\"\"\n\nimport inspect\nimport json\nimport base64\nimport re\n\nfrom uuid import UUID\n\nimport tornado.web\nimport tornado.httpserver\n\nfrom tornado.web import Application\nfrom pymodm.errors import ValidationError\n\nfrom empower_core.serialize import serialize\nfrom empower_core.service import EService\nfrom empower_core.launcher import srv_or_die, srv\nfrom empower_core.launcher import SERVICES\n\nDEBUG = True\nDEFAULT_PORT = 8888\nDEFAULT_WEBUI = \"/var/www/webui/\"\nCOOKIE_SECRET = b'xyRTvZpRSUyk8/9/McQAvsQPB4Rqv0w9mBtIpH9lf1o='\nLOGIN_URL = \"/auth/login\"\n\n\ndef validate(returncode=200, min_args=0, max_args=0):\n \"\"\"Validate REST method.\"\"\"\n\n def decorator(func):\n\n def magic(self, *args):\n\n try:\n\n if len(args) < min_args or len(args) > max_args:\n msg = \"Invalid url (%u, %u)\" % (min_args, max_args)\n raise ValueError(msg)\n\n params = {}\n\n if self.request.body and json.loads(self.request.body):\n params = json.loads(self.request.body)\n\n if \"version\" in params:\n del params[\"version\"]\n\n output = func(self, *args, **params)\n\n if returncode == 200:\n self.write_as_json(output)\n\n except KeyError as ex:\n self.send_error(404, message=str(ex))\n\n except ValueError as ex:\n self.send_error(400, message=str(ex))\n\n except AttributeError as ex:\n self.send_error(400, message=str(ex))\n\n except TypeError as ex:\n self.send_error(400, message=str(ex))\n\n except ValidationError as ex:\n self.send_error(400, message=ex.message)\n\n self.set_status(returncode, None)\n\n magic.__doc__ = func.__doc__\n\n return magic\n\n return decorator\n\n\n# pylint: disable=W0223\nclass BaseHandler(tornado.web.RequestHandler):\n \"\"\"Base Handler.\"\"\"\n\n # service associated to this handler\n service = None\n\n URLS = []\n\n def get_current_user(self):\n \"\"\"Return username of the currently logged user or None.\"\"\"\n\n return self.get_secure_cookie(\"username\")\n\n @classmethod\n def auth_based(cls):\n \"\"\"Return true if both account and project managers are available\"\"\"\n\n pmngr = srv(\"projectsmanager\")\n amngr = srv(\"accountsmanager\")\n\n return bool(pmngr and amngr)\n\n\nclass IndexHandler(BaseHandler):\n \"\"\"Index page handler.\"\"\"\n\n URLS = [r\"/\", r\"/([a-z]*).html\"]\n\n def get_project(self):\n \"\"\"Get the current project or return None if not project is set.\"\"\"\n\n # check if a project has been selected\n project_id = self.get_secure_cookie(\"project_id\")\n\n if not project_id:\n return None\n\n project_id = UUID(project_id.decode('UTF-8'))\n projects_manager = srv_or_die(\"projectsmanager\")\n\n if project_id not in projects_manager.projects:\n self.clear_cookie(\"project_id\")\n return None\n\n return projects_manager.projects[project_id]\n\n @tornado.web.authenticated\n def get(self, args=None):\n \"\"\"Render index page.\"\"\"\n\n try:\n\n if self.auth_based():\n\n username = self.get_secure_cookie(\"username\").decode('UTF-8')\n accounts_manager = srv_or_die(\"accountsmanager\")\n account = accounts_manager.accounts[username]\n\n page = \"index.html\" if not args else \"%s.html\" % args\n\n self.render(page,\n username=account.username,\n password=account.password,\n name=account.name,\n email=account.email,\n project=self.get_project())\n\n else:\n\n page = \"index.html\" if not args else \"%s.html\" % args\n\n self.render(page)\n\n except KeyError as ex:\n self.send_error(404, message=str(ex))\n\n except ValueError as ex:\n self.send_error(400, message=str(ex))\n\n\nclass AuthSwitchProjectHandler(BaseHandler):\n \"\"\"Login page handler.\"\"\"\n\n URLS = [r\"/auth/switch_project\"]\n\n def get(self):\n \"\"\"Set the active project.\"\"\"\n\n username = self.get_secure_cookie(\"username\").decode('UTF-8')\n\n # if root deselect project\n if username == \"root\":\n self.clear_cookie(\"project_id\")\n self.redirect('/')\n return\n\n # check if the project id is in the URL\n project_id = self.get_argument(\"project_id\", None)\n\n # reset project selected\n if not project_id:\n self.clear_cookie(\"project_id\")\n self.redirect('/')\n return\n\n try:\n\n # set project\n project_id = UUID(project_id)\n projects_manager = srv_or_die(\"projectsmanager\")\n project = projects_manager.projects[project_id]\n\n if project.owner != username:\n self.clear_cookie(\"project_id\")\n self.redirect('/')\n return\n\n self.set_secure_cookie(\"project_id\", str(project.project_id))\n\n except KeyError:\n self.clear_cookie(\"project_id\")\n\n except ValueError:\n self.clear_cookie(\"project_id\")\n\n self.redirect('/')\n\n\nclass AuthLoginHandler(BaseHandler):\n \"\"\"Login page handler.\"\"\"\n\n URLS = [r\"/auth/login\"]\n\n def get(self):\n \"\"\"Render login page.\"\"\"\n\n if not self.auth_based():\n self.set_secure_cookie(\"username\", \"none\")\n self.redirect('/')\n return\n\n if self.get_current_user():\n self.redirect('/')\n return\n\n self.render(\"login.html\", error=self.get_argument(\"error\", \"\"))\n\n def post(self):\n \"\"\"Process login credentials.\"\"\"\n\n username = self.get_argument(\"username\", \"\")\n password = self.get_argument(\"password\", \"\")\n\n accounts_manager = srv_or_die(\"accountsmanager\")\n\n if accounts_manager.check_permission(username, password):\n self.set_secure_cookie(\"username\", username)\n self.redirect(\"/index.html\")\n else:\n self.clear_cookie(\"username\")\n self.redirect(\"/auth/login?error=Wrong credentials!\")\n\n\nclass AuthLogoutHandler(BaseHandler):\n \"\"\"Logout page handler.\"\"\"\n\n URLS = [r\"/auth/logout\"]\n\n def get(self):\n \"\"\"Process logout request.\"\"\"\n\n self.clear_cookie(\"username\")\n self.clear_cookie(\"project_id\")\n self.redirect(\"/auth/login\")\n\n\nclass APIHandler(tornado.web.RequestHandler):\n \"\"\"Base class for all the REST calls.\"\"\"\n\n # service associated to this handler\n service = None\n\n @classmethod\n def auth_based(cls):\n \"\"\"Return true if both account and project managers are available\"\"\"\n\n pmngr = srv(\"projectsmanager\")\n amngr = srv(\"accountsmanager\")\n\n return bool(pmngr and amngr)\n\n def write_error(self, status_code, **kwargs):\n \"\"\"Write error as JSON message.\"\"\"\n\n self.set_header('Content-Type', 'application/json')\n\n value = {\n \"title\": self._reason,\n \"status_code\": status_code,\n \"detail\": kwargs.get(\"message\"),\n }\n\n self.finish(json.dumps(serialize(value), indent=4))\n\n def write_as_json(self, value):\n \"\"\"Return reply as a json document.\"\"\"\n\n self.write(json.dumps(serialize(value), indent=4))\n\n def prepare(self):\n \"\"\"Prepare to handler reply.\"\"\"\n\n self.set_header('Content-Type', 'application/json')\n\n # no account manager or project manager\n if not self.auth_based():\n return\n\n # get requests do not require authentication\n if self.request.method == \"GET\":\n return\n\n accounts_manager = srv_or_die(\"accountsmanager\")\n projects_manager = srv_or_die(\"projectsmanager\")\n\n auth_header = self.request.headers.get('Authorization')\n\n if auth_header is None or not auth_header.startswith('Basic '):\n self.set_header('WWW-Authenticate', 'Basic realm=Restricted')\n self.send_error(401, message=\"Missing authorization header\")\n return\n\n auth_bytes = bytes(auth_header[6:], 'utf-8')\n auth_decoded = base64.b64decode(auth_bytes).decode()\n username, password = auth_decoded.split(':', 2)\n\n # account does not exists\n if not accounts_manager.check_permission(username, password):\n self.send_error(401, message=\"Invalid username/password\")\n return\n\n account = accounts_manager.accounts[username]\n\n # root can do everything\n if account.username == \"root\":\n return\n\n # check if logged user is accessing his/her own account\n if self.request.uri.startswith(\"/api/v1/accounts\"):\n\n pattern = re.compile(\"/api/v1/accounts/([a-zA-Z0-9:-]*)/?\")\n match = pattern.match(self.request.uri)\n\n if match and match.group(1):\n username = match.group(1)\n if username == account.username:\n return\n\n # check if logged user is accessing one of his/her projects\n if self.request.uri.startswith(\"/api/v1/projects\"):\n\n pattern = re.compile(\"/api/v1/projects/([a-zA-Z0-9-]*)/?\")\n match = pattern.match(self.request.uri)\n\n if match and match.group(1):\n project_id = UUID(match.group(1))\n if project_id in projects_manager.projects:\n project = projects_manager.projects[project_id]\n if account.username == project.owner:\n return\n\n self.send_error(401, message=\"URI not authorized\")\n\n\nBOILER_PLATE = \"\"\"# REST API\n\nThe REST API consists of a set of RESTful resources and their attributes.\nThe base URL for the REST API is the following:\n\n http{s}://{username}:{password}@{hostname}:{port}/api/v1/{resource}\n\nOf course, you need to replace hostname and port with the hostname/port\ncombination for your controller.\n\nThe current (and only) version of the API is v1.\n\nThe REST API uses HTTP basic authentication control access to RESTful resource.\n\nNotice that there are two kinds of accounts:\n\n * user accounts, which have complete CRUD access only to all the URLs that\n begins with /api/v1/projects/{project_id}.\n\n * root account, which has complete CRUD access to all URLs. All the URLs that\n DO NOT start with /api/v1/projects/{project_id} require a root account to\n be accessed. The only exception is the URL /api/v1/accounts/{user_id} which\n is fully accessible to all users.\n \"\"\"\n\n\n# pylint: disable=W0223\nclass DocHandler(APIHandler):\n \"\"\"Generates markdown documentation.\"\"\"\n\n URLS = [r\"/api/v1/doc/?\"]\n\n def get(self):\n \"\"\"Generates markdown documentation.\n\n Args:\n\n None\n\n Example URLs:\n\n GET /api/v1/doc\n \"\"\"\n\n exclude_list = [\"StaticFileHandler\", \"DocHandler\"]\n handlers = set()\n accum = [BOILER_PLATE]\n\n for rule in self.service.application.default_router.rules:\n if not rule.target.rules:\n continue\n handlers.add(rule.target.rules[0].target)\n\n handlers = sorted(handlers, key=lambda x: x.__name__)\n\n accum.append(\"## Handlers\\n\")\n\n for handler in handlers:\n\n if handler.__name__ in exclude_list:\n continue\n\n accum.append(\" * [%s](#%s)\" %\n (handler.__name__, handler.__name__))\n\n accum.append(\"\\n\")\n\n for handler in handlers:\n\n if handler.__name__ in exclude_list:\n continue\n\n accum.append(\"# %s ([Top](#handlers))\\n\" %\n (handler.__name__, handler.__name__))\n\n accum.append(\"%s\\n\" % inspect.getdoc(handler))\n\n if hasattr(handler, \"URLS\") and handler.URLS:\n accum.append(\"### URLs\\n\")\n for url in handler.URLS:\n accum.append(\" %s\" % url)\n\n accum.append(\"\\n\")\n\n if hasattr(handler, \"get\"):\n doc = inspect.getdoc(getattr(handler, \"get\"))\n if doc:\n accum.append(\"### GET\\n\")\n accum.append(doc)\n accum.append(\"\\n\")\n\n if hasattr(handler, \"put\"):\n doc = inspect.getdoc(getattr(handler, \"put\"))\n if doc:\n accum.append(\"### PUT\\n\")\n accum.append(doc)\n accum.append(\"\\n\")\n\n if hasattr(handler, \"post\"):\n doc = inspect.getdoc(getattr(handler, \"post\"))\n if doc:\n accum.append(\"### POST\\n\")\n accum.append(doc)\n accum.append(\"\\n\")\n\n if hasattr(handler, \"delete\"):\n doc = inspect.getdoc(getattr(handler, \"delete\"))\n if doc:\n accum.append(\"### DELETE\\n\")\n accum.append(doc)\n accum.append(\"\\n\")\n\n self.write('\\n'.join(accum))\n\n\n# pylint: disable=W0223\nclass ManagersHandler(APIHandler):\n \"\"\"Handle managers.\"\"\"\n\n URLS = [r\"/api/v1/managers/?\",\n r\"/api/v1/managers/([a-zA-Z0-9-]*)/?\"]\n\n @validate(min_args=0, max_args=1)\n def get(self, *args):\n \"\"\"Get the active managers\n Args:\n [0]: the manager name\n \"\"\"\n\n if not args:\n return list(SERVICES.values())\n\n return SERVICES[args[0]]\n\n\nclass APIManager(EService):\n \"\"\"Service exposing a REST API\n\n Parameters:\n port: the port on which the HTTP server should listen (optional,\n default: 8888)\n \"\"\"\n\n HANDLERS = [IndexHandler, AuthLoginHandler, AuthLogoutHandler,\n DocHandler, ManagersHandler, AuthSwitchProjectHandler]\n\n def __init__(self, context, service_id, webui, port):\n\n super().__init__(context=context, service_id=service_id, webui=webui,\n port=port)\n\n self.settings = {\n \"static_path\": self.webui + \"static/\",\n \"cookie_secret\": COOKIE_SECRET,\n \"template_path\": self.webui + \"templates/\",\n \"login_url\": LOGIN_URL,\n \"debug\": DEBUG,\n }\n\n self.application = Application([], **self.settings)\n\n self.http_server = tornado.httpserver.HTTPServer(self.application)\n\n @property\n def webui(self):\n \"\"\"Return path to Web UI.\"\"\"\n\n return self.params[\"webui\"]\n\n @webui.setter\n def webui(self, value):\n \"\"\"Set path to Web UI.\"\"\"\n\n if \"webui\" in self.params and self.params[\"webui\"]:\n raise ValueError(\"Param webui can not be changed\")\n\n self.params[\"webui\"] = value\n\n @property\n def port(self):\n \"\"\"Return port.\"\"\"\n\n return self.params[\"port\"]\n\n @port.setter\n def port(self, value):\n \"\"\"Set port.\"\"\"\n\n if \"port\" in self.params and self.params[\"port\"]:\n raise ValueError(\"Param port can not be changed\")\n\n self.params[\"port\"] = int(value)\n\n def start(self):\n \"\"\"Start api manager.\"\"\"\n\n super().start()\n\n self.http_server.listen(self.port)\n\n self.log.info(\"Listening on port %u\", self.port)\n\n self.http_server.start()\n\n def register_handler(self, handler):\n \"\"\"Add a new handler class.\"\"\"\n\n for url in handler.URLS:\n self.log.info(\"Registering URL: %s\", url)\n self.application.add_handlers(r\".*$\", [(url, handler)])\n\n\ndef launch(context, service_id, webui=DEFAULT_WEBUI, port=DEFAULT_PORT):\n \"\"\" Initialize the module. \"\"\"\n\n return APIManager(context=context, service_id=service_id, webui=webui,\n port=port)\n","sub_path":"empower_core/apimanager/apimanager.py","file_name":"apimanager.py","file_ext":"py","file_size_in_byte":16584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"424217925","text":"# -*- coding: utf-8 -*-\r\n\r\nimport sqlite3, csv, gspread, configparser, re, glob, codecs\r\nfrom urllib.parse import _NetlocResultMixinStr\r\nfrom tkinter import filedialog, messagebox\r\nfrom tkinter import *\r\nfrom PIL import Image, ImageTk\r\n\r\n# remote_sheet_exists = False # Why is this here? Belongs in a class handling the database and/or cloud integration\r\n\r\nclass Editor: # Parent class\r\n def __init__(self):\r\n print(\"Starting editor...\")\r\n self.config = configparser.ConfigParser(allow_no_value=True) # no_value must be allowed so that we can read the list of valid pop types, which is just a list of names\r\n self.config.read('config/MapEditor.ini')\r\n\r\n self.remote_sheet = None # Set later by self.setup_remote_sheet()\r\n\r\n self.has_remote_sheet = True # If true, functions related to getting remote data will be used.\r\n\r\n self.remote_sheet_columns = self.get_remote_sheet_column_indices(self.config.items('AlphanumericColumns')) | self.get_remote_sheet_column_indices(self.config.items('NumericColumns'))\r\n sorted_tuples = sorted(self.remote_sheet_columns.items(), key=lambda item: item[1])\r\n self.remote_sheet_columns = {k: v for k, v in sorted_tuples}\r\n\r\n valid_cultures = self.get_valid_cultures(\"../../common/cultures/\")\r\n valid_religions = self.get_valid_religions(\"../../common/religions/\")\r\n valid_trade_goods = self.get_valid_trade_goods(\"../../common/trade_goods/\")\r\n\r\n # Declare the credentials var on init, but it will only be given a file at the credentials select stage by the GUI object\r\n self.remote_credentials = None # NEED TO GET THIS FROM GUI FUNCTION\r\n\r\n self.map_handler = MapHandler(\"land_input.bmp\",\"sea_input.bmp\")\r\n self.gui = EditorGUI(self.remote_sheet_columns,\r\n remote_sheet=None, # Remote sheet = none until loaded\r\n db = None, # Database = none until loaded\r\n valid_cultures = valid_cultures,\r\n valid_religions = valid_religions,\r\n valid_trade_goods = valid_trade_goods,\r\n config = self.config) \r\n # Prompt a selection of the database path\r\n db_path = self.gui.prompt_file_select()\r\n self.db = database_connection(self.remote_sheet,db_path)\r\n self.gui.db = self.db # Load database now that it has been initialised\r\n self.remote_credentials = self.gui.prompt_remote_credentials() # Get remote credentials\r\n self.setup_remote_sheet() # Load the remote data now that we have the credentials ready\r\n self.gui.remote_sheet = self.remote_sheet # Load the remote sheet for reference by GUI functions\r\n self.gui.start_main_gui()\r\n \r\n # Declare the map var on init, but it will only be given a file at the file select stage\r\n self.editor_file = None # NEED TO GET THIS FROM GUI FUNCTION\r\n\r\n def config_to_dict(self, input_config):\r\n config_as_dict = {s:dict(input_config.items(s)) for s in input_config.sections()}\r\n return config_as_dict\r\n\r\n def get_remote_sheet_column_indices(self, input_columns):\r\n remote_sheet_columns = dict(input_columns)\r\n for k, v in remote_sheet_columns.items():\r\n remote_sheet_columns[k] = int(v) # Convert the column indices to integers\r\n return remote_sheet_columns # Dict\r\n\r\n def setup_remote_sheet(self):\r\n remote_sheet_name = self.config['RemoteSheet']['SheetName']\r\n self.remote_sheet = RemoteSheet(\r\n sheet_name = remote_sheet_name, \r\n credentials = self.remote_credentials,\r\n column_indices = self.remote_sheet_columns\r\n )\r\n self.has_remote_sheet = True\r\n\r\n def get_valid_cultures(self, cultures_directory):\r\n replace_values = {\" \": \"\", \"{\": \"\", \"}\": \"\", \"=\": \"\",\r\n \"\\r\": \"\",\r\n \"\\t\": \"\"}\r\n replace_values = dict((re.escape(k), v) for k, v in replace_values.items())\r\n pattern = re.compile(\"|\".join(replace_values.keys()))\r\n valid_cultures = []\r\n for cultures_file in glob.glob(cultures_directory+\"*.txt\"):\r\n with codecs.open(cultures_file, \"r+\", \"utf-8-sig\") as culture_file_data:\r\n data = culture_file_data.read()\r\n # Find the bit that says cultures and cut off everything before\r\n #cultures = data.partition(\"culture = {\")[2]\r\n cultures = data.partition(\"culture = {\")[2]\r\n cultures = cultures.partition(\"barbarian_names\")[0]\r\n cultures = re.sub(\"#.*\", \"\", cultures)\r\n cultures = re.sub(\".*names\", \"\", cultures)\r\n cultures = re.sub(\".*family\", \"\", cultures)\r\n cultures = re.sub(\"\\\\{(.|\\\\n|\\\\r|\\\\t)*?\\\\}\", \"\", cultures)\r\n cultures = pattern.sub(lambda m: replace_values[re.escape(m.group(0))], cultures)\r\n cultures = cultures.split(\"\\n\")\r\n for culture in cultures:\r\n if len(culture) > 0 and culture not in valid_cultures:\r\n valid_cultures.append(culture)\r\n #cultures = cultures.partition(\"\")[1]\r\n #cultures = regex.sub(br'\\{[^()]*+(?:(?R)[^()]*)*+\\}', '', cultures)\r\n #print(cultures)\r\n culture_file_data.close()\r\n print(\"Valid cultures = \" + str(valid_cultures))\r\n return valid_cultures\r\n \r\n def get_valid_religions(self, religions_directory):\r\n replace_values = {\" \": \"\", \"{\": \"\", \"}\": \"\", \"=\": \"\",\r\n \"\\r\": \"\",\r\n \"\\t\": \"\",\r\n }\r\n replace_values = dict((re.escape(k), v) for k, v in replace_values.items())\r\n pattern = re.compile(\"|\".join(replace_values.keys()))\r\n valid_religions = []\r\n for religions_file in glob.glob(religions_directory+\"*.txt\"):\r\n with codecs.open(religions_file, \"r+\", \"utf-8-sig\") as religion_file_data:\r\n data = religion_file_data.read()\r\n # Find the bit that says religions and cut off everything before\r\n religions = re.sub(\" .*\", \"\", data)\r\n religions = re.sub(\" .*\", \"\", religions)\r\n religions = re.sub(\"\\\\{\\\\{[^}]*\\\\}\\\\}\", \"\", religions, re.MULTILINE | re.DOTALL)\r\n pattern = re.compile(\"|\".join(replace_values.keys()))\r\n religions = pattern.sub(lambda m: replace_values[re.escape(m.group(0))], religions)\r\n religions = re.sub(\"#.*\", \"\", religions)\r\n religions = religions.split(\"\\n\")\r\n for religion in religions:\r\n if len(religion) > 0 and religion not in valid_religions:\r\n valid_religions.append(religion)\r\n #religions = religions.partition(\"\")[1]\r\n #religions = regex.sub(br'\\{[^()]*+(?:(?R)[^()]*)*+\\}', '', religions)\r\n #print(religions)\r\n religion_file_data.close()\r\n print(\"Valid religions = \" + str(valid_religions))\r\n return valid_religions\r\n \r\n def get_valid_trade_goods(self, trade_goods_directory):\r\n replace_values = {\" \": \"\", \"{\": \"\", \"}\": \"\", \"=\": \"\",\r\n \"\\r\": \"\",\r\n \"\\t\": \"\",\r\n }\r\n replace_values = dict((re.escape(k), v) for k, v in replace_values.items())\r\n pattern = re.compile(\"|\".join(replace_values.keys()))\r\n valid_trade_goods = []\r\n for trade_goods_file in glob.glob(trade_goods_directory+\"*.txt\"):\r\n with codecs.open(trade_goods_file, \"r+\", \"utf-8-sig\") as trade_good_file_data:\r\n data = trade_good_file_data.read()\r\n # Find the bit that says trade_goods and cut off everything before\r\n trade_goods = re.sub(\" .*\", \"\", data)\r\n trade_goods = re.sub(\"\\t.*\", \"\", trade_goods)\r\n trade_goods = re.sub(\"\\\\{\\\\{[^}]*\\\\}\\\\}\", \"\", trade_goods, re.MULTILINE | re.DOTALL)\r\n pattern = re.compile(\"|\".join(replace_values.keys()))\r\n trade_goods = pattern.sub(lambda m: replace_values[re.escape(m.group(0))], trade_goods)\r\n trade_goods = re.sub(\"#.*\", \"\", trade_goods)\r\n trade_goods = trade_goods.split(\"\\n\")\r\n for trade_good in trade_goods:\r\n if len(trade_good) > 0 and trade_good not in valid_trade_goods:\r\n valid_trade_goods.append(trade_good)\r\n #trade_goods = trade_goods.partition(\"\")[1]\r\n #trade_goods = regex.sub(br'\\{[^()]*+(?:(?R)[^()]*)*+\\}', '', trade_goods)\r\n #print(trade_goods)\r\n trade_good_file_data.close()\r\n print(\"Valid tradegoods = \" + str(valid_trade_goods))\r\n return valid_trade_goods\r\n\r\n# MapHandler deals with the map image files\r\nclass MapHandler:\r\n def __init__(self, img_land, img_sea):\r\n # Images for the land and sea maps. These contain the colours of provinces and searegions\r\n self.img_land = Image.open(img_land,\"r\") # Should be PNG to save space\r\n self.img_sea = Image.open(img_sea,\"r\") # Should be PNG to save space\r\n\r\n # Create lists of colours in each file, which we can use to iterate through all the provinces/searegions\r\n # Each colour is effectively a unique ID for the province/searegion\r\n # Maxcolors set to 100,000 to exceed the default maximum, as we have over 10,000 provinces\r\n self.land_colours = self.img_land.getcolors(maxcolors=100000)\r\n self.sea_colours = self.img_sea.getcolors(maxcolors=100000)\r\n\r\n # List of colours in the land provinces file\r\n # Each item is a tuple of the RGB value of a land province's colour\r\n self.land_provinces = []\r\n # Add colours to the list. Index [1] of each is a tuple with the RGB value\r\n for colour in self.land_colours:\r\n self.land_provinces.append(colour[1])\r\n # Ignore white, which we use in the input images to delineate sea and land.\r\n self.land_provinces.remove((255,255,255))\r\n\r\n # List of colours in the sea provinces file\r\n # See above land provinces\r\n self.sea_provinces = []\r\n for colours in self.sea_provinces:\r\n self.sea_provinces.append(colour[1])\r\n\r\n # Get the total number of provinces\r\n # Why do we need this again?\r\n self.total_provinces = len(self.sea_provinces) + len(self.land_provinces)\r\n\r\n # Read back the lengths to the user\r\n print(str(len(self.sea_provinces)) + \" sea provinces found and \" +\r\n str(len(self.land_provinces)) + \" land provinces found.\")\r\n print(\"Total provinces in land and sea: \" + str(self.total_provinces))\r\n\r\n # Get the definition CSV file. If there isn't one, one will be generated on the first time it's loaded.\r\n try:\r\n self.definition_csv = open(\"definition.csv\",\"r\")\r\n except:\r\n self.definition_csv = False\r\n \r\n # Check for a local setup file - maybe not necessary if we're just pulling from the remote\r\n try:\r\n self.province_setup_csv = open(\"province_setup.csv\",'r',encoding='UTF-8')\r\n except:\r\n self.province_setup_csv = False\r\n\r\n\r\n \r\nclass RemoteSheet:\r\n # https://youtu.be/cnPlKLEGR7E?t=346\r\n def __init__(self, sheet_name, credentials, column_indices):\r\n self.credentials = credentials # Credentials are loaded from a separate file, selected when the user is prompted on startup\r\n \r\n client = gspread.service_account(filename=credentials)\r\n \r\n self.sheet = client.open(sheet_name).sheet1 # Sheet name is passed from config by the parent class\r\n\r\n self.column_indices = column_indices\r\n\r\n def write_to_sheet(self, provid, column, data):\r\n # Data is a row from the database\r\n rownum = int(provid) + 1\r\n column = column + 1 # Google sheets counts from 1. Great job, Google sheets. \r\n # colnum = self.column_indices[column]\r\n self.sheet.update_cell(rownum, column, str(data))\r\n \r\n def get_province_data(self, provid):\r\n # THOUGHTS:\r\n # Is it best to read straight from the sheet, and not rely on anything local at all?\r\n # We could just read one row at a time when we click on the corresponding province\r\n #\r\n # Process is as follows:\r\n # 1) Get the PROVID locally, from the save file using the RGB comparison\r\n # 2) Lookup the PROVID on the spreadsheet\r\n # 3) Return the data from that PROVID as a tuple/list\r\n province_data = self.sheet.row_values(int(provid) + 1) # Add one, as the first row is used by columns\r\n return province_data\r\n\r\n# Database connection class\r\n# Only needed for the definition reading so we can interpret the province map\r\n# As we will be reading directly from the remote sheet at all times\r\nclass database_connection(object):\r\n def __init__(self, column_indices, db_path):\r\n self.connection = sqlite3.connect(db_path)\r\n self.cursor = self.connection.cursor()\r\n \r\n self.load_db()\r\n\r\n self.checksum_query = \"\"\"INSERT OR IGNORE INTO province_checksums(province_checksum)\r\n VALUES (:checksum)\"\"\"\r\n\r\n self.definition_query = \"\"\"INSERT OR IGNORE INTO definition(\r\n Province_id,\r\n R,\r\n G,\r\n B,\r\n Name,\r\n x\r\n )\r\n VALUES (\r\n ?,\r\n ?,\r\n ?,\r\n ?,\r\n ?,\r\n ?\r\n )\"\"\"\r\n\r\n # A list to hold new provinces with checksums not existing in the current save\r\n self.new_sea_provinces = []\r\n self.new_land_provinces = []\r\n\r\n # A list of free province IDs which can be re-used when provinces are deleted\r\n self.free_ids = []\r\n\r\n self.column_indices = column_indices\r\n\r\n def db_fetchone(self):\r\n return self.cursor.fetchone()\r\n\r\n def setup_update_query(self, row):\r\n # Instead of defining the columns individually, just get their column index by the name\r\n for item in row:\r\n if item == \"\":\r\n item = \"0\"\r\n query = \"UPDATE province_setup SET Culture ='\" + row[self.column_indices(\"Culture\")]+\"',\" \\\r\n \" Religion ='\" + row[self.column_indices(\"Religion\")]+\"',\" \\\r\n \" TradeGoods ='\" + row[self.column_indices(\"Culture\")]+\"',\" \\\r\n \" Citizens =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" Freedmen =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" LowerStrata =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" MiddleStrata =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" Proletariat =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" Slaves =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" Tribesmen =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" UpperStrata =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" Civilization =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" SettlementRank =\" + row[self.column_indices(\"Culture\")]+\",\" \\\r\n \" NameRef ='\" + row[self.column_indices(\"Culture\")].replace(\"'\",\"’\")+\"',\" \\\r\n \" AraRef ='\" + row[self.column_indices(\"Culture\")].replace(\"'\",\"’\")+\"',\" \\\r\n \" Terrain ='\" + row[self.column_indices(\"Culture\")].replace(\"'\", \"’\") + \"' WHERE ProvID = \" + row[provid_col]\r\n return self.cursor.execute(query, \"\")\r\n\r\n def db_fetchall(self):\r\n return self.cursor.fetchall()\r\n\r\n def query(self,query,params):\r\n # For functions that don't need to create any new fields\r\n return self.cursor.execute(query,params)\r\n\r\n def commit_many(self,query,params):\r\n # For functions that create many new fields\r\n self.cursor.executemany(query, params)\r\n self.connection.commit()\r\n\r\n def db_commit(self,query):\r\n # For functions that need to create a new field\r\n self.cursor.execute(query)\r\n self.connection.commit()\r\n\r\n def load_db(self):\r\n # Populate a database with default province IDs\r\n db_schema = \"province_setup_schema.sql\"\r\n #Read the schema file and output it as a string\r\n all_schema_contents = str(open(db_schema).read())\r\n\r\n #Separate the schema contents into separate commands by semicolons\r\n individual_schema_contents = all_schema_contents.split(';')\r\n #Get rid of newline and tab indicators from the raw string\r\n for schema_command in individual_schema_contents:\r\n for ch in [\"\\n\", \"\\t\"]:\r\n schema_command.replace(ch, \"\")\r\n for schema_command in individual_schema_contents:\r\n self.db_commit(schema_command + \";\")\r\n\r\n def province_checksum(self,province):\r\n R = province[0]\r\n G = province[1]*1000\r\n B = province[2]*1000000\r\n province_checksum = R + G + B\r\n return str(province_checksum)\r\n\r\n\r\n def clear_old_provinces(self, provinces):\r\n RGB_query = \"SELECT R, G, B FROM definition;\"\r\n self.query(RGB_query, \"\")\r\n RGBs = self.db_fetchall()\r\n for RGB in RGBs:\r\n if RGB not in provinces:\r\n params = RGB\r\n search_query = \"SELECT Province_ID FROM definition WHERE R=? AND G=? AND B=?;\"\r\n self.query(search_query,params)\r\n province_id = str(self.db_fetchone()[0])\r\n print(\"Province \" + province_id + \" no longer exists\")\r\n self.free_ids.append(province_id)\r\n deletion_params = (province_id,)\r\n definition_deletion = \"DELETE FROM definition WHERE Province_ID = ?;\"\r\n self.query(definition_deletion,deletion_params)\r\n setup_deletion = \"DELETE FROM province_setup WHERE ProvID = ?;\"\r\n self.query(setup_deletion,deletion_params)\r\n # Also delete checksum from checksums table\r\n checksum_params = (self.province_checksum(RGB),)\r\n checksum_deletion = \"DELETE FROM province_checksums WHERE province_checksum = ?;\"\r\n self.query(checksum_deletion,checksum_params)\r\n if len(self.free_ids) > 0:\r\n self.db_commit(\"\")\r\n # Free up this RGB's Province ID\r\n # Add it to a list of free Province IDs to be assigned to new provinces\r\n # And make sure that other province IDs above it are shifted down\r\n\r\n def checksum_search(self, province):\r\n checksum = self.province_checksum(province)\r\n search_checksum_query = \"SELECT * FROM province_checksums WHERE province_checksum = \" + checksum + \";\"\r\n self.query(search_checksum_query,\"\")\r\n if self.db_fetchone() != None:\r\n # print(\"Checksum \" + checksum + \" verified\")\r\n return True\r\n else:\r\n # print(\"No previously existing province with checksum \" + checksum)\r\n return False \r\n\r\n def submit_province(self, province, provtype, new_province,i):\r\n R = str(province[0])\r\n G = str(province[1])\r\n B = str(province[2])\r\n # If the checksum does not exist, create the province\r\n if self.checksum_search(province) == False:\r\n if new_province == True:\r\n definition_params = (str(i), R, G, B, provtype+str(i),\"x\")\r\n definition_query = self.definition_query\r\n self.query(definition_query, definition_params)\r\n checksum_params = {\"checksum\":self.province_checksum(province)}\r\n checksum_query = self.checksum_query\r\n self.query(checksum_query, checksum_params)\r\n # print(\"Created definition for province \" + str(i))\r\n return True\r\n elif new_province == False:\r\n if provtype == \"seaprov\":\r\n self.new_sea_provinces.append(province)\r\n return False\r\n elif provtype == \"landprov\":\r\n self.new_land_provinces.append(province)\r\n return False\r\n\r\n def import_definition(self):\r\n # Import definition\r\n if definition_csv:\r\n rows = list(csv.reader(definition_csv, delimiter=\";\"))\r\n for i, row in enumerate(rows):\r\n rows[i] = list(row)\r\n for row in rows:\r\n # print(row)\r\n self.query(self.definition_query, (row[0], row[1], row[2], row[3], row[4], row[5]))\r\n self.connection.commit()\r\n\r\n def fill_definition(self):\r\n self.clear_old_provinces(land_sea_provinces)\r\n self.compensate_for_deleted_provinces()\r\n self.query(\"SELECT max(rowid) from definition;\",\"\")\r\n num_defined_provinces = self.db_fetchone()[0]\r\n if num_defined_provinces != None:\r\n i = num_defined_provinces + 1\r\n # print(\"Found \" + str(i - 1) + \" provinces already defined.\")\r\n else:\r\n i = 1\r\n while i < total_provinces:\r\n try:\r\n for province in land_provinces:\r\n if self.submit_province(province, \"landprov\", True,i) == True:\r\n i = i+1\r\n for province in sea_provinces:\r\n if self.submit_province(province, \"seaprov\", True,i) == True:\r\n i = i+1\r\n for province in self.new_land_provinces:\r\n self.submit_province(province, \"landprov\", False,i)\r\n i = i+1\r\n for province in self.new_sea_provinces:\r\n self.submit_province(province, \"seaprov\", False,i)\r\n i = i+1\r\n finally:\r\n self.db_commit(\"\")\r\n break\r\n\r\n def compensate_for_deleted_provinces(self):\r\n for free_id in self.free_ids:\r\n params = (free_id,)\r\n definition_query = \"UPDATE definition SET Province_id = (Province_id - 1) WHERE Province_id > ?;\"\r\n self.query(definition_query,params)\r\n province_setup_query = \"UPDATE province_setup SET ProvID = (ProvID - 1) WHERE ProvID > ?;\"\r\n self.query(province_setup_query,params)\r\n self.db_commit(\"\")\r\n\r\n def export_to_csv(self): # Rework - needs to export to CSV from sheet\r\n print(\"Exporting to CSV\")\r\n select_setup = \"SELECT * FROM province_setup;\"\r\n self.query(select_setup, \"\")\r\n with open(\"pyParaMapEditor_OUTPUT.csv\",\"w\", newline=\"\",encoding=\"UTF-8\") as csv_file:\r\n csv_writer = csv.writer(csv_file)\r\n csv_writer.writerow([i[0] for i in self.cursor.description])\r\n for row in self.cursor:\r\n # print(row)\r\n csv_writer.writerow(row)\r\n\r\nclass EditorGUI():\r\n def __init__(self, column_indices, remote_sheet, db, valid_cultures, valid_religions, valid_trade_goods, config):\r\n self.root = Tk()\r\n\r\n self.im_selector = Image.open(\"selector.gif\", \"r\")\r\n\r\n self.config = config # In order to get column identities\r\n self.minority_pop_start_column = self.config['MinorityPopDef']['StartColumn'] # Column where the first minority pop is defined\r\n self.minority_pop_columns = self.config['MinorityPopColumns']\r\n self.columns_per_minority = len(self.config.items('MinorityPopColumns')) # Number of columns to iterate per minority pop\r\n self.valid_pop_types = self.config['ValidPopTypes']\r\n\r\n self.remote_sheet = remote_sheet\r\n self.db = db # Reference to database for picking out province ID from RGB values on the image\r\n\r\n # Take the column names and use them for editable fields on the GUI. The names are stored as keys in the indices dict\r\n # Unpack the dict into a list literal\r\n self.data_fields = [*column_indices]\r\n\r\n # Get lists of valid cultures, religions and tradegoods in the mod so we can refuse to submit an invalid culture\r\n self.valid_cultures = valid_cultures\r\n self.valid_religions = valid_religions\r\n self.valid_trade_goods = valid_trade_goods\r\n\r\n def start_main_gui(self): # Called by main Editor class when it's time to call up the main view\r\n self.create_mapview()\r\n self.create_minorities_button()\r\n self.frame.pack(fill=BOTH,expand=1)\r\n self.add_map_canvas()\r\n\r\n self.list_of_entries = self.create_fields()\r\n self.create_minority_pop_fields()\r\n\r\n # Empty value for comparing when field values are changed\r\n self.entry_value = None\r\n\r\n # Empty value for comparing the previous selected province\r\n self.prevprovince = None\r\n\r\n self.selector_img = ImageTk.PhotoImage(Image.open(\"selector.gif\").convert(\"RGBA\"))\r\n\r\n #mouseclick event definitions\r\n self.canvas.bind_all(\"\", self._on_mousewheel_dn)\r\n self.canvas.bind_all(\"\", self._on_mousewheel_up)\r\n self.canvas.bind_all(\"\",self.scan)\r\n self.canvas.bind_all(\"\", lambda event, fieldvar=self.list_of_entries:self.submit_entry(event, fieldvar))\r\n self.canvas.bind(\"\", self.getprovince)\r\n # self.canvas.bind(\"\", self.zoom_view) # TODO\r\n\r\n self.root.mainloop()\r\n \r\n def prompt_file_select(self): # Select the local database, used for loading and saving map data. Data will also be saved to the remote sheet if there is one\r\n # We have to initialise Tkinter so we can create GUI, but we'll just use the default file select function\r\n file_select = Tk()\r\n # Hide the default Tkinter window, as we'll be popping up a file select dialog\r\n file_select.withdraw()\r\n file_name = filedialog.asksaveasfilename( # Use saveas as this allows the user to create a new file if there isn't one, or to load & overwrite an existing one\r\n initialdir = \"./\",\r\n title = \"Select or create map editor save file\",\r\n filetypes = ((\"all files\",\"\"),(\"all files\",\"*\"))\r\n )\r\n # Update the class attribute to select the database\r\n database_file = file_name\r\n file_select.destroy()\r\n return database_file # Pass this back to the main Editor class\r\n\r\n def prompt_remote_credentials(self): # Get the JSON credentials for connecting to the Google Sheet\r\n # We have to initialise Tkinter so we can create GUI, but we'll just use the default file select function\r\n credentials_select = Tk()\r\n credentials_select.withdraw()\r\n # Check if the user wants to connect to the remote sheet\r\n file_name = filedialog.askopenfilename(\r\n initialdir = \"./\",\r\n title = \"Select credentials for remote editing. Cancel to edit remotely\",\r\n filetypes = ((\"json files\",\"*.json\"),(\"json files\",\"*.json\"))\r\n )\r\n # Update the class attribute if a file was selected\r\n if str(file_name) != \"\":\r\n self.remote_credentials = file_name\r\n credentials_select.destroy()\r\n return(self.remote_credentials) # Flag that we are indeed using remote credentials\r\n\r\n def create_mapview(self):\r\n #setting up a tkinter canvas with scrollbars\r\n self.frame = Frame(self.root, bd=2, relief=SUNKEN)\r\n self.frame.grid_rowconfigure(0, weight=1)\r\n self.frame.grid_columnconfigure(0, weight=1)\r\n xscroll = Scrollbar(self.frame, orient=HORIZONTAL)\r\n xscroll.grid(row=1, column=0, sticky=E+W)\r\n yscroll = Scrollbar(self.frame)\r\n yscroll.grid(row=0, column=1, sticky=N+S)\r\n self.canvas = Canvas(self.frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)\r\n self.canvas.grid(row=0, column=0, sticky=N+S+E+W)\r\n xscroll.config(command=self.canvas.xview)\r\n yscroll.config(command=self.canvas.yview)\r\n\r\n self.editorframe = Frame(self.frame, bd=2, relief=SUNKEN, padx=30) # Main frame for basisc province data on the right of the map\r\n self.editorframe.grid(row=0, column=2)\r\n self.minoritiesframe = Frame (self.frame, bd=2, relief=SUNKEN, pady=30)# Extra frame for minority pop fields at the bottom\r\n self.minoritiesframe.grid(row=2, column = 0) # Beneath the map and X-axis scrollbar\r\n\r\n self.event2canvas = lambda e, c: (c.canvasx(e.x), c.canvasy(e.y))\r\n\r\n self.mousewheel = 0 # Mousewheel press status\r\n\r\n def export_to_csv(self):\r\n pass\r\n # Get data from Google Sheets API\r\n\r\n def create_minority_pop_fields(self):\r\n self.minority_pop_entries = []\r\n # Create 7 columns of 4 entry fields to populate each with the 4 minority pop columns\r\n entry_fields = self.config.items('MinorityPopColumns')\r\n num_minority_pops = self.config['MinorityPopDef']['NumMinorityPops']\r\n i = 1 # Value for column placement in the GUI\r\n ref_column = 0\r\n while i < ( int(num_minority_pops) * 2 ) + 1: # Double these to add space for labels between each column, and add one for space for the first label\r\n for field, value in entry_fields:\r\n self.make_minority_entry(self.minoritiesframe,field,value,i,str(int(value)+ref_column))\r\n ref_column = ref_column + self.columns_per_minority\r\n i = i+2\r\n \r\n def make_minority_entry(self, parent, caption, row_num, col_num, ref_column, **options):\r\n Label(parent, text=caption, pady=10).grid(row = row_num, column = str(int(col_num)-1))\r\n entry = Entry(parent, width=10, font=(\"Arial 18\"), **options)\r\n entry.category = \"minority_province_data\"\r\n entry.row = row_num\r\n entry.column = ref_column # Get the number of the column to search from in the remote sheet\r\n entry.name = caption\r\n entry.grid(row = row_num, column = col_num)\r\n self.minority_pop_entries.append(entry)\r\n return entry\r\n\r\n def get_minority_pop_entry_column(self, entry):\r\n column = int(self.minority_pop_start_column) + int(entry.column)\r\n return column\r\n \r\n def refresh_minority_pop_entry(self, entry):\r\n entry.config(state=\"normal\")\r\n entry.config({\"background\":\"yellow\"})\r\n entry.delete(0,999) # Clear the contents of the entry widget\r\n try:\r\n entry.insert(0,self.province_data[self.get_minority_pop_entry_column(entry)]) # Get the cell data from the remote sheet\r\n except Exception as ex: # If there is no data\r\n pass\r\n entry.config({\"background\":\"white\"}) # Reset colour as it may have been yellow or green when edited\r\n \r\n def create_fields(self):\r\n i = 1\r\n list_of_entries = []\r\n for field in self.data_fields:\r\n setting = \"normal\"\r\n if field == \"PROVID\":\r\n setting = \"readonly\"\r\n entry = self.make_entry(self.editorframe, field, i, state=setting)\r\n entry.bind(\"\", self.entry_changing)\r\n entry.bind(\"\", self.entry_changed)\r\n list_of_entries.append(entry) # Appends in column order\r\n i += 1\r\n return list_of_entries\r\n \r\n # These two functions handle how a field shows that its value has been edited but not submitted, or edited and submitted\r\n def entry_changing(self, event):\r\n value = event.widget.get()\r\n self.entry_value = value\r\n\r\n def entry_changed(self, event):\r\n value = event.widget.get()\r\n if value != self.entry_value:\r\n event.widget.config({\"background\":\"yellow\"})\r\n \r\n def create_minorities_button(self):\r\n minorities_button = Button(self.frame, command= lambda: self.view_minority_pops(), text=\"View minority pops\", bd=4, height=2, padx=2, bg=\"deep sky blue\")\r\n minorities_button.grid(row=1, column=2)\r\n\r\n # If name changes, it also needs to change in the definition.csv\r\n def change_name(self,submission):\r\n # definition.csv puts semicolons between spaces in names\r\n csv_submission = str(submission).replace(\" \",\";\")\r\n extra_query = \"UPDATE definition SET 'Name'='\" + csv_submission + \"' WHERE Province_id = \"+ self.list_of_entries[0].get() +\";\"\r\n self.db.db_commit(extra_query)\r\n print(\"Name changed in definition\")\r\n\r\n def make_entry(self, parent, caption, rownum, **options):\r\n Label(parent, text=caption, pady=10).grid(row = rownum, column = 0)\r\n entry = Entry(parent, width=16, font=(\"Arial 18\"), **options)\r\n entry.category = \"main_province_data\"\r\n entry.name = str(caption)\r\n entry.grid(row = rownum, column = 1)\r\n return entry\r\n\r\n def province_submission_warning(self, messagetitle, messagetext):\r\n messagebox.showwarning(messagetitle, messagetext)\r\n print(messagetitle + \" \" + messagetext)\r\n\r\n\r\n def validate_culture(self, event, submission):\r\n if submission not in self.valid_cultures:\r\n event.widget.config({\"background\":\"orange\"})\r\n self.province_submission_warning(\"Unrecognised culture\", \"The culture '\" + submission + \"' which you entered is invalid. Check for typos, or add the culture to the mod files before proceeding.\")\r\n return False\r\n \r\n def validate_religion(self, event, submission):\r\n if submission not in self.valid_religions:\r\n event.widget.config({\"background\":\"orange\"})\r\n self.province_submission_warning(\"Unrecognised religion\", \"The religion '\" + submission + \"' which you entered is invalid. Check for typos, or add the religion to the mod files before proceeding.\")\r\n return False\r\n\r\n def validate_trade_goods(self, event, submission):\r\n if submission not in self.valid_trade_goods:\r\n event.widget.config({\"background\":\"orange\"})\r\n self.province_submission_warning(\"Unrecognised tradegood\", \"The tradegood '\" + submission + \"' which you entered is invalid. Check for typos, or add the tradegood to the mod files before proceeding.\")\r\n return False\r\n \r\n def validate_numeric_only(self, event, submission):\r\n if not submission.isnumeric():\r\n event.widget.config({\"background\":\"orange\"})\r\n self.province_submission_warning(\"Value must be a number\", \"The value for this field must always be a number\")\r\n return False\r\n\r\n def validate_pop_type(self, event, submission):\r\n if submission not in self.valid_pop_types:\r\n event.widget.config({\"background\":\"orange\"})\r\n self.province_submission_warning(\"Invalid pop type\", \"The pop type '\" + submission + \"' which you entered is invalid. Check for typos.\")\r\n return False\r\n\r\n def submit_main_province_data(self, event, submission, fields):\r\n self.widget_id = fields.index(event.widget) # Get column number\r\n print(\"Attempting to submit value \" + submission + \" in field \" + event.widget.name)\r\n if event.widget.name == \"culture\":\r\n if self.validate_culture(event, submission) == False:\r\n return False\r\n elif event.widget.name == \"religion\":\r\n if self.validate_religion(event, submission) == False:\r\n return False\r\n elif event.widget.name == \"tradegoods\":\r\n if self.validate_trade_goods(event, submission) == False:\r\n return False\r\n elif event.widget.name == \"nameref\":\r\n self.change_name(submission)\r\n elif event.widget.name in {k.lower(): v for k, v in self.config.items('NumericColumns')}: # All others must only accept numeric data\r\n if self.validate_numeric_only(event, submission) == False:\r\n return False\r\n self.remote_sheet.write_to_sheet(provid = self.list_of_entries[0].get(), column = self.widget_id, data = submission)\r\n print(\"Submission successful\")\r\n\r\n def submit_minority_province_data(self, event, submission):\r\n print(\"Attempting to submit value \" + submission + \" in minority pop field \" + event.widget.name)\r\n if event.widget.name == \"culture\":\r\n if self.validate_culture(event, submission) == False:\r\n return False\r\n elif event.widget.name == \"religion\":\r\n if self.validate_religion(event, submission) == False:\r\n return False\r\n elif event.widget.name == \"size\":\r\n if self.validate_numeric_only(event, submission) == False:\r\n return False\r\n elif event.widget.name == \"poptype\":\r\n if self.validate_pop_type(event, submission) == False:\r\n return False\r\n self.remote_sheet.write_to_sheet(provid = self.list_of_entries[0].get(), column = self.get_minority_pop_entry_column(event.widget), data = submission)\r\n print(\"Submission successful\")\r\n \r\n def submit_entry(self, event, fields): # Refactored - write to remote only\r\n try:\r\n submission = event.widget.get()\r\n # Now find the field that corresponds to the widget\r\n # If event widget is in main province data\r\n if event.widget.category == \"main_province_data\":\r\n if self.submit_main_province_data(event, submission, fields) == False:\r\n return False # The submit data function will return False if the submission was erroneous, do not continue.\r\n # If the event widget is in minority pops\r\n elif event.widget.category == \"minority_province_data\":\r\n if self.submit_minority_province_data(event, submission) == False:\r\n return False # The submit data function will return False if the submission was erroneous, do not continue.\r\n # Send the submission to the database at the correct PROVID (list of entries 0) and column (widget_id)\r\n event.widget.config({\"background\":\"lime\"})\r\n except Exception as ex:\r\n print(\"Submission failed.\")\r\n print(ex)\r\n event.widget.config({\"background\":\"red\"})\r\n \r\n def add_map_canvas(self):\r\n self.canvas_img = ImageTk.PhotoImage(file='main_input.png', size=(1024,768))\r\n pxdata = Image.open('main_input.png','r')\r\n self.px = pxdata.load()\r\n self.canvas.create_image(0, 0, image=self.canvas_img, anchor=\"nw\")\r\n self.canvas.config(scrollregion=self.canvas.bbox(ALL))\r\n\r\n #function to be called when mouse is clicked\r\n def getprovince(self,event):\r\n #outputting x and y coords to console\r\n cx, cy = self.event2canvas(event, self.canvas)\r\n print (\"click at (%d, %d) / (%d, %d)\" % (event.x,event.y,cx,cy))\r\n colour = self.px[cx,cy]\r\n params = colour # Pass the RGB colour as a database query to find the PROVID\r\n self.refresh_selector_position(cx, cy) # Redraw selector and canvas, prevents lag\r\n province = self.lookup_province_rgb(params)\r\n # Do not refresh / overwrite the contents of data entry fields if the province is already selected\r\n if province != self.prevprovince:\r\n self.refresh_province_data_fields(province)\r\n \r\n def refresh_selector_position(self, cx, cy):\r\n # Clear the canvas and draw a selector where you last clicked\r\n self.canvas.delete(\"all\")\r\n self.canvas.create_image(0, 0, image=self.canvas_img, anchor=\"nw\")\r\n self.canvas.create_image((cx, cy), image=self.selector_img)\r\n \r\n def lookup_province_rgb(self, params):# Look in definition first to get the province ID from RGB\r\n search_query = \"SELECT Province_ID FROM definition WHERE R=? AND G=? AND B=?;\"\r\n self.db.query(search_query,params)\r\n province = str(self.db.db_fetchone()[0])\r\n return province\r\n \r\n def refresh_province_data_fields(self,province):\r\n self.prevprovince = province\r\n print(\"province ID is \" + province)\r\n # Below three lines are obsolete, as we will read directly from the remote sheet\r\n # province_data_query = \"SELECT * FROM province_setup WHERE ProvID = \" + province + \";\"\r\n # self.db.query(province_data_query, \"\")\r\n # province_data = self.db.db_fetchone()\r\n # TODO\r\n self.province_data = self.remote_sheet.get_province_data(province) # Get the row's data for this province from the remote spreadsheet\r\n for index, entry in enumerate(self.list_of_entries): # Load the new data for the relevant province from the province data sheet\r\n self.refresh_entry(index, entry)\r\n for entry in self.minority_pop_entries:\r\n self.refresh_minority_pop_entry(entry)\r\n\r\n def refresh_entry(self, index, entry):\r\n entry.config(state=\"normal\")\r\n entry.delete(0,999) # Clear the contents of the entry widget\r\n try:\r\n entry.insert(0,self.province_data[index]) # Get the cell data from the remote sheet\r\n except: # If there is no data\r\n pass\r\n entry.config({\"background\":\"white\"}) # Reset colour as it may have been yellow or green when edited\r\n if index == 0:\r\n entry.config(state=\"readonly\")\r\n \r\n def _on_mousewheel_dn(self, event):\r\n self.mousewheel = 1\r\n self.canvas.scan_mark(event.x, event.y)\r\n\r\n def _on_mousewheel_up(self, event):\r\n self.mousewheel = 0\r\n\r\n def scan(self, event):\r\n if self.mousewheel == 1:\r\n self.canvas.scan_dragto(event.x,event.y, gain = 1)\r\n\r\n\r\neditor = Editor()","sub_path":"map_data/pyParaMapEditor_imp19c/PyParaMapEditor_imp19c_v2.py","file_name":"PyParaMapEditor_imp19c_v2.py","file_ext":"py","file_size_in_byte":41933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"554704881","text":"from flask import Flask, render_template, make_response\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.linear_model import LinearRegression\nimport io\napp = Flask(__name__,static_folder='public')\n\n@app.route('/')\ndef index():\n dataset =pd.read_csv('Salary_Data.csv') #use the correct data set\n x=dataset.iloc[:,:-1].values\n y=dataset.iloc[:,1].values\n X_train, X_test, Y_train, Y_test=train_test_split(x,y,test_size=1/3,random_state=0)\n regressor = LinearRegression()\n regressor.fit(X_train,Y_train)\n fig = Figure()\n axis = fig.add_subplot(1, 1, 1)\n\n axis.scatter(X_train,Y_train,color='red')\n axis.plot(X_train,regressor.predict(X_train),color='blue')\n axis.set_title('asd')\n canvas = FigureCanvas(fig)\n output = io.BytesIO()\n canvas.print_png(output)\n response = make_response(output.getvalue())\n response.mimetype = 'image/png'\n return response\n\n@app.route('/home')\ndef home():\n return render_template('home.html')\n@app.route('/show')\ndef showGraph():\n return render_template('show.html')\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"aiml/webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"4946948","text":"def fight(text):\n \"\"\"\n >>> fight('')\n \"Let's fight again!\"\n >>> fight('abracadabra')\n 'army3 wins!'\n >>> fight('wmu')\n \"Let's fight again!\"\n \"\"\"\n\n army = {\n 'army1': {'w': 4, 'p': 3, 'b': 2, 's': 1},\n 'army2': {'m': 4, 'q': 3, 'd': 2, 'z': 1},\n 'army3': {'a': 4, 'e': 3, 'o': 2, 'u': 1, 'i': 1}\n }\n power = {}\n\n for name_army in army:\n power[name_army] = 0\n for char in text:\n power[name_army] += army[name_army].get(char, 0)\n max_power_befor = max(power.values())\n max_power_army_befor = list(power.keys())[list(power.values()).index(max_power_befor)]\n power_compare = {}\n power_compare[max_power_army_befor] = max_power_befor\n del power[max_power_army_befor]\n max_power_after = max(power.values())\n max_power_army_after = list(power.keys())[list(power.values()).index(max_power_after)]\n power_compare[max_power_army_after] = max_power_after\n if power_compare[max_power_army_befor] != power_compare[max_power_army_after]:\n return f\"{max_power_army_befor} wins!\"\n else:\n return \"Let's fight again!\"\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","sub_path":"Alphabet war.py","file_name":"Alphabet war.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"102384082","text":"import telnetlib\nimport re\nimport time\n\n\ndef extractip(ip, port, interface):\n import time\n import telnetlib\n import re\n ipRegexPatt = re.compile('(([2][5][0-5]\\.)|([2][0-4][0-9]\\.)|([0-1]?[0-9]?[0-9]\\.)){3}'\n + '(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9]))')\n\n telNetSession = telnetlib.Telnet()\n\n telNetSession.open(ip, port)\n\n time.sleep(2)\n\n telNetSession.write('enable\\n')\n time.sleep(2)\n\n telNetSession.write('show ip int brief ' + interface + '\\n')\n\n time.sleep(2)\n\n ResultString = telNetSession.read_very_eager()\n telNetSession.close()\n\n result = ipRegexPatt.search(ResultString)\n return result.group()\n\n\nclass IpExtractorClass:\n pass\n","sub_path":"Scratchfiles/IpExtractor.py","file_name":"IpExtractor.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"111986530","text":"#\n# === Introduction ===\n#\n# In this problem, you will again build a planner that helps a robot\n# find the best path through a warehouse filled with boxes\n# that it has to pick up and deliver to a dropzone. Unlike Part A,\n# however, in this problem the robot is moving in a continuous world\n# (albeit in discrete time steps) and has constraints on the amount\n# it can turn its wheels in a given time step.\n# \n# Your file must be called `partB.py` and must have a class\n# called `DeliveryPlanner`.\n# This class must have an `__init__` function that takes five \n# arguments: `self`, `warehouse`, `todo`, `max_distance`, and\n# `max_steering`.\n# The class must also have a function called `plan_delivery` that \n# takes a single argument, `self`.\n#\n# === Input Specifications ===\n# \n# `warehouse` will be a list of m strings, each with n characters,\n# corresponding to the layout of the warehouse. The warehouse is an\n# m x n grid. warehouse[i][j] corresponds to the spot in the ith row\n# and jth column of the warehouse, where the 0th row is the northern\n# end of the warehouse and the 0th column is the western end.\n#\n# The characters in each string will be one of the following:\n#\n# '.' (period) : traversable space.\n# '#' (hash) : a wall. If the robot contacts a wall space, it will crash.\n# '@' (dropzone): the space where all boxes must be delivered. The dropzone may be traversed like \n# a '.' space.\n#\n# Each space is a 1 x 1 block. The upper-left corner of space warehouse[i][j] is at the point (j,-i) in\n# the plane. Spaces outside the warehouse are considered walls; if any part of the robot leaves the \n# warehouse, it will be considered to have crashed into the exterior wall of the warehouse.\n# \n# For example, \n# warehouse = ['.#.',\n# '.#.',\n# '..@']\n# is a 3x3 warehouse. The dropzone is at space (2,-2) and there are walls at spaces (1,0) \n# and (1,-1). The rest of the warehouse is empty space.\n#\n# The robot is a circle of radius 0.25. The robot begins centered in the dropzone space.\n# The robot's initial bearing is 0.\n#\n# The argument `todo` is a list of points representing the center point of each box.\n# todo[0] is the first box which must be delivered, followed by todo[1], and so on.\n# Each box is a square of size 0.2 x 0.2. If the robot contacts a box, it will crash.\n#\n# The arguments `max_distance` and `max_steering` are parameters constraining the movement\n# of the robot on a given time step. They are described more below.\n#\n# === Rules for Movement ===\n#\n# - The robot may move any distance between 0 and `max_distance` per time step.\n# - The robot may set its steering angle anywhere between -`max_steering` and \n# `max_steering` per time step. A steering angle of 0 means that the robot will\n# move according to its current bearing. A positive angle means the robot will \n# turn counterclockwise by `steering_angle` radians; a negative steering_angle \n# means the robot will turn clockwise by abs(steering_angle) radians.\n# - Upon a movement, the robot will change its steering angle instantaneously to the \n# amount indicated by the move, and then it will move a distance in a straight line in its\n# new bearing according to the amount indicated move.\n# - The cost per move is 1 plus the amount of distance traversed by the robot on that move.\n#\n# - The robot may pick up a box whose center point is within 0.5 units of the robot's center point.\n# - If the robot picks up a box, it incurs a total cost of 2 for that move (this already includes \n# the 1-per-move cost incurred by the robot).\n# - While holding a box, the robot may not pick up another box.\n# - The robot may put a box down at a total cost of 1.5 for that move. The box must be placed so that:\n# - The box is not contacting any walls, the exterior of the warehouse, any other boxes, or the robot\n# - The box's center point is within 0.5 units of the robot's center point\n# - A box is always oriented so that two of its edges are horizontal and the other two are vertical.\n# - If a box is placed entirely within the '@' space, it is considered delivered and is removed from the \n# warehouse.\n# - The warehouse will be arranged so that it is always possible for the robot to move to the \n# next box on the todo list without having to rearrange any other boxes.\n#\n# - If the robot crashes, it will stop moving and incur a cost of 100*distance, where distance\n# is the length it attempted to move that move. (The regular movement cost will not apply.)\n# - If an illegal move is attempted, the robot will not move, but the standard cost will be incurred.\n# Illegal moves include (but are not necessarily limited to):\n# - picking up a box that doesn't exist or is too far away\n# - picking up a box while already holding one\n# - putting down a box too far away or so that it's touching a wall, the warehouse exterior, \n# another box, or the robot\n# - putting down a box while not holding a box\n#\n# === Output Specifications ===\n#\n# `plan_delivery` should return a LIST of strings, each in one of the following formats.\n#\n# 'move {steering} {distance}', where '{steering}' is a floating-point number between\n# -`max_steering` and `max_steering` (inclusive) and '{distance}' is a floating-point\n# number between 0 and `max_distance`\n# \n# 'lift {b}', where '{b}' is replaced by the index in the list `todo` of the box being picked up\n# (so if you intend to lift box 0, you would return the string 'lift 0')\n#\n# 'down {x} {y}', where '{x}' is replaced by the x-coordinate of the center point of where the box\n# will be placed and where '{y}' is replaced by the y-coordinate of that center point\n# (for example, 'down 1.5 -2.9' means to place the box held by the robot so that its center point\n# is (1.5,-2.9)).\n#\n# === Grading ===\n# \n# - Your planner will be graded against a set of test cases, each equally weighted.\n# - Each task will have a \"baseline\" cost. If your set of moves results in the task being completed\n# with a total cost of K times the baseline cost, you will receive 1/K of the credit for the\n# test case. (Note that if K < 1, this means you earn extra credit!)\n# - Otherwise, you will receive no credit for that test case. This could happen for one of several \n# reasons including (but not necessarily limited to):\n# - plan_delivery's moves do not deliver the boxes in the correct order.\n# - plan_delivery's output is not a list of strings in the prescribed format.\n# - plan_delivery does not return an output within the prescribed time limit.\n# - Your code raises an exception.\n#\n# === Additional Info ===\n# \n# - You may add additional classes and functions as needed provided they are all in the file `partB.py`.\n# - Your partB.py file must not execute any code when it is imported. \n# - Upload partB.py to Project 2 on T-Square in the Assignments section. Do not put it into an \n# archive with other files.\n# - Ask any questions about the directions or specifications on Piazza.\n#\nimport numpy as np\nfrom math import *\n\nPI = pi\n\ndef padding(warehouse, n=5):\n warehouse = np.array(warehouse)\n r = len(warehouse[0])*n\n c = len(warehouse)*n\n n_pad = int(0.25*n)\n new_ware = np.array([['.']*r]*c)\n for i in range(len(warehouse)):\n for j in range(len(warehouse[i])):\n if warehouse[i][j] == '#':\n for k in range(max(0,i*n-n_pad),min(r*n,(i+1)*n+n_pad)):\n for l in range(max(0,j*n-n_pad),min(c*n,(j+1)*n+n_pad)):\n try:\n new_ware[k][l] = '#'\n except IndexError:\n continue\n warehouse_padded=[]\n for row in new_ware.tolist():\n warehouse_padded.append(\"\".join(row))\n \n return warehouse_padded\n\ndef angle_trunc(a):\n \"\"\"This maps all angles to a domain of [-pi, pi]\"\"\"\n while a < 0.0:\n a += pi * 2\n return ((a + pi) % (pi * 2)) - pi\n\nclass DeliveryPlanner:\n\n def __init__(self, warehouse, todo, max_distance, max_steering):\n self.ori_todo = todo\n self.n = len(warehouse)\n self.m = len(warehouse[0])\n self.k = 4\n self.max_distance = max_distance\n self.max_steering = max_steering\n \n new_ware = padding(warehouse, self.k)\n self.warehouse = new_ware\n \n new_todo = []\n for target in todo:\n (j,i) = target\n i = -int(i*self.k)\n j = int(j*self.k)\n new_todo.append([i,j])\n self.todo = new_todo\n \n for i in range(self.n):\n for j in range(self.m):\n if warehouse[i][j]==\"@\":\n self.remove = [j+0.5, -i-0.5]\n self.dz = [i*self.k+2, j*self.k+2]\n \n\n def plan_delivery(self):\n \n moves = []\n current = self.dz\n now = 0\n for x in range(0, len(self.todo)):\n target = x\n\n goal = self.todo[x]\n \n route = self.find_route(current, goal, target)\n route1 = self.zip_route(route)\n new_route = route1[:len(route1)-1]\n new_move,now = self.route2move(new_route,now)\n moves += new_move\n \n lift = 'lift '+ str(target)\n moves.append(lift)\n \n route2 = route1[::-1]\n new_route = route2[1:]\n new_move,now = self.route2move(new_route,now)\n moves += new_move\n \n down = 'down '+str(self.remove[0])+' '+str(self.remove[1])\n moves.append(down)\n \n return moves\n\n def find_route(self, init, goal, target):\n grid = list()\n for i in range(self.n*self.k):\n line1 = list()\n for j in range(self.m*self.k):\n if self.warehouse[i][j] in [\"@\", \".\"]:\n line1.append(0)\n elif self.warehouse[i][j]==\"#\":\n line1.append(1)\n grid.append(line1)\n \n for todo1 in self.todo[target+1:]:\n x = todo1[0]\n y = todo1[1]\n grid[x][y] = 1\n try:\n grid[x+1][y] = 1\n grid[x-1][y] = 1\n grid[x][y+1] = 1\n grid[x][y-1] = 1\n grid[x+1][y+1] = 1\n grid[x-1][y+1] = 1\n grid[x-1][y-1] = 1\n grid[x+1][y-1] = 1\n except IndexError:\n continue\n \n heuristic = [[-1 for col in range(len(grid[0]))] for row in range(len(grid))]\n for i in range(self.n):\n for j in range(self.m):\n distance = ( (i-goal[0])**2 + (j-goal[1])**2 ) ** 0.5\n heuristic[i][j] = distance\n \n delta = [[-1, 0],[0,-1],[1,0],[0,1],\n [-1,-1],[-1,1],[1,-1],[1,1]]\n \n closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]\n closed[init[0]][init[1]] = 1\n \n expand = [[9999 for col in range(len(grid[0]))] for row in range(len(grid))]\n \n x = init[0]\n y = init[1]\n g = 0\n f = g + heuristic[x][y]\n \n open = [[f, g, x, y]]\n \n found = False # flag that is set when search is complete\n resign = False # flag set if we can't find expand\n count = 0\n \n while not found and not resign:\n if len(open) == 0:\n resign = True\n return \"Fail\"\n else:\n open.sort()\n open.reverse()\n next = open.pop()\n x = next[2]\n y = next[3]\n g = next[1]\n expand[x][y] = count\n count += 1\n \n if x == goal[0] and y == goal[1]:\n found = True\n else:\n for i in range(len(delta)):\n x2 = x + delta[i][0]\n y2 = y + delta[i][1]\n if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):\n if closed[x2][y2] == 0 and grid[x2][y2] == 0:\n if i < 4:\n g2 = g + 2\n else:\n g2 = g + 3\n f2 = g2 + heuristic[x2][y2]\n open.append([f2, g2, x2, y2])\n closed[x2][y2] = 1\n route = [goal]\n current = goal\n cost1 = expand[current[0]][current[1]]\n while expand[current[0]][current[1]]>0:\n for i in range(len(delta)):\n x2 = current[0] + delta[i][0]\n y2 = current[1] + delta[i][1]\n if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):\n if expand[x2][y2]1 or abs(diff3[1])>1:\n x1 = temp[0] + copysign(abs(diff3[0])-1.3, diff3[0])\n y1 = temp[1] + copysign(abs(diff3[1])-1.3, diff3[1])\n out_route.append([x1,y1])\n out_route.append(route[len(route)-1])\n return out_route\n \n def route2move(self, route, now):\n route = np.array(route)\n turns = []\n for i in range(1,len(route)):\n x = route[i][1]-route[i-1][1]\n y = route[i-1][0]-route[i][0]\n distance = (x**2 + y**2)**0.5 / self.k\n angle = atan2(y, x)\n angle = angle_trunc(angle)\n turn = angle_trunc(angle-now)\n \n if abs(turn)>self.max_steering:\n string = \"move \"+str(turn/2)+\" 0\"\n turns.append(string)\n if distance>self.max_distance:\n string = \"move \"+str(turn/2)+\" \"+str(distance/2) \n turns.append(string)\n string = \"move 0 \"+str(distance/2)\n turns.append(string)\n else:\n string = \"move \"+str(turn/2)+\" \"+str(distance) \n turns.append(string)\n else: \n if distance>self.max_distance:\n string = \"move \"+str(turn)+\" \"+str(distance/2) \n turns.append(string)\n string = \"move 0 \"+str(distance/2)\n turns.append(string)\n else:\n string = \"move \"+str(turn)+\" \"+str(distance) \n turns.append(string)\n now = angle\n return turns,now\n\n#warehouse=['#######.',\n# '#.......',\n# '#@......']\n#todo=[(7.5, -1.5), (7.5, -0.5)]\n#max_distance=3.0\n#max_steering=PI / 2. + 0.01\n#\n#exec_count = 1\n#def execute_student_plan(warehouse, todo,\n# max_distance, max_steering):\n# global exec_count\n#\n# student_planner = DeliveryPlanner(warehouse, todo,\n# max_distance, max_steering)\n#\n# action_list = student_planner.plan_delivery()\n# drawMoves.drawWH2(exec_count, warehouse, todo, action_list)\n# exec_count += 1\n#\n# state = State(warehouse, todo, max_distance, max_steering)\n# num_delivered = 0\n# next_box_to_deliver = num_delivered\n#\n#execute_student_plan(warehouse, todo, max_distance, max_steering)\n","sub_path":"Project2/partB.py","file_name":"partB.py","file_ext":"py","file_size_in_byte":16064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}