要素内の要素を取得する。\n td_all = tr.find_all('td')\n for td in td_all:\n row.append(td.text)\n \n # 1行のデータを格納したリストを、リストに格納\n rows.append(row)\n \n # DataFrameを生成する\n df = pd.DataFrame(rows, columns=headers)\n df = df.set_index(headers[0]) # 先頭の列(決算期)をインデックスに指定する\n \n return df\n \n##############################\n# キャッシュフロー情報を抽出する\n##############################\ndef get_cf_table(bs):\n \"\"\" キャッシュフロー情報を抽出する\n \n Args:\n bs (BeautifulSoup) : 抽出対象HTMLのBeautifulSoupオブジェクト\n\n Returns:\n DataFrame : 要素を格納したDataFrame\n \"\"\"\n \n # 全要素を抽出\n table_all = bs.find_all('table')\n \n # キャッシュフロー情報の要素を検索する。\n cf_table = None\n for table in table_all:\n \n # 要素を取得\n thead = table.find('thead')\n if thead is None:\n continue\n \n # 内の全要素を取得\n thead_th = thead.find_all('th')\n for th in thead_th:\n if th.text == '営業CF':\n cf_table = table\n break\n \n # 要素内のヘッダ情報を取得する。\n headers = []\n thead_th = cf_table.find('thead').find_all('th')\n for th in thead_th:\n headers.append(th.text)\n \n # 要素内のデータを取得する。\n rows = []\n tbody_tr = cf_table.find('tbody').find('tr').find_all('tr')\n for tr in tbody_tr:\n \n # 1行内の全データを格納するためのリスト\n row = []\n \n # 要素内の| 要素を取得する。\n th = tr.find('th')\n row.append(th.text)\n \n # | 要素内の要素を取得する。\n td_all = tr.find_all('td')\n for td in td_all:\n row.append(td.text)\n \n # 1行のデータを格納したリストを、リストに格納\n rows.append(row)\n\n # DataFrameを生成する\n df = pd.DataFrame(rows, columns=headers)\n df = df.set_index(headers[0]) # 先頭の列(決算期)をインデックスに指定する\n \n return df\n \n##############################\n# DataFrameから不要なデータを削る。\n##############################\ndef trim_unnecessary_from_dataframe(df):\n \"\"\" DataFrameから不要なデータを削る。\n \n Args:\n df (DataFrame) : データフレーム\n\n Returns:\n DataFrame : 不要データ削除後のDataFrame\n \"\"\"\n \n # 数値のカンマを削除する関数\n def trim_camma(x):\n # 2,946,639.3のようなカンマ区切り、小数点有りの数値か否か確認する\n comma_re = re.search(r\"([+-]?\\d{1,3}(,\\d{3})*(\\.\\d+){0,1})\", x)\n if comma_re:\n value = comma_re.group(1)\n value = value.replace(',', '') # カンマを削除\n return np.float64(value) # 数値に変換\n \n return x\n \n # 各列に対して、trim_cammaを適用する\n new_df = df.copy()\n for col in df.columns:\n new_df[col] = df[col].map(lambda v : trim_camma(v))\n \n # 括弧内の文字列を削除する関数(括弧自体も削除する)\n def remove_inparentheses(s):\n \n # インデックス(決算情報)の括弧内要素を削除する。\n # ex) 決算期(決算発表)\n result = re.search(r\"(.+)(\\(.+\\))\", s)\n if result:\n str = result.group(1)\n return str\n \n return s\n \n # インデックス(決算情報)の括弧内要素を削除する。\n new_df.index.name = remove_inparentheses(new_df.index.name)\n new_df.index = new_df.index.map(lambda s : remove_inparentheses(s))\n \n return new_df\n \n##############################\n# 複数銘柄の決算情報を整形する\n##############################\ndef reshape_financial_info(df):\n \"\"\" 複数銘柄の決算情報を整形する。\n \n Args:\n df (DataFrame) : 複数銘柄の決算情報が格納されたデータフレーム\n\n Returns:\n DataFrame : 整形後のDataFrame\n \"\"\"\n \n # 各銘柄のデータと統計量を結合する。\n new_df = df.copy()\n \n # 売上高(百万円) -> 売上高(十億円)\n # 営業利益(百万円) -> 営業利益(十億円)\n # 経常利益(百万円) -> 経常利益(十億円)\n # 純利益(百万円) -> 純利益(十億円)\n # 総資産(百万円) -> 総資産(十億円)\n # 純資産(百万円) -> 純資産(十億円)\n # 営業CF(百万円) -> 営業CF(十億円)\n # 投資CF(百万円) -> 投資CF(十億円)\n # 財務CF(百万円) -> 財務CF(十億円)\n # 現金期末残高(百万円) -> 現金期末残高(十億円)\n # フリーCF(百万円) -> フリーCF(十億円)\n new_df['売上高'] = new_df['売上高'] / 1.0e+3\n new_df['営業利益'] = new_df['営業利益'] / 1.0e+3\n new_df['経常利益'] = new_df['経常利益'] / 1.0e+3\n new_df['純利益'] = new_df['純利益'] / 1.0e+3\n new_df['総資産'] = new_df['総資産'] / 1.0e+3\n new_df['純資産'] = new_df['純資産'] / 1.0e+3\n new_df['営業CF'] = new_df['営業CF'] / 1.0e+3\n new_df['投資CF'] = new_df['投資CF'] / 1.0e+3\n new_df['財務CF'] = new_df['財務CF'] / 1.0e+3\n new_df['現金期末残高'] = new_df['現金期末残高'] / 1.0e+3\n new_df['フリーCF'] = new_df['フリーCF'] / 1.0e+3\n new_df = new_df.rename(columns={\n '売上高' : '売上高(十億円)', \n '営業利益' : '営業利益(十億円)',\n '経常利益' : '経常利益(十億円)',\n '純利益' : '純利益(十億円)',\n '1株益' : '1株益(円)',\n '1株純資産' : '1株純資産(円)',\n '総資産' : '総資産(十億円)',\n '純資産' : '純資産(十億円)',\n '営業CF' : '営業CF(十億円)',\n '投資CF' : '投資CF(十億円)',\n '財務CF' : '財務CF(十億円)',\n '現金期末残高' : '現金期末残高(十億円)',\n 'フリーCF' : 'フリーCF(十億円)',\n })\n \n return new_df\n \n##################################################\n# 決算情報のうち指定したデータを棒グラフで可視化する\n##################################################\ndef visualize_financial_info_in_bar(df, data_name, filepath):\n \"\"\" 決算情報のうち指定したデータを棒グラフで可視化する\n \n Args:\n df (DataFrame) : 複数銘柄の基本情報が格納されたデータフレーム\n data_name (string) : 可視化する列名\n filepath (string) : 可視化したグラフを保存するファイルパス\n \n Returns:\n \"\"\"\n \n # FigureとAxesを取得\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n \n # 銘柄の名称リスト\n brand_names = list(df.index.unique('名称'))\n \n # 全銘柄のデータを折れ線グラフに表示\n for brand_name in brand_names:\n \n brand_df = df.loc[(brand_name,)] # 指定した銘柄のデータ\n x = brand_df.index # 決算期\n y = brand_df[data_name] # 可視化するデータ\n \n # 折れ線グラフ表示\n ax.plot(x, y, marker='o')\n \n # 補助線を描画\n ax.grid(axis='y', color='gray', ls='--')\n \n # 軸ラベルをセット\n plt.xlabel(data_name, size=15)\n \n # 凡例を表示\n ax.legend(brand_names)\n \n # グラフを表示\n fig.show()\n fig.savefig(filepath)\n \n##################################################\n# 決算情報のうち指定した複数データを\n# 折れ線グラフで可視化する\n##################################################\ndef visualize_financial_infos_in_line(df, data_names, filepath, from_zero=False):\n \"\"\" 決算情報のうち指定した複数データを折れ線グラフで可視化する\n \n Args:\n df (DataFrame) : 複数銘柄の基本情報が格納されたデータフレーム\n data_names (list) : 可視化する列名のリスト\n filepath (string) : 可視化したグラフを保存するファイルパス\n \n Returns:\n \"\"\"\n \n data_num = len(data_names)\n \n # サブプロットの行数・列数を決定\n if data_num == 1:\n rows, cols = (1, 1)\n figsize=(6, 4)\n elif data_num == 2:\n rows, cols = (1, 2)\n figsize=(10, 4)\n elif data_num == 3:\n rows, cols = (1, 3)\n figsize=(15, 4)\n elif data_num == 4:\n rows, cols = (2, 2)\n figsize=(10, 8)\n elif data_num <= 6:\n rows, cols = (2, 3)\n figsize=(15, 8)\n elif data_num <= 9:\n rows, cols = (3, 3)\n figsize=(15, 12)\n else:\n rows, cols = (4, 4)\n figsize=(20, 16)\n \n # Figurを取得\n fig = plt.figure(figsize=figsize)\n #fig = plt.figure()\n \n # 指定した全データをデータ別に折れ線グラフで表示する\n for i in range(data_num):\n \n # Axesを取得\n ax = fig.add_subplot(rows, cols, i+1)\n \n # データ名\n data_name = data_names[i]\n \n # 銘柄の名称リスト\n brand_names = list(df.index.unique('名称'))\n \n # 全銘柄のデータを折れ線グラフに表示\n for brand_name in brand_names:\n \n brand_df = df.loc[(brand_name,)] # 指定した銘柄のデータ\n x = brand_df.index # 決算期\n y = brand_df[data_name] # 可視化するデータ\n \n # 折れ線グラフ表示\n ax.plot(x, y, marker='o')\n \n # 補助線を描画\n ax.grid(axis='y', color='gray', ls='--')\n \n # 軸ラベルをセット\n plt.xlabel(data_name, size=15)\n \n # 凡例を表示\n ax.legend(brand_names)\n \n # Y軸の表示範囲を設定\n if from_zero:\n ax.set_ylim(ymin=0)\n \n # 不要な余白を削る\n plt.tight_layout()\n \n # グラフを表示\n fig.show()\n fig.savefig(filepath)\n\n##############################\n# 決算情報のうちROEとROAを可視化する\n##############################\ndef visualize_roe_roa(df, filepath):\n \"\"\" 決算情報のうち指定した複数データを可視化する\n \n Args:\n df (DataFrame) : 複数銘柄の基本情報が格納されたデータフレーム\n filepath (string) : 可視化したグラフを保存するファイルパス\n \n Returns:\n \"\"\"\n \n # 可視化するデータ\n data_names = ['ROE', 'ROA']\n\n # Figurを取得\n fig = plt.figure(figsize=(10, 4))\n\n # 指定した全データをデータ別に折れ線グラフで表示する\n for i, data_name in enumerate(data_names):\n \n # Axesを取得\n ax = fig.add_subplot(1, 2, i+1)\n \n # 銘柄の名称リスト\n brand_names = list(df.index.unique('名称'))\n \n # 全銘柄のデータを折れ線グラフに表示\n for brand_name in brand_names:\n \n brand_df = df.loc[(brand_name,)] # 指定した銘柄のデータ\n x = brand_df.index # 決算期\n y = brand_df[data_name] # 可視化するデータ\n \n # 折れ線グラフ表示\n ax.plot(x, y, marker='o')\n \n # 補助線を描画\n ax.grid(axis='y', color='gray', ls='--')\n \n # 軸ラベルをセット\n plt.xlabel(data_name, size=15)\n \n # 凡例を表示\n ax.legend(brand_names)\n \n # 不要な余白を削る\n plt.tight_layout()\n \n # グラフを表示\n fig.show()\n fig.savefig(filepath)\n\n##################################################\n# 決算情報のうち指定した1銘柄の指定データを可視化する\n##################################################\ndef visualize_financial_info_for_specified_brand(df, brand_name, bar_datas, line_datas=None, filepath=None):\n \"\"\" 決算情報のうち指定した1銘柄の指定データを可視化する\n \n Args:\n df (DataFrame) : 複数銘柄の基本情報が格納されたデータフレーム\n brand_name (string) : 可視化する銘柄の名称\n bar_datas (list) : 棒グラフで可視化する列名のリスト\n line_datas (list) : 折れ線グラフで可視化する列名のリスト\n filepath (string) : 可視化したグラフを保存するファイルパス\n \n Returns:\n \"\"\"\n \n # 可視化するデータを抽出\n brand_df = df.loc[(brand_name,)] # 指定した銘柄\n fiscal_year = brand_df.index.values # 決��期\n \n # データ数を取得\n num_year = len(fiscal_year) # 可視化する決算期の数\n num_bar_data = len(bar_datas) # 棒グラフで可視化するデータ数\n \n # FigureとAxesを取得\n fig = plt.figure()\n ax1 = fig.add_subplot(1,1,1)\n \n # 色\n color_count = 0\n colors = plt.get_cmap('tab10')\n \n ########################################\n # 棒グラフの可視化処理\n ########################################\n \n # 棒グラフを横並びで表示するためのパラメータ\n width = 0.8 / num_bar_data # 棒グラフの幅\n xpos = np.arange(num_year) # X軸上の位置\n \n # 可視化するデータ数分ループ\n for i, data_name in enumerate(bar_datas):\n \n x = xpos + width * i\n y = brand_df[data_name]\n \n # 棒グラフを表示\n ax1.bar(x, y, width=width, align='center', label=data_name, color=colors(color_count))\n color_count += 1\n \n # X軸の目盛位置を調整し、銘柄名を表示\n offset = width / 2 * (num_bar_data - 1)\n ax1.set(xticks=xpos+offset, xticklabels=fiscal_year)\n \n # Y軸の表示範囲を設定\n ymin, ymax = get_yminmax_financial_info(brand_df, bar_datas)\n ax1.set_ylim(ymin=ymin*1.5, ymax=ymax*1.5)\n \n ########################################\n # 折れ線グラフの可視化処理\n ########################################\n if line_datas is not None:\n \n # 右軸のAxesを取得\n ax2 = ax1.twinx()\n \n # 可視化するデータ数分ループ\n for i, data_name in enumerate(line_datas):\n \n # 折れ線グラフ表示\n y = brand_df[data_name]\n ax2.plot(xpos+offset, y, marker='o', label=data_name, color=colors(color_count))\n color_count += 1\n \n # Y軸の表示範囲を設定\n ymin, ymax = get_yminmax_financial_info(brand_df, line_datas)\n ax2.set_ylim(ymin=ymin*1.3, ymax=ymax*1.3)\n\n # 補助線を描画\n ax1.grid(axis='y', color='gray', ls='--')\n \n # 凡例を表示\n h1, l1 = ax1.get_legend_handles_labels()\n if line_datas is None:\n ax1.legend(h1, l1, loc='upper right')\n else:\n h2, l2 = ax2.get_legend_handles_labels()\n ax1.legend(h1+h2, l1+l2, loc='upper right')\n \n # グラフのタイトルを追加\n plt.title(brand_name)\n\n # グラフを表示\n fig.show()\n \n # グラフをファイルに出力\n if filepath is not None:\n fig.savefig(filepath) \n \n \n##################################################\n# 指定した列を可視化する際のY軸の表示範囲を取得する\n##################################################\ndef get_yminmax_financial_info(df, columns):\n \"\"\" 指定した列を可視化する際のY軸の表示範囲を取得する\n \n Args:\n df (DataFrame) : 複数銘柄の決算情報が格納されたデータフレーム\n columns (list) : 可視化する列\n \n Returns:\n tuple : Y軸の表示範囲を(ymin, ymax)の形で返す\n \"\"\"\n \n # 最大値・最小値を取得\n ymax = df[columns].max().max() \n ymin = df[columns].min().min()\n \n if ymin >= 0:\n return(0, ymax)\n else:\n abs_max = max([abs(ymin), ymax])\n return(-abs_max, abs_max)\n ","sub_path":"01.stock_investment/01.corporate_analysis/stinfo/financial_info.py","file_name":"financial_info.py","file_ext":"py","file_size_in_byte":20897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"195212101","text":"# Данный класс унаследован от класса Player, и отличается тем,\n# что после каждой проверки на выигрыш комбинация игрока\n# меняется, для этого переопределен метод cap_calc базового класса\n# с сохранением прежнего функционала и с добавлением нового\n\nimport player\nclass Change_Player(player.Player):\n def __init__(self,capital,set_player,name,n1,k1,k2):\n super().__init__(capital,set_player,name)\n self.__n1=n1\n self.__k1=k1\n self.__k2=k2\n def cap_calc(self,exset):\n super().cap_calc(exset)\n super().init_random(self.__n1,self.__k1,self.__k2)\n \n","sub_path":"change_player.py","file_name":"change_player.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"12284444","text":"# Copyright (c) 2019 The Boule Developers.\n# Distributed under the terms of the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# This code is part of the Fatiando a Terra project (https://www.fatiando.org)\n#\nr\"\"\"\n.. _normal_gravity:\n\nNormal Gravity\n==============\n\nOne of the main uses for ellipsoids in geodesy and geophysics is the\ncomputation of *normal gravity* (usually represented by :math:`\\gamma`):\n\n Normal gravity is the magnitude of the gradient of the gravity potential\n (gravitational + centrifugal) generated by the ellipsoid.\n\nThe calculation is performed by the :meth:`boule.Ellipsoid.normal_gravity`\nmethod.\nIt implements the closed-form formula of [LiGotze2001]_ which can calculate\nnormal gravity at any latitude and (geometric) height.\n\nAs an example, lets calculate a profile of normal gravity from pole to pole\nat a height of 1000 m using the :ref:`WGS84 ` ellipsoid.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport boule as bl\n\n\nlatitude = np.linspace(-90, 90, 100)\ngamma = bl.WGS84.normal_gravity(latitude, height=1000)\n\nplt.figure(figsize=(8, 5))\nplt.plot(latitude, gamma, \"-k\")\nplt.title(\"WGS84 normal gravity\")\nplt.xlabel(\"latitude\")\nplt.ylabel(\"normal gravity (mGal)\")\nplt.show()\n\n###############################################################################\n# This calculation can be performed for any ellipsoid. For example, here is the\n# normal gravity of the :ref:`Martian ellipsoid `:\n\ngamma_mars = bl.MARS.normal_gravity(latitude, height=1000)\n\nplt.figure(figsize=(8, 5))\nplt.plot(latitude, gamma_mars, \"-k\")\nplt.title(\"Mars normal gravity\")\nplt.xlabel(\"latitude\")\nplt.ylabel(\"normal gravity (mGal)\")\nplt.show()\n\n\n###############################################################################\n# Notice that the overall trend is the same as for the Earth (the Martian\n# ellipsoid is also oblate) but the range of values is different. The mean\n# gravity on Mars is much weaker than on the Earth: around 370,000 mGal or 3.7\n# m/s² when compared to 970,000 mGal or 9.7 m/s².\n","sub_path":"tutorials/normal_gravity.py","file_name":"normal_gravity.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"490206856","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 12 17:14:09 2017\r\n\r\n@author: HP\r\n\"\"\"\r\nimport re\r\nimport hindi_stemmer as hs\r\nimport string\r\nfrom collections import defaultdict\r\n\r\nexclude1 = set([u'।',u'-',u',',u'ॽ',u'॥',u'(',u')',u'.',u'…', u'…', u'०', u'१', u'२', u'३', u'४', u'५', u'६', u'७', u'८', u'९'])\r\nexclude2 = set(string.punctuation)\r\nstopwords=[]\r\nhindi_stop_words = open('hindi_stopwords.txt','r')\r\nfor line in hindi_stop_words:\r\n stopwords.append(line.decode('utf-8').strip('\\n'))\r\n \r\nstopwords = set(stopwords)\r\n\r\nemoji_pattern = re.compile(\r\n u\"(\\ud83d[\\ude00-\\ude4f])|\" # emoticons\r\n u\"(\\ud83c[\\udf00-\\uffff])|\" # symbols & pictographs (1 of 2)\r\n u\"(\\ud83d[\\u0000-\\uddff])|\" # symbols & pictographs (2 of 2)\r\n u\"(\\ud83d[\\ude80-\\udeff])|\" # transport & map symbols\r\n u\"(\\ud83c[\\udde0-\\uddff])\" # flags (iOS)\r\n \"+\", flags=re.UNICODE)\r\n\r\n\r\ndef clean_tweet(tweet):\r\n \r\n tweet_new = Remove_AlphaNumeric(tweet)\r\n \r\n \r\n \r\n tweet_new = Remove_Punctuation(tweet_new)\r\n\r\n tweet_new = Remove_stopwords(tweet_new)\r\n \r\n tweet_new = Remove_stem(tweet_new)\r\n\r\n tweet_new = Remove_Emoji(tweet_new)\r\n \r\n return tweet_new\r\n\r\n\r\ndef Remove_AlphaNumeric(tweet):\r\n\r\n tweet_new = re.sub(\"[a-zA-Z0-9@]\",\"\",tweet)\r\n tweet_new = re.sub(\"[\\nEOF]\",\" \",tweet_new)\r\n \r\n return tweet_new\r\n\r\ndef Remove_Emoji(data):\r\n \r\n\r\n if not data:\r\n return data\r\n if not isinstance(data, basestring):\r\n return data\r\n try:\r\n # UCS-4\r\n patt = re.compile(u'([\\U00002600-\\U000027BF])|([\\U0001f300-\\U0001f64F])|([\\U0001f680-\\U0001f6FF])')\r\n except re.error:\r\n # UCS-2\r\n patt = re.compile(u'([\\u2600-\\u27BF])|([\\uD83C][\\uDF00-\\uDFFF])|([\\uD83D][\\uDC00-\\uDE4F])|([\\uD83D][\\uDE80-\\uDEFF])')\r\n return patt.sub('', data)\r\n #remove_emoji(tweet)\r\n\r\n\r\ndef Remove_Punctuation(tweet):\r\n ### Removing punctuations\r\n tweet_new = ''.join(ch for ch in tweet if ch not in exclude1)\r\n tweet_new = ''.join(ch for ch in tweet_new if ch not in exclude2)\r\n return tweet_new\r\n \r\ndef Remove_stopwords(tweet):\r\n tweet_new = \" \".join([i for i in tweet.split() if i not in stopwords])\r\n return tweet_new\r\n\r\ndef Remove_stem(tweet):\r\n tweet_list = tweet.split()\r\n tweet_list = [hs.hi_stem(word) for word in tweet_list]\r\n tweet_new = \" \".join(tweet_list)\r\n return tweet_new \r\n\r\ndef clean_tweet_by_frequency(tweet_file_name, processed_tweets_file_name):\r\n \r\n frequency = defaultdict(int)\r\n tweet_file = open(tweet_file_name,'r')\r\n new_tweet_file = open(processed_tweets_file_name,'w')\r\n \r\n for tweet in tweet_file:\r\n for token in tweet.split():\r\n frequency[token] += 1\r\n \r\n tweet_file.seek(0)\r\n \r\n \r\n for tweet in tweet_file:\r\n text = [token for token in tweet.split() if frequency[token]>1]\r\n if text is not None:\r\n new_tweet_file.write(\" \".join(text)+\"\\n\")\r\n \r\n \r\n tweet_file.close()\r\n new_tweet_file.close() \r\n\r\n\r\n#for ch in str:\r\n# print ch\r\n","sub_path":"tweet_clean.py","file_name":"tweet_clean.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"167775156","text":"#Basic dictionary\r\nalien_0 = {'color' : 'green', 'points': 5}\r\n\r\nprint(alien_0['color'])\r\nprint(alien_0['points'])\r\n\"\"\"\r\nalien_0 딕셔너리는 외계인 색과 점수를 저장한다 두 print문은 정보에 접근하고\r\nprint(alien_0['color']) 는 green을 출력하게 되고, print(alien_0['points'])는\r\n5를 출력하게 된다 dictionary는 처음 배울 때는 익숙치 않으니 연습이 필요하다\r\n\"\"\"\r\n# use dictionary\r\n\"\"\"\r\n파이썬 딕셔너리는 키-값 쌍의 모음이다 각 키는 값에 연결되며, 키에 연결된 값에\r\n접근할 때도 키를 사용한다. 키의 값은 숫자, 문자열, 리스트, 심지어\r\n다른 딕셔셔너리도 가능하다\r\n\"\"\"\r\n# contact dictionary value\r\nalien_0 = {'color' : 'green'}\r\nprint(alien_0['color'])\r\n# 딕셔너리에 쓸 수 있는 키-값 쌍의 숫자에는 제한이 없다\r\nalien_0 = {'color' : 'green', 'points': 5}\r\n\r\nnew_points = alien_0['points']\r\nprint(\"You just earned \" +str(new_points) + \" points!\")\r\n\"\"\"\r\nnew_points는 딕셔너리에서 키'points'의 값을 가져온다 그리고\r\n그 값을 new_points 변수에 저장한다 str()은 정수 값을 문자열로 바꿔서 플레이어가\r\n몇 점을 얻었는지 출력한다\r\n\"\"\"\r\n# 새 키-값 쌍 추가하기\r\nprint('\\n' + str(alien_0))\r\n\r\nalien_0['x_position'] = 0\r\nalien_0['y_position'] = 25\r\nprint(alien_0)\r\n\"\"\"\r\n딕셔너리는 문자열이 아니라 str을 통해 문자열로 바꿔줬다\r\n그리고 마지막 버전에서 키-값 쌍이 네 개 생겼다 원래 두 땃응ㄴ 색과 점수르 저장하고\r\n추가한 두 쌍은 외계인 위치를 저장했다. 키-값이 표시되는 순서는 추가한 순서와\r\n일치하지 않는다 파이썬은 각 키-값 쌍을 저장한 순서는 신경 쓰지 않고 각 키와 값의 연결\r\n만 중시한다\r\n\"\"\"\r\n# start empty dictionary\r\nalien_0 = {}\r\n\r\nalien_0['color'] = 'green'\r\nalien_0['points'] = 5\r\n\r\nprint(\"\\n\" + str(alien_0))\r\n\"\"\"\r\n때로는 빈 딕셔너리로 시작하고 새 항목을 추가하는 방법이 더 간편하거나 필요할 때도\r\n있다 빈 딕셔너리로 시작하려면 빈 중괄호로 딕셔너리를 정의하고 다른 행에서 키-값 쌍을\r\n추가한다\r\n\"\"\"\r\n# modify value of dictionary\r\nalien_0 = {'color' : 'green'}\r\nprint(\"\\nThe alien is \" + alien_0['color'] + \".\")\r\n\r\nalien_0['color'] = 'yellow'\r\nprint(\"The alien is \" + alien_0['color'] + \".\")\r\n\"\"\"\r\n딕셔너리의 값을 수정할 때는 딕셔너리 이름 다음에 대괄호 속에 키를 쓰고 그 키에 연결할\r\n새 값을 지정한다.\r\n\"\"\"\r\nalien_0 = {'x_position' : 0, 'y_position' : 25, 'speed' : 'medium',}\r\nprint(\"Original x-position: \" + str(alien_0['x_position']))\r\n\r\n# 외계인을 오른쪽으로 움직인다\r\n# 현재 속도를 기준으로 외계인이 얼마나 빨리 움직이는지 판단한다\r\n\r\nif alien_0['speed'] == 'slow':\r\n x_increment = 1\r\nelif alien_0['speed'] == 'medium':\r\n x_increment = 2\r\nelse:\r\n # 이 외계인을 빠른놈이다\r\n x_increment = 3\r\n\r\n# 새 위치는 이전 위치에 증가분을 더한 값이다\r\nalien_0['x_position'] = alien_0['x_position'] + x_increment\r\nprint(\"New x-position: \" + str(alien_0['x_position']))\r\n\"\"\"\r\n먼저 외계인의 첫 x 위치와 y 위치, 'medium' 속도를 지정했다 단순하게 보이려고 색과\r\n점수는 생략했지만, 색과 점수가 있더라도 똑같이 작동한다 외계인이 오른쪽으로 얼마나\r\n빨리 움직이는 보기 위해 x_position의 원래 값도 출력했다\r\nif-elif-else 문을 써서 외계인이 오른쪽으로 얼마나 빨리 움직이는지 판단하고\r\n그 값을 x_increment 변수에 저장했다 외계인의 속도가 'slow'이면 한 칸을, 속도가\r\n'medium'이면 두 칸을, 'fast'이면 세 칸을 오른쪽으로 움직인다. 이동거리를\r\nx_position 값에 더하고 그 결과를 딕셔너리의 x_position에 저장했다 이 외계인은\r\n중간 속도이므로 오른쪽으로 두 칸 이동했다\r\n만약 중간 속도 외게인을 빠른 속도로 바꾸고싶다면 if문 위에 alien_0['speed'] = 'fast'\r\n코드를 추가하면 x_increment에 더 큰 값을 할당한다\r\n\"\"\"\r\n# 키-값 쌍 제거하기\r\nalien_0 = {'color' : 'green','points': 5}\r\nprint(alien_0)\r\n\r\ndel alien_0['points']\r\nprint(alien_0)\r\n\"\"\"\r\n딕셔너리에 저장된 정보가 더 이상 필요 없다면 del 문을 써서 완벽히 제거할 수 있다\r\ndel 문에는 디겻너리 이름과 제거할 키만 필요하다\r\n\"\"\"\r\n","sub_path":"dictionary/alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"454094529","text":"import argparse\nimport os\nimport os.path as osp\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom tensorboardX import SummaryWriter\n\nfrom proto_mdd.dataloader.samplers import CategoriesSampler, CategoriesSamplerOurs\nfrom proto_mdd.models.proto import proto_net\nfrom proto_mdd.models.proto_attention import proto_attention_net\nfrom proto_mdd.models.mdd import MDDNet, mdd_loss\nfrom proto_mdd.utils import pprint, set_gpu, ensure_path, Averager, Timer, count_acc, euclidean_metric, compute_confidence_interval, log, setup_seed\n\nfrom baseline_data.datamgr import SimpleDataManager, SetDataManager\n\n\nsetup_seed(666)\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--max_epoch', type=int, default=600)\n parser.add_argument('--train_way', type=int, default=5) \n parser.add_argument('--val_way', type=int, default=5)\n parser.add_argument('--shot', type=int, default=5)\n parser.add_argument('--query', type=int, default=15)\n parser.add_argument('--lr', type=float, default=0.0001)\n parser.add_argument('--lr_mul', type=float, default=10) # lr is the basic learning rate, while lr * lr_mul is the lr for other parts \n parser.add_argument('--temperature', type=float, default=128) \n parser.add_argument('--step_size', type=int, default=10)\n parser.add_argument('--gamma', type=float, default=0.5)\n parser.add_argument('--class_num', default=64, type=int)\n parser.add_argument('--srcweight', default=-1, type=int)\n parser.add_argument('--lambda_pre_fsl_loss', default= 1, type=float)\n parser.add_argument('--lambda_da', default=1, type=float) \n parser.add_argument('--lambda_new_fsl_loss', default = 1, type=float) \n parser.add_argument('--proto_attention', default = 0, type = int) \n parser.add_argument('--model_type', type=str, default='ResNet18', choices=['ConvNet', 'ResNet', 'ResNet18'])\n parser.add_argument('--dataset', type=str, default='cross', choices=['MiniImageNet', 'CUB', 'TieredImageNet','cross'])\n parser.add_argument('--init_weights', type = str, default= None) \n parser.add_argument('--head', type=int, default=1)\n parser.add_argument('--gpu', default='0,1')\n parser.add_argument('--print_i_mdd', default=0, type= int)\n parser.add_argument('--num_train_episodes', default = 100, type = int)\n args = parser.parse_args() \n\n if args.dataset == 'MiniImageNet':\n args.class_num = 64\n args.width = 1024\n args.srcweight = 4\n is_cen = False\n elif args.dataset == 'TieredImageNet':\n args.class_num = 351\n args.width = 1024\n args.srcweight = 4\n args.num_train_episodes = 1000\n is_cen = False\n elif args.dataset == 'CUB':\n args.class_num = 100\n args.width = 1024\n args.srcweight = 4\n is_cen = False\n elif args.dataset == 'cross':\n args.class_num = 100\n args.width = 1024\n args.srcweight = 4\n args.lr = 0.01\n args.lr_mul = 0.1\n is_cen = False\n\n else:\n print('Dataset not supported!')\n exit()\n \n\n set_gpu(args.gpu)\n if args.proto_attention:\n save_path1 = '-'.join([args.dataset, args.model_type, 'proto_atten', str(args.shot), str(args.train_way)])\n else:\n save_path1 = '-'.join([args.dataset, args.model_type, 'proto', str(args.shot), str(args.train_way)])\n save_path2 = '_'.join([str(args.lr),str(args.temperature), str(args.lambda_pre_fsl_loss), str(args.lambda_da), str(args.lambda_new_fsl_loss)])\n\n args.save_path = osp.join(save_path1, save_path2)\n ensure_path(save_path1, remove=False)\n ensure_path(args.save_path)\n train_log_file_path = os.path.join(args.save_path, 'train_log.txt') \n val_log_file_path = os.path.join(args.save_path, 'val_log.txt')\n log(train_log_file_path, str(vars(args)))\n log(val_log_file_path, str(vars(args)))\n\n\n if args.dataset == 'MiniImageNet': \n from proto_mdd.dataloader.mini_imagenet import MiniImageNet as Dataset\n elif args.dataset == 'CUB':\n from proto_mdd.dataloader.cub import CUB as Dataset\n elif args.dataset == 'TieredImageNet':\n from proto_mdd.dataloader.tiered_imagenet import tieredImageNet as Dataset\n elif args.dataset == 'cross':\n from proto_mdd.dataloader.mini_imagenet_pre import MiniImageNet as Dataset_mini\n from proto_mdd.dataloader.cub import CUB as Dataset_cub\n else:\n raise ValueError('Non-supported Dataset.')\n \n if args.dataset == 'cross': \n train_file = '~/filelists/miniImagenet/all.json'\n val_file = '~/filelists/CUB/val.json'\n image_size = 224\n base_datamgr = SetDataManager(image_size, n_query = args.query, n_way = args.train_way * 2, n_support = args.shot)\n train_loader = base_datamgr.get_data_loader( train_file , aug = True) \n val_datamgr = SetDataManager(image_size, n_query = args.query, n_way = args.val_way, n_support = args.shot)\n val_loader = val_datamgr.get_data_loader( val_file, aug = False) \n else:\n trainset = Dataset('train', args)\n train_sampler = CategoriesSamplerOurs(trainset.label, args.num_train_episodes, args.train_way, args.shot + args.query)\n train_loader = DataLoader(dataset=trainset, batch_sampler=train_sampler, num_workers=8, pin_memory=True)\n valset = Dataset('val', args)\n val_sampler = CategoriesSampler(valset.label, 600, args.val_way, args.shot + args.query)\n val_loader = DataLoader(dataset=valset, batch_sampler=val_sampler, num_workers=8, pin_memory=True)\n \n if args.proto_attention:\n base_net = proto_attention_net(args, dropout = 0.5) \n else:\n base_net = proto_net(args, dropout = 0.5)\n\n mdd_net = MDDNet(base_net=args.model_type, use_bottleneck=True,\n bottleneck_dim=args.width, width=args.width,\n class_num=args.class_num).cuda()\n\n\n # parameter list to optimize\n base_net_param_list = [{'params': base_net.encoder.parameters()}]\n if args.proto_attention:\n base_net_param_list = base_net_param_list + [{'params': base_net.slf_attn.parameters(), 'lr': args.lr * args.lr_mul}]\n \n mdd_net_param_list = mdd_net.get_parameter_list()\n mdd_net_param_list = [{'params':x['params'], 'lr': x['lr'] * args.lr * args.lr_mul} for x in mdd_net_param_list] \n\n parameter_list = base_net_param_list + mdd_net_param_list\n\n if args.model_type == 'ConvNet':\n optimizer = torch.optim.Adam(parameter_list, lr=args.lr)\n elif args.model_type == 'ResNet' or args.model_type == \"ResNet18\":\n optimizer = torch.optim.SGD(parameter_list, lr=args.lr, momentum=0.9, nesterov=True, weight_decay=0.0005)\n else:\n raise ValueError('No Such Encoder')\n \n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=args.gamma) \n \n # load pre-trained model (no FC weights)\n base_net_dict = base_net.state_dict()\n if args.init_weights is not None:\n pretrained_dict = torch.load(args.init_weights)['state_dict']\n # remove weights for FC\n # pretrained_dict = {k[7:]: v for k, v in pretrained_dict.items()} # for cross-domain setting\n pretrained_dict = {'encoder.' + k[7:]: v for k, v in pretrained_dict.items()}\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in base_net_dict and base_net_dict[k].shape == pretrained_dict[k].shape}\n print(pretrained_dict.keys())\n base_net_dict.update(pretrained_dict) \n base_net.load_state_dict(base_net_dict, False) \n \n if args.train_way >= 10:\n \tbase_net.encoder = torch.nn.DataParallel(base_net.encoder, device_ids = [0,1]).cuda()\n \tbase_net = base_net.cuda()\n else:\n \tbase_net = base_net.cuda()\n \n def save_model(name):\n torch.save(dict(params=base_net.state_dict()), osp.join(args.save_path, name + '.pth'))\n torch.save(dict(params=mdd_net.state_dict()), osp.join(args.save_path, name + '_mdd.pth'))\n \n trlog = {}\n trlog['args'] = vars(args)\n trlog['train_loss'] = []\n trlog['val_loss'] = []\n trlog['train_acc'] = []\n trlog['val_acc'] = []\n trlog['max_acc'] = 0.0\n trlog['max_acc_epoch'] = 0\n \n timer = Timer()\n global_count = 0 \n \n label = torch.arange(args.train_way, dtype=torch.int8).repeat(args.query).type(torch.LongTensor) \n if torch.cuda.is_available():\n label = label.cuda() \n \n for epoch in range(1, args.max_epoch + 1):\n if args.dataset != 'cross':\n lr_scheduler.step()\n base_net.train()\n mdd_net.train()\n tl = Averager()\n ta = Averager()\n \n for i, batch in enumerate(train_loader, 1):\n args.print_i_mdd = i\n global_count = global_count + 1\n\n n_imgs = args.train_way * (args.shot + args.query) # 5*(5+15) = 100 \n data, index_label = batch[0].cuda(), batch[1].cuda()\n data_1 = data[:args.train_way]\n data_2 = data[args.train_way:]\n index_label_1 = index_label[:args.train_way]\n index_label_2 = index_label[args.train_way:]\n data_1 = data_1.permute(1,0,2,3,4)\n data_2 = data_2.permute(1,0,2,3,4)\n data_1 = data_1.reshape([-1] + list(data_1.shape[-3:]))\n data_2 = data_2.reshape([-1] + list(data_2.shape[-3:]))\n index_label_1 = index_label_1.permute(1,0)\n index_label_2 = index_label_2.permute(1,0)\n index_label_1 = index_label_1.reshape([-1])\n index_label_2 = index_label_2.reshape([-1])\n data = torch.cat([data_1, data_2], dim = 0)\n index_label = torch.cat([index_label_1, index_label_2]) \n # print(index_label)\n # prototypical network part\n # the first FSL loss i.e. (2 * N)-train_way K-shot learning\n \n pre_data_src = data[:n_imgs]\n pre_data_tgt = data[n_imgs:]\n\n p = args.shot * args.train_way\n pre_data_src_shot = pre_data_src[:p]\n pre_data_src_query = pre_data_src[p:]\n pre_data_tgt_shot = pre_data_tgt[:p]\n pre_data_tgt_query = pre_data_tgt[p:]\n pre_data_shot = torch.cat([pre_data_src_shot, pre_data_tgt_shot], dim = 0)\n pre_data_query = torch.cat([pre_data_src_query, pre_data_tgt_query], dim = 0)\n pre_fea_shot, pre_fea_query, pre_logits = base_net(pre_data_shot, pre_data_query)\n\n pre_label_fsl_s = torch.arange(args.train_way).repeat(args.query)\n pre_label_fsl_t = torch.arange(args.train_way, 2 * args.train_way).repeat(args.query)\n pre_label_fsl = torch.cat([pre_label_fsl_s, pre_label_fsl_t], dim = 0)\n pre_label_fsl = pre_label_fsl.type(torch.cuda.LongTensor)\n\n pre_fsl_loss = F.cross_entropy(pre_logits, pre_label_fsl) \n pre_fsl_acc = count_acc(pre_logits, pre_label_fsl)\n\n # rearrange the feature index\n pre_fea_src_shot = pre_fea_shot[:p]\n pre_fea_tgt_shot = pre_fea_shot[p:]\n pre_fea_src_query = pre_fea_query[:(n_imgs-p)]\n pre_fea_tgt_query = pre_fea_query[(n_imgs-p):]\n pre_src_features = torch.cat([pre_fea_src_shot, pre_fea_src_query], dim = 0)\n pre_tgt_features = torch.cat([pre_fea_tgt_shot, pre_fea_tgt_query], dim = 0)\n\n # domain adaptation part\n # the second FSL loss i.e. N-train_way K-shot learning\n pre_features = torch.cat([pre_src_features, pre_tgt_features], dim = 0)\n new_features, outputs, outputs_adv = mdd_net(pre_features)\n\n new_fea_s = new_features[:n_imgs]\n new_fea_t = new_features[n_imgs:]\n \n new_fea_shot_s, new_fea_query_s = new_fea_s[:p], new_fea_s[p:]\n new_fea_shot_t, new_fea_query_t = new_fea_t[:p], new_fea_t[p:]\n new_logits_s = base_net(new_fea_shot_s, new_fea_query_s, input_type = \"feature\")\n new_logits_t = base_net(new_fea_shot_t, new_fea_query_t, input_type = \"feature\")\n new_label_fsl = torch.arange(args.train_way).repeat(args.query)\n new_label_fsl = new_label_fsl.type(torch.cuda.LongTensor) \n new_fsl_loss_s = F.cross_entropy(new_logits_s, new_label_fsl)\n new_fsl_loss_t = F.cross_entropy(new_logits_t, new_label_fsl)\n new_fsl_loss = new_fsl_loss_s + new_fsl_loss_t\n\n new_fsl_acc_s = count_acc(new_logits_s, new_label_fsl)\n new_fsl_acc_t = count_acc(new_logits_t, new_label_fsl)\n\n # domain adaptation loss \n src_idx = list(range(n_imgs))\n tgt_idx = list(range(n_imgs, (2 * n_imgs)))\n # src_support_num = args.train_way * args.shot\n # tgt_support_num = args.train_way * args.query\n # src_idx = list(range(src_support_num))\n # tgt_idx = list(range((2 * n_imgs - tgt_support_num), (2 * n_imgs)))\n\n transfer_loss = mdd_loss(args, new_features, outputs, outputs_adv, index_label, src_idx, tgt_idx)\n if torch.isnan(transfer_loss):\n print(index_label[src_idx])\n print(index_label[tgt_idx])\n transfer_loss = pre_fsl_loss\n\n \n # total loss\n total_loss = args.lambda_pre_fsl_loss * pre_fsl_loss + args.lambda_new_fsl_loss * new_fsl_loss + args.lambda_da * transfer_loss\n\n if i % 25 == 0:\n \tlog(train_log_file_path, \"epoch: {} iter: {} transfer_loss: {:.4f} pre_fsl_loss: {:.4f} new_fsl_loss: {:.4f} total_fsl_loss: {:.4f}\".format\\\n \t\t(epoch, i, transfer_loss.item(), pre_fsl_loss.item(), new_fsl_loss.item(), total_loss.item()))\n \tlog(train_log_file_path, \"epoch: {} iter: {} fsl_acc_s: {:.4f} fsl_acc_t: {:.4f} pre_fsl_acc: {:.4f}\".format\\\n \t\t(epoch, i, new_fsl_acc_s, new_fsl_acc_t, pre_fsl_acc))\n \tif i% 100 == 0:\n \t\tlog(train_log_file_path, \"\\n\") \n \n tl.add(total_loss.item())\n ta.add(pre_fsl_acc)\n\n optimizer.zero_grad()\n total_loss.backward()\n optimizer.step()\n\n tl = tl.item()\n ta = ta.item()\n\n base_net.eval()\n mdd_net.eval()\n\n vl = Averager()\n va = Averager()\n\n label_val = torch.arange(args.val_way).repeat(args.query)\n label_val = label_val.type(torch.cuda.LongTensor)\n \n with torch.no_grad():\n for i, batch in enumerate(val_loader, 1): \n data, _ = [_.cuda() for _ in batch]\n data = data.permute(1, 0, 2, 3, 4)\n data = data.reshape([-1] + list(data.shape[-3:])) \n p = args.shot * args.val_way\n data_shot, data_query = data[:p], data[p:]\n _, _, logits = base_net(data_shot, data_query)\n loss = F.cross_entropy(logits, label_val)\n acc = count_acc(logits, label_val) \n vl.add(loss.item())\n va.add(acc)\n\n vl = vl.item()\n va = va.item() \n log(val_log_file_path,'epoch {}, val, loss={:.4f} acc={:.4f}'.format(epoch, vl, va) \\\n \t+ ' *** best epoch and acc: {} {:.4f}'.format(trlog['max_acc_epoch'], trlog['max_acc']))\n\n if va >= trlog['max_acc']:\n trlog['max_acc'] = va\n trlog['max_acc_epoch'] = epoch\n save_model('max_acc') \n \n trlog['train_loss'].append(tl)\n trlog['train_acc'].append(ta)\n trlog['val_loss'].append(vl)\n trlog['val_acc'].append(va)\n\n torch.save(trlog, osp.join(args.save_path, 'trlog'))\n\n save_model('epoch-{}'.format(epoch))\n\n print('ETA:{}/{}'.format(timer.measure(), timer.measure(epoch / args.max_epoch))) \n\n # Test Phase\n trlog = torch.load(osp.join(args.save_path, 'trlog'))\n if args.dataset == \"cross\":\n # test_set = Dataset_cub('test', args)\n # sampler = CategoriesSampler(test_set.label, 10000, args.val_way, args.shot + args.query)\n # loader = DataLoader(test_set, batch_sampler=sampler, num_workers=8, pin_memory=True) \n test_file = '~/filelists/CUB/novel.json'\n image_size = 224 \n test_datamgr = SetDataManager(image_size, n_query = args.query, n_way = args.val_way, n_support = args.shot)\n test_loader = test_datamgr.get_data_loader( test_file, aug = False) \n else:\n test_set = Dataset('test', args)\n sampler = CategoriesSampler(test_set.label, 2000, args.val_way, args.shot + args.query)\n test_loader = DataLoader(test_set, batch_sampler=sampler, num_workers=8, pin_memory=True)\n\n if args.dataset == 'cross':\n \ttest_acc_record = np.zeros((len(test_loader),))\n else:\n \ttest_acc_record = np.zeros((2000,))\n\n base_net.load_state_dict(torch.load(osp.join(args.save_path, 'max_acc' + '.pth'))['params'])\n base_net.eval()\n\n ave_acc = Averager()\n label_val = torch.arange(args.val_way).repeat(args.query)\n label_val = label_val.type(torch.cuda.LongTensor) \n\n with torch.no_grad():\n for i, batch in enumerate(test_loader, 1): \n data, _ = [_.cuda() for _ in batch]\n data = data.permute(1, 0, 2, 3, 4) \n data = data.reshape([-1] + list(data.shape[-3:])) \n k = args.val_way * args.shot\n data_shot, data_query = data[:k], data[k:]\n _, _, logits = base_net(data_shot, data_query)\n acc = count_acc(logits, label_val)\n ave_acc.add(acc)\n test_acc_record[i-1] = acc\n if i % 100 == 0:\n \tprint('batch {}: {:.2f}({:.2f})'.format(i, ave_acc.item() * 100, acc * 100))\n \n m, pm = compute_confidence_interval(test_acc_record)\n log(val_log_file_path, 'Val Best Epoch {}, Acc {:.4f}, Test Acc {:.4f}'.format(trlog['max_acc_epoch'], trlog['max_acc'], ave_acc.item()))\n log(val_log_file_path, 'Test Acc {:.6f} + {:.6f}'.format(m, pm)) ","sub_path":"cross_domain_train.py","file_name":"cross_domain_train.py","file_ext":"py","file_size_in_byte":18364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"212476430","text":"from nbodykit.lab import *\nfrom nbodykit.cosmology.correlation import pk_to_xi, xi_to_pk\nimport mcfit\nfrom mcfit import P2xi, xi2P\n\nfrom scipy.integrate import quad, cumtrapz\nfrom scipy.special import spherical_jn\nfrom scipy.interpolate import interp1d\nfrom sympy.physics.wigner import wigner_3j\n\nclass model_4PCF(object):\n \n def __init__(self, meta_data, do_rsd=False, r_in=None, xi_in=None, verbose=False):\n\n '''\n lls is a list specifies the angular momentum\n e.g.\n \n ['000',\n '011',\n '022',\n '033']\n '''\n \n self.meta_data = meta_data\n self.lls = meta_data.ell_gaussian\n self.verbose = verbose\n self.do_rsd = do_rsd\n self.k_in = meta_data.k_in\n if r_in is None:\n self.r_in = meta_data.rbins_1d\n else:\n self.r_in = r_in\n self.redshift = meta_data.redshift\n \n if hasattr(self.meta_data, 'bias'):\n self.bias = self.meta_data.bias\n else:\n self.bias = 1\n \n if not self.do_rsd:\n if hasattr(self.meta_data, 'pk_in'):\n self.Pr = self.meta_data.pk_in\n else:\n self.Pr = None\n if hasattr(self.meta_data, 'twopcf_mean'):\n self.xir = self.meta_data.twopcf_mean\n else:\n self.xir = None\n \n elif self.do_rsd:\n if hasattr(self.meta_data, 'pk_in'):\n print(\"load existing Pr\")\n self.Pr = meta_data.pk_in\n else:\n self.Pr = None\n self.pk_ell = {}\n self.xi_ell = {}\n for ii in [0, 2, 4]:\n if hasattr(self.meta_data, 'pk_zs_mean'):\n try:\n # print(\"load existing Pk%s\"%ii)\n self.pk_ell[ii] = self.meta_data.pk_zs_mean[ii]\n except:\n pass\n if hasattr(self.meta_data, 'xi_zs_mean'):\n self.xi_ell[ii] = self.meta_data.xi_zs_mean[ii] \n \n def run(self):\n \n self.init_arrs()\n self.init_2stat()\n self.get_jnbar()\n self.get_zeta_model()\n \n def init_arrs(self):\n \n kbin_min= 1e-3\n kbin_max= 5\n nbink = 1000\n if self.r_in is None:\n sbin_min= 8.5\n sbin_max = 170\n dsbin = 17\n self.rr= numpy.arange(sbin_min, sbin_max, dsbin)\n else:\n self.rr = self.r_in.copy()\n self.nbins = len(self.rr)\n self.kk = numpy.linspace(kbin_min, kbin_max, nbink)\n self.kk_log = numpy.logspace(numpy.log10(kbin_min), numpy.log10(kbin_max), nbink)\n self.dkk = self.kk[1]-self.kk[0]\n self.rrv, self.kkv = numpy.meshgrid(self.rr, self.kk)\n \n def init_cosmo(self):\n h = 0.676\n Omega_nu = 0.00140971\n Omega0_m = 0.31\n Omega0_b = 0.022/h**2\n Omega0_cdm = Omega0_m - Omega0_b - Omega_nu\n n_s = 0.96\n sigma8 = 0.824\n self.cosmo = cosmology.Cosmology(h=h, Omega0_b=Omega0_b, \n Omega0_cdm=Omega0_cdm, n_s=n_s)\n self.cosmo.match(sigma8=sigma8)\n \n def init_2stat(self):\n \n if not self.do_rsd:\n if self.Pr is not None:\n print(\"load existing Pk\")\n pk_interp = interp1d(self.k_in, self.Pr, kind='cubic', bounds_error=False, fill_value=0)\n self.Pk = pk_interp(self.kk)\n if self.xir is not None:\n print(\"load existing xi\")\n self.r = self.r_in.copy()\n self.xi_interp = interp1d(self.r_in, self.xir, kind='cubic', fill_value='extrapolate')\n else:\n print(\"FT xi from existing Pk\")\n Pk_log = pk_interp(self.kk_log)\n self.r, self.xi = P2xi(self.kk_log)(Pk_log)\n self.xi_interp = interp1d(self.r, self.xi, kind='cubic', fill_value='extrapolate')\n\n elif self.Pkr is None:\n print(\"calculate linear Pk\")\n print(\"FT xi from linear theory Pk\")\n self.init_cosmo()\n Plin = cosmology.LinearPower(self.cosmo, redshift=self.redshift, transfer='CLASS')\n self.Pk = Plin(self.kk)\n Pk_log = Plin(self.kk_log)\n self.r, self.xi = P2xi(self.kk_log)(Pk_log)\n self.xi_interp = interp1d(self.r, self.xi, kind='cubic', fill_value='extrapolate') \n \n elif self.do_rsd:\n self.xi_ell_interp = {}\n if (not bool(self.pk_ell)) or (not bool(self.xi_ell)) or (len(self.pk_ell)<3):\n if not hasattr(self, 'cosmo'):\n print(\"init cosmo\")\n self.init_cosmo()\n growth_rate = self.cosmo.scale_independent_growth_rate(0.57)\n beta = growth_rate/self.bias\n kaiser_fac = {}\n kaiser_fac[0] = (1 + 2*beta/3 + beta**2/5) * self.bias**2\n kaiser_fac[2] = (4*beta/3 + 4*beta**2/7) * self.bias**2\n kaiser_fac[4] = (8*beta**2/35) * self.bias**2\n \n if not bool(self.pk_ell):\n self.Pk_ell = {}\n self.Pk_ell[1], self.Pk_ell[3], self.Pk_ell[5] = 0, 0, 0\n if self.Pr is None:\n Plin = cosmology.LinearPower(self.cosmo, redshift=self.redshift, transfer='CLASS')\n self.Pk = Plin(self.kk)\n print(\"linear Pk for ell=[0,2,4]\")\n else:\n pk_interp = interp1d(self.k_in, self.Pr, kind='cubic', bounds_error=False, fill_value=0)\n self.Pk = pk_interp(self.kk)\n print(\"lieanr Kaiser + input Pr for ell=[0,2,4]\")\n for ii in [0, 2, 4]:\n if ii not in self.Pk_ell.keys():\n self.Pk_ell[ii] = self.Pk * kaiser_fac[ii]\n elif len(self.pk_ell)==3:\n self.Pk_ell = {}\n self.Pk_ell[1], self.Pk_ell[3], self.Pk_ell[5] = 0, 0, 0\n for ii in [0, 2, 4]:\n pk_interp = interp1d(self.k_in, self.pk_ell[ii], kind='cubic', bounds_error=False, fill_value=0)\n self.Pk_ell[ii] = pk_interp(self.kk) \n print(\"load existing pk_%s\"%ii)\n elif len(self.pk_ell)<3:\n self.Pk_ell = {}\n self.Pk_ell[1], self.Pk_ell[3], self.Pk_ell[5] = 0, 0, 0\n for ii in [0, 2, 4]:\n try:\n pk_interp = interp1d(self.k_in, self.pk_ell[ii], kind='cubic', bounds_error=False, fill_value=0)\n self.Pk_ell[ii] = pk_interp(self.kk) \n print(\"load existing pk_%s\"%ii)\n except:\n if self.Pr is None:\n Plin = cosmology.LinearPower(self.cosmo, redshift=self.redshift, transfer='CLASS')\n self.Pk = Plin(self.kk)\n print(\"linear Pk%s\"%ii)\n else:\n pk_interp = interp1d(self.k_in, self.Pr, kind='cubic', bounds_error=False, fill_value=0)\n self.Pk = pk_interp(self.kk) \n print(\"lieanr Kaiser + input Pr for ell=%s\"%ii)\n self.Pk_ell[ii] = self.Pk * kaiser_fac[ii] \n \n if not bool(self.xi_ell): \n if self.Pr is not None:\n pk_interp = interp1d(self.k_in, self.Pr, kind='cubic', bounds_error=False, fill_value=0)\n Pk_log = pk_interp(self.kk_log)\n self.r, self.xi = P2xi(self.kk_log)(Pk_log)\n self.xi_interp = interp1d(self.r, self.xi, kind='cubic', fill_value='extrapolate')\n self.get_xibar()\n for ii in [0, 2, 4]:\n print(\"linear xi%s\"%ii)\n xi = self.xi_interp(self.r) \n if ii == 2:\n xi -= self.xi_bar\n elif ii == 4:\n xi -= self.xi_bar_bar\n self.xi_ell_interp[ii] = interp1d(self.r, xi * kaiser_fac[ii], kind='cubic', fill_value='extrapolate')\n if hasattr(self.meta_data, 'pk_zs_mean'):\n print(\"FT pk_zs_mean to xi_ell\")\n for ii in [0, 2, 4]:\n pk_interp = interp1d(self.k_in, self.pk_ell[ii], kind='cubic', bounds_error=False, fill_value=0)\n Pk_log = pk_interp(self.kk_log)\n self.r, self.xi = P2xi(self.kk_log)(Pk_log)\n self.xi_ell_interp[ii] = interp1d(self.r, self.xi, kind='cubic', fill_value='extrapolate')\n \n else:\n self.r = self.r_in.copy()\n for ii in [0, 2, 4]:\n print(\"load existing xi%s\"%ii)\n self.xi_ell_interp[ii] = interp1d(self.r, self.xi_ell[ii], kind='cubic', fill_value='extrapolate')\n for ii in [1, 3, 5]:\n self.xi_ell_interp[ii] = interp1d(self.r, numpy.zeros_like(self.r), kind='cubic', fill_value='extrapolate')\n\n \n def get_xibar(self):\n ss = numpy.linspace(1e-2, 200, 1e3)\n ds = numpy.average(ss[1:]-ss[:-1])\n self.xi_bar = numpy.zeros(len(self.r))\n self.xi_bar_bar = numpy.zeros(len(self.r))\n for ii in range(len(self.r)):\n si = ss[ss < self.r[ii]]\n self.xi_bar[ii] = numpy.sum(self.xi_interp(si)*ds*si**2)/self.r[ii]**3*3\n self.xi_bar_bar[ii] = numpy.sum(self.xi_interp(si)*ds*si**4)/self.r[ii]**5*5\n \n def get_jnbar(self):\n\n self.jn_bar = {}\n nkbins = len(self.kk)\n half_width = (self.rr[1] - self.rr[0])*0.49\n\n for l in range(0,6):\n self.jn_bar[l] = numpy.zeros([len(self.rr), nkbins])\n \n for ii, ir in enumerate(self.rr):\n u = numpy.linspace(ir-half_width, ir+half_width, 100)\n du = u[1] - u[0]\n uv, kv = numpy.meshgrid(u, self.kk, indexing='ij')\n norm = numpy.sum(uv*uv, axis=0)*du\n for l in range(0,6):\n ans = numpy.sum(uv*uv*spherical_jn(l, uv*kv), axis=0)*du\n ans /= norm\n self.jn_bar[l][ii,:] = ans\n \n def get_flll(self, ells, a, b, c, verbose=False):\n \n ells = numpy.array(ells)\n if not self.do_rsd:\n if len(set(ells)) > 1:\n ells_unit = numpy.ones_like(ells)\n ells_unit[ells==0] = 0\n ans = (self.Pk * \n (self.jn_bar[ells[0]][a])**ells_unit[0] *\n (self.jn_bar[ells[1]][b])**ells_unit[1] *\n (self.jn_bar[ells[2]][c])**ells_unit[2] *\n self.kk**2) \n else:\n ans = (self.Pk * \n (self.jn_bar[ells[0]][a])**ells[0] *\n (self.jn_bar[ells[1]][b]) *\n (self.jn_bar[ells[2]][c]) *\n self.kk**2)\n elif self.do_rsd:\n ans = (self.Pk_ell[ells[0]] * \n (self.jn_bar[ells[1]][a]) *\n (self.jn_bar[ells[2]][b]) *\n self.kk**2) \n \n if verbose:\n try:\n print(\"ells_unit\", ells_unit)\n except:\n pass\n\n return ans\n\n def get_zeta_model(self):\n \n self.zetas_dict = {}\n self.zetas_dict_1d = {}\n \n for il in self.lls:\n self.zetas_dict[il] = numpy.zeros([self.nbins, self.nbins, self.nbins])\n\n for il in self.lls:\n ells = numpy.array([int(i) for i in il])\n for ii, ir1 in enumerate(self.rr):\n for jj, ir2 in enumerate(self.rr):\n for mm, ir3 in enumerate(self.rr):\n if not self.do_rsd:\n y_int = numpy.sum(self.get_flll(ells, ii, jj, mm))*self.dkk/2./numpy.pi**2\n rs = numpy.array([ir1, ir2, ir3])\n if len(set(ells)) > 1:\n self.zetas_dict[il][ii, jj, mm] = self.xi_interp(rs[ells==0])*y_int\n else:\n self.zetas_dict[il][ii, jj, mm] = 0\n y_int = numpy.sum(self.get_flll(ells, ii, jj, mm))*self.dkk/2./numpy.pi**2\n self.zetas_dict[il][ii, jj, mm] += self.xi_interp(ir1)*y_int \n y_int = numpy.sum(self.get_flll(ells, jj, mm, ii))*self.dkk/2./numpy.pi**2\n self.zetas_dict[il][ii, jj, mm] += self.xi_interp(ir2)*y_int \n y_int = numpy.sum(self.get_flll(ells, mm, ii, jj))*self.dkk/2./numpy.pi**2\n self.zetas_dict[il][ii, jj, mm] += self.xi_interp(ir3)*y_int \n elif self.do_rsd:\n ells_perm = [ells[0], ells[1], ells[2]]\n y_int1 = numpy.sum(self.get_flll(ells_perm, jj, mm, 0))*self.dkk/2./numpy.pi**2\n y_int1 *= (self.xi_ell_interp[ells_perm[0]](ir1) *\n ((1j)**(ells_perm[1]-ells_perm[2])).real/(2*ells_perm[0]+1)**2.)\n ells_perm = [ells[1], ells[0], ells[2]]\n y_int2 = numpy.sum(self.get_flll(ells_perm, ii, mm, 0))*self.dkk/2./numpy.pi**2\n y_int2 *= (self.xi_ell_interp[ells_perm[0]](ir2) *\n ((1j)**(ells_perm[1]-ells_perm[2])).real/(2*ells_perm[0]+1)**2.)\n ells_perm = [ells[2], ells[0], ells[1]]\n y_int3 = numpy.sum(self.get_flll(ells_perm, ii, jj, 0))*self.dkk/2./numpy.pi**2\n y_int3 *= (self.xi_ell_interp[ells_perm[0]](ir3) *\n ((1j)**(ells_perm[1]-ells_perm[2])).real/(2*ells_perm[0]+1)**2.)\n self.zetas_dict[il][ii, jj, mm] = (y_int1 + y_int2 + y_int3) # il is ell combo, ii, jj, mm is bin index\n\n if not self.do_rsd:\n phase = (4*numpy.pi)**1.5*(-1)**max(ells)*numpy.sqrt(2*max(ells)+1)\n elif self.do_rsd:\n threej = numpy.float64(wigner_3j(ells[0],ells[1],ells[2],0,0,0))\n phase = (4*numpy.pi)**1.5*numpy.sqrt((2*ells[0]+1)*(2*ells[1]+1)*(2*ells[2]+1))*threej\n #print(ells, max(ells))\n self.zetas_dict[il] *= phase\n\n self.zetas_1d = []\n bin_idx = []\n self.rbin_3d = []\n for ii in range(self.nbins):\n for jj in range(ii+1, self.nbins):\n for mm in range(jj+1, self.nbins):\n bin_idx.append([ii, jj, mm])\n self.rbin_3d.append([self.rr[ii], self.rr[jj], self.rr[mm]])\n self.zetas_1d.append(self.zetas_dict[il][ii, jj, mm])\n\n self.zetas_dict_1d[il] = numpy.array(self.zetas_1d)","sub_path":"Testing/model_4PCF_Gaussian_isotropic_basis.py","file_name":"model_4PCF_Gaussian_isotropic_basis.py","file_ext":"py","file_size_in_byte":15479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"69492969","text":"from datetime import datetime, timedelta\n\nfrom django.urls import reverse\n\nfrom general_test import ProjectViewsTestGeneral\nfrom students.models import Application, StudentFile\n\n\nclass StudentsViewsTest(ProjectViewsTestGeneral):\n def setUp(self):\n self.app = 'students'\n super(StudentsViewsTest, self).setUp()\n # self.debug=True\n self.f = StudentFile(\n Caption='testfiletype',\n Distribution=self.dist,\n )\n self.f.save()\n\n def test_view_status(self):\n \"\"\"\n Test pages related to applications\n\n :return:\n \"\"\"\n # Track for the project, with trackhead t-h\n s = self\n # General pages\n code_general = [\n [['list_applications', None], [s.p_student_only]],\n [['addfile', {'dist': self.dist.pk}], [s.p_student_dist]],\n [['editfile', {'dist': self.dist.pk, 'file': self.f.pk}], [s.p_student_dist]],\n [['files', {'dist': self.dist.pk}], [s.p_all_this_dist]],\n ]\n # Status: 1 2 3 notpublic 3public 3+exec 3+finished\n # For projects that can be applied to via marketplace\n code_project_apply = [\n [['apply', {'pk': self.p}],\n [s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_student_only, s.p_student_only, s.p_forbidden]],\n [['confirmapply', {'pk': self.p}],\n [s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_student_only, s.p_student_only, s.p_forbidden]],\n ]\n # For projects that cannot be applied using marketplace\n code_project_notapply = [\n [['apply', {'pk': self.p}],\n [s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden]],\n [['confirmapply', {'pk': self.p}],\n [s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden, s.p_forbidden]],\n ]\n code_application_none = [\n [['retractapplication', {'application_id': 0}], [s.p_student404]],\n # [['prioUp', {'application_id': 0}], [student404]],\n # [['prioDown', {'application_id': 0}], [student404]]\n ]\n\n self.status = 1\n # info object with debug info if assertion fails\n info = {}\n # Test general page (not project specific)\n if self.debug:\n print(\"Testing general\")\n info['type'] = 'general'\n if self.debug:\n print('General 1')\n self.loop_code_user(code_general)\n\n # Project specific\n if self.debug:\n print(\"Testing project apply\")\n info['type'] = 'apply system'\n self.project.Apply = 'system'\n self.project.save()\n self.loop_code_user(code_project_apply)\n\n # Project specific, not apply\n if self.debug:\n print(\"Testing project apply for contacting supervisor\")\n info['type'] = 'apply supervisor'\n self.project.Apply = 'supervisor'\n self.project.save()\n self.loop_code_user(code_project_notapply)\n\n # application pages\n if self.debug:\n print(\"Testing project apply for applications student only\")\n info['type'] = 'apply general'\n self.project.Status = 3\n self.project.EndDate = datetime.now().date() + timedelta(days=2)\n self.project.Progress = None\n self.project.save()\n a = Application(Student=self.users.get('r-s'), Project=self.project)\n a.save()\n self.loop_code_user(code_application_none)\n\n self.assertListEqual(self.allurls, [], msg=\"Not all URLs of this app are tested!\")\n\n def test_apply_retract(self):\n \"\"\"\n Test apply retract pages in status 3\n\n :return:\n \"\"\"\n self.project.Status = 3\n self.project.EndDate = datetime.now().date() + timedelta(days=2)\n self.project.Progress = None\n self.project.Apply = 'system'\n self.project.save()\n\n # student\n s = self.users.get('r-s')\n\n # Test apply\n view = \"students:apply\"\n self.client.force_login(s)\n response = self.client.get(reverse(view, kwargs={\"pk\": self.p}))\n self.assertEqual(response.status_code, 200, msg=\"Student cannot apply to project!\")\n self.assertTrue(Application.objects.exists(), msg=\"Application is not made!\")\n\n # Test retract\n view = \"students:retractapplication\"\n app = Application.objects.get(Student=s)\n response = self.client.get(reverse(view, kwargs={\"application_id\": app.id}))\n self.assertEqual(response.status_code, 200, msg=\"Student cannot retract application!\")\n self.assertFalse(Application.objects.exists(), msg=\"Application is not retracted!\")\n\n self.client.logout()\n","sub_path":"students/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"477463504","text":"import os\nimport platform\nfrom ..Task import Task, TaskError\n\nclass LinkTaskTargetDirectoryError(TaskError):\n \"\"\"Link Target Directory Error.\"\"\"\n\nclass LinkTask(Task):\n \"\"\"\n Links (hardlink or symlink) a file to the target file path.\n \"\"\"\n\n __defaultLinkType = \"hardlink\"\n __kernelDll = None\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Create a Link task.\n \"\"\"\n super(LinkTask, self).__init__(*args, **kwargs)\n\n self.setOption('type', self.__defaultLinkType)\n self.setMetadata('dispatch.split', True)\n self.setMetadata('dispatch.splitSize', 20)\n\n def _perform(self):\n \"\"\"\n Perform the task.\n \"\"\"\n assert self.option('type') in ('hardlink', 'symlink'), \"Invalid link type {}\".format(self.option())\n\n for crawler in self.crawlers():\n filePath = self.target(crawler)\n\n # trying to create the directory automatically in case it does not exist\n try:\n os.makedirs(os.path.dirname(filePath))\n except OSError:\n pass\n\n # linking the file to the new target\n sourceFilePath = crawler.var('filePath')\n targetFilePath = filePath\n\n # Check if the target path already exists, if it is file remove it else raise an exception\n if os.path.isfile(targetFilePath):\n os.remove(targetFilePath)\n elif os.path.isdir(targetFilePath):\n raise LinkTaskTargetDirectoryError(\n 'Target directory already exists {}'.format(targetFilePath)\n )\n\n # linking\n if platform.system() == \"Windows\":\n self.__linkOnWindows(\n sourceFilePath,\n targetFilePath\n )\n else:\n self.__linkOnUnix(\n sourceFilePath,\n targetFilePath\n )\n\n # default result based on the target filePath\n return super(LinkTask, self)._perform()\n\n def __linkOnWindows(self, sourceFilePath, targetFilePath):\n \"\"\"\n Create a link on windows.\n \"\"\"\n # loading the kernel dll when necessary\n if self.__kernelDll is None:\n import ctypes\n self.__kernelDll = ctypes.windll.LoadLibrary(\"kernel32.dll\")\n\n sourceFilePath = os.path.normpath(sourceFilePath)\n targetFilePath = os.path.normpath(targetFilePath)\n\n # NOTE: creating a symlinks on windows requires additional permissions\n if self.option('type') == \"symlink\":\n createSymboliclink = ctypes.windll.kernel32.CreateSymbolicLinkW\n createSymboliclink.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n createSymboliclink.restype = ctypes.c_ubyte\n flags = int(os.path.isdir(sourceFilePath))\n if createSymboliclink(targetFilePath, sourceFilePath, flags) == 0:\n raise ctypes.WinError()\n\n elif self.option('type') == \"hardlink\":\n createHardlink = ctypes.windll.kernel32.CreateHardLinkW\n createHardlink.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n createHardlink.restype = ctypes.c_ubyte\n flags = 0\n if createHardlink(targetFilePath, sourceFilePath, flags) == 0:\n raise ctypes.WinError()\n\n def __linkOnUnix(self, sourceFilePath, targetFilePath):\n \"\"\"\n Create a link on unix.\n \"\"\"\n if self.option('type') == \"symlink\":\n os.symlink(\n sourceFilePath,\n targetFilePath\n )\n elif self.option('type') == \"hardlink\":\n os.link(\n sourceFilePath,\n targetFilePath\n )\n\n\n# registering task\nTask.register(\n 'link',\n LinkTask\n)\n","sub_path":"src/lib/kombi/Task/Fs/LinkTask.py","file_name":"LinkTask.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"481650719","text":"from flask import Flask\nfrom flask_cors import CORS\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_restplus import Api\n\napp = Flask(__name__)\nCORS(app, supports_credentials=True, max_age=86400)\napp.config.from_object('config')\napi = Api(app=app,\n catch_all_404s=True,\n title=\"2017 OMS API\",\n description=\"2017년도 한양대학교 주문관리시스템 API description page\",\n contact=\"한양대학교 한기훈\",\n contact_email=\"kordreamfollower@gmail.com\",\n prefix=\"/api\")\n\ndb = None\ndb_engine = None\nif db is None and db_engine is None:\n db = SQLAlchemy(app)\n db_engine = db.create_engine(app.config['SQLALCHEMY_DATABASE_URI'],\n encoding='utf-8',\n connect_args=app.config['DATABASE_CONNECT_OPTIONS'],\n pool_size=20, max_overflow=0)\n\nfrom app.modules import helper\napp.before_request(helper.before_request)\n\nfrom app.resources import *\napi.add_resource(user.User, '/user')\napi.add_resource(group.Group, '/group')\napi.add_resource(group.GroupEach, '/group/')\napi.add_resource(member.Member, '/member')\napi.add_resource(menu.Menu, '/menu')\napi.add_resource(menu.MenuEach, '/menu/')\napi.add_resource(setmenu.Setmenu, '/setmenu')\napi.add_resource(setmenu.SetmenuEach, '/setmenu/')\napi.add_resource(order.Order, '/order')\napi.add_resource(order.OrderEach, '/order/')\napi.add_resource(queue.Queue, '/queue')\napi.add_resource(statistics.Statistics, '/statistics')\napi.add_resource(download.Download, '/download')\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"566319171","text":"from django.shortcuts import render, redirect\nfrom django.views.generic import View\nfrom main.forms import UserForm, UserProfileForm\n\n\nclass IndexView(View):\n def get(self, request):\n return render(request, 'main/index.html', {\n })\n\n\nclass RegisterView(View):\n def get(self, request):\n uform = UserForm()\n pform = UserProfileForm()\n return render(request, 'main/register.html', {\n 'uform': uform,\n 'pform': pform,\n })\n\n def post(self, request):\n uform = UserForm(data=request.POST)\n pform = UserProfileForm(data=request.POST)\n if uform.is_valid() and pform.is_valid():\n user = uform.save(commit=False)\n user.set_password(user.password)\n user.save()\n profile = pform.save(commit=False)\n profile.user = user\n profile.save()\n return redirect('/')\n return render(request, 'main/register.html', {\n 'uform': uform,\n 'pform': pform,\n })\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"68826183","text":"\"\"\"\n-------------------------------------------------------------------------------------------------------------------\n\n Project: Web Application, supporting search by keywords.\n Databases:\n 1. World:\n consists of country, city and countrylanguage of World database\n @https://dev.mysql.com/doc/world-setup/en/\n 2. FilmsActors:\n consists of film, film_actor, language and actor of Sakila database\n @https://dev.mysql.com/doc/sakila/en/\n 3. CustomersOrder:\n consists of products, orderdetails, productlines, orders and customers of classicmodels database\n @https://www.mysqltutorial.org/mysql-sample-database.aspx\n\n\n Execution Format:\n $ python import.py \n\n e.g.\n $ python import.py World World\n $ python import.py FilmsActors FilmsActors\n $ python import.py CustomersOrder CustomersOrder\n\n-------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nimport mysql.connector\nfrom mysql.connector import errorcode\nimport json\nimport decimal\nimport datetime\nimport sys\nimport requests\nimport re\n\n\ndef _build_connector(project_metadata):\n \"\"\"\n This function builds the connector instance to a database, with handling the exception.\n \"\"\"\n try:\n # Creates connector to database\n cnx = mysql.connector.connect(host='localhost', user='inf551', password='inf551',\n database=project_metadata['database'])\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Wrong username or password!\")\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist!\")\n else:\n print(err)\n return cnx\n\n\ndef _read_database(db_name, project_metadata):\n \"\"\"\n This function transforms the database in MySQL server to JSON serializable Object.\n \"\"\"\n cnx = _build_connector(project_metadata)\n\n result = _query_data(cnx, project_metadata)\n\n cnx.close()\n return result\n\n\ndef _query_data(cnx, project_metadata):\n \"\"\"\n This function queries the data in the database, and transforms the data into JSON.\n\n e.g.\n project_metadata = {'database': 'World', 'tables': ['city', 'country', 'countrylanguage']}\n\n ===>\n\n {'city': {'1': {'CountryCode': 'AFG',\n 'District': 'Kabol',\n 'ID': 1,\n 'Name': 'Kabul',\n 'Population': 1780000},\n ...\n 'country': {'ABW': {'Capital': 129,\n 'Code': 'ABW',\n 'Code2': 'AW',\n 'Continent': 'North America',\n 'GNP': '828.00',\n ...\n 'SurfaceArea': '193.00'},\n ...\n }\n\n 'countrylanguage': {'ABWDutch': {'CountryCode': 'ABW',\n 'IsOfficial': 'T',\n 'Language': 'Dutch',\n 'Percentage': '5.3'},\n ...\n }\n }\n \"\"\"\n\n data = dict()\n for table in project_metadata['tables']: # iterate tables chosen.\n data[table] = dict()\n # https://stackoverflow.com/questions/29772337/python-mysql-connector-unread-result-found-when-using-fetchone\n cursor = cnx.cursor(buffered=True)\n\n \"\"\"\n 1. Query the primary keys\n \"\"\"\n primaryKey = _retrieve_primary_key(table, project_metadata)\n\n \"\"\"\n 2. Query the data\n \"\"\"\n columns = _retrieve_columns(table, project_metadata)\n cursor.execute(\"SELECT {} FROM {}\".format(', '.join(columns), table))\n table_values = cursor.fetchall()\n for row_values in table_values:\n tmp = dict()\n # Handle the values that are not JSON serializable.\n for attr_name, row_value in zip(columns, row_values):\n if not isinstance(row_value, (set, decimal.Decimal, datetime.date)):\n tmp[attr_name] = row_value\n elif isinstance(row_value, set):\n tmp[attr_name] = list(row_value)\n elif isinstance(row_value, (datetime.date, decimal.Decimal)):\n tmp[attr_name] = str(row_value)\n attr_pk = _normalize_primaryKey('&'.join([str(tmp[pk]) for pk in primaryKey])) # normalize key\n data[table][attr_pk] = tmp\n cursor.close()\n\n return data\n\n\ndef _retrieve_primary_key(table, project_metadata):\n \"\"\"\n This function returns a list of column(s), which is the primary key(s) of .\n \"\"\"\n metadata_cnx = _build_connector({'database': 'INFORMATION_SCHEMA'})\n cursor = metadata_cnx.cursor(buffered=True)\n query = \"SELECT kcu.COLUMN_NAME \" \\\n \"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \" \\\n \"USING(CONSTRAINT_NAME,TABLE_SCHEMA,TABLE_NAME) \" \\\n \"WHERE tc.TABLE_SCHEMA='{}' AND tc.TABLE_NAME='{}' \" \\\n \"AND tc.CONSTRAINT_TYPE='PRIMARY KEY';\".format(project_metadata['database'], table)\n cursor.execute(query)\n metadata_cnx.close()\n return [i[0] for i in cursor.fetchall()]\n\n\ndef _retrieve_columns(table, project_metadata):\n \"\"\"\n This function returns column(s) of .\n \"\"\"\n metadata_cnx = _build_connector({'database': 'INFORMATION_SCHEMA'})\n cursor = metadata_cnx.cursor(buffered=True)\n query = \"SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA=\\'{}\\' AND TABLE_NAME=\\'{}\\'\"\\\n .format(project_metadata['database'], table)\n cursor.execute(query)\n metadata_cnx.close()\n return [i[0] for i in cursor.fetchall()]\n\n\ndef _normalize_primaryKey(string):\n \"\"\"\n Normalizes the string.\n\n e.g.\n 'North America' -> ['north', america']\n 'Washington.DC' -> ['woshingtondc']\n ...\n \"\"\"\n return re.sub(r'[^A-Za-z0-9 ]+', '', string) # only keeps english letter\n\n\ndef _normalize_index(value):\n \"\"\"\n Normalize the string and split string if needed.\n e.g.\n 'North America' -> ['north', america']\n 'Washington.DC' -> ['woshingtondc']\n ...\n \"\"\"\n # lower the value, and only keep letters, numbers and spaces in the value.\n\n string = str(value)\n _ = re.sub(r'[^A-Za-z0-9 ]+', '', string.lower()).strip() # only keeps english letter\n # _ = re.sub(r'[^\\w\\s]+', '', string.lower()).strip()\n\n # split the value by space(s)\n _ = re.split(r'\\s+', _)\n return _\n\n\ndef _patch_data_to_firebase(data, node):\n \"\"\"\n Patches data to firebase.\n \"\"\"\n URL = 'https://inf551-project-msl-wqd.firebaseio.com/{}.json'.format(node)\n print('Patching data to {}...'.format(URL))\n requests.patch(URL, json.dumps(data))\n\n\ndef _save_json(json_content, json_path):\n \"\"\"\n Save to local.\n \"\"\"\n with open(json_path, 'w') as file:\n file.write(json.dumps(json_content, indent=4))\n\n\ndef _project_metadata(db_name):\n \"\"\"\n Typically, it is solid to use information_schema.tables to query the tables for each database.\n \n However, as we planned in the project proposal, only a subset of tables is chosen for each database,\n so we have to give EXPLICIT table names.\n \"\"\"\n if db_name not in {'World', 'FilmsActors', 'CustomersOrder'}:\n print(\"The {} database is not available. Please choose database from 'World', 'FilmsActors' \"\n \"or 'CustomersOrder'\".format(db_name))\n exit(0)\n\n if db_name == 'World':\n return {'database': 'World',\n 'tables': ['city', 'country', 'countrylanguage']}\n elif db_name == 'FilmsActors':\n return {'database': 'sakila',\n 'tables': ['film', 'film_actor', 'language', 'actor']}\n else:\n return {'database': 'classicmodels',\n 'tables': ['products', 'orderdetails', 'productlines', 'orders', 'customers']}\n\n\ndef _build_index(data):\n \"\"\"\n This function builds inverted index for every word inside data,\n storing mapping from word to its location in table.\n\n\n e.g. the index of \"davidson\" in the CustomersOrder database\n \"davidson\":\n [\n {\n \"TABLE\": \"products\",\n \"PRIMARYKEY\": \"S101678\",\n \"COLUMN\": \"productName\"\n },\n\n ...\n\n {\n \"TABLE\": \"productlines\",\n \"PRIMARYKEY\": \"Motorcycles\",\n \"COLUMN\": \"textDescription\"\n }\n ]\n \"\"\"\n index = dict()\n for table_name, table_data in data.items():\n for primary_key, row_data in table_data.items():\n for column_name, value in row_data.items():\n words_list = _normalize_index(value)\n for word in words_list:\n try:\n int(word)\n continue\n except ValueError:\n index[word] = index.get(word, []) + \\\n [{'TABLE': table_name, 'PRIMARYKEY': primary_key, 'COLUMN': column_name}]\n if '' in index:\n del index['']\n return index\n\n\ndef _retrieve_schema(project_metadata):\n \"\"\"\n e.g.\n project_metadata = {'database': 'World', 'tables': ['city', 'country', 'countrylanguage']}\n\n result:\n {\n \"city\": {\n \"columns\": [\n \"CountryCode\",\n \"District\",\n \"ID\",\n \"Name\",\n \"Population\"\n ],\n \"foreign_key\": {\n \"CountryCode\": {\n \"referenced_table\": \"country\",\n \"referenced_column\": \"Code\"\n }\n }\n },\n \"country\": {\n ...\n },\n \"countrylanguage\": {\n ...\n }\n }\n \"\"\"\n schema = dict()\n for table in project_metadata['tables']:\n schema[table] = dict()\n schema[table]['columns'] = _retrieve_columns(table, project_metadata)\n schema[table]['foreign_key'] = _retrieve_foreign_key_constraints(project_metadata, table)\n return schema\n\n\ndef _retrieve_foreign_key_constraints(project_metadata, table):\n \"\"\"\n This function connects to INFORMATION_SCHEMA of MySQL DBMS, returns foreign keys constraint.\n \"\"\"\n metadata_cnx = _build_connector({'database': 'INFORMATION_SCHEMA'})\n cursor = metadata_cnx.cursor(buffered=True)\n query = \"SELECT kcu.COLUMN_NAME, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME \" \\\n \"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \" \\\n \"USING(CONSTRAINT_NAME,TABLE_SCHEMA,TABLE_NAME) \" \\\n \"WHERE tc.TABLE_SCHEMA='{}' AND tc.TABLE_NAME='{}' \" \\\n \"AND tc.CONSTRAINT_TYPE='FOREIGN KEY'\".format(project_metadata['database'], table)\n\n fk_cons = dict()\n cursor.execute(query)\n for cons in cursor.fetchall():\n if cons[1] in project_metadata['tables']:\n fk_cons[cons[0]] = {'referenced_table': cons[1], 'referenced_column': cons[2]}\n metadata_cnx.close()\n\n return fk_cons\n\n\nif __name__ == '__main__':\n database_name = sys.argv[1]\n firebase_node = sys.argv[2]\n\n _project_metadata = _project_metadata(database_name)\n\n print('\\nRetrieving schema...')\n _schema = _retrieve_schema(_project_metadata)\n # _save_json(_schema, '{}_schema.json'.format(database_name))\n _patch_data_to_firebase(_schema, '{}_schema'.format(firebase_node))\n\n print('\\nRetrieving data...')\n results = _read_database(database_name, _project_metadata)\n # _save_json(results, '{}.json'.format(database_name))\n _patch_data_to_firebase(results, database_name)\n\n print('\\nBuilding indices...')\n inverted_index = _build_index(results)\n # _save_json(inverted_index, '{}_index.json'.format(firebase_node))\n _patch_data_to_firebase(inverted_index, '{}_index'.format(firebase_node))\n\n print('\\nDone!')\n\n","sub_path":"Coding_for_once/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":12218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"453153350","text":"# -*- coding: UTF-8 -*-\n'''\nAuthor: Jaime Rivera\nFile: 3ddist_exec.py\nDate: 2019.01.06\nRevision: 2019.01.06\nCopyright: Copyright Jaime Rivera 2019 | www.jaimervq.com\n The program(s) herein may be used, modified and/or distributed in accordance with the terms and conditions\n stipulated in the Creative Commons license under which the program(s) have been registered. (CC BY-SA 4.0)\n\nBrief: Executable file that lets the user calculate distances between Nuke 3D objects (cameras, geometries...)\n\n'''\n\n__author__ = 'Jaime Rivera '\n__copyright__ = 'Copyright 2019, Jaime Rivera'\n__credits__ = []\n__license__ = 'Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)'\n__maintainer__ = 'Jaime Rivera'\n__email__ = 'jaime.rvq@gmail.com'\n__status__ = 'Testing'\n\nimport nuke\n\n# NUKE FLAGS USED\n# ---------------\n# STARTLINE = 0x00001000\n# SLIDER = 0x00000002\n# READ_ONLY = 0x10000000\n# NO_ANIMATION = 0x00000100\n# INVISIBLE = 0x00000400\n\n\n# -------------------------------- NUMBER INPUT -------------------------------- #\n\ntotal_objects = None\n\nwhile total_objects is None:\n try:\n input_count = nuke.getInput(\"Enter number of 3D objects to compare\", '')\n total_objects = int(2.0 * round(abs(float(input_count)) / 2.0))\n except ValueError:\n nuke.message('Not a valid number')\n pass\n\n\n# -------------------------------- NODE CREATION -------------------------------- #\n\nsticky_note = nuke.nodes.StickyNote(name='Distances',\n label='3D distances',\n note_font='Arial Bold',\n note_font_size=35,\n tile_color=2566914303)\n\n# Knobs creation\nfor i in range(1, total_objects + 1):\n\n source = nuke.String_Knob('source_row_{}'.format(i), 'Source'.format(i))\n sticky_note.addKnob(source)\n\n button_code_source = \"if len(nuke.selectedNodes())==1:\" \\\n \"\\n if 'translate' in nuke.selectedNode().knobs().keys():\" \\\n \"\\n nuke.thisNode()['source_row_{0}'].setValue(nuke.selectedNode()['name'].value())\" \\\n \"\\n else:\" \\\n \"\\n nuke.thisNode()['source_row_{0}'].setValue('')\" \\\n \"\\nelif len(nuke.selectedNodes())>1:\" \\\n \"\\n nuke.message('Please select only one node')\" \\\n \"\\nelse:\" \\\n \"\\n nuke.message('Please select a node')\".format(i)\n source_button = nuke.PyScript_Knob('source_button_row_{}'.format(i), 'Select', button_code_source)\n source_button.setTooltip(\"Select a 3D object and press this button to add it to the field on the left (Source)\"\n \"\\nYou can also type any node's name into these fields\".format(i))\n sticky_note.addKnob(source_button)\n\n target = nuke.String_Knob('target_row_{}'.format(i), ' Target '.format(i))\n sticky_note.addKnob(target)\n target.clearFlag(0x00001000)\n\n button_code_target = \"if len(nuke.selectedNodes())==1:\" \\\n \"\\n if 'translate' in nuke.selectedNode().knobs().keys():\" \\\n \"\\n nuke.thisNode()['target_row_{0}'].setValue(nuke.selectedNode()['name'].value())\" \\\n \"\\n else:\" \\\n \"\\n nuke.thisNode()['target_row_{0}'].setValue('')\" \\\n \"\\nelif len(nuke.selectedNodes())>1:\" \\\n \"\\n nuke.message('Please select only one node')\" \\\n \"\\nelse:\" \\\n \"\\n nuke.message('Please select a node')\".format(i)\n target_button = nuke.PyScript_Knob('target_button_row_{}'.format(i), 'Select', button_code_target)\n target_button.setTooltip(\n \"Select a 3D object and press this button to add it to the field on the left (Target)\\nYou can also type any node's name into these fields\".format(\n i))\n sticky_note.addKnob(target_button)\n\n\n result = nuke.Double_Knob('result_row_{}'.format(i), ' DIST')\n result.setExpression(\"sqrt((pow2([value source_row_{0}].translate.x-[value target_row_{0}].translate.x))+\"\n \"(pow2([value source_row_{0}].translate.y-[value target_row_{0}].translate.y))+\"\n \"(pow2([value source_row_{0}].translate.z - [value target_row_{0}].translate.z)))\".format(i))\n sticky_note.addKnob(result)\n result.clearFlag(0x00001000)\n result.clearFlag(0x00000002)\n result.setFlag(0x10000000)\n result.setFlag(0x10000000)\n\n\nreset_code = \"for knob in nuke.thisNode().allKnobs():\"\\\n \"\\n if 'target_' in knob.name() or 'source_' in knob.name():\" \\\n \"\\n if 'button' not in knob.name():\" \\\n \"\\n knob.setValue('')\"\nreset_knob = nuke.PyScript_Knob('reset', 'RESET ALL', reset_code)\nsticky_note.addKnob(reset_knob)\nreset_knob.setFlag(0x00001000)\n\n\nformat_knob = nuke.Int_Knob('format', '')\nformat_knob.setExpression(\"[python -execlocal {if not nuke.selectedNode()['result_row_1'].getFlag(0x10000000):\"\n \"\\n for knob in nuke.thisNode().allKnobs():\"\n \"\\n if 'result_' in knob.name():\"\n \"\\n knob.clearFlag(0x00000002)\"\n \"\\n knob.setFlag(0x10000000)\"\n \"\\n knob.setFlag(0x10000000)\"\n \"\\nret=0}]\")\nsticky_note.addKnob(format_knob)\nformat_knob.setFlag(0x00000400)\n\n\nformat3_knob = nuke.Int_Knob('format3', '')\nformat3_knob.setExpression(\"[python -execlocal {for knob in nuke.thisNode().allKnobs():\"\n \"\\n if 'source_row_' in knob.name() and nuke.toNode(knob.value()) is not None:\"\n \"\\n if 'translate' not in nuke.toNode(knob.value()).knobs().keys():\"\n \"\\n knob.setValue('')\"\n \"\\n if 'target_row_' in knob.name() and nuke.toNode(knob.value()) is not None:\"\n \"\\n if 'translate' not in nuke.toNode(knob.value()).knobs().keys():\"\n \"\\n knob.setValue('')\"\n \"\\nret=0}]\")\nsticky_note.addKnob(format3_knob)\nformat3_knob.setFlag(0x00000400)\n\n\n# -------------------------------- FRAMING -------------------------------- #\n\nsticky_note.setSelected(True)\nnuke.show(sticky_note)\nnuke.zoomToFitSelected()\nfor n in nuke.allNodes():\n n.setSelected(False)","sub_path":"3ddist_exec.py","file_name":"3ddist_exec.py","file_ext":"py","file_size_in_byte":6699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"219591644","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport subprocess\nimport distutils.cmd\nimport distutils.log\nfrom distutils.errors import DistutilsPlatformError\nfrom distutils.dir_util import copy_tree\nimport glob\nimport re\nimport shlex\n\n\ndef compileJava(self, coverage):\n target_version = \"1.7\"\n srcs = glob.glob('native/java/**/*.java', recursive=True)\n src1 = [i for i in srcs if \"JPypeClassLoader\" in i]\n src2 = [i for i in srcs if not \"JPypeClassLoader\" in i]\n cmd1 = shlex.split('javac -d build/lib -g:none -source %s -target %s' %\n (target_version, target_version))\n cmd1.extend(src1)\n debug = \"-g:none\"\n if coverage:\n debug = \"-g:lines,vars,source\"\n cmd2 = shlex.split('javac -d build/classes %s -source %s -target %s -cp build/lib' %\n (debug, target_version, target_version))\n cmd2.extend(src2)\n os.makedirs(\"build/lib\", exist_ok=True)\n os.makedirs(\"build/classes\", exist_ok=True)\n self.announce(\" %s\" % \" \".join(cmd1), level=distutils.log.INFO)\n subprocess.check_call(cmd1)\n self.announce(\" %s\" % \" \".join(cmd2), level=distutils.log.INFO)\n subprocess.check_call(cmd2)\n cmd3 = shlex.split(\n 'jar cvf build/lib/org.jpype.jar -C build/classes/ .')\n self.announce(\" %s\" % \" \".join(cmd3), level=distutils.log.INFO)\n subprocess.check_call(cmd3)\n\n\nclass BuildJavaCommand(distutils.cmd.Command):\n \"\"\"A custom command to create jar file during build.\"\"\"\n\n description = 'build jpype jar'\n user_options = []\n\n def initialize_options(self):\n \"\"\"Set default values for options.\"\"\"\n pass\n\n def finalize_options(self):\n \"\"\"Post-process options.\"\"\"\n pass\n\n def run(self):\n \"\"\"Run command.\"\"\"\n java = self.distribution.enable_build_jar\n\n # Try to use the cach if we are not requested build\n if not java:\n src = os.path.join('native', 'jars')\n dest = os.path.join('build', 'lib')\n if os.path.exists(src):\n distutils.log.info(\"Using Jar cache\")\n copy_tree(src, dest)\n return\n\n distutils.log.info(\n \"Jar cache is missing, using --enable-build-jar to recreate it.\")\n\n coverage = self.distribution.enable_coverage\n\n # build the jar\n try:\n compileJava(self, coverage)\n except subprocess.CalledProcessError as exc:\n distutils.log.error(exc.output)\n raise DistutilsPlatformError(\"Error executing {}\".format(exc.cmd))\n","sub_path":"setupext/build_java.py","file_name":"build_java.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"652611660","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 17 23:33:03 2019\n\n\"\"\"\n\n\"\"\"\n Peer review comments:\n This looks like a good solution to the problems, I just have a couple of comments:\n - It is generally good style to import modules at the top of the file rather than where you use them\n - I would advise when you have a (value, flag) return style that you alwyas return a number\n as the first value instead of '_' in case someone tries to use the result before they check the flag.\n This would cause a crash if you return a string\n\"\"\"\n\n\ndef lp_apply(p, i):\n \"\"\"Applies a permutation p, given as a linear order, to a point i.\"\"\"\n n = len(p)\n if 0 <= i and i < n:\n return p[i]\n\n\ndef lp_orbit(p, i):\n \"\"\"Computes the orbit of i under p\"\"\"\n n = len(p)\n if 0 <= i and i < n:\n rv = [i]\n k = lp_apply(p, i)\n while k != i:\n rv.append(k)\n k = lp_apply(p, k)\n return rv\n\n\ndef lp_moves_to(p, i, j):\n n = len(lp_orbit(p, i))\n \"\"\"If j is not in the orbit of p under i then there is no k for which\"\"\"\n \"\"\"p**k(i)=j; test for membership and then work out position in orbit\"\"\"\n if j in lp_orbit(p, i):\n for l in range(n):\n if j == lp_orbit(p, i)[l]:\n flag = True\n if l == 0:\n \"\"\"Don't want value of k=0 returned\"\"\"\n return (n, flag)\n else:\n return (l, flag)\n else:\n flag = False\n return ('_', flag)\n\n\nfrom nose.tools import ok_\n\nok_((2, True) == lp_moves_to([7, 3, 6, 2, 0, 5, 1, 4], 6, 3))\n_, flag = lp_moves_to([7, 3, 6, 2, 0, 5, 1, 4], 6, 7)\nok_(not flag)\n\nok_((1, True) == lp_moves_to([4, 2, 5, 1, 3, 0], 3, 1))\nok_((4, True) == lp_moves_to([7, 3, 6, 2, 0, 5, 1, 4], 6, 6))\n\n\ndef lp_times(p, q):\n \"\"\"Computes the product of two permutations p and q, given as linear orders.\"\"\"\n n, m = len(p), len(q)\n if n == m:\n pq = n * [None]\n for i in range(n):\n pq[i] = lp_apply(p, lp_apply(q, i))\n return pq\n\n\ndef lp_inv(p):\n \"\"\"Computes the inverse of a permutation p, given as a linear order\"\"\"\n n = len(p)\n pinv = n * [None]\n for i in range(n):\n pinv[p[i]] = i\n return pinv\n\n\ndef lp_orbits(p):\n \"\"\"Partitions [0, ..., n - 1] by orbits of p.\n nb. Returns them sorted by length\n \"\"\"\n n = len(p)\n seen = set()\n orbits = []\n for i in range(n):\n if i not in seen:\n o = lp_orbit(p, i)\n seen |= set(o) # add multiple elements to seen\n orbits.append(o)\n orbits.sort(key=len)\n return orbits\n\n\ndef flat(p):\n \"\"\"Flattens the list\"\"\"\n x = []\n for a in p:\n for b in a:\n x.append(b)\n return x\n\n\ndef check_conj(p, q):\n \"\"\"Checks if p and q can be conjugate\"\"\"\n porbits, qorbits = lp_orbits(p), lp_orbits(q)\n m, n = len(porbits), len(qorbits)\n if m == n:\n for i in range(m):\n if len(porbits[i]) == len(qorbits[i]):\n return True\n else:\n return False\n\n\ndef lp_isconj(p, q):\n \"\"\"Finds function t\"\"\"\n rv = []\n x = flat(lp_orbits(p))\n y = flat(lp_orbits(q))\n if check_conj(p, q) == True:\n for i in range(len(x)):\n s = y.index(i)\n rv.append(x[s])\n t = rv\n return (t, True)\n else:\n return ('t', False)\n\n\n\"\"\"Tests\"\"\"\n\nfrom nose.tools import ok_\n\nt, flag = lp_isconj([7, 3, 6, 2, 0, 5, 1, 4], [3, 6, 2, 7, 5, 1, 4, 0])\nok_(flag and [7, 3, 6, 2, 0, 5, 1, 4] == lp_times(lp_times(t, [3, 6, 2, 7, 5, 1, 4, 0]), lp_inv(t)))\n\nu, flag = lp_isconj([0, 1, 2, 3, 4, 5, 6, 7], [3, 6, 2, 7, 5, 1, 4, 0])\nok_(not flag)\n\nok_('t', False == lp_isconj([1, 0, 2], [2, 0, 1])) \n\n","sub_path":"Peer Feedback/18th Feb.py","file_name":"18th Feb.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"546841684","text":"from abc import ABC, abstractmethod\nimport tensorflow as tf \nimport tensorflow.compat.v1 as v1\n\nclass BaseModel(ABC):\n \"\"\"\n Abstract base class for TensorFlow dataset.\n To create a subclass, you need to implement at least these functions:\n -- <__init__>: initialize the class\n -- : parse/pre-process model input\n -- : main function to build computation graph\n -- : (optionally) add dataset-specific options, called in base_options.py\n \"\"\"\n def __init__(self, opt):\n self.opt = opt\n\n @staticmethod\n def modify_commandline_options(parser):\n return parser\n \n @abstractmethod\n def set_input(self, model_input):\n raise NotImplementedError\n\n @abstractmethod\n def build_graph(self):\n raise NotImplementedError\n\nclass VideoPredictionModel(BaseModel):\n \"\"\"\n Generic model class for video prediction task.\n The driver scripts (train.py and test.py) will use function to build computational graph, like\n doing forward pass, computing losses/metrics/gradients, optimizing parameters and adding summaries. \n \"\"\"\n def __init__(self, opt):\n BaseModel.__init__(self, opt)\n\n @staticmethod\n def modify_commandline_options(parser):\n BaseModel.modify_commandline_options(parser)\n return parser\n\n def build_graph(self, isTrain=True):\n \"\"\"\n Function for building computational graph.\n Parameters:\n isTrain (bool) -- identify train/val process and test process\n Return:\n ret_fetch (dict) -- dictionary of tensorflow tensors\n \"\"\"\n # get global step #\n self.global_step = v1.train.get_or_create_global_step()\n\n # get learning rate and other step dependent properties #\n self.get_learning_rate()\n self.get_kl_weight()\n \n # forward function #\n input_dict = {}\n input_dict[\"image_seq\"] = self.image_seq\n try:\n if self.action is not None:\n input_dict[\"action\"] = self.action\n except AttributeError:\n pass\n try:\n if self.state is not None:\n input_dict[\"state\"] = self.state\n except AttributeError:\n pass\n \n if isTrain:\n self.outputs = self.forward(input_dict, training=True, _reuse=None)\n self.eval_outputs = self.forward(input_dict, training=False, _reuse=True)\n else:\n # in test mode, use only eval_output\n # self.outputs is used to initialize graph\n self.outputs = self.forward(input_dict, training=True, _reuse=None)\n self.eval_outputs = self.forward(input_dict, training=False, _reuse=True)\n\n # compute loss #\n if isTrain:\n self.losses = self.compute_losses(self.image_seq, self.outputs)\n self.eval_losses = self.compute_losses(self.image_seq, self.eval_outputs)\n else:\n self.losses = None\n self.eval_losses = self.compute_losses(self.image_seq, self.eval_outputs)\n\n # compute metrics #\n if isTrain:\n # since we compute l1 loss use posterior, use prior here\n self.metrics = self.compute_metrics(self.image_seq, self.outputs[\"gen_images_prior\"])\n self.eval_metrics = self.compute_metrics(self.image_seq, self.eval_outputs[\"gen_images_prior\"])\n else:\n self.metrics = None\n self.eval_metrics = self.compute_metrics(self.image_seq, self.eval_outputs[\"gen_images_prior\"])\n\n # optimizer routine only in train mode #\n if isTrain:\n train_op = self.optimize_parameters(self.losses[\"d_loss\"], self.losses[\"g_loss\"])\n \n # add summaries #\n if isTrain:\n image_sum_op, scalar_sum_op, hist_sum_op = self.create_summaries(prefix=\"train\")\n eval_image_sum_op, eval_scalar_sum_op, eval_hist_sum_op = self.create_summaries(prefix=\"eval\")\n\n # store mode-specific fetches # \n ret_fetch = {}\n # train operation\n if isTrain:\n ret_fetch[\"train_op\"] = train_op\n # global steps \n if isTrain:\n ret_fetch[\"global_step\"] = self.global_step\n # losses dict\n if self.losses:\n ret_fetch[\"losses\"] = self.losses \n ret_fetch[\"eval_losses\"] = self.eval_losses\n # metrics dict\n if self.metrics:\n ret_fetch[\"metrics\"] = self.metrics\n ret_fetch[\"eval_metrics\"] = self.eval_metrics\n # other scalars\n ret_fetch[\"batch_size\"] = tf.constant(self.image_seq.get_shape().as_list()[0], dtype=tf.float32)\n if isTrain:\n ret_fetch[\"learning_rate\"] = self.learning_rate\n ret_fetch[\"kl_weight\"] = self.kl_weight\n # summary ops\n if isTrain:\n ret_fetch[\"scalar_sum_op\"] = scalar_sum_op\n ret_fetch[\"image_sum_op\"] = image_sum_op\n ret_fetch[\"hist_sum_op\"] = hist_sum_op\n ret_fetch[\"eval_scalar_sum_op\"] = eval_scalar_sum_op\n ret_fetch[\"eval_image_sum_op\"] = eval_image_sum_op\n ret_fetch[\"eval_hist_sum_op\"] = eval_hist_sum_op\n # saved images \n ret_fetch[\"target_images\"] = self.image_seq\n ret_fetch[\"eval_gen_images\"] = self.eval_outputs[\"gen_images_prior\"]\n return ret_fetch","sub_path":"video_prediction/models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"302527059","text":"class Node: \n def __init__(self, data): \n self.data = data \n self.next = None\n\nclass LinkedList: \n def __init__(self): \n self.head = None\n\n def pairSwap(self): \n temp = self.head \n if temp is None: \n return\n while(temp is not None and temp.next is not None): \n if(temp.data == temp.next.data): \n temp = temp.next.next\n else: \n temp.data, temp.next.data = temp.next.data, temp.data \n temp = temp.next.next\n\n def push(self, new_data): \n new_node = Node(new_data) \n new_node.next = self.head \n self.head = new_node \n\n def printList(self): \n temp = self.head \n while(temp): \n print(temp.data) \n temp = temp.next\n\nll = LinkedList() \nll.push(5) \nll.push(4) \nll.push(3) \nll.push(11) \nll.push(27) \nll.pairSwap() \nll.printList()\n","sub_path":"Day 28 - Pair Swap Linked List.py","file_name":"Day 28 - Pair Swap Linked List.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"226132651","text":"from collections import defaultdict\n\n\nclass TimeMap:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.dict1 = {}\n self.dict2 = defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.dict1[(key, timestamp)] = value\n self.dict2[key].append(timestamp)\n\n def get(self, key: str, timestamp: int) -> str:\n arr = self.dict2[key]\n p1, p2 = 0, len(arr) - 1\n\n while p1 <= p2:\n m = p1 + (p2 - p1) // 2\n if arr[m] == timestamp:\n return self.dict1[(key, arr[m])]\n elif arr[m] < timestamp:\n p1 = m + 1\n elif arr[m] > timestamp:\n p2 = m - 1\n if p1 == 0:\n return \"\"\n return self.dict1[(key, arr[p1 - 1])]","sub_path":"leetcode/p0981_time_based_key_value_store/my_attempt.py","file_name":"my_attempt.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"84225356","text":"\"\"\"\nHelper functions for financial computations.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom main import database_manager\nfrom typing import Tuple\nfrom abc import ABC, abstractmethod\n\n\nLOOKBACK_PERIOD_ANNUAL = 252\n\n\nclass TimeVaryingPortfolioStrategy(object):\n \"\"\"\n Example Usage:\n st_1 = main.portfolio_strategy.ConstantVolatilityStrategy(dbm, df, 0.4)\n res_1 = st_1.compute_strategy()\n\n st_2 = main.portfolio_strategy.TSMOMStrategy(dbm, df, 0.4)\n res_2 = st_2.compute_strategy()\n \"\"\"\n def __init__(self, dbm: database_manager.DatabaseManager, data: pd.DataFrame, sigma_target: float):\n self.dbm = dbm\n self.data = data\n self.n_t = None\n self.aggregated_assets = None\n self.table_in_assets = []\n self.sigma_target = sigma_target\n\n def __aggregate_assets(self):\n \"\"\"\n Joins PX_LAST of all assets.\n \"\"\"\n agg_assets, _ = self.dbm.get_table(self.data.index[0])\n\n agg_assets['PX_LAST_' + self.data.index[0]] = agg_assets['PX_LAST']\n agg_assets['PX_LAST_' + self.data.index[0]].fillna(method='ffill', inplace=True)\n agg_assets = agg_assets[['PX_LAST_' + self.data.index[0]]]\n\n table_present = np.zeros(self.data.shape[0])\n table_present[0] = 1\n i = 1\n\n for t in range(1, self.data.shape[0]):\n # if self.verbose:\n # print('Progress: {0:.2f}%'.format(i / self.data.shape[0]))\n\n tbl_name = self.data.index[t]\n df_curr, _ = self.dbm.get_table(tbl_name)\n\n if df_curr is not None:\n if df_curr.shape[0] < LOOKBACK_PERIOD_ANNUAL + 1:\n i += 1\n continue\n\n table_present[i] = 1\n\n df_curr['PX_LAST_' + tbl_name] = df_curr['PX_LAST']\n df_curr = df_curr[['PX_LAST_' + tbl_name]]\n\n agg_assets = agg_assets.join(df_curr, on='Dates', how='outer', sort=True)\n agg_assets.fillna(method='ffill', inplace=True)\n\n i += 1\n\n self.n_t = agg_assets.notna().sum(axis=1)\n self.aggregated_assets = agg_assets\n self.table_in_assets = table_present\n\n def __compute_annualized_returns(self, sd_window) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:\n \"\"\"\n Computes annualized return and rolling standard deviation for lookback period.\n :return: tuple of daily return, annual return and rolling standard deviation of all assets. \n \"\"\"\n daily_ret = self.aggregated_assets.pct_change()\n annual_ret = self.aggregated_assets.pct_change(periods=LOOKBACK_PERIOD_ANNUAL)\n rolling_std = daily_ret.rolling(sd_window).std() * np.sqrt(LOOKBACK_PERIOD_ANNUAL)\n rolling_std[rolling_std < self.sigma_target / 10.0] = self.sigma_target / 10.0\n\n return daily_ret, annual_ret, rolling_std\n\n def pre_strategy(self, sd_window) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:\n \"\"\"\n Prepares & computes the necessary variables needed before computating the strategy. \n :return: \n \"\"\"\n self.__aggregate_assets()\n daily_ret, annual_ret, rolling_std = self.__compute_annualized_returns(sd_window)\n\n return daily_ret, annual_ret, rolling_std\n\n @abstractmethod\n def compute_strategy(self, sd_window):\n pass\n\n\nclass ConstantVolatilityStrategy(TimeVaryingPortfolioStrategy):\n def __init__(self, dbm: database_manager.DatabaseManager, data: pd.DataFrame, sigma_target):\n super().__init__(dbm, data, sigma_target)\n\n def compute_strategy(self, sd_window):\n daily_ret, annual_ret, rolling_std = super().pre_strategy(sd_window)\n\n asset_weight = self.sigma_target / rolling_std\n asset_weight = asset_weight.div(self.n_t, axis=0)\n asset_weight = asset_weight.shift(1)\n\n portfolio_return = (asset_weight * daily_ret).sum(axis=1)\n # portfolio_return = portfolio_return.div(self.n_t, axis=0)\n\n return portfolio_return, asset_weight, daily_ret\n\n\nclass TSMOMStrategy(TimeVaryingPortfolioStrategy):\n def __init__(self, dbm: database_manager.DatabaseManager, data: pd.DataFrame, sigma_target):\n super().__init__(dbm, data, sigma_target)\n\n def compute_strategy(self, sd_window):\n daily_ret, annual_ret, rolling_std = super().pre_strategy(sd_window)\n\n annual_ret = annual_ret > 0\n annual_ret = (annual_ret * 2) - 1\n\n asset_weight = self.sigma_target * annual_ret / rolling_std\n asset_weight = asset_weight.div(self.n_t, axis=0)\n asset_weight = asset_weight.shift(1)\n\n portfolio_return = (asset_weight * daily_ret).sum(axis=1)\n # portfolio_return = portfolio_return.div(self.n_t, axis=0)\n\n return portfolio_return, asset_weight, daily_ret\n\n\nclass CorrAdjustedTSMOMStrategy(TimeVaryingPortfolioStrategy):\n def __init__(self, dbm: database_manager.DatabaseManager, data: pd.DataFrame, sigma_target):\n super().__init__(dbm, data, sigma_target)\n\n def compute_strategy(self, sd_window):\n daily_ret, annual_ret, rolling_std = super().pre_strategy(sd_window)\n\n annual_ret_signed = (annual_ret > 0)\n annual_ret_signed = (annual_ret_signed * 2) - 1\n\n cf_list = []\n\n for t in range(annual_ret.shape[0]):\n curr_date = annual_ret.index[t]\n annual_ret_upto_curr = annual_ret[annual_ret.index <= curr_date]\n\n assets_present = annual_ret.columns[annual_ret.iloc[t].notnull()]\n\n if t % 100 == 0:\n print('Progress: {0:.2f}%'.format(int(t * 100 / self.n_t.shape[0])))\n\n annual_ret_upto_curr_assets = annual_ret_upto_curr[assets_present]\n annual_ret_upto_curr_assets = annual_ret_upto_curr_assets.dropna(how='all')\n\n if annual_ret_upto_curr_assets.shape[0] < 2 or annual_ret_upto_curr_assets.shape[1] < 2:\n cf_list.append(1)\n continue\n\n annual_ret_upto_curr_assets_signed = annual_ret_upto_curr_assets > 0\n annual_ret_upto_curr_assets_signed *= 2\n annual_ret_upto_curr_assets_signed -= 1\n\n asset_corr = annual_ret_upto_curr_assets.corr().values\n\n co_sign = np.eye(*asset_corr.shape)\n\n for i in range(co_sign.shape[0]):\n for j in range(i + 1, co_sign.shape[1]):\n temp = annual_ret_upto_curr_assets_signed.iloc[-1].values\n co_sign[i, j] = temp[i] * temp[j]\n co_sign[j, i] = temp[i] * temp[j]\n\n # N = self.n_t[t]\n N = asset_corr.shape[0]\n rho_bar = ((asset_corr * co_sign).sum() - asset_corr.shape[0]) / (N * (N - 1))\n temp = N / (1 + ((N - 1) * rho_bar))\n\n if temp < 0:\n print('Warning: negative value encountered for taking square root.')\n cf_list.append(1)\n continue\n\n cf_t = np.sqrt(temp)\n cf_list.append(cf_t)\n\n asset_weight = self.sigma_target * annual_ret_signed / rolling_std\n asset_weight = asset_weight.div(self.n_t, axis=0)\n asset_weight = asset_weight.mul(np.array(cf_list), axis=0)\n asset_weight = asset_weight.shift(1)\n\n portfolio_return = (asset_weight * daily_ret).sum(axis=1)\n # portfolio_return = portfolio_return.div(self.n_t * np.array(cf_list), axis=0)\n\n return portfolio_return, asset_weight, daily_ret\n","sub_path":"main/portfolio_strategy.py","file_name":"portfolio_strategy.py","file_ext":"py","file_size_in_byte":7462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"165142206","text":"import subprocess\nimport shlex\n\ndef run(**args):\n f_result = '../natypi/data/nmap_scan_result.txt'\n #command = 'nmap -T4 -A 192.168.0.1/24'\n command = 'nc -v 10.0.0.12 22'\n \n command = shlex.split(command)\n process = subprocess.Popen(command, stdout=subprocess.PIPE)\n output, err = process.communicate()\n result = '********** [ STDOUT ] **********\\n%s********** [ STDERR ] **********\\n%s' % (output, err)\n with open(f_result, 'w') as f:\n f.write(result)\n return result\n","sub_path":"modules/shell_cmd_nmap.py","file_name":"shell_cmd_nmap.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"629032054","text":"\"\"\" This rule checks for any unused security groups in AWS account.\n\"\"\"\n__version__ = '0.6.2'\n__author__ = 'Bhupender Kumar'\nimport boto3\nimport craws\nimport datetime\n\ndef handler(event, context):\n logger = craws.get_logger(name='UnusedSecurityGroups', level='DEBUG')\n logger.debug('Unused Security Groups check started')\n\n sts = boto3.client('sts')\n \n for account in craws.accounts:\n try:\n # Check if this rule has already been executed today for this account\n response = sts.assume_role(RoleArn='arn:aws:iam::926760075421:role/crawsExecution', RoleSessionName='GenerateReports')\n s3_client = boto3.client('s3', aws_access_key_id=response['Credentials']['AccessKeyId'], \n aws_secret_access_key=response['Credentials']['SecretAccessKey'], \n aws_session_token=response['Credentials']['SessionToken'])\n today = str(datetime.datetime.now().date())\n response = s3_client.head_object(Bucket = craws.bucket, Key = today+'/'+account['account_id']+'/UnusedSecurityGroups.json')\n logger.info('Account ' + account['account_id'] + ' already checked. Skipping.')\n except Exception:\n # This rule has not been executed today for this account, go ahead and execute\n results = {'Rule Name': 'Unused Custom Security Groups'}\n results['Area'] = 'EC2'\n results['Description'] = 'This rule checks the unused and dangling custom security groups in the AWS account. Security ' +\\\n 'groups that are not attached to any resource should be deleted to minimize the surface of attack.'\n details = []\n try:\n response = sts.assume_role(RoleArn=account['role_arn'], RoleSessionName='unused_SG')\n except Exception as e:\n logger.error(e)\n continue\n credentials = response['Credentials']\n regions = craws.get_region_descriptions()\n green_count = red_count = orange_count = yellow_count = grey_count = 0\n\n for region in regions:\n ec2_client = boto3.client('ec2', region_name=region['Id'],\n aws_access_key_id=credentials['AccessKeyId'], \n aws_secret_access_key=credentials['SecretAccessKey'], \n aws_session_token=credentials['SessionToken'])\n cloudtrail_client = boto3.client('cloudtrail', region_name=region['Id'],\n aws_access_key_id=credentials['AccessKeyId'], \n aws_secret_access_key=credentials['SecretAccessKey'], \n aws_session_token=credentials['SessionToken'])\n try:\n result = []\n sgrps = ec2_client.describe_security_groups()\n default_sgrps = set([sg['GroupId'] for sg in sgrps['SecurityGroups'] if \n sg['Description'] == 'default VPC security group' and sg['GroupName'] == 'default'])\n all_sgrps = set([sg['GroupId'] for sg in sgrps['SecurityGroups']])\n cstm_sgrps = set()\n cstm_sgrps = all_sgrps - default_sgrps\n used_sgrps = set()\n net_interface = ec2_client.describe_network_interfaces()\n for interface in net_interface['NetworkInterfaces']:\n for grp in interface['Groups']:\n used_sgrps.add(grp['GroupId'])\n green_count += len(list(used_sgrps))\n \n unused_sgs = cstm_sgrps - used_sgrps\n for unused_sec_grp in list(unused_sgs):\n # Some issues found, mark it as Red/Orange/Yellow depending on this check's risk level\n #details.append({'Status': craws.status['Red'], 'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Result': result})\n orange_count += 1\n unused_sec_grp = craws.get_cloudtrail_data(lookup_value=unused_sec_grp, \n cloudtrail_client=cloudtrail_client, region_id=region['Id'])\n result.append({'Security Group Id': unused_sec_grp})\n \n except Exception as e:\n logger.error(e)\n # Exception occured, mark it as Grey (not checked)\n details.append({'Status': craws.status['Grey'], 'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Result': result})\n grey_count += 1\n \n if len(result) == 0:\n # All good, mark it as Green\n #details.append({'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Status': craws.status['Green'], 'Result': result})\n details.append({'Status': craws.status['Green'], 'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Result': result})\n else:\n # Some issues found, mark it as Red/Orange/Yellow depending on this check's risk level\n details.append({'Status': craws.status['Orange'], 'Region': region['Id'] + \" (\" + region['ShortName'] + \")\", 'Result': result})\n\n results['Details'] = details\n results['GreenCount'] = green_count\n results['RedCount'] = red_count\n results['OrangeCount'] = orange_count\n results['YellowCount'] = yellow_count\n results['GreyCount'] = grey_count\n craws.upload_result_json(results, 'UnusedSecurityGroups.json', account['account_id'])\n logger.info('Results for account %s uploaded to s3', account['account_id'])\n\n logger.debug('Unused Security Groups check finished')\n\n","sub_path":"unused_security_groups.py","file_name":"unused_security_groups.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"383272556","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndata = []\r\nfor i in range(31):\r\n name = 'New_experiments/Q_learning_'+str(i+1)+'_all.csv'\r\n df = pd.read_csv(name)\r\n avg_roll = df['Reward']\r\n data.append(avg_roll)\r\n\r\ndata = np.array(data)\r\ndata_avg = data.mean(axis = 0)\r\ndata_std = data.std(axis = 0)\r\ndict = {'Average_data': data_avg}\r\ndf = pd.DataFrame(dict)\r\ndf['roll'] = df['Average_data'].rolling(window = 500).mean()\r\nvar = df['Average_data'].rolling(window = 500).std()\r\nx = np.arange(1, 100001, 1)\r\n\r\ndata = []\r\nfor i in range(31):\r\n name = 'New_experiments/Q_learning_'+str(i+1)+'.csv'\r\n df = pd.read_csv(name)\r\n avg_roll = df['Avg_rewards']\r\n data.append(avg_roll)\r\n\r\ndata = np.array(data)\r\ndata_avg = data.mean(axis = 0)\r\ndata_std = data.std(axis = 0)\r\ndict = {'Average_data': data_avg}\r\ndf1 = pd.DataFrame(dict)\r\ndf1['roll'] = df1['Average_data'].rolling(window = 200).mean()\r\nvar1 = df1['Average_data'].rolling(window = 200).std()\r\nx1 = np.arange(1, 100001, 10)\r\n\r\nplt.plot(x, df['rolling'], c = 'blue')\r\nplt.fill_between(x, df['rolling']-var, df['rolling']+var, facecolor = 'blue', alpha = 0.2)\r\nplt.plot(x, df1['rolling'], c = 'red')\r\nplt.fill_between(x, df1['rolling']-var1, df1['rolling']+var1, facecolor = 'red', alpha = 0.2)\r\nplt.show()\r\n","sub_path":"Transfer/Plot.py","file_name":"Plot.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"617260575","text":"from decimal import Decimal\nfrom datetime import timedelta, datetime\nfrom model_mommy import mommy\nfrom django.test import TestCase\nfrom callcenter.models import CallRecord, Bill, PriceRule\n\n\nclass CallRecordTest(TestCase):\n def setUp(self):\n self.call_record = mommy.make(\n CallRecord, pk=10, type=1, timestamp='2018-11-25 08:08:08',\n call_id=50, source='11986091154', destination='11988888888'\n )\n\n def test_call_record_creation(self):\n self.assertTrue(isinstance(self.call_record, CallRecord))\n self.assertEquals(self.call_record.type, 1)\n self.assertEquals(self.call_record.call_id, 50)\n self.assertEquals(self.call_record.timestamp, '2018-11-25 08:08:08')\n self.assertEquals(self.call_record.source, '11986091154')\n self.assertEquals(self.call_record.destination, '11988888888')\n self.assertEquals(self.call_record.__str__(), '11986091154')\n\n\nclass BillTest(TestCase):\n def setUp(self):\n self.call_record_start_one = mommy.make(\n CallRecord, pk=1, type=1, timestamp='2018-10-31 23:55:00',\n call_id=1, source='11999998888', destination='11982223454'\n )\n\n self.call_record_end_one = mommy.make(\n CallRecord, pk=2, type=2, timestamp='2018-11-2 00:01:08',\n call_id=1, source='', destination=''\n )\n\n def test_create(self):\n bill_instance = Bill()\n bill_data_to_save = {\n 'call': CallRecord.objects.get(id=2),\n 'cost': 12.76,\n 'call_duration': timedelta(hours=24, minutes=6, seconds=8),\n 'call_start': datetime(2018, 10, 31, 23, 55, 00),\n 'call_end': datetime(2018, 11, 2, 00, 1, 8),\n 'month': 11,\n 'year': 2018\n }\n\n bill_instance.create(bill_data=bill_data_to_save)\n\n def test_call_record_creation_exception(self):\n bill_instance = Bill()\n bill_data_to_save = {\n 'call': CallRecord.objects.get(id=2),\n 'cost': 12.76,\n 'call_duration': timedelta(hours=24, minutes=6, seconds=8),\n 'call_start': datetime(2018, 10, 31, 23, 55, 00),\n 'call_end': timedelta(hours=10),\n 'month': 11,\n 'year': 2018\n }\n\n expected = (\n '[\"\\'10:00:00\\' value has an invalid format. It must '\n 'be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.\"]'\n )\n\n actual = bill_instance.create(bill_data=bill_data_to_save)\n\n self.assertEqual(actual, expected)\n\n\nclass PriceRuleTest(TestCase):\n def setUp(self):\n self.price_rule = mommy.make(\n PriceRule, pk=1, rule_type=1, fixed_charge=Decimal('0.36'),\n call_charge=Decimal('0.09'),\n start_period=datetime(2018, 7, 10, 22, 0, 0).time(),\n end_period=datetime(2018, 7, 10, 6, 0, 0).time()\n )\n\n def test_price_rule_create(self):\n price_rule_one = PriceRule.objects.get(id=1)\n\n self.assertEqual(\n self.price_rule.rule_type,\n price_rule_one.rule_type\n )\n self.assertEqual(\n self.price_rule.fixed_charge,\n price_rule_one.fixed_charge\n )\n self.assertEqual(\n self.price_rule.call_charge,\n price_rule_one.call_charge\n )\n self.assertEqual(\n self.price_rule.start_period,\n price_rule_one.start_period\n )\n self.assertEqual(\n self.price_rule.end_period,\n price_rule_one.end_period\n )\n","sub_path":"callcenter/tests/tests_models.py","file_name":"tests_models.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"21037305","text":"def swapingFileData():\n file1=input(\"Give Original File: \")\n file2=input(\"Give the file to be swapped:\")\n\n with open(file1, 'r') as a:\n data_a=a.read()\n with open(file2, 'r') as b:\n data_b=b.read()\n\n with open(file1, 'w+') as a:\n a.write(data_a)\n with open(file2, 'w+') as b:\n b.write(data_b)\n\nswapingFileData()\n\n \n","sub_path":"swapingFile.py","file_name":"swapingFile.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"290828025","text":"\"\"\"validate prosper.test_utils.schema_utils\"\"\"\nimport datetime\nimport json\nimport jsonschema\nimport pathlib\nfrom plumbum import local\n\nimport pytest\nimport helpers\n\nimport prosper.test_utils.schema_utils as schema_utils\nimport prosper.test_utils.exceptions as exceptions\nimport prosper.test_utils._version as _version\n\n@pytest.fixture\ndef mongo_fixture(tmpdir):\n \"\"\"helper for making testmode mongo context managers\n\n Args:\n tmpdir: PyTest magic\n\n Returns:\n schema_utils.MongoContextManager: in tinydb mode\n\n \"\"\"\n mongo_context = schema_utils.MongoContextManager(\n helpers.TEST_CONFIG,\n _testmode_filepath=tmpdir,\n _testmode=True,\n )\n return mongo_context\n\n\nclass TestMongoContextManager:\n \"\"\"validate expected behavior for MongoContextManager\"\"\"\n demo_data = [\n {'butts': True, 'many': 10},\n {'butts': False, 'many': 100},\n ]\n def test_mongo_context_testmode(self, tmpdir):\n \"\"\"test with _testmode enabled\"\"\"\n mongo_context = schema_utils.MongoContextManager(\n helpers.TEST_CONFIG,\n _testmode=True,\n _testmode_filepath=tmpdir,\n )\n\n with mongo_context as t_mongo:\n t_mongo['test_collection'].insert(self.demo_data)\n\n with mongo_context as t_mongo:\n data = t_mongo['test_collection'].find_one({'butts': True})\n\n assert data['many'] == 10\n\n def test_mongo_context_prodmode(self):\n \"\"\"test against real mongo\"\"\"\n if not helpers.can_connect_to_mongo(helpers.TEST_CONFIG):\n pytest.xfail('no mongo credentials')\n\n mongo_context = schema_utils.MongoContextManager(\n helpers.TEST_CONFIG,\n )\n\n with mongo_context as mongo:\n mongo['test_collection'].insert(self.demo_data)\n\n with mongo_context as _:\n data = mongo['test_collection'].find_one({'butts': True})\n\n assert data['many'] == 10\n\n\nclass TestFetchLatestSchema:\n \"\"\"validate expected behavior for fetch_latest_schema()\"\"\"\n fake_schema_table = [\n {'schema_group':'test', 'schema_name':'fake.schema', 'version':'1.0.0',\n 'schema':{'result':'NOPE'}},\n {'schema_group':'test', 'schema_name':'fake.schema', 'version':'1.1.0',\n 'schema':{'result':'NOPE'}},\n {'schema_group':'test', 'schema_name':'fake.schema', 'version':'1.1.1',\n 'schema':{'result':'YUP'}},\n {'schema_group':'not_test', 'schema_name':'fake.schema', 'version':'1.1.2',\n 'schema':{'result':'NOPE'}},\n ]\n def test_fetch_latest_version(self, mongo_fixture):\n \"\"\"try to find latest schema\"\"\"\n collection_name = 'fake_schema_table'\n\n with mongo_fixture as t_mongo:\n t_mongo[collection_name].insert(self.fake_schema_table)\n\n with mongo_fixture as t_mongo:\n latest_schema = schema_utils.fetch_latest_schema(\n 'fake.schema',\n 'test',\n t_mongo[collection_name]\n )\n\n assert latest_schema['schema'] == {'result': 'YUP'}\n assert latest_schema['version'] == '1.1.1'\n\n def test_fetch_latest_version_empty(self, mongo_fixture):\n \"\"\"make sure function returns expected for no content\"\"\"\n collection_name = 'blank_schema_table'\n\n with pytest.warns(exceptions.FirstRunWarning):\n with mongo_fixture as t_mongo:\n latest_schema = schema_utils.fetch_latest_schema(\n 'fake.schema',\n 'test',\n t_mongo[collection_name]\n )\n\n assert latest_schema['schema'] == {}\n assert latest_schema['version'] == '1.0.0'\n\n\nclass TestCompareSchemas:\n \"\"\"validate expected behavior for compare_schemas()\"\"\"\n base_schema = helpers.load_schema_from_file('base_schema.json')\n minor_change = helpers.load_schema_from_file('minor_schema_change.json')\n major_removed_value = helpers.load_schema_from_file('major_items_removed.json')\n #major_values_changed = helpers.load_schema_from_file('major_values_changed.json')\n unhandled_diff = set(helpers.load_schema_from_file('unhandled_diff.json'))\n\n def test_compare_schemas_happypath(self):\n \"\"\"make sure equivalence works as expected\"\"\"\n status = schema_utils.compare_schemas(\n self.base_schema,\n self.base_schema\n )\n\n assert status == schema_utils.Update.no_update\n\n def test_compare_schemas_minor(self):\n \"\"\"make sure minor updates are tagged as such\"\"\"\n status = schema_utils.compare_schemas(\n self.base_schema,\n self.minor_change\n )\n\n assert status == schema_utils.Update.minor\n\n def test_compare_schemas_major(self):\n \"\"\"make sure major updates are tagged as such\"\"\"\n status = schema_utils.compare_schemas(\n self.base_schema,\n self.major_removed_value\n )\n\n assert status == schema_utils.Update.major\n\n\n def test_compare_schemas_empty(self):\n \"\"\"make sure empty case signals first-run\"\"\"\n status = schema_utils.compare_schemas(\n {},\n self.base_schema,\n )\n\n assert status == schema_utils.Update.first_run\n\n def test_compare_schemas_error(self):\n \"\"\"make sure raises for really screwed up case\"\"\"\n pytest.xfail('compare_schemas raise case not working yet')\n with pytest.raises(exceptions.UnhandledDiff):\n status = schema_utils.compare_schemas(\n self.base_schema,\n self.unhandled_diff\n )\n\n\nclass TestBuildMetadata:\n \"\"\"validate expected behavior for build_metadata()\"\"\"\n fake_metadata = {\n 'schema_group': 'fake_group',\n 'schema_name': 'fake_name',\n 'update': datetime.datetime.utcnow().isoformat(),\n 'version': '1.2.1',\n 'schema': {'type': 'DONTCARE'},\n }\n dummy_schema = {'fake': 'DONTCARE'}\n\n def test_build_schema_no_update(self):\n \"\"\"assert behavior for no_update\"\"\"\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n self.fake_metadata,\n schema_utils.Update.no_update,\n )\n assert metadata == self.fake_metadata\n\n def test_build_schema_first_run(self):\n \"\"\"assert behavior for first_run\"\"\"\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n self.fake_metadata,\n schema_utils.Update.first_run,\n )\n\n assert metadata['schema'] == self.dummy_schema\n assert metadata['update'] != self.fake_metadata['update']\n assert metadata['version'] == self.fake_metadata['version']\n\n def test_build_schema_minor(self):\n \"\"\"assert behavior for minor update\"\"\"\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n self.fake_metadata,\n schema_utils.Update.minor,\n )\n\n assert metadata['schema'] == self.dummy_schema\n assert metadata['update'] != self.fake_metadata['update']\n assert metadata['version'] == '1.2.2'\n\n def test_build_schema_major(self):\n \"\"\"assert behavior for major update\"\"\"\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n self.fake_metadata,\n schema_utils.Update.major,\n )\n\n assert metadata['schema'] == self.dummy_schema\n assert metadata['update'] != self.fake_metadata['update']\n assert metadata['version'] == '1.3.0'\n\n def test_build_schema_badschema(self):\n \"\"\"assert behavior for bad schema\"\"\"\n dummy_meta = {\n 'schema': '',\n 'version': '1.0.0',\n 'update': datetime.datetime.utcnow().isoformat(),\n }\n\n with pytest.raises(jsonschema.exceptions.ValidationError):\n metadata = schema_utils.build_metadata(\n self.dummy_schema,\n dummy_meta,\n schema_utils.Update.first_run\n )\n\n\nclass TestDumpMajorUpdate:\n \"\"\"validate expected behavior for dump_major_update()\"\"\"\n\n dummy_metadata1 = {'butts': 'yes'}\n dummy_metadata2 = {'butts': 'no'}\n def test_dump_major_udpate_empty(self, tmpdir):\n \"\"\"validate system doesn't raise for empty data\"\"\"\n filename = tmpdir / 'empty.json'\n schema_utils.dump_major_update(\n self.dummy_metadata1,\n filename,\n )\n\n with open(str(filename), 'r') as tmp_fh:\n saved_data = json.load(tmp_fh)\n\n assert saved_data[0] == self.dummy_metadata1\n\n\n def test_dump_major_update_exists(self, tmpdir):\n \"\"\"validate system appends new metadata to report\"\"\"\n filename = tmpdir / 'exists.json'\n with open(str(filename), 'w') as tmp_fh:\n json.dump([self.dummy_metadata1], tmp_fh)\n\n schema_utils.dump_major_update(\n self.dummy_metadata2,\n filename,\n )\n\n with open(str(filename), 'r') as tmp_fh:\n saved_data = json.load(tmp_fh)\n\n assert saved_data[1] == self.dummy_metadata2\n\n\nclass TestSchemaHelper:\n \"\"\"validate expected behavior for schema_helper()\"\"\"\n base_sample = helpers.load_schema_from_file('base_sample.json')\n minor_sample = helpers.load_schema_from_file('minor_sample.json')\n major_sample = helpers.load_schema_from_file('major_sample.json')\n\n name = 'dummy_name'\n group = 'dummy_group'\n collection = 'TESTSCHEMA_'\n\n def do_the_thing(self, mongo_fixture, data, collection):\n \"\"\"helper: run schema_utils.schema_helper\"\"\"\n schema_utils.schema_helper(\n data=data,\n data_source='DONTCARE',\n schema_name=self.name,\n schema_group=self.group,\n config=helpers.TEST_CONFIG,\n _collection_name=collection,\n _testmode=True,\n _dump_filepath=str(mongo_fixture._testmode_filepath),\n )\n\n def test_schema_helper_blank(self, mongo_fixture):\n \"\"\"exercise first_run path\"\"\"\n collection = self.collection + __name__\n with pytest.warns(exceptions.FirstRunWarning):\n self.do_the_thing(\n mongo_fixture, self.base_sample, self.collection + __name__)\n\n with mongo_fixture as t_mongo:\n results = list(t_mongo[collection].find({}))\n\n assert results[0]['version'] == '1.0.0'\n\n def test_schema_helper_no_update(self, mongo_fixture):\n \"\"\"exercise no_update path\"\"\"\n collection = self.collection + __name__\n with mongo_fixture as t_mongo:\n written_metadata = helpers.init_schema_database(\n context=t_mongo[collection],\n group_tag=self.group,\n name_tag=self.name,\n data=self.base_sample,\n version='1.1.0',\n )\n\n self.do_the_thing(\n mongo_fixture, self.base_sample, collection\n )\n\n with mongo_fixture as t_mongo:\n results = list(t_mongo[collection].find({}))\n\n assert results[0] == written_metadata\n\n def test_schema_helper_minor_update(self, mongo_fixture):\n \"\"\"exercise minor_update path\"\"\"\n collection = self.collection + __name__\n with mongo_fixture as t_mongo:\n written_metadata = helpers.init_schema_database(\n context=t_mongo[collection],\n group_tag=self.group,\n name_tag=self.name,\n data=self.base_sample,\n version='1.1.0',\n )\n\n self.do_the_thing(\n mongo_fixture, self.minor_sample, collection\n )\n\n with mongo_fixture as t_mongo:\n updated_metadata = schema_utils.fetch_latest_schema(\n self.name, self.group, t_mongo[collection]\n )\n\n #sanitize outputs\n written_metadata.pop('_id', None)\n updated_metadata.pop('_id', None)\n\n assert updated_metadata != written_metadata\n assert updated_metadata['version'] == '1.1.1'\n\n def test_schema_helper_major_update(self, mongo_fixture):\n \"\"\"exercise major_update path\"\"\"\n collection = self.collection + __name__\n with mongo_fixture as t_mongo:\n written_metadata = helpers.init_schema_database(\n context=t_mongo[collection],\n group_tag=self.group,\n name_tag=self.name,\n data=self.base_sample,\n version='1.1.0',\n )\n\n with pytest.raises(exceptions.MajorSchemaUpdate) as e:\n self.do_the_thing(\n mongo_fixture, self.major_sample, collection\n )\n with open(str(e.value), 'r') as major_fh:\n major_update_list = json.load(major_fh)\n\n todo_metadata = major_update_list[0]\n assert todo_metadata['version'] == '1.2.0'\n\n with mongo_fixture as t_mongo:\n updated_metadata = schema_utils.fetch_latest_schema(\n self.name, self.group, t_mongo[collection]\n )\n\n #sanitize outputs\n written_metadata.pop('_id', None)\n updated_metadata.pop('_id', None)\n\n assert updated_metadata['version'] == '1.1.0'\n\nclass TestCLI:\n \"\"\"validate update-prosper-schemas behavior\"\"\"\n CLI_name = 'update-prosper-schemas'\n update_command = local['update-prosper-schemas']\n update_path = pathlib.Path(helpers.HERE) / 'dummy-schema-update.json'\n\n def test_cli_help(self):\n \"\"\"make sure help command works\"\"\"\n output = self.update_command('-h')\n\n def test_cli_name(self):\n \"\"\"make sure --version command works\"\"\"\n output = self.update_command('--version').strip()\n\n assert output == '{cli_name} {version}'.format(\n cli_name=self.CLI_name, version=_version.__version__\n )\n\n def test_cli_happypath(self, tmpdir):\n \"\"\"dry-run CLI\"\"\"\n collection_name = 'TESTDUMMY'\n output = self.update_command(\n self.update_path,\n '--verbose',\n '--debug',\n '--local-dir={}'.format(tmpdir),\n '--collection={}'.format(collection_name),\n )\n\n mongo_context = schema_utils.MongoContextManager(\n config=helpers.ROOT_CONFIG,\n _testmode=True,\n _testmode_filepath=tmpdir,\n )\n mongo_context.database = 'TESTprosper'\n with mongo_context as t_mongo:\n results = t_mongo[collection_name].find_one({})\n\n with open(str(self.update_path), 'r') as update_fh:\n expected_results = json.load(update_fh)\n\n results.pop('_id')\n print(expected_results[0])\n print(results)\n assert results == expected_results[0]\n","sub_path":"tests/test_schema_utils.py","file_name":"test_schema_utils.py","file_ext":"py","file_size_in_byte":14715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"232528997","text":"import os \n\nfrom requests import post, codes\nfrom flask import jsonify, request, session\nfrom json import dumps\nfrom random import randint\nfrom pubnub_client import send_message\n\nfrom defaults import (CHILD_MDN,\n ACTION_URL,\n FOUNDRY_AUTH_URL)\n\n\nfrom subscription_manager import create_subscription\n\ndef create_routes(app):\n @app.route('/')\n def hello_world():\n return 'Hello World!'\n \n @app.route(\"/auth\", methods=[\"POST\"])\n def auth():\n \"\"\"\n 1. Creates an auth token that gets stored in the session itself.\n 2. Creates a call direciton subscription for a hardcoded mdn\n\n Return 401 if it can't create an auth\n Return 200 if the auth token was created and a subscription already existed for the mdn\n Return 201 if the auth token was created and a subscription was created for the mdn\n \"\"\"\n payload = {\n \"client_id\": app.config['CONSUMER_KEY'],\n \"client_secret\": app.config['CONSUMER_SECRET']\n }\n\n # This doesn't have to have content-type json because the OAuth Token request\n # expects a content type of \"Content-Type: application/x-www-form-urlencoded\",\n # aka the default behavior of requests.\n result = post(url=FOUNDRY_AUTH_URL, data=payload)\n\n if result.status_code != codes.ok:\n return \"Unable to create auth token\", codes.UNAUTHORIZED\n\n app.config[\"AUTH_TOKEN\"] = result.json()[\"access_token\"]\n app.logger.debug(\"Created an auth token: \" + app.config[\"AUTH_TOKEN\"])\n\n return create_subscription(app, CHILD_MDN)\n\n @app.route(\"/auth\", methods=[\"GET\"])\n def get_auth_token():\n if not \"auth_token\" in session:\n return \"No auth token found\", codes.NOT_FOUND\n\n return session[\"auth_token\"], codes.OK\n \n\n @app.route(\"/callback\", methods=[\"POST\"])\n def callback():\n \"\"\"\n Each subscription has a unique callback url. For now, \n use a common callback url endpoint that will defer all calls.\n \"\"\"\n\n caller = request.json['eventNotification']['callingParticipant']\n\n # We have the ability to maintain a record of the request to defer\n # via a unique decision id. For now, we'll just use the caller and a \n # random int\n decision_id = caller + str(randint(0, 10000))\n app.config[\"DECISION_ID\"] = decision_id\n\n send_message(app, request.json)\n\n callback_response = {\n \"actionToPerform\": \"Deferred\",\n \"routingAddress\": decision_id + \";display=originator\",\n \"decisionId\": decision_id\n }\n\n return jsonify(action=callback_response)\n\n @app.route(\"/action\", methods=[\"POST\"])\n def action():\n \"\"\"\n Based on the deferred decision id and the subscription id, make a decision on the call.\n ACTIONS: EndCall, Route, Continue\n \"\"\"\n subscription_id = app.config[\"SUB_ID\"]\n decision_id = app.config[\"DECISION_ID\"]\n action = request.json[\"action\"]\n\n headers = {\n \"Authorization\": \"Bearer {}\".format(app.config[\"AUTH_TOKEN\"]),\n }\n\n decision_url = ACTION_URL.format(subscription_id, decision_id, action)\n\n if action == \"Route\":\n headers[\"Content-Type\"] = \"application/json\"\n route_addr = request.json['routeAddress']\n decision_url += \"?routeAddr={route_addr}\".format(route_addr=route_addr)\n app.logger.debug(\"Routing call to: \" + decision_url)\n result = post(url=decision_url,\n headers=headers,\n data=dumps({\"display\": \"originator\"}))\n else:\n headers[\"Content-Length\"] = 0\n result = post(url=decision_url,\n headers=headers)\n\n return result.text, result.status_code\n\n\n","sub_path":"controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"339928373","text":"#-----------------------------------------------------------\n# Licensed under the terms of GNU GPL 2\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.\n#---------------------------------------------------------------------\n# Tim Hancock/Matthias Kuhn 2017\n\nfrom qgis.PyQt.QtCore import (\n QObject,\n QDate,\n pyqtSignal\n)\n\nfrom qgis.PyQt.QtWidgets import (\n QMessageBox,\n QAction\n)\n\nfrom qgis.core import (\n QgsMessageLog, QgsFeature, QgsGeometry,\n QgsFeatureRequest,\n QgsRectangle, QgsExpression\n)\n\nfrom ..proposalTypeUtilsClass import ProposalTypeUtilsMixin\n\n#from .TOMsProposalElement import *\nfrom ..core.TOMsProposal import (TOMsProposal)\n\nfrom ..constants import (\n ProposalStatus,\n RestrictionAction\n)\n\nclass TOMsTile(QObject):\n def __init__(self, proposalsManager, tileNr=None):\n QObject.__init__(self)\n\n self.proposalsManager = proposalsManager\n self.tableNames = self.proposalsManager.tableNames\n\n self.setTilesLayer()\n\n if tileNr is not None:\n self.setTile(tileNr)\n\n def setTilesLayer(self):\n self.tilesLayer = self.tableNames.setLayer(\"MapGrid\")\n if self.tilesLayer is None:\n QgsMessageLog.logMessage(\"In TOMsProposal:setTilesLayer. tilesLayer layer NOT set !!!\", tag=\"TOMs panel\")\n QgsMessageLog.logMessage(\"In TOMsProposal:setTilesLayer... \", tag=\"TOMs panel\")\n\n self.tilesInAcceptedProposalsLayer = self.tableNames.setLayer(\"TilesInAcceptedProposals\")\n if self.tilesLayer is None:\n QgsMessageLog.logMessage(\"In TOMsProposal:setTilesLayer. tilesInAcceptedProposalsLayer layer NOT set !!!\", tag=\"TOMs panel\")\n QgsMessageLog.logMessage(\"In TOMsProposal:setTilesLayer... tilesInAcceptedProposalsLayer \", tag=\"TOMs panel\")\n\n def setTile(self, tileNr):\n\n self.thisTileNr = tileNr\n self.setTilesLayer()\n\n if (tileNr is not None):\n query = '\\\"tileNr\\\" = {tileNr}'.format(proposalID=tileNr)\n request = QgsFeatureRequest().setFilterExpression(query)\n for tile in self.tilesLayer.getFeatures(request):\n self.thisTile = tile # make assumption that only one row\n return True\n\n return False # either not found or 0\n\n def tile(self):\n return self\n\n def tileNr(self):\n return self.thisTileNr\n\n def revisionNr(self):\n return self.thisTile.attribute(\"RevisionNr\")\n\n def setRevisionNr(self, value):\n return self.thisTile.setAttribute(\"RevisionNr\", value)\n\n def lastRevisionDate(self):\n return self.thisTile.attribute(\"LastRevisionDate\")\n\n def setLastRevisionDate(self, value):\n return self.thisTile.setAttribute(\"LastRevisionDate\", value)\n\n def getTileRevisionNrAtDate(self, filterDate=None):\n\n QgsMessageLog.logMessage(\"In TOMsTile:getTileRevisionNrAtDate.\", tag=\"TOMs panel\")\n\n if filterDate is None:\n filterDate = self.proposalsManager.date()\n\n #query2 = '\"tile\" = \\'{tileid}\\''.format(tileid=currTile)\n\n queryString = \"\\\"TileNr\\\" = \" + str(self.thisTileNr)\n\n QgsMessageLog.logMessage(\"In getTileRevisionNrAtDate: queryString: \" + str(queryString), tag=\"TOMs panel\")\n\n expr = QgsExpression(queryString)\n\n # Grab the results from the layer\n features = self.tilesInAcceptedProposalsLayer.getFeatures(QgsFeatureRequest(expr))\n tileProposal = TOMsProposal(self)\n\n for feature in sorted(features, key=lambda f: f[2], reverse=True):\n lastProposalID = feature[\"ProposalID\"]\n lastRevisionNr = feature[\"RevisionNr\"]\n\n tileProposal.setProposal(lastProposalID)\n\n #lastProposalOpendate = self.proposalsManager.getProposalOpenDate(lastProposalID)\n lastProposalOpendate = tileProposal.getProposalOpenDate()\n\n QgsMessageLog.logMessage(\n \"In getTileRevisionNrAtDate: last Proposal: \" + str(lastProposalID) + \"; \" + str(lastRevisionNr),\n tag=\"TOMs panel\")\n\n QgsMessageLog.logMessage(\n \"In getTileRevisionNrAtDate: last Proposal open date: \" + str(lastProposalOpendate) + \"; filter date: \" + str(filterDate),\n tag=\"TOMs panel\")\n\n if lastProposalOpendate <= filterDate:\n QgsMessageLog.logMessage(\n \"In getTileRevisionNrAtDate: using Proposal: \" + str(lastProposalID) + \"; \" + str(lastRevisionNr),\n tag=\"TOMs panel\")\n return lastRevisionNr, lastProposalOpendate\n\n return 0, None\n\n def updateTileRevisionNr(self):\n\n QgsMessageLog.logMessage(\n \"In TOMsTile:updateTileRevisionNr. tile\" + str(self.thisTileNr) + \" currRevNr: \", tag=\"TOMs panel\")\n\n # This will update the revision numberwithin \"Tiles\" and add a record to \"TilesWithinAcceptedProposals\"\n\n currProposal = self.proposalsManager.currentProposalObject()\n\n # check that there are no revisions beyond this date\n if self.lastRevisionDate < currProposal.getProposalOpenDate():\n QgsMessageLog.logMessage(\n \"In updateTileRevisionNr. tile\" + str(self.thisTileNr) + \" revision numbers are out of sync\",\n tag=\"TOMs panel\")\n QMessageBox.information(self.iface.mainWindow(), \"ERROR\", (\"In updateTileRevisionNr. tile\" + str(self.thisTileNr) + \" revision numbers are out of sync\"))\n return False\n\n if self.revisionNr() is None:\n newRevisionNr = 1\n else:\n newRevisionNr = self.revisionNr() + 1\n\n self.setRevisionNr(newRevisionNr)\n self.setLastRevisionDate(currProposal.getProposalOpenDate())\n\n # Now need to add the details of this tile to \"TilesWithinAcceptedProposals\" (including revision numbers at time of acceptance)\n\n newRecord = QgsFeature(self.tilesInAcceptedProposalsLayer.fields())\n\n idxProposalID = self.tilesInAcceptedProposalsLayer.fields().indexFromName(\"ProposalID\")\n idxTileNr = self.tilesInAcceptedProposalsLayer.fields().indexFromName(\"TileNr\")\n idxRevisionNr = self.tilesInAcceptedProposalsLayer.fields().indexFromName(\"RevisionNr\")\n\n newRecord[idxProposalID] = currProposal.getProposalNr()\n newRecord[idxTileNr] = self.thisTileNr\n newRecord[idxRevisionNr] = newRevisionNr\n newRecord.setGeometry(QgsGeometry())\n\n status = self.tilesInAcceptedProposalsLayer.addFeature(newRecord)\n\n return status\n\n\n","sub_path":"core/TOMsTile.py","file_name":"TOMsTile.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"224998346","text":"\r\nfrom PyQt4 import QtCore, QtGui, Qt\r\nfrom PyQt4.QtCore import *\r\nfrom PyQt4.QtGui import *\r\nimport ImageWindow\r\nimport NewMapWindow\r\n\r\n\r\nclass ToolBox(QtGui.QFrame):\r\n def __init__(self, parent=None):\r\n super(ToolBox, self).__init__(parent)\r\n \r\n self.newMap = QPushButton(\"new map\")\r\n self.newMap.clicked.connect(self.newMapDialog)\r\n \r\n self.loadImage = QPushButton(\"load image\")\r\n self.loadImage.clicked.connect(self.loadImageDialog)\r\n \r\n self.loadMap = QPushButton(\"load map\")\r\n self.loadMap.clicked.connect(self.loadMapDialog)\r\n \r\n self.saveMap = QPushButton(\"save map\")\r\n self.saveMap.clicked.connect(self.saveMapDialog)\r\n \r\n self.mapGrid = QCheckBox(\"grid on map\")\r\n self.mapGrid.stateChanged.connect(self.toggleMapGrid)\r\n \r\n self.imageGrid = QCheckBox(\"grid on image\")\r\n self.imageGrid.stateChanged.connect(self.toggleImageGrid)\r\n \r\n self.layerSpinBox = QSpinBox()\r\n self.layerSpinBox.setRange(0, 2)\r\n self.layerSpinBox.valueChanged.connect(self.layerChanged)\r\n \r\n self.bgColor = QPushButton(\"background\")\r\n self.bgColor.clicked.connect(self.setBgColor)\r\n \r\n self.editCollision = QCheckBox(\"edit collision\")\r\n self.editCollision.stateChanged.connect(self.toggleEditCollision)\r\n \r\n self.imageWindow = ImageWindow.ImageWindow()\r\n \r\n buttonLayout = QtGui.QGridLayout()\r\n buttonLayout.addWidget(self.newMap, 0, 0)\r\n buttonLayout.addWidget(self.loadImage, 1, 0)\r\n buttonLayout.addWidget(self.loadMap, 0, 1)\r\n buttonLayout.addWidget(self.saveMap, 1, 1)\r\n \r\n gridLayout = QtGui.QHBoxLayout()\r\n gridLayout.addWidget(self.mapGrid)\r\n gridLayout.addWidget(self.imageGrid)\r\n \r\n layerLayout = QtGui.QHBoxLayout()\r\n layerLayout.addWidget(self.layerSpinBox)\r\n layerLayout.addWidget(self.bgColor)\r\n \r\n \r\n mainLayout = QtGui.QVBoxLayout()\r\n mainLayout.addLayout(buttonLayout)\r\n mainLayout.addWidget(self.imageWindow)\r\n mainLayout.addLayout(gridLayout)\r\n mainLayout.addLayout(layerLayout)\r\n mainLayout.addWidget(self.editCollision)\r\n \r\n self.setLayout(mainLayout)\r\n \r\n def loadImageDialog(self):\r\n file = QFileDialog.getOpenFileName(None, \"open image\", QString(), \"Images (*.png *.jpg *.gif)\")\r\n self.imageWindow.loadImage(file)\r\n \r\n def loadMapDialog(self):\r\n file = QFileDialog.getOpenFileName(None, \"open map\", QString(), \"Map (*.txt)\")\r\n if file == '' or file is None:\r\n return\r\n self.mapWindow.loadMap(file)\r\n \r\n \r\n def saveMapDialog(self):\r\n file = QFileDialog.getSaveFileName(None, \"save map\", QString(), \"Map (*.txt)\")\r\n if file == '' or file is None:\r\n return\r\n self.mapWindow.saveMap(file)\r\n \r\n def newMapDialog(self):\r\n d = NewMapWindow.NewMapDialog(self)\r\n if d.exec_() == QDialog.Accepted:\r\n \r\n self.mapWindow.mapArea.mapWidth = d.widthLine.value()\r\n self.mapWindow.mapArea.mapHeight = d.heightLine.value()\r\n self.mapWindow.mapArea.gridSize = d.gridSizeLine.value()\r\n self.mapWindow.mapArea.create()\r\n self.imageWindow.imageArea.gridsize = d.gridSizeLine.value()\r\n \r\n def toggleMapGrid(self, e):\r\n if e == Qt.Unchecked:\r\n self.mapWindow.mapArea.drawGrid = False\r\n elif e == Qt.Checked:\r\n self.mapWindow.mapArea.drawGrid = True\r\n self.mapWindow.mapArea.update()\r\n \r\n def toggleImageGrid(self, e):\r\n if e == Qt.Unchecked:\r\n self.imageWindow.imageArea.drawGrid = False\r\n elif e == Qt.Checked:\r\n self.imageWindow.imageArea.drawGrid = True\r\n self.imageWindow.imageArea.update()\r\n \r\n def layerChanged(self, val):\r\n self.mapWindow.mapArea.layer = val\r\n \r\n def setBgColor(self):\r\n color = QColorDialog.getColor(self.mapWindow.mapArea.bgColor)\r\n self.mapWindow.mapArea.bgColor = color\r\n self.mapWindow.mapArea.update()\r\n \r\n def toggleEditCollision(self, e):\r\n if e == Qt.Unchecked:\r\n self.mapWindow.mapArea.editCollision = False\r\n elif e == Qt.Checked:\r\n self.mapWindow.mapArea.editCollision = True\r\n self.mapWindow.mapArea.update()\r\n \r\n ","sub_path":"ToolBox.py","file_name":"ToolBox.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"135421425","text":"class Solution:\n \"\"\"\n @param n: The integer n\n @param k: The integer k\n @return: Return the combination\n \"\"\"\n def getCombination(self, n, k):\n comb = [[-1 for j in range(n//2 + 1)] for i in range(n+1)]\n def get_comb(n, m):\n if comb[n][m] != -1: return comb[n][m]\n if m == 0 or n == m:\n comb[n][m] = 1\n else:\n comb[n][m] = get_comb(n-1, m-1) + get_comb(n-1, m)\n return comb[n][m]\n\n ans = [-1] * (n//2)\n pos = -1\n for i in range(n//2):\n cnt = 0\n for j in range(pos+1, n):\n v = get_comb(n-j-1, n//2-i-1)\n if k-v <= 0:\n pos = j\n break\n k -= v\n\n ans[i] = pos+1\n\n return ans\n\n\nsol = Solution()\nprint(sol.getCombination(18, 3014))\n","sub_path":"lint/1500/1464.py","file_name":"1464.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"224531666","text":"## License: Apache 2.0. See LICENSE file in root directory.\n## Copyright(c) 2017 Intel Corporation. All Rights Reserved.\n\n#####################################################\n## Align Depth to Color ##\n#####################################################\nimport sys\n\nsy_root = '/home/nvidia/realsense/librealsense-master/build/wrappers/python'\nsys.path.insert(0, sy_root)\n# First import the library\n#import pyrealsense2 as rs\n# Import Numpy for easy array manipulation\nimport numpy as np\n# Import OpenCV for easy image rendering\nimport cv2\nimport numpy as np\nimport time\n\ndef hough(picture):\n img=cv2.cvtColor(picture, cv2.COLOR_RGB2GRAY)\n #uu=rgb2gray(picture)\n cv2.imshow(\"gray\", img)\n #gradX = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx = 1, dy = 0, ksize = -1)\n #gradY = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 0, dy = 1, ksize = -1)\n\n #cv2.imshow(\"gradX\", gradX)\n #x=cv2.waitKey(1)& 0xFF\n #cv2.imshow(\"gradY\", gradY)\n #x=cv2.waitKey(1)\n # subtract the y-gradient from the x-gradient\n #gradient = cv2.subtract(gradX, gradY)\n #img = cv2.convertScaleAbs(gradient)\n img = cv2.blur(img, (3, 3))\n edges = cv2.Canny(img, 50, 150, apertureSize=3)\n cv2.imshow('cannyuu',edges)\n lines = cv2.HoughLines(edges, 1, np.pi / 180, 118) # 这里对最后一个参数使用了经验型的值\n result = img.copy()\n shuipingx=[]\n if(lines is not None):\n for lop in range(int(lines.size/2)):\n for line in lines[lop]:\n rho = line[0] # 第一个元素是距离rho\n theta = line[1] # 第二个元素是角度theta\n print(rho)\n print(theta)\n if (theta < (np.pi / 4.)) or (theta > (3. * np.pi / 4.0)): # 垂直直线\n # 该直线与第一行的交点\n pt1 = (int(rho / np.cos(theta)), 0)\n # 该直线与最后一行的焦点\n pt2 = (int((rho - result.shape[0] * np.sin(theta)) / np.cos(theta)), result.shape[0])\n # 绘制一条白线\n cv2.line(result, pt1, pt2,0,1)\n else: # 水平直线\n # 该直线与第一列的交点\n pt1 = (0, int(rho / np.sin(theta)))\n # 该直线与最后一列的交点\n pt2 = (result.shape[1], int((rho - result.shape[1] * np.cos(theta)) / np.sin(theta)))\n # 绘制一条直线\n if(pt2[0]-pt1[0]>0):\n cv2.line(result, pt1, pt2,0, 1)\n shuipingx.append(pt1[1])\n print(('pt2=',pt2,'pt1 =',pt1))\n #if shuipingx>0:\n # break\n return result, shuipingx\ndef imgread(picture,imgcutxia, r, g, b):\n x = (imgcutxia[:, :, 0] > r)\n y = (imgcutxia[:, :, 1] > g)\n z = (imgcutxia[:, :, 2] > b)\n imgcutxia[(x & y & z), :] = 0\n x = (imgcutxia[:, :, 0] < 8)\n y = (imgcutxia[:, :, 1] < 8)\n z = (imgcutxia[:, :, 2] < 8)\n imgcutxia[(x & y & z), :] = 0\n \"\"\"\n NpKernel = np.uint8(np.zeros((3, 3)))\n for i in range(3):\n NpKernel[2, i] = 1 # 感谢chenpingjun1990的提醒,现在是正确的\n NpKernel[i, 2] = 1\n imgcutxia = cv2.erode(imgcutxia, NpKernel)\n \"\"\"\n x = (imgcutxia[:, :, 0] > 10)\n y = (imgcutxia[:, :, 1] > 10)\n z = (imgcutxia[:, :, 2] > 10)\n\n p = np.sum((x & y & z))\n return p\n\n\ndef huojia(picture, pix, r, g, b):\n shang=0\n xia=0\n img = cv2.imread(picture)\n imgcutshang = img[140:300, 150:550]\n _,shuipingx=hough(imgcutshang)\n max1=max(shuipingx)\n min2=min(shuipingx)\n print('shuipilllllllllllllllllllllllllllllllllllllllllllllllllllllngx',max1,min2)\n #imgcutshang = img[(140+max1-130):(140+max1+4), 150:550]\n imgcutshang = img[(140 + max1 - 130):(140 + max1 -15), 200:480]\n cv2.imwrite('%s_yuanshang.jpg' % (picture), imgcutshang)\n #imgcutxia= img[140+max1+70:480, 150:550]\n imgcutxia = img[140 + max1 + 70:480, 200:480]\n cv2.imwrite('%s_yuanxia.jpg' % (picture), imgcutxia)\n\n # cv2.imwrite('%s_yuanxia.jpg' % (picture), imgcutxia)\n p1 = imgread(picture + 'shang', imgcutshang, r, g, b)\n print(picture, 'shang has ', p1)\n if (p1 > pix):\n print(picture, 'shang is you')\n shang = 1\n else:\n print((picture, 'shang is wu'))\n p2 = imgread(picture + 'xia', imgcutxia, r, g, b)\n print(picture, 'xia has ', p2)\n if (p2 > pix):\n print(picture, 'xia is you')\n xia = 1\n else:\n print((picture, 'xia is wu'))\n cv2.imwrite('%s_shang.jpg' % (picture), imgcutshang)\n cv2.imwrite('%s_xia.jpg' % (picture), imgcutxia)\n cv2.imwrite('maskshang.jpg', imgcutshang)\n cv2.imwrite('maskxia.jpg', imgcutxia)\n return shang, xia, p1, p2\n\n\n# Streaming loop\ndef picture():\n pipeline = rs.pipeline()\n\n # Create a config and configure the pipeline to stream\n # different resolutions of color and depth streams\n config = rs.config()\n config.enable_stream(rs.stream.depth, 640, 360, rs.format.z16, 30)\n config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)\n\n # Start streaming\n profile = pipeline.start(config)\n\n # Getting the depth sensor's depth scale (see rs-align example for explanation)\n depth_sensor = profile.get_device().first_depth_sensor()\n depth_scale = depth_sensor.get_depth_scale()\n print\n \"Depth Scale is: \", depth_scale\n\n # We will be removing the background of objects more than\n # clipping_distance_in_meters meters away\n clipping_distance_in_meters = 0.65 # 1 meter\n clipping_distance = clipping_distance_in_meters / depth_scale\n\n # Create an align object\n # rs.align allows us to perform alignment of depth frames to others frames\n # The \"align_to\" is the stream type to which we plan to align depth frames.\n align_to = rs.stream.color\n align = rs.align(align_to)\n\n print(' start ')\n\n while True:\n # Get frameset of color and depth\n frames = pipeline.wait_for_frames()\n # frames.get_depth_frame() is a 640x360 depth image\n # Align the depth frame to color frame\n aligned_frames = align.proccess(frames)\n # Get aligned frames\n aligned_depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image\n color_frame = aligned_frames.get_color_frame()\n # Validate that both frames are valid\n if not aligned_depth_frame or not color_frame:\n continue\n depth_image = np.asanyarray(aligned_depth_frame.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n # Remove background - Set pixels further than clipping_distance to grey\n grey_color = 0\n depth_image_3d = np.dstack(\n (depth_image, depth_image, depth_image)) # depth image is 1 channel, color is 3 channels\n bg_removed = np.where((depth_image_3d > clipping_distance) | (depth_image_3d <= 0), grey_color, color_image)\n # Render images\n # depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.09), cv2.COLORMAP_JET)\n # images = np.hstack((bg_removed, depth_colormap))\n cv2.namedWindow('Align Example', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('Align Example', bg_removed)\n key = cv2.waitKey(110)\n # print key\n picname = 6\n for lm in range(picname + 1):\n if key == ord('%d' % (lm)):\n cv2.imwrite('picture/%d.jpg' % (lm), bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (lm), color_image)\n\n if key == ord('s'):\n print('kjkk')\n pipeline.stop()\n break\n \"\"\"\n\n\n # Get frameset of color and depth\n\n frames = pipeline.wait_for_frames()\n # frames.get_depth_frame() is a 640x360 depth image\n\n # Align the depth frame to color frame\n aligned_frames = align.process(frames)\n\n # Get aligned frames\n aligned_depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image\n color_frame = aligned_frames.get_color_frame()\n\n # Validate that both frames are valid\n #if not aligned_depth_frame or not color_frame:\n # continue\n\n depth_image = np.asanyarray(aligned_depth_frame.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n\n # Remove background - Set pixels further than clipping_distance to grey\n grey_color = 0\n depth_image_3d = np.dstack((depth_image,depth_image,depth_image)) #depth image is 1 channel, color is 3 channels\n bg_removed = np.where((depth_image_3d > clipping_distance) | (depth_image_3d <= 0), grey_color, color_image)\n # Render images\n #depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.09), cv2.COLORMAP_JET)\n #images = np.hstack((bg_removed, depth_colormap))\n #cv2.namedWindow('Align Example', cv2.WINDOW_AUTOSIZE)\n #cv2.imshow('Align Example', bg_removed)\n key = cv2.waitKey(12)\n #print key\n cv2.imwrite('picture/%d.jpg' % (1), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (2), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (3), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (4), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (5), bg_removed)\n time.sleep(4)\n cv2.imwrite('picture/%d.jpg' % (6), bg_removed)\n if key ==ord('1'):\n cv2.imwrite('picture/%d.jpg'%(1),bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (1),color_image)\n if key ==ord('2'):\n cv2.imwrite('picture/_%d.jpg'%(2),bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (2), color_image)\n if key ==ord('3'):\n cv2.imwrite('picture/_%d.jpg'%(3),bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (3), color_image)\n if key == ord('4'):\n cv2.imwrite('picture/%d.jpg' % (4), bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (4), color_image)\n if key == ord('5'):\n cv2.imwrite('picture/%d.jpg' % (5), bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (5), color_image)\n if key == ord('6'):\n cv2.imwrite('picture/%d.jpg' % (6), bg_removed)\n cv2.imwrite('picture/color_%d.jpg' % (6), color_image)\n if key == ord('s'):\n print('kjkk')\n print('true is pp')\n time.sleep(5)\n cv2.destroyAllWindows()\n pipeline.stop()\n \"\"\"\n\n\ndef huop():\n # alist1=[]\n # alist2=[]\n pix1 = []\n pix2 = []\n pix3 = []\n #picture()\n start = time.clock()\n for kl in range(1, 7):\n shang, xia, p1, p2 = huojia('picture/%d.jpg' % (kl), pix=800, r=70, g=70, b=75)\n # alist1.append([shang])\n # alist2.append([xia])\n pix3.append(p1)\n pix3.append(p2)\n pix1.append(p1)\n pix2.append(p2)\n # alist=alist2+alist1\n pixt = pix1 + pix2\n pix3.sort()\n # print(alist)\n print(pixt)\n print((pix3))\n for xpo in pixt:\n if xpo == pix3[0] or xpo == pix3[1] or xpo == pix3[2]:\n pixt[pixt.index(xpo)] = 0\n else:\n pixt[pixt.index(xpo)] = 1\n\n # print(alist)\n print(pixt)\n last_tiem = [[pixt[0], pixt[1], pixt[2], pixt[3], pixt[4], pixt[5]],\n [pixt[6], pixt[7], pixt[8], pixt[9], pixt[10], pixt[11]\n ]]\n # print(' last item',last_tiem)\n end = time.clock()\n print('cost time is', end - start)\n return last_tiem\n\n\nif __name__ == \"__main__\":\n \"\"\"\n cap = cv2.VideoCapture(3)\n cap.set(3, 1920)\n cap.set(4, 1080)\n time.sleep(2)\n ret, frame = cap.read()\n print(frame.shape)\n cv2.imshow('hhhh', frame)\n cv2.waitKey(110)\n time.sleep(0.74)\n cv2.imwrite('ggggg.jpg', frame)\n print('has done ')\n cap.release()\n cv2.destroyAllWindows()\n \"\"\"\n last_tiem = huop()\n print(' last item', last_tiem)\n","sub_path":"pic_for_car.py","file_name":"pic_for_car.py","file_ext":"py","file_size_in_byte":11853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"138953449","text":"#!/usr/bin/env python\n\n# (c) David Sykes 2013\n# One more time, for the kids!\n\nimport sys\nimport os\nfrom Parameters import Parameters, ParamError\nfrom CompileEngine import CompileEngine\nfrom CompileError import CompileError\nfrom TokenParser import TokenParser\nfrom VariableEngine import VariableEngine\nfrom ScriptEngine import ScriptEngine\nfrom NullFileWrapper import NullFileWrapper\n\ndef Useage(mess = None):\n\tprint('Useage: ' + sys.argv[0] + \" {script file} -variables {variable file} -functions {functions file}\")\n\tprint(\"Options: -lst : Ouptut debug information\")\n\tif mess:\n\t\tprint()\n\t\tprint(mess)\n\t\tsys.exit(-1)\n\tsys.exit(0)\n\ndef Quit(mess):\n\tprint(mess)\n\tsys.exit(-1)\n\ndef fetch_output_folder(parameters):\n\treturn p.GetOption('output')\n\ndef make_output_script_path(script_path, output_folder):\n\t(full_path, extension) = os.path.splitext(script)\n\t(folder, file_name) = os.path.split(full_path)\n\tif output_folder:\n\t\treturn os.path.join(output_folder, file_name)\n\treturn full_path\n\ndef get_list_file(path, create_list_file_path_flag):\n\tif create_list_file_path_flag:\n\t\treturn open(output_script_path + '.lst', 'w')\n\ntry:\n\tp = Parameters(['test','lst'],'[variables,functions,output]','[undefined]', sys.argv[1:])\nexcept ParamError as e:\n\tUseage('Param error: ' + e.value )\n\nif p.GetSwitch('test'):\n\tsys.path.append('./Tests')\n\tfrom Tests import RunTests\n\tRunTests()\n\tsys.exit(0)\n\nif len(p.GetParameters()) < 1:\n\tUseage('No script to compile')\n\nif p.GetOption('variables') == None and p.GetOption('functions') == None:\n\tUseage('No variable or functions file specified')\n\noutput_folder = fetch_output_folder(p)\n\nvariableengine = VariableEngine()\ntry:\n\tif p.GetOption('variables') != None:\n\t\tvariableengine.LoadXml(p.GetOption('variables'))\n\tif p.GetOption('functions') != None:\n\t\tvariableengine.LoadXml(p.GetOption('functions'))\nexcept CompileError as e:\n\tQuit(''.join([p.GetOption('variables'), ': ', e.value]))\n\nscriptengine = ScriptEngine()\n\nfor script in p.GetParameters():\n\ttry:\n\t\tfiledata = open(script).read()\n\texcept IOError as e:\n\t\tUseage(e)\n\ttokenparser = TokenParser(filedata)\n\te = CompileEngine(tokenparser, variableengine, scriptengine)\n\ttry:\n\t\te.Process()\n\t\ttry:\n\t\t\toutput_script_path = make_output_script_path(script, output_folder)\n\t\t\ttarget = output_script_path + '.bytes'\n\t\t\tobjf = open(target, 'wb')\n\t\t\tlistFile = NullFileWrapper(get_list_file(output_script_path, p.GetSwitch('lst')))\n\t\t\tscriptengine.Write(objf, listFile)\n\t\texcept IOError as e:\n\t\t\tUseage(e)\n\texcept CompileError as e:\n\t\tQuit(''.join(['Error:', script, '(', str(e.line), '): ', e.value]))\n","sub_path":"Compiler/CompileScript.py","file_name":"CompileScript.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"261776198","text":"from django.shortcuts import render,render_to_response\nfrom django.http import HttpResponse\nfrom models import Category,Service,Comment,UserAQL\nfrom django.template import RequestContext, loader\nfrom django.template import RequestContext as RC\nfrom django.utils import timezone\n# Create your views here.\ndef Categories (request):\n\tcategory_list = {'Category':Category.objects.all()}\n\treturn render(request,'CategoriasDjango.html',category_list)\ndef Cat (request,Name):\n\tif request.method == 'GET':\n\t\t\"\"\"return render(request,'categoriaDjango.html',suppliers_list)\"\"\"\n\t\t\"\"\"return render_to_response('categoriaDjango.html', {'suppliers':Supplier.objects.all().filter(category_id=supplier).order_by('-calificacion')},context_instance = RC( request, {} ),)\"\"\"\n\t\treturn render_to_response('CategoriaDjango.html', {'Services':Service.objects.all().filter(Category=Name).order_by('-Calification')},context_instance = RC( request, {} ),)\ndef Serv(request,Name,NameService):\n\tif request.method == 'GET':\n\t\ttheService = Service.objects.get(NameService=NameService)\n\t\trealComment = dict()\n\t\tcomments = Comment.objects.filter(Service=theService)\n\t\trealComments = list() \n\t\tfor c in comments:\n\t\t\trealComment = dict()\n\t\t\trealComment['User'] = c.User\n\t\t\trealComment['Opinion'] = c.Opinion\n\t\t\trealComment['Image'] = realComment['User'].Image\n\t\t\trealComments.append(realComment)\n\t\trealComments.reverse()\n\t\treturn render_to_response('Service.html', {'Service': theService,'Comments':realComments},context_instance = RC( request, {} ),)\ndef All(request):\n\tif request.method == 'GET':\n\t\treturn render_to_response('AllCategories.html', {'Services':Service.objects.all().order_by('-Calification')},context_instance = RC( request, {} ),)\ndef New(request):\n\tif request.method == 'GET':\n\t\tallServices = Service.objects.all()\n\t\ttoday = timezone.now()\n\t\tnewServices = list() \n\t\tfor a in allServices:\n\t\t\tif a.CreationDate.month == today.month:\n\t\t\t\tnewServices.append(a)\n\t\tnewServices = reversed(newServices)\n\t\treturn render_to_response('NewService.html', {'Services':newServices},context_instance = RC( request, {} ),)","sub_path":"aquienllamo9.0/Service/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"416218159","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, redirect, get_object_or_404, get_list_or_404\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .forms import SupplierForm, NewIndustryForm, NewProductCategoryForm, SupplierQueryForm, ContactUsForm\nfrom .models import Supplier, Industry, ProductCategory\nfrom django.core.mail import send_mail, BadHeaderError\n\nfrom django.views.generic import ListView, CreateView\nfrom django.urls import reverse_lazy\n#construir view da página de buscas. Método GET vai retornar\n#sem nenhum parâmetro, método POST vai retornar com query\n\ndef homePage(request):\n contact_email = \"contato@mysupplier.com.br\"\n if request.method == \"POST\":\n form = ContactUsForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n from_email = form.cleaned_data['email']\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n try:\n send_mail(subject, message, from_email, [contact_email])\n except BadHeaderError:\n return HttpResponse(\"Header inválido encontrado\")\n return redirect(\"success_message\")\n else:\n form = ContactUsForm()\n industries = Industry.objects.all()\n return render(request, \"home.html\", {\"form\" : form, \"industries\" : industries})\n\n\ndef successMessage(request):\n return render(request, \"message_success.html\")\n\n#formulários internos (administração) para criar novas industrias\n#e categorias de produtos\ndef newIndustry(request):\n if request.method == \"POST\":\n form = NewIndustryForm(request.POST, request.FILES)\n if form.is_valid():\n form.save(commit=True)\n return redirect(\"new_category\")\n else:\n form = NewIndustryForm()\n return render(request, \"gen_form.html\", {\"form\" : form})\n\ndef newCategory(request):\n if request.method == \"POST\":\n form = NewProductCategoryForm(request.POST)\n if form.is_valid():\n category = form.save(commit=True)\n return redirect(\"new_category\")\n else:\n form = NewProductCategoryForm()\n return render(request, \"gen_form.html\", {\"form\" : form})\n\n\n#view do usuário, para criação de novos anúncios\n@login_required\ndef newSupplier(request):\n if request.method == \"POST\":\n form = SupplierForm(request.POST)\n if form.is_valid():\n #create object with correct parameters\n #use commit=false to add extra infor before saving to DB\n supplier = form.save(commit=False)\n supplier.owner = request.user\n supplier.save()\n\n return redirect(\"query_supplier_list\")\n else:\n form = SupplierForm()\n return render(request, \"gen_form.html\", {\"form\" : form})\n\n#View para realizar buscas no BD de forncedores\ndef querySupplierList(request):\n if request.method == \"POST\":\n form = SupplierQueryForm(request.POST)\n if form.is_valid():\n category = form.cleaned_data['category']\n suppliers = Supplier.objects.filter(category__name=category)\n\n form = SupplierQueryForm()\n return render(request, \"query.html\", {'suppliers' : suppliers,\n 'form' : form})\n form = SupplierQueryForm()\n suppliers = Supplier.objects.all()\n return render(request, \"query.html\", {'suppliers' : suppliers,\n 'form' : form})\n\n\n#later substitute 404 for page showing no results and askinjg for new query\ndef queryAllSuppliers(request, industry, category):\n if request.method == \"GET\":\n suppliers = get_list_or_404(Supplier.objects.filter(category__rel_industry=industry))\n\n if category != 0:\n pass\n #suppliers = get_list_or_404(suppliers.filter(category=category))\n form = SupplierQueryForm()\n\n return render(request, \"query.html\", {'suppliers' : suppliers,\n 'form' : form})\n","sub_path":"project_django/mysupplier/suppliers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"253154474","text":"import numpy as np\nimport numba as nb\nimport awkward as awk\nimport operator\nfrom cachetools import cachedmethod\nfrom cachetools.keys import hashkey\nfrom functools import partial\n\nfrom utils.Geometry import RadToCart2D, CartToRad2D\n\n@nb.njit\ndef pt_shift_numba(pt, nsig, up, down):\n return pt*(1 + (nsig>=0)*nsig*up - (nsig<0)*nsig*down)\n\ndef jet_pt_shift():\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fjet_pt_shift'))\n def fjet_pt_shift(ev, evidx, nsig, source):\n nominal = ev.Jet.pt\n try:\n up = getattr(ev.Jet, 'JEC{}Up'.format(source)).content\n down = getattr(ev.Jet, 'JEC{}Down'.format(source)).content\n except AttributeError:\n up = 0.\n down = 0.\n return awk.JaggedArray(nominal.starts, nominal.stops, pt_shift_numba(\n nominal.content, nsig, up, down,\n ))\n\n def return_jet_pt_shift(ev):\n source = ev.source if ev.source in ev.attribute_variation_sources else ''\n return fjet_pt_shift(ev, ev.iblock, ev.nsig, source)\n\n return return_jet_pt_shift\n\ndef muon_pt_shift():\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fmuon_pt_shift'))\n def fmuon_pt_shift(ev, evidx, nsig, source):\n shift = (source==\"muonPtScale\")*ev.Muon.ptErr.content/ev.Muon.pt.content\n return awk.JaggedArray(ev.Muon.pt.starts, ev.Muon.pt.stops, pt_shift_numba(\n ev.Muon.pt.content, nsig, shift, -1.*shift\n ))\n\n def ret_func(ev):\n source = ev.source if ev.source == \"muonPtScale\" else ''\n return fmuon_pt_shift(ev, ev.iblock, ev.nsig, source)\n\n return ret_func\n\ndef ele_pt_shift():\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fele_pt_shift'))\n def fele_pt_shift(ev, evidx, nsig, source):\n shift = (source==\"eleEnergyScale\")*ev.Electron_energyErr.content/ev.Electron.pt.content\n return awk.JaggedArray(ev.Electron.pt.starts, ev.Electron.pt.stops, pt_shift_numba(\n ev.Electron.pt.content, nsig, shift, -shift\n ))\n\n def ret_func(ev):\n source = ev.source if ev.source == \"eleEnergyScale\" else \"\"\n return fele_pt_shift(ev, ev.iblock, ev.nsig, source)\n\n return ret_func\n\ndef photon_pt_shift():\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fphoton_pt_shift'))\n def fphoton_pt_shift(ev, evidx, nsig, source):\n shift = (source==\"photonEnergyScale\")*ev.Photon_energyErr.content/ev.Photon.pt.content\n result = awk.JaggedArray(ev.Photon.pt.starts, ev.Photon.pt.stops, pt_shift_numba(\n ev.Photon.pt.content, nsig, shift, -shift\n ))\n result.content[np.isnan(result).content] = 0.\n return result\n\n def ret_func(ev):\n source = ev.source if ev.source == \"photonEnergyScale\" else \"\"\n return fphoton_pt_shift(ev, ev.iblock, ev.nsig, source)\n\n return ret_func\n\ndef met_shift(arg, unclust_energy):\n @nb.njit\n def met_shift_numba(\n met, mephi, jpt, jptcorr, jphi, jstarts, jstops, metuncx, metuncy, nsig,\n ):\n jpx_old, jpy_old = RadToCart2D(jpt, jphi)\n jpx_new, jpy_new = RadToCart2D(jptcorr, jphi)\n\n mex, mey = RadToCart2D(met, mephi)\n for iev, (start, stop) in enumerate(zip(jstarts, jstops)):\n for iob in range(start, stop):\n if jpt[iob] > unclust_energy:\n mex[iev] += jpx_old[iob]\n mey[iev] += jpy_old[iob]\n if jptcorr[iob] > unclust_energy:\n mex[iev] -= jpx_new[iob]\n mey[iev] -= jpy_new[iob]\n\n mex += nsig*metuncx\n mey += nsig*metuncy\n\n return CartToRad2D(mex, mey)\n\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fmet_shift'))\n def fmet_shift(ev, evidx, nsig, source, arg_):\n return met_shift_numba(\n ev.MET_pt, ev.MET_phi, ev.Jet_pt.content,\n ev.Jet_ptShift(ev).content, ev.Jet_phi.content,\n ev.Jet_pt.starts, ev.Jet_pt.stops,\n (source==\"unclust\")*ev.MET_MetUnclustEnUpDeltaX,\n (source==\"unclust\")*ev.MET_MetUnclustEnUpDeltaY,\n nsig,\n )[arg_]\n\n return lambda ev: fmet_shift(ev, ev.iblock, ev.nsig, ev.source, arg)\n\ndef obj_selection(objname, selection, xclean=False):\n @cachedmethod(operator.attrgetter('cache'), key=partial(hashkey, 'fobj_selection'))\n def fobj_selection(ev, evidx, nsig, source, objname_, selection_, xclean_, attr):\n mask = getattr(ev, \"{}_{}Mask\".format(objname_, selection_))(ev)\n if xclean_:\n mask = mask & getattr(ev, \"{}_XCleanMask\".format(objname_))(ev)\n\n obj = getattr(ev, \"{}_{}\".format(objname_, attr))\n if callable(obj):\n obj = obj(ev)\n\n return obj[mask]\n\n def return_obj_selection(ev, attr):\n source = ev.source if ev.source in ev.attribute_variation_sources else ''\n return fobj_selection(\n ev, ev.iblock, ev.nsig, source, objname, selection, xclean, attr,\n )\n\n return return_obj_selection\n\nclass ObjectFunctions(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n def begin(self, event):\n event.Jet_ptShift = jet_pt_shift()\n event.Muon_ptShift = muon_pt_shift()\n event.Electron_ptShift = ele_pt_shift()\n event.Photon_ptShift = photon_pt_shift()\n event.Tau_ptShift = lambda ev: ev.Tau_pt\n event.MET_ptShift = met_shift(0, self.unclust_threshold)\n event.MET_phiShift = met_shift(1, self.unclust_threshold)\n\n for objname, selection, xclean in self.selections:\n if xclean:\n setattr(event, selection+\"NoXClean\", obj_selection(objname, selection))\n setattr(event, selection, obj_selection(objname, selection, xclean=True))\n else:\n setattr(event, selection, obj_selection(objname, selection))\n","sub_path":"sequence/Readers/ObjectFunctions.py","file_name":"ObjectFunctions.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"476844250","text":"from .. import IrisCommand\nfrom .. import state_types as t\nfrom .. import state_machine as sm\nfrom .. import util as util\nfrom .. import iris_objects\n\nclass Mean(IrisCommand):\n title = \"take mean of {dataframe}\"\n examples = [\n \"mean of {dataframe} of numbers\",\n \"mean {dataframe}\",\n \"average of {dataframe}\",\n \"average value of {dataframe}\",\n ]\n help_text = [\n \"This computes the average values of an array of numbers\"\n ]\n argument_types = {\n \"dataframe\": t.Dataframe(\"What dataframe would you like to analyze?\"),\n \"selector\": t.DataframeSelector(\"What are the columns you'd like to transform?\", dataframe=\"dataframe\")\n }\n def command(self, dataframe, selector):\n import numpy as np\n return np.average(selector.to_matrix().flatten())\n def explanation(self, val):\n return \"The mean is {}\".format(round(val, 6))\n\nmean = Mean()\n\nclass LogTransform(IrisCommand):\n title = \"log-transform {dataframe}\"\n examples = [\n \"log-transform {dataframe} of numbers\",\n \"log {dataframe}\",\n \"log of {dataframe}\",\n \"log value of {dataframe}\",\n ]\n help_text = [\n \"This computes the log values of an array of numbers\"\n ]\n argument_types = {\n \"dataframe\": t.Dataframe(\"What dataframe would you like to analyze?\"),\n \"selector\": t.DataframeSelector(\"What are the columns you'd like to transform?\", dataframe=\"dataframe\")\n }\n def command(self, dataframe, selector):\n import numpy as np\n data = selector.to_matrix()\n data_out = []\n for col in range(0,data.shape[1]):\n data_out.append(np.log(data[:,col]))\n data_out = np.array(data_out).T\n return iris_objects.IrisDataframe(column_names=selector.column_names, column_types=selector.column_types, data=data_out)\n\nlog = LogTransform()\n\nclass PearsonCorrelation(IrisCommand):\n title = \"compute pearson correlation: {x} and {y}\"\n examples = [ \"pearson correlation between {x} and {y}\",\n \"pearson correlation {x} {y}\",\n \"how are {x} and {y} correlated\" ]\n help_text = [\n \"A pearson correlation coefficient is a measure of linear dependence between two variables.\",\n \"A coefficient greater than 0 indicates a positive linear relationship\",\n \"A coefficient less than 0 indicates a negative relationship\",\n \"And a coefficient near 0 indicates the absence of any relationship.\",\n \"This command returns a coefficient and a p-value that measures the degree of confidence in its significance.\"\n ]\n argument_help = {\n \"x\": \"The x value should be an array from the current environment\",\n \"y\": \"The y value should be an array from the current environment\",\n }\n def command(self, x : t.Array(\"What is the first array?\"), y : t.Array(\"The second array?\")):\n from scipy.stats import pearsonr\n return pearsonr(x,y)\n def explanation(self, corr_pval):\n corr = round(corr_pval[0],4)\n pval = round(corr_pval[1],4)\n return \"Correlation of {} with p-value of {}\".format(corr, pval)\n\npearsonCorrelation = PearsonCorrelation()\n\nclass FindQuartiles(IrisCommand):\n title = \"find quartiles {array}\"\n expamples = [\"quartiles {array}\", \"Q1 Q2 Q3 Q4 {array}\"]\n argument_types ={\n \"array\": t.Array(\"What array do you want to use?\")\n }\n def command(self, array):\n import numpy as np\n min_, max_ = min(array), max(array)\n q25, q50, q75 = np.percentile(array, [25, 50, 75])\n return (min_, q25, q50, q75, max_)\n def explanation(self, results):\n out_s = \"Q1 is from {} to {}, Q2 is from {} to {}, Q3 is from {} to {}, and Q4 is from {} to {}\"\n return out_s.format(results[0], results[1], results[1], results[2], results[2], results[3], results[3], results[4])\n\nfindQuartiles = FindQuartiles()\n\nclass StatisticalTestDataframe(IrisCommand):\n title = \"two-sample statistical test {stats_test} on columns in {data1} and {data2}\"\n examples = [\"two-sample {stats_test} on columns in {data1} {data2}\"]\n argument_types = {\n \"stats_test\": t.Select(options={\n \"Mann-Whitney U test (does not assume data is normally distributed)\": \"mann_whitney\",\n \"Welch's t-test (assumes normal distibution, not equal variance)\": \"welch\",\n \"Student's t-test (assumes normal distribution and equal variance)\": \"student_t\"\n }),\n \"data1\": t.Dataframe(\"What data for first population?\"),\n \"data2\": t.Dataframe(\"What data for second population?\")\n }\n def command(self, stats_test, data1, data2):\n from scipy.stats import ttest_ind, mannwhitneyu\n from collections import namedtuple\n import numpy as np\n if stats_test == \"mann_whitney\":\n ttest = mannwhitneyu\n elif stats_test == \"welch\":\n ttest = lambda x,y: ttest_ind(x,y,equal_var=False)\n else:\n ttest = ttest_ind\n data1M, data2M = [data.to_matrix() for data in [data1, data2]]\n results = []\n Statistic = namedtuple('Statistic', ['stat', 'p_val', 'odds'])\n for i in range(0, data1M.shape[1]):\n stat_val = ttest(data1M[:,i], data2M[:,i])\n results.append(Statistic(stat_val[0], stat_val[1], np.average(data1M[:,i].flatten())/np.average(data2M[:,i].flatten())))\n results = np.array(results).reshape(1, data1M.shape[1], 3)\n df = iris_objects.IrisDataframe(column_names=list(data1.column_names), column_types=[], data=results)\n df.pops = [data1.name, data2.name]\n return df\n\nstatisticalTestDataframe = StatisticalTestDataframe()\n\nclass BonferroniCorrection(IrisCommand):\n title = \"apply bonferroni correction to {data}\"\n examples = [ \"bonferroni {data}\" ]\n argument_types = {\n \"data\": t.Dataframe(\"Where is the collection of statistics?\")\n }\n def command(self, data):\n import numpy as np\n dataM = data.to_matrix()\n num_tests = dataM.shape[1]\n new_data = np.copy(dataM)\n for i in range(0, num_tests):\n new_data[0,i,1] = new_data[0,i,1] * num_tests\n df = iris_objects.IrisDataframe(column_names=list(data.column_names), column_types=[], data=new_data)\n df.pops = list(data.pops)\n return df\n\nbonferroniCorrection = BonferroniCorrection()\n\nclass HolmCorrection(IrisCommand):\n title = \"apply holm correction to {data}\"\n examples = [ \"holm {data}\" ]\n argument_types = {\n \"data\": t.Dataframe(\"Where is the collection of statistics?\")\n }\n def command(self, data):\n import numpy as np\n dataM = data.to_matrix()\n num_tests = dataM.shape[1]\n new_data = np.copy(dataM)\n pvals = sorted([(i, new_data[0,i,1]) for i in range(0, num_tests)], key=lambda x: x[1])\n p2i = {k[0]:i for i,k in enumerate(pvals)}\n for i in range(0, num_tests):\n new_data[0,i,1] = new_data[0,i,1] * (num_tests-p2i[i]+1)\n df = iris_objects.IrisDataframe(column_names=list(data.column_names), column_types=[], data=new_data)\n df.pops = list(data.pops)\n return df\n\nholmesCorrection = HolmCorrection()\n\nclass ShowSignificantValues(IrisCommand):\n title = \"show significant values for {data}\"\n examples = [ \"significant values {data}\"]\n argument_types = {\n \"data\": t.Dataframe(\"Where is the collection of statistics?\")\n }\n def command(self, data):\n dmatrix = data.to_matrix()\n pvals = [dmatrix[0, i, 1] for i in range(0, dmatrix.shape[1])]\n odds = [dmatrix[0, i, 2] for i in range(0, dmatrix.shape[1])]\n results = [(p_val, odds[i], data.column_names[i]) for i, p_val in enumerate(pvals) if p_val < 0.05]\n return (results, data.pops)\n def explanation(self, results):\n stats, pops = results\n new_results = []\n for r in stats:\n if r[1] < 1:\n direction = \"{} more likely in \\\"{}\\\"\".format(round(1.0/r[1],6), pops[1])\n else:\n direction = \"{} more likely in \\\"{}\\\"\".format(round(r[1],6), pops[0])\n new_results.append(\"\\\"{}\\\" with p-value of {} is {}\".format(r[2], round(r[0],6), direction))\n return new_results\n\nshowSignificantValues = ShowSignificantValues()\n\nclass StudentTTest(IrisCommand):\n title = \"student t-test on {dataframe}\"\n argument_types = {\n \"dataframe\": t.Dataframe(\"What dataframe contains the data?\"),\n \"pop1\": t.DataframeSelector(\"What is the first population to analyze?\", dataframe=\"dataframe\"),\n \"pop2\": t.DataframeSelector(\"What is the second population to analyze?\", dataframe=\"dataframe\"),\n }\n def command(self, dataframe, pop1, pop2):\n from scipy.stats import ttest_ind\n data_pop1 = pop1.to_matrix().flatten() # TODO: in future, force single column selection\n data_pop2 = pop2.to_matrix().flatten()\n return ttest_ind(data_pop1, data_pop2)\n def explanation(self, results):\n return \"The p-value is {:.2e} and t-statistic is {}.\".format(results[1], round(results[0],6))\n\nstudentTTest = StudentTTest()\n\n# class StudentTTest(IrisCommand):\n# title = \"calculate two sample Student t-test on {x} and {y}\"\n# examples = [\n# \"Student t-test on {x} {y}\",\n# \"statistical test\",\n# \"two sample statistical test\",\n# \"test statistic\"\n# ]\n# help_text = [\n# \"This test determines whether two independent samples are significantly different from one another.\",\n# \"It assumes that both samples are normally distributed with equal variance.\"\n# ]\n# def command(self, x : t.Array(), y : t.Array()):\n# from scipy.stats import ttest_ind\n# return ttest_ind(x,y)\n# def explanation(self, results):\n# pval = round(results[1], 4)\n# if pval < 0.05:\n# return \"These distributions are significantly different, with p-value of {}.\".format(pval)\n# else:\n# return \"These distributions are not significantly different, with p-value of {}.\".format(pval)\n#\n# studentTTest = StudentTTest()\n\nclass WelchTTest(IrisCommand):\n title = \"calculate Welch t-test on {x} and {y}\"\n examples = [\n \"Welch t-test on {x} and {y}\",\n \"statistical test\",\n \"two sample statistical test\",\n \"statistical\"\n ]\n help_text = [\n \"This test determines whether two independent samples are significantly different from one another.\",\n \"It assumes that both samples are normally distributed, but does not assume they have equal variance.\"\n ]\n def command(self, x : t.Array(), y : t.Array()):\n from scipy.stats import ttest_ind\n return ttest_ind(x,y, equal_var=False)\n def explanation(self, results):\n pval = round(results[1], 4)\n if pval < 0.05:\n return \"These distributions are significantly different, with p-value of {}.\".format(pval)\n else:\n return \"These distributions are not significantly different, with p-value of {}.\".format(pval)\n\nwelchTTest = WelchTTest()\n\nclass MannWhitney(IrisCommand):\n title = \"calculate Mann-Whitney U test on {x} and {y}\"\n examples = [\n \"Mann-Whitney U test on {x} and {y}\",\n \"statistical test\",\n \"two sample statistical test\"\n ]\n help_text = [\n \"This test determines whether two independent samples are significantly different from one another.\",\n \"It does not assume that both samples are normally distributed.\"\n ]\n def command(self, x : t.Array(), y : t.Array()):\n from scipy.stats import mannwhitneyu\n return mannwhitneyu(x,y)\n def explanation(self, results):\n pval = round(results[1], 4)\n if pval < 0.05:\n return \"These distributions are significantly different, with p-value of {}.\".format(pval)\n else:\n return \"These distributions are not significantly different, with p-value of {}.\".format(pval)\n\nmannWhitney = MannWhitney()\n\nclass TTestHelp(IrisCommand):\n title = \"help me run a t-test\"\n example = [\n \"which t-test should I use?\"\n ]\n help_text = [\n \"This command walks you through choosing a t-test\"\n ]\n argument_types = {\n \"choice\": t.YesNo(\"Is your data normally distributed?\",\n yes=t.YesNo(\"Do your samples have equal variance?\",\n yes=\"use student's t-test\",\n no=\"use welch's t-test\"\n ),\n no=\"use mann-whitney u test\"\n )\n }\n def command(self, choice):\n return choice\n\ntTestHelp = TTestHelp()\n","sub_path":"backend/iris/stdlib/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":12607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"429050028","text":"from __init__ import *\n\nimport sys\nimport os.path\nfrom PIL import Image\nimport numpy as np\nfrom arg_parser import parse_args\n\nfrom printer import print_header, print_usage, print_line\n\nsys.path.insert(0, ROOT)\nfrom utils import *\n\ndef init_images(app_data):\n print(\"[init.py] : initializing images...\")\n\n app_args = app_data['app_args']\n rows = 2048\n cols = 2048\n\n # input image:\n img_path1 = app_args.img_file1\n img1 = np.array(Image.open(img_path1))\n\n img_path2 = app_args.img_file2\n img2 = np.array(Image.open(img_path2))\n\n if img1.shape != img2.shape:\n app_data['error'] = 1\n return \n\n R = img1.shape[0]\n C = img1.shape[1]\n\n off_left = 31\n total_pad = 60\n\n # convert input image to floating point\n image1_f = np.float32(img1) / 255.0\n image2_f = np.float32(img2) / 255.0\n\n # create ghost zone and copy image roi\n\n # Image 1:\n image1_ghost = np.empty((rows+total_pad, cols+total_pad, 3), np.float32)\n image1_ghost[off_left:rows+off_left, off_left:cols+off_left, 0:3] = \\\n np.array(img1[0:rows, 0:cols, 0:3], np.float32)\n # clamp the boundary portions\n image_clamp(img1, image1_ghost, rows, cols, 3,\n np.float32, 1, off_left, total_pad)\n\n # Image 2\n image2_ghost = np.empty((rows+total_pad, cols+total_pad, 3), np.float32)\n image2_ghost[off_left:rows+off_left, off_left:cols+off_left, 0:3] = \\\n np.array(img2[0:rows, 0:cols, 0:3], np.float32)\n # clamp the boundary portions\n image_clamp(img2, image2_ghost, rows, cols, 3,\n np.float32, 1, off_left, total_pad)\n\n # create a simple mask of size (rows+total_pad) x (cols+total_pad)\n maskRow = 820\n half1 = np.zeros((maskRow, cols+total_pad), np.float32)\n half2 = np.ones((rows+total_pad-maskRow, cols+total_pad), np.float32)\n\n mask_ghost = np.vstack((half1, half2))\n\n # move colour dimension outside\n image1_f_flip = np.rollaxis(image1_ghost, 2).ravel()\n image2_f_flip = np.rollaxis(image2_ghost, 2).ravel()\n\n # result array\n OUT = np.empty((3, rows, cols), np.float32) \n\n img_data = {}\n img_data['IN1'] = image1_f_flip\n img_data['IN2'] = image2_f_flip\n img_data['OUT'] = OUT\n img_data['mask_ghost'] = mask_ghost\n\n app_data['img_data'] = img_data\n app_data['rows'] = rows\n app_data['cols'] = cols\n app_data['total_pad'] = 60\n return\n\ndef get_input(app_data):\n # parse the command-line arguments\n app_args = parse_args()\n app_data['app_args'] = app_args\n\n app_data['mode'] = app_args.mode\n app_data['runs'] = int(app_args.runs)\n app_data['graph_gen'] = bool(app_args.graph_gen)\n app_data['timer'] = app_args.timer\n\n # storage optimization\n app_data['optimize_storage'] = bool(app_args.optimize_storage)\n # early freeing of allocated arrays\n app_data['early_free'] = bool(app_args.early_free)\n # pool allocate option\n app_data['pool_alloc'] = bool(app_args.pool_alloc)\n\n return\n\ndef init_all(app_data):\n pipe_data = {}\n app_data['pipe_data'] = pipe_data\n\n get_input(app_data)\n\n init_images(app_data)\n\n return\n\n","sub_path":"sandbox/apps/python/img_proc/pyramid_blend/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"536154207","text":"\"\"\"Test for the ui element TimePicker\"\"\"\nimport os, unittest\n\nfrom mock import patch, Mock\n\ntry:\n\tfrom ui import TimePicker\nexcept ImportError:\n\tprint(\"Absolute imports failed, trying relative imports\")\n\tos.sys.path.append(os.path.dirname(os.path.abspath('.')))\n\t# Store original __import__\n\torig_import = __import__\n\n\tdef import_mock(name, *args):\n\t\tif name in ['helpers']:\n\t\t\treturn Mock()\n\t\telif name == 'ui.utils':\n\t\t\timport utils\n\t\t\treturn utils\n\t\treturn orig_import(name, *args)\n\n\twith patch('__builtin__.__import__', side_effect=import_mock):\n\t\tfrom time_picker import TimePicker\n\ndef get_mock_input():\n\treturn Mock()\n\ndef get_mock_output(width=128, height=64, mode=\"1\"):\n m = Mock()\n m.configure_mock(width=width, height=height, device_mode=mode, type=[\"b&w\"])\n return m\n\ntp_name = \"Test TimePicker\"\n\nclass TestDatePicker(unittest.TestCase):\n\t\"\"\"Tests TimePicker\"\"\"\n\n\tdef test_constructor(self):\n\t\t\"\"\"Tests constructor\"\"\"\n\t\ttp = TimePicker(get_mock_input(), get_mock_output(), name=tp_name)\n\t\tself.assertIsNotNone(tp)\n\n\tdef test_keymap(self):\n\t\t\"\"\"Tests keymap\"\"\"\n\t\ttp = TimePicker(get_mock_input(), get_mock_output(), name=tp_name)\n\t\tself.assertIsNotNone(tp)\n\t\tfor key_name, callback in tp.keymap.iteritems():\n\t\t\tself.assertIsNotNone(callback)\n\n\t# Test whether it returns None when deactivating it\n\tdef test_left_key_returns_none(self):\n\t\ttp = TimePicker(get_mock_input(), get_mock_output(), name=tp_name)\n\t\ttp.refresh = lambda *args, **kwargs: None\n\n\t\t# Checking at start\n\t\tdef scenario():\n\t\t\ttp.deactivate()\n\t\t\tassert not tp.in_foreground\n\n\t\twith patch.object(tp, 'idle_loop', side_effect=scenario) as t:\n\t\t\treturn_value = tp.activate()\n\t\tassert return_value is None\n\n\t\t# Chechking after changing the numbers a little\n\t\tdef scenario():\n\t\t\tfor i in range(3):\n\t\t\t\ttp.decrease_one()\n\t\t\t\ttp.move_right()\n\t\t\t\ttp.increase_one()\n\t\t\ttp.deactivate()\n\t\t\tassert not tp.in_foreground\n\n\t\twith patch.object(tp, 'idle_loop', side_effect=scenario) as t:\n\t\t\treturn_value = tp.activate()\n\t\tassert return_value is None\n\nif __name__ == '__main__':\n\tunittest.main()\n","sub_path":"ui/tests/test_time_picker.py","file_name":"test_time_picker.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"628655637","text":"import re\r\nfile=input(\"Enter the file name: \")\r\ntry:\r\n fh=open(file)\r\nexcept:\r\n print(\"Invalid File name:\",file)\r\n quit()\r\nnumlist=list()\r\nfor line in fh:\r\n line=line.strip()\r\n splitspace=line.split()\r\n if len(splitspace)<1: #Removing Blank Lines\r\n continue\r\n for item in splitspace:\r\n numbers=re.findall('[0-9]+',item) \r\n if item==\"http://www.py4e.com/code3/\":\r\n num1=item.split('/')\r\n for item2 in num1:\r\n numbers2=re.findall('[0-9]+',item2)\r\n #numlist.append(numbers2) #Creates list within list, since the re has already o/ps list\r\n numlist=numlist+numbers2 #to avoid list within list, also doesn't adds blank values.\r\n elif len(numbers)!=0:\r\n #numlist.append(numbers)\r\n numlist=numlist+numbers\r\n\r\n \r\nprint(numlist,'\\n')\r\nintlist=list()\r\nfor stringitem in numlist:\r\n intitem=int(stringitem) #Converting the list items in the string format to integer format\r\n intlist.append(intitem)\r\nprint(\"The number of items in the list is: \",len(intlist))\r\nprint('\\nThe total of the number of the items in the list is: ',sum(intlist))","sub_path":"asample_11.py","file_name":"asample_11.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"131448187","text":"import cv2\nimport numpy as np\n\nfrom helpers import *\n\nimg = cv2.imread('data/stone1.jpg', cv2.IMREAD_COLOR)\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ngray = np.float32(gray)\ndst = cv2.cornerHarris(gray, 2, 1, 0.04)\n# result is dilated for marking the corners, not important\ndst = cv2.dilate(dst, None)\n# Threshold for an optimal value, it may vary depending on the image.\nimg[dst > 0.01 * dst.max()] = [0, 0, 255]\n\ncv2.imshow('edge', img)\ncv2.waitKey(0)\n","sub_path":"src/CornerHarris.py","file_name":"CornerHarris.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"398672700","text":"# function for reshaping two categorical columns\n# to create a matrix for heatmap\ndef category_matrix(dataframe, col1, col2):\n ''' Takes two categorical columns and regroup them and return dict of dicts\n Input: dataframe, header_string1, header_string2\n Output: Nested Dictionary >>> {col1_val1: {col2_val1: num_intersect}, ..., col1_valX : {col2_valX: num_intersect}}\n '''\n # get list of unique values from provided columns\n val_list1 = dataframe[col1].unique()\n val_list2 = dataframe[col2].unique()\n\n # create condition dict for first column\n condition = {}\n for i, val1 in enumerate(val_list1):\n condition[i] = (dataframe[col1] == val1)\n\n reshaped_dataframe = {} # empty dict for storing reshaped dataframe\n\n for i, val1 in enumerate(val_list1):\n # get unique intersection of val2 for each val 1 in dataframe\n val2_per_val1 = dataframe.loc[condition[i]][col2].unique()\n reshaped_dataframe[val1] = {}\n for j, val2 in enumerate(val2_per_val1):\n try:\n reshaped_dataframe[val1][val2] = (\n dataframe.loc[condition[i]][col2] == val2).value_counts()[1]\n except KeyError:\n reshaped_dataframe[val1][val2] = 0\n return reshaped_dataframe\n","sub_path":"helpers/category_matrix.py","file_name":"category_matrix.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"557743528","text":"from jinja2 import Template\nfrom markdown import markdown\nimport json\nfrom os import path, makedirs\n\n\nTEMPLATES_DIR = 'templates'\nOUTPUT_DIR = 'output'\n\n\ndef load_config(filepath):\n with open(filepath, 'r') as config:\n return json.load(config)\n\n\ndef create_dir(directory):\n if not path.exists(directory):\n makedirs(directory)\n\n\ndef get_index_page(config):\n template = get_template('index.html')\n for article in config['articles']:\n article['article_url'] = get_article_url(article['source'])\n output_filepath = '{0}/{1}'.format(OUTPUT_DIR, 'index.html')\n render_page(config, output_filepath, template)\n\n\ndef get_article_page(config):\n template = get_template('article.html')\n for article in config['articles']:\n article_info = {'title': article['title'],\n 'text': convert_md_to_html(article['source']),\n }\n filepath = path.dirname(article['source'])\n article_url = get_article_url(article['source'])\n create_dir('{0}/{1}'.format(OUTPUT_DIR, filepath))\n render_page(article_info, '{0}/{1}'.format(OUTPUT_DIR, article_url), template)\n\n\ndef get_article_url(source):\n source = replace_spesial_symbols(source)\n output_source = '{0}.{1}'.format(source, 'html')\n return output_source\n\n\ndef replace_spesial_symbols(source):\n symbols = ['&', '<', '>', ' ']\n source = path.splitext(source)[0]\n for symbol in symbols:\n if symbol in source:\n source = source.replace(symbol, '_')\n return source\n\ndef get_template(template_name):\n template_filepath = '{0}/{1}'.format(TEMPLATES_DIR, template_name)\n pattern = open(template_filepath).read()\n template = Template(pattern)\n return template\n\n\ndef render_page(data, filepath, template):\n with open(filepath, 'w', encoding='utf-8') as file:\n file.write(template.render(info=data))\n\n\ndef convert_md_to_html(filepath):\n filepath = '{0}/{1}'.format('articles', filepath)\n with open(filepath, 'r', encoding='utf-8') as data:\n return markdown(data.read(), extensions=['codehilite', 'fenced_code'])\n\n\nif __name__ == '__main__':\n config = load_config('config.json')\n create_dir(OUTPUT_DIR)\n get_index_page(config)\n get_article_page(config)\n","sub_path":"site_generator.py","file_name":"site_generator.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"29469397","text":"import math\nimport operator\nimport pygame\nimport random\n\ndef distance(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n dx = x1 - x2\n dy = y1 - y2\n return math.sqrt(dx * dx + dy * dy)\n\ndef is_exit_event(event):\n if event.type == pygame.QUIT:\n return True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n return True\n elif event.key == pygame.K_F4 and event.mod & pygame.KMOD_ALT:\n return True\n return False\n\ndef ab(attr, rect, inside):\n \"\"\"\n Find the a, b arguments for random.\n \"\"\"\n assert attr in 'wh' or attr in ['width', 'height']\n\n if attr.startswith('w'):\n attr = 'right'\n other = 'x'\n else:\n attr = 'bottom'\n other = 'y'\n\n a = getattr(inside, other)\n b = getattr(inside, attr) - getattr(rect, attr)\n\n return (a, b)\n\ndef randomize(rect, inside, nocollide):\n \"\"\"\n Randomly place rect inside another, until it doesn't collide.\n :param rect: rect to place\n :param inside: container\n :param nocollide: list of rect to avoid\n \"\"\"\n a, b = ab('width', rect, inside)\n c, d = ab('height', rect, inside)\n while True:\n rect.x = random.randint(a, b)\n rect.y = random.randint(c, d)\n if rect.collidelist(nocollide) == -1:\n break\n\npointsgetter = operator.attrgetter('topleft', 'topright', 'bottomright', 'bottomleft')\n\ndef rect2points(rect):\n for point in pointsgetter(rect):\n yield point\n\ndef calculate_direction(origin, target):\n \"\"\"\n :param origin: position calculate from\n :param target: position calculate to\n \"\"\"\n cx, cy = origin\n sx, sy = target\n\n cy = -cy\n sy = -sy\n\n theta_radians = math.atan2(sy - cy, sx - cx)\n\n return theta_radians\n\ndirection = calculate_direction\n\ndef rect_sweep_polygon(origin, destination):\n # ( (x1, y1), (x2, y2) )\n l1 = (origin.topleft, destination.topleft)\n l2 = (origin.bottomright, destination.bottomright)\n\n return (l1, l2)\n\ndef make_explosion_from_rect(rect, time_to_live):\n pixels = [ (x, y) for x in xrange(rect.left, rect.right)\n for y in xrange(rect.top, rect.bottom) ]\n centers = random.sample(pixels, 100)\n for center in centers:\n for spark in make_explosion(center, time_to_live, 1):\n yield spark\n\n# want only upwardly flying sparks\n# remember coordinates are upside down\nANGLES = range(225, 315)\n\nFORCES = [n/1000000.0 for n in range(500, 750)]\n\nfrom .sprites.spark import VerletSpark as Spark\n\ndef make_explosion(center, time_to_live, n=10):\n for _ in xrange(n):\n angle = math.radians(random.choice(ANGLES))\n force = random.choice(FORCES)\n velocity = (0.0, 0.0)\n acceleration = (math.cos(angle) * force, math.sin(angle) * force)\n spark = Spark(center, velocity, acceleration, time_to_live)\n yield spark\n","sub_path":"01-dodger/dodger1/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"45256527","text":"\"\"\"\nAdd Two Numbers II\nYou are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\nFollow up:\nWhat if you cannot modify the input lists? In other words, reversing the lists is not allowed.\n\nExample:\n\nInput: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)\nOutput: 7 -> 8 -> 0 -> 7\n\"\"\"\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n # Solution 1 - 68 ms\n \"\"\"\n st1, st2 = [], []\n while l1:\n st1.append(l1.val)\n l1 = l1.next\n\n while l2:\n st2.append(l2.val)\n l2 = l2.next\n\n carry, head = 0, None\n\n while st1 or st2 or carry:\n d1, d2 = 0, 0\n d1 = st1.pop() if st1 else 0\n d2 = st2.pop() if st2 else 0\n carry, digit = divmod(d1 + d2 + carry, 10)\n head_new = ListNode(digit)\n head_new.next = head\n head = head_new\n\n return head\n \"\"\"\n # Solution 2 - 48 ms\n a = 0\n b = 0\n head1, head2 = l1, l2\n while head1:\n a = a * 10 + head1.val\n head1 = head1.next\n while head2:\n b = b * 10 + head2.val\n head2 = head2.next\n res = a + b\n new_head = None\n if res == 0:\n node = ListNode(0)\n node.next = new_head\n new_head = node\n return new_head\n while res:\n val = res % 10\n res = res // 10\n node = ListNode(val)\n node.next = new_head\n new_head = node\n return new_head\n\n def printList(self, node):\n temp = node\n while (temp):\n print(temp.val)\n temp = temp.next\n\n\n# Main Call\nnode = ListNode(7)\nnode.next = ListNode(2)\nnode.next.next = ListNode(4)\nnode.next.next.next = ListNode(3)\n\nnode_2 = ListNode(5)\nnode_2.next = ListNode(6)\nnode_2.next.next = ListNode(4)\n\nsolution = Solution()\nsum_node = solution.addTwoNumbers(node, node_2)\nsolution.printList(sum_node)\n","sub_path":"src/linkedLists/addTwoNumbers.py","file_name":"addTwoNumbers.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"453239213","text":"import pandas as pd\nimport numpy as np\nimport re\nimport json\nfrom sklearn.linear_model import LinearRegression\n\ndf = pd.read_csv('/Users/keinobaird/Desktop/labspt15-cityspire-g-ds/notebooks/data/population2010-2019/metropop_2010_2019.csv')\n\ndef explode_str(df, col='Metro-Area', sep='-'):\n s = df[col]\n i = np.arange(len(s)).repeat(s.str.count(sep) +1)\n return df.iloc[i].assign(**{col: sep.join(s).split(sep)})\n\nnew_df = explode_str(df)\n\ndef metro_lists_gen(new_df):\n new_df.rename(columns={\"Metro-Area\": 'metro_area'}, inplace=True)\n new_df['metro_area'] = new_df['metro_area'].apply(lambda row: row.lower())\n lists = new_df['metro_area'].unique().tolist()\n with open('metro_list.json', 'w', encoding='utf-8') as f:\n json.dump(lists, f, ensure_ascii=False, indent=4)\n return lists, new_df\n\n\ndef selecting_metro(df, metro):\n df = df.loc[df['metro_area'] == metro]\n df.drop(['metro_area', 'State', 'Census', 'Estimate Base'], axis=1, inplace=True)\n df = df.T\n df.dropna(inplace=True)\n df = df.reset_index()\n return df\n\ndef prediction_model(df):\n x = df.iloc[:, 0].values.reshape(-1, 1)\n y = df.iloc[:, 1].values.reshape(-1, 1)\n model = LinearRegression().fit(x,y)\n return model\n\ndef prediction(model, year):\n return int(model.coef_[0][0] * year + model.intercept_[0])\n\ndef main():\n metro = input('Please input the metro area: ').lower()\n year = int(input('Pleae enter the year to predict: '))\n df = new_df\n lists, df = metro_lists_gen(df)\n if metro in lists:\n df = selecting_metro(df, metro)\n model = prediction_model(df)\n result = prediction(model, year)\n print(f'\\n Result: {metro.upper()} population in {year} will be {result:,d}')\n else:\n print(\"Kindly check available metro anmes and spelling from metro_list.json\")\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"notebooks/datasets/data/population2010-2019/population_prediction.py","file_name":"population_prediction.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"297081615","text":"############### import module ###############\nimport pygame\nimport os\nfrom math import floor\n\n############### import my module ###############\nimport function_main as func\n\n############### class player ###############\nclass Player(object):\n \n def __init__(self,x,y,width,height,velocity,stand_right_path,stand_left_path,move_right_path,move_left_path,dash_right_path,dash_left_path,dead_down_path,dash_gauge_path):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.velocity = velocity\n self.hitbox = (self.x,self.y,self.x+self.width,self.y+self.height)\n self.is_jumping = False\n self.jump_power = func.CHARACTER_JUMP\n self.status = 'STAND'\n self.facing = 'RIGHT'\n self.is_dead = False\n self.image = ''\n self.dash_gauge = 0\n\n self.health = 30 \n self.median = (self.x+self.width/2,self.y+self.height/2)\n \n self.stand_right_path = stand_right_path\n self.stand_right_list = os.listdir(self.stand_right_path)\n self.stand_right_index = 0\n \n self.stand_left_path = stand_left_path\n self.stand_left_list = os.listdir(self.stand_left_path)\n self.stand_left_index = 0\n\n self.move_right_path = move_right_path\n self.move_right_list = os.listdir(self.move_right_path)\n self.move_right_index = 0\n\n self.move_left_path = move_left_path\n self.move_left_list = os.listdir(self.move_left_path)\n self.move_left_index = 0\n\n self.dash_right_path = dash_right_path\n self.dash_right_list = os.listdir(self.dash_right_path)\n self.dash_right_index = 0\n\n self.dash_left_path = dash_left_path\n self.dash_left_list = os.listdir(self.dash_left_path)\n self.dash_left_index = 0\n\n self.dead_down_path = dead_down_path\n self.dead_down_list = os.listdir(self.dead_down_path)\n self.dead_down_index = 0\n\n self.dash_gauge_path = dash_gauge_path\n self.dash_gauge_list = os.listdir(self.dash_gauge_path)\n\n def key_continuous_input(self,screen):\n pygame.event.pump() # initialize key press\n keys = pygame.key.get_pressed() # key press\n\n if 1 not in keys:\n self.status = 'STAND'\n\n if keys[pygame.K_RIGHT]:\n self.facing = 'RIGHT'\n self.status = 'MOVE'\n self.dash_gauge += 1\n self.x += self.velocity\n\n if keys[pygame.K_LEFT]:\n self.facing = 'LEFT'\n self.status = 'MOVE'\n self.dash_gauge += 1\n self.x -= self.velocity\n \n if keys[pygame.K_RIGHT] and keys[pygame.K_a] and self.dash_gauge >= 260:\n self.facing = 'RIGHT'\n self.status = 'DASH'\n self.dash_gauge = 0\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[0])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 10\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[1])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 5\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[2])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 2.5\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[3])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 1.25\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[4])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 0.625\n for i in range(10):\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[5])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x += 0.3125\n \n if keys[pygame.K_LEFT] and keys[pygame.K_a] and self.dash_gauge >= 260:\n self.facing = 'LEFT'\n self.status = 'DASH'\n self.dash_gauge = 0\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[0])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 10\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[1])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 5\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[2])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 2.5\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[3])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 1.25\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[4])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 0.625\n for i in range(10):\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[5])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.x -= 0.3125\n \n if keys[pygame.K_RIGHT] and keys[pygame.K_s]:\n self.facing = 'RIGHT'\n self.status = 'ATTACK'\n\n if keys[pygame.K_LEFT] and keys[pygame.K_s]:\n self.facing = 'LEFT'\n self.status = 'ATTACK'\n\n if not self.is_jumping:\n if keys[pygame.K_UP]:\n self.is_jumping = True\n else:\n if self.jump_power >= -1*func.CHARACTER_JUMP:\n neg = 1\n if self.jump_power < 0:\n neg = -1\n \n self.y -= (self.jump_power ** 2) * 0.5 * neg \n self.jump_power -= 1\n \n else:\n self.is_jumping = False\n\n self.jump_power = func.CHARACTER_JUMP\n\n def character_district(self):\n if self.x < 0: self.x = 0\n if self.x > func.WINDOW_WIDTH - self.width : self.x = func.WINDOW_WIDTH - self.width\n \n def hit(self,other):\n self.hitbox = (self.x,self.y,self.x+self.width,self.y+self.height) # declare more for initialize player's hitbox\n if (other.median[0] < self.hitbox[2]) and (other.median[0] > self.hitbox[0]) and (other.median[1] < self.hitbox[3]) and (other.median[1] > self.hitbox[1]) and self.status != 'DASH': # if monster's median touches player's hitbox\n self.health -= 1\n\n if self.health >= 30:\n self.image = pygame.image.load('./image/healthbar/RedHP3.png')\n self.image = pygame.transform.scale(self.image,(200,20))\n func.screen.blit(self.image,(self.x+80, self.y+30))\n elif self.health >= 20 and self.health < 30:\n self.image = pygame.image.load('./image/healthbar/RedHP2.png')\n self.image = pygame.transform.scale(self.image,(200,20))\n func.screen.blit(self.image,(self.x+80, self.y+30)) \n elif self.health > 0:\n self.image = pygame.image.load('./image/healthbar/RedHP1.png')\n self.image = pygame.transform.scale(self.image,(200,20)) \n func.screen.blit(self.image,(self.x+80, self.y+30)) \n\n return True if self.health == 0 else False\n\n def draw_components(self,screen):\n \n if not self.is_dead:\n if self.status == 'STAND' and self.facing == 'RIGHT':\n self.stand_right(screen)\n if self.status == 'STAND' and self.facing == 'LEFT':\n self.stand_left(screen)\n if self.status == 'MOVE' and self.facing == 'RIGHT':\n self.move_right(screen)\n if self.status == 'MOVE' and self.facing == 'LEFT':\n self.move_left(screen)\n '''\n if self.status == 'DASH' and self.facing == 'RIGHT':\n self.dash_right(screen)\n if self.status == 'DASH' and self.facing == 'LEFT':\n self.dash_left(screen)\n '''\n\n if self.dash_gauge < 20:\n self.draw_dash_gauge(screen,0)\n elif self.dash_gauge < 40:\n self.draw_dash_gauge(screen,1)\n elif self.dash_gauge < 60:\n self.draw_dash_gauge(screen,2)\n elif self.dash_gauge < 80:\n self.draw_dash_gauge(screen,3)\n elif self.dash_gauge < 100:\n self.draw_dash_gauge(screen,4)\n elif self.dash_gauge < 120:\n self.draw_dash_gauge(screen,5)\n elif self.dash_gauge < 140:\n self.draw_dash_gauge(screen,6)\n elif self.dash_gauge < 160:\n self.draw_dash_gauge(screen,7)\n elif self.dash_gauge < 180:\n self.draw_dash_gauge(screen,8)\n elif self.dash_gauge < 200:\n self.draw_dash_gauge(screen,9)\n elif self.dash_gauge < 220:\n self.draw_dash_gauge(screen,10)\n elif self.dash_gauge < 240:\n self.draw_dash_gauge(screen,11)\n else:\n self.draw_dash_gauge(screen,12)\n \n def draw_dash_gauge(self,screen,index):\n self.image = pygame.image.load(self.dash_gauge_path+'/'+self.dash_gauge_list[index])\n self.image = pygame.transform.scale(self.image,(250,50))\n screen.blit(self.image,(func.WINDOW_WIDTH-290,30))\n\n def stand_right(self,screen):\n self.stand_right_list = os.listdir(self.stand_right_path)\n self.image = pygame.image.load(self.stand_right_path+'/'+self.stand_right_list[floor(self.stand_right_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.stand_right_index += 0.05\n if self.stand_right_index >= len(self.stand_right_list)-1: self.stand_right_index = 0\n\n def stand_left(self,screen):\n self.stand_left_list = os.listdir(self.stand_left_path)\n self.image = pygame.image.load(self.stand_left_path+'/'+self.stand_left_list[floor(self.stand_left_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.stand_left_index += 0.05\n if self.stand_left_index >= len(self.stand_left_list)-1: self.stand_left_index = 0\n \n def move_right(self,screen):\n self.move_right_list = os.listdir(self.move_right_path)\n self.image = pygame.image.load(self.move_right_path+'/'+self.move_right_list[floor(self.move_right_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.move_right_index += 0.1\n if self.move_right_index >= len(self.move_right_list)-1: self.move_right_index = 0\n \n def move_left(self,screen):\n self.move_left_list = os.listdir(self.move_left_path)\n self.image = pygame.image.load(self.move_left_path+'/'+self.move_left_list[floor(self.move_left_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.move_left_index += 0.1\n if self.move_left_index >= len(self.move_left_list)-1: self.move_left_index = 0\n '''\n def dash_right(self,screen):\n self.dash_right_list = os.listdir(self.dash_right_path)\n self.image = pygame.image.load(self.dash_right_path+'/'+self.dash_right_list[floor(self.dash_right_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.dash_right_index += 0.01\n if self.dash_right_index >= len(self.dash_right_list)-1: self.dash_right_index = 0\n \n def dash_left(self,screen):\n self.dash_left_list = os.listdir(self.dash_left_path)\n self.image = pygame.image.load(self.dash_left_path+'/'+self.dash_left_list[floor(self.dash_left_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n self.dash_left_index += 0.01\n if self.dash_left_index >= len(self.dash_left_list)-1: self.dash_left_index = 0\n '''\n def dead_down(self,screen):\n self.dead_down_list = os.listdir(self.dead_down_path)\n self.image = pygame.image.load(self.dead_down_path+'/'+self.dead_down_list[floor(self.dead_down_index)])\n self.image = pygame.transform.scale(self.image,(self.width,self.height))\n screen.blit(self.image,(self.x,self.y))\n if self.dead_down_index < len(self.dead_down_list)-0.1:\n self.dead_down_index += 0.1\n \n \n","sub_path":"class_player.py","file_name":"class_player.py","file_ext":"py","file_size_in_byte":14117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"20542844","text":"#!/usr/bin/env python3.7\n\nfrom openpyxl import load_workbook\n\nworkbook = load_workbook(filename=\"sample.xlsx\")\nsheet = workbook.active\n\nfor value in sheet.iter_rows(min_row=1,\n max_row=2,\n min_col=1,\n max_col=3,\n values_only=False):\n print(value)\n\n","sub_path":"openpyxl/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"341889014","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n path ('register',views.register,name = \"register\"),# when user wants to signup\n path ('report',views.report,name = \"report\"),# showing report page\n path('result',views.result, name=\"result\"),# when submit button is clicked\n url(r'find',views.find,name=\"find\"),#when submit to doctor button is clicked\n path('home',views.home,name=\"home\"),#main page where info is entered\n path('signup',views.signup,name=\"signup\"),# when signup is clicked\n path('login',views.login,name=\"login\"),# when login is clicked\n path('searching',views.searching,name=\"searching\"),\n path('enter',views.enter,name=\"enter\"),#starting page showing login\n path('submit',views.submit,name=\"submit\"),\n path('logout',views.logout,name=\"logout\"),\n path('',views.welcome,name=\"welcome\"),\n \n]\n","sub_path":"pred/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"142199231","text":"#!/usr/bin/python\nimport sys\nimport re\nfrom seq import Sequence\nfrom seq import ResidueError\n\nclass AlignedSequence(Sequence):\n\tdef __init__(self, fn1=None, ssq1=None):\n\t\tsuper().__init__(fn1, ssq1)\n\t\tif not self.is_dna():\n\t\t\tself.is_protein()\n\tdef __getitem__(self,i):\n\t\treturn self.seq_[i]\n\tdef is_gap(self,pos):\n\t\treturn self.seq_[pos]==\"-\"\n\tdef is_dna(self):\n\t\tnot re.search(r\"[^ATGC-]\",self.seq_)\n\tdef is_protein(self):\n\t\tif self.is_dna():\n\t\t\treturn False\n\t\telse:\n\t\t\tfor i in self.seq_:\n\t\t\t\tif i not in ['G','A','V','L','I','P','F','Y','W','S','T','C','M','N','Q','K','R','H','D','E','-','X','Z','B']: #'X' a feature where the identity of the amino acid is unknown (an X is shown at this position in the sequence) and the only information concerning the modification is that the N-terminus is blocked: P80979 (Blocked amino end (Xaa))\n#Note: Pyro-Glu is often indicated in papers as ‘pGlu’ and sometimes, in one-letter code as “U”, although this is now used for selenocysteine. In figures of publications, it may be cited as Z, pQ or E\n\t\t\t\t\traise ResidueError(\"Residue '%s' cannot be identified as either a nucleotide or amino acid for sequence %s.\"%(i, self.name_))\n\t\t\treturn True \n\t#Given aligned position returns the actual sequece position \n\tdef aligned_to_sequence_position(self, apos):\n\t\tspos=0\n\t\ti=0\n\t\twhile i < apos:\n\t\t\tif self.seq_[i] != \"-\":\n\t\t\t\tspos=spos+1\n\t\t\ti=i+1\n\t\treturn spos\n\t#Given actual sequence position returns the aligned position\n\tdef sequence_to_aligned_position(self,spos):\n\t\tapos=0\n\t\ti=0\n\t\twhile spos > 0:\n\t\t\tif not self.is_gap(i):\n\t\t\t\tapos = apos+1\n\t\t\t\tspos=spos-1\n\t\t\t\ti=i+1\n\t\t\telse:\n\t\t\t\tapos= apos+1\n\t\t\t\ti=i+1\n\t\treturn apos\n","sub_path":"src/alignedseq.py","file_name":"alignedseq.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"274924978","text":"def get_eig_Jacobian(pars, fp):\n \"\"\"\n Simulate the Wilson-Cowan equations \n \n Args:\n pars : Parameter dictionary\n fp : fixed point (E, I), array\n \n Returns:\n evals : 2x1 vector of eigenvalues of the Jacobian matrix\n \"\"\"\n \n #get the parameters\n tau_E, a_E, theta_E = pars['tau_E'], pars['a_E'], pars['theta_E']\n tau_I, a_I, theta_I = pars['tau_I'], pars['a_I'], pars['theta_I']\n wEE, wEI = pars['wEE'], pars['wEI'] \n wIE, wII = pars['wIE'], pars['wII']\n I_ext_E, I_ext_I = pars['I_ext_E'], pars['I_ext_I']\n\n #initialization\n E = fp[0]\n I = fp[1]\n J = np.zeros((2,2))\n \n #Jacobian matrix\n J[0,0] = (-1 + wEE*dF(wEE*E-wEI*I+I_ext_E,a_E,theta_E))/tau_E #dGE_dE\n J[0,1] = (-wEI*dF(wEE*E-wEI*I+I_ext_E,a_E,theta_E))/tau_E #dGE_dI\n J[1,0] = (wIE*dF(wIE*E-wII*I+I_ext_I,a_I,theta_I))/tau_I #dGI_dE\n J[1,1] = (-1 - wII*dF(wIE*E-wII*I,a_I+I_ext_I,theta_I))/tau_I #dGI_dI \n \n # Eigenvalues\n evals = np.linalg.eig(J)[0]\n \n return evals\n\neig_1 = get_eig_Jacobian(pars, x_fp_1)\neig_2 = get_eig_Jacobian(pars, x_fp_2)\neig_3 = get_eig_Jacobian(pars, x_fp_3)\nprint(eig_1, 'Stable point')\nprint(eig_2, 'Unstable point')\nprint(eig_3, 'Stable point')","sub_path":"tutorials/W3D2_DynamicNetworks/solutions/W3D2_Tutorial2_Solution_0349af2c.py","file_name":"W3D2_Tutorial2_Solution_0349af2c.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"94880513","text":"# Log analyzer script using pandas\nimport pandas as pd\nimport os, logging, sys, re, argparse, json\n\nconfig = {\n \"REPORT_SIZE\": 1000,\n \"REPORT_DIR\": \"./reports\",\n \"LOG_DIR\": \"./log\"\n}\nnames = ['remote_addr', 'remote_user', 'empty_1', 'http_x_real_ip', 'time_local', 'timezone', 'request', 'status', 'body_bytes_sent',\n 'http_referer', \"http_user_agent\", \"http_x_forwarded_for\", \"http_X_REQUEST_ID\", \"http_X_RB_USER\", 'request_time']\nres_names = ['url', 'count', 'count_perc', 'time_sum', 'time_perc', 'time_avg', 'time_max', 'time_med']\n\ndef get_log_file_name(log_dir=config['LOG_DIR']):\n log_files = {re.findall('nginx-access-ui.log-([^\\.]+)', f)[0]: f for f in os.listdir('.'+log_dir) if re.match(r'nginx-access-ui.log-', f)}\n return log_files[max(log_files, key=int)]\n\ndef parse_command_line_arguments(config):\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--config', type=argparse.FileType('r'),\n help='Configuration json file'\n )\n args = parser.parse_args()\n defaults = config\n if args.config:\n try:\n defaults = json.load(args.config)\n except ValueError:\n print('Error: Could not parse config file', sys.stderr.write())\n finally:\n args.config.close()\n return defaults\n\ndef read_log_name(config):\n actual_log_file_name, actual_date = get_log_file_name(), re.findall('log-([^\\.]+)', get_log_file_name())[0]\n report_file = '.' + config['REPORT_DIR'] + '/report-' + actual_date[:4] + '.' + actual_date[4:6] + '.' + actual_date[6:] + '.html'\n print('Last actual log date is ' + actual_date + ', loading...')\n return actual_log_file_name, actual_date, report_file\n\ndef load_log(actual_log_file_name, names, config):\n return pd.read_table('.' + config['LOG_DIR'] + '/' + actual_log_file_name, sep=' ', names=names, index_col=False)\n\ndef process_log(actual_log_file_name, actual_date, report_file, df, res_names):\n print('Processing report for ' + actual_date + '...')\n url_regexp = '([^\\s]+)\\sHTTP'\n df['url'] = df['request'].str.extract(url_regexp, expand=False)\n res = df.groupby(['url']).agg({'request_time':['count', 'sum', 'mean', 'max', 'median']}).reset_index()\n res.columns = res.columns.droplevel(0)\n res['time_perc'], res['count_perc'] = 100 * res['sum'] / res['sum'].sum(), 100 * res['count'] / res['count'].sum()\n res.columns = ['url', 'count', 'time_sum', 'time_avg', 'time_max', 'time_med', 'time_perc', 'count_perc']\n return res[res_names].sort_values('time_sum', ascending=False).reset_index(drop=True)\n\ndef write_report(res, report_file, actual_date):\n path = os.path.dirname(report_file)\n if not os.path.exists(path):\n try:\n os.makedirs(path)\n except OSError:\n print (\"Creation of the directory %s failed\" % path)\n else:\n print (\"Successfully created the directory %s \" % path)\n pd.set_option('display.max_columns', None)\n pd.set_option('display.max_colwidth',100)\n pd.set_option('display.float_format', lambda x: '%.3f' % x)\n res.to_html(report_file, index=False)\n print('Report done for ' + actual_date)\n\ndef main():\n # Reading config\n actual_config = parse_command_line_arguments(config)\n\n # Reading log\n actual_log_file_name, actual_date, report_file = read_log_name(config=actual_config)\n\n # Check_if_report_exists\n if os.path.isfile(report_file):\n print('!!! Last actual date report file already exists !!!')\n sys.exit()\n\n # Loading log file\n df = load_log(actual_log_file_name, names, config=actual_config)\n\n # Processing log\n res = process_log(actual_log_file_name, actual_date, report_file, df, res_names)\n\n # Writing html report\n write_report(res, report_file, actual_date)\n\n# main\nif __name__ == \"__main__\":\n main()\n","sub_path":"01_advanced_basics/log_analyzer/src/log_analyzer_pandas.py","file_name":"log_analyzer_pandas.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"151908308","text":"import abc\nfrom collections import OrderedDict, deque\nimport time\n\nimport gtimer as gt\nfrom tqdm import trange\nimport numpy as np\nimport torch\n\nfrom utils.logging import logger\nimport utils.pytorch_util as ptu\nimport ray\n\n\nclass BatchMetaRLAlgorithm(metaclass=abc.ABCMeta):\n def __init__(\n self,\n trainer,\n path_collector,\n train_buffer,\n train_goals,\n wd_goals,\n ood_goals,\n num_epochs,\n num_train_loops_per_epoch,\n num_tasks,\n num_workers,\n ):\n super().__init__()\n\n self.train_buffer = train_buffer\n self.num_epochs = num_epochs\n self.num_train_loops_per_epoch = num_train_loops_per_epoch\n self.path_collector = path_collector\n self.num_tasks = num_tasks\n self.num_workers = num_workers\n self.train_goals = [goal for goal in train_goals]\n self.wd_goals = [goal for goal in wd_goals]\n self.ood_goals = [goal for goal in ood_goals]\n\n self.trainer = trainer\n\n self.avg_train_episode_returns = []\n self.final_train_achieved = []\n self.train_avg_returns = 0.\n\n self.avg_wd_episode_returns = []\n self.final_wd_achieved = []\n self.wd_avg_returns = 0.\n\n self.avg_ood_episode_returns = []\n self.final_ood_achieved = []\n self.ood_avg_returns = 0.\n\n self._start_epoch = 0\n\n def train(self, start_epoch=0):\n self._start_epoch = start_epoch\n self._train()\n\n def _train(self):\n\n batch_idxes = np.arange(self.num_tasks)\n\n gt.start()\n\n for epoch in gt.timed_for(\n trange(self._start_epoch, self.num_epochs),\n save_itrs=True,\n ): \n # Distribute the evaluation. We ship the \n # params of each needed network to the \n # remote path collector\n params_list = []\n for net in self.trainer.networks:\n params_list.append(ptu.state_dict_cpu(net))\n\n self.path_collector.set_network_params(params_list)\n\n gt.stamp('ship_params_to_evaluate', unique=False)\n\n evaluation_train_obj_id_list = []\n count = 0\n while count < len(self.train_goals) :\n if len(self.train_goals) - count < self.num_workers:\n evaluation_obj_id = self.path_collector.async_evaluate(self.train_goals[count:])\n count = len(self.train_goals)\n else:\n evaluation_obj_id = self.path_collector.async_evaluate(self.train_goals[count:count + self.num_workers])\n count += self.num_workers\n evaluation_train_obj_id_list.extend(evaluation_obj_id)\n\n assert len(evaluation_train_obj_id_list) == len(self.train_goals)\n\n evaluation_wd_obj_id_list = []\n count = 0\n while count < len(self.wd_goals) :\n if len(self.wd_goals) - count < self.num_workers:\n evaluation_obj_id = self.path_collector.async_evaluate(self.wd_goals[count:])\n count = len(self.wd_goals)\n else:\n evaluation_obj_id = self.path_collector.async_evaluate(self.wd_goals[count:count + self.num_workers])\n count += self.num_workers\n evaluation_wd_obj_id_list.extend(evaluation_obj_id)\n\n assert len(evaluation_wd_obj_id_list) == len(self.wd_goals)\n\n # evaluation_ood_obj_id_list = []\n # count = 0\n # while count < len(self.ood_goals) :\n # if len(self.ood_goals) - count < self.num_workers:\n # evaluation_obj_id = self.path_collector.async_evaluate(self.ood_goals[count:])\n # count = len(self.ood_goals)\n # else:\n # evaluation_obj_id = self.path_collector.async_evaluate(self.ood_goals[count:count + self.num_workers])\n # count += self.num_workers\n # evaluation_ood_obj_id_list.extend(evaluation_obj_id)\n\n # assert len(evaluation_ood_obj_id_list) == len(self.ood_goals)\n\n gt.stamp('set_up_evaluation', unique=False)\n\n # Sample meta training tasks. And transfer the\n # transitions sampling job to each remote replay buffer.\n train_batch_obj_id = self.train_buffer.sample_training_data(batch_idxes)\n\n for it in range(self.num_train_loops_per_epoch):\n train_raw_batch = ray.get(train_batch_obj_id)\n gt.stamp('sample_training_data', unique=False)\n\n # In this way, we can start the data sampling job for the\n # next training while doing training for the current loop.\n train_batch_obj_id = self.train_buffer.sample_training_data(batch_idxes)\n gt.stamp('set_up_sampling', unique=False)\n\n train_data = self.construct_training_batch(train_raw_batch)\n gt.stamp('construct_training_batch', unique=False)\n\n self.trainer.train(train_data, batch_idxes)\n\n if (it + 1) % 100 == 0:\n print(it)\n\n eval_train_returns = ray.get(evaluation_train_obj_id_list)\n\n self.avg_train_episode_returns = [item[0] for item in eval_train_returns]\n self.final_train_achieved = [item[1] for item in eval_train_returns]\n self.train_avg_returns = np.mean(self.avg_train_episode_returns)\n \n eval_wd_returns = ray.get(evaluation_wd_obj_id_list)\n\n self.avg_wd_episode_returns = [item[0] for item in eval_wd_returns]\n self.final_wd_achieved = [item[1] for item in eval_wd_returns]\n self.wd_avg_returns = np.mean(self.avg_wd_episode_returns)\n\n # eval_ood_returns = ray.get(evaluation_ood_obj_id_list)\n\n # self.avg_ood_episode_returns = [item[0] for item in eval_ood_returns]\n # self.final_ood_achieved = [item[1] for item in eval_ood_returns]\n # self.ood_avg_returns = np.mean(self.avg_ood_episode_returns)\n\n gt.stamp('evaluation', unique=False)\n\n self._end_epoch(epoch)\n\n def construct_training_batch(self, raw_batch):\n ''' Construct training batch from raw batch'''\n # obs = np.concatenate([rb[0] for rb in raw_batch], axis=0)\n # actions = np.concatenate([rb[2] for rb in raw_batch], axis=0)\n # contexts = np.concatenate([rb[4] for rb in raw_batch], axis=0)\n # rewards = np.concatenate([rb[3] for rb in raw_batch], axis=0)\n # next_obs = np.concatenate([rb[1] for rb in raw_batch], axis=0)\n\n obs = torch.cat(tuple(\n ptu.elem_or_tuple_to_variable(rb[0]) for rb in raw_batch\n ), dim=0)\n actions = torch.cat(tuple(\n ptu.elem_or_tuple_to_variable(rb[2]) for rb in raw_batch\n ), dim=0)\n\n # contexts: list of contexts from each tasks: \n # (num_candidate_context, num_trans_context, context_dim)\n contexts = [ptu.elem_or_tuple_to_variable(rb[4]) for rb in raw_batch]\n\n return {\n 'obs': obs,\n 'actions': actions,\n 'contexts': contexts,\n }\n \n def get_evaluation_diagnostics(self):\n eval = OrderedDict()\n\n eval['avg_train_episode_returns'] = self.avg_train_episode_returns\n eval['final_train_achieved'] = self.final_train_achieved\n eval['train_avg_returns'] = self.train_avg_returns\n\n eval['avg_wd_episode_returns'] = self.avg_wd_episode_returns\n eval['final_wd_achieved'] = self.final_wd_achieved\n eval['wd_avg_returns'] = self.wd_avg_returns\n\n eval['avg_ood_episode_returns'] = self.avg_ood_episode_returns\n eval['final_ood_achieved'] = self.final_ood_achieved\n eval['ood_avg_returns'] = self.ood_avg_returns\n return eval\n\n def _end_epoch(self, epoch):\n\n self._log_stats(epoch)\n if epoch > 0:\n snapshot = self._get_snapshot(epoch)\n logger.save_itr_params(epoch + 1, snapshot)\n gt.stamp('saving', unique=False)\n\n self.trainer.end_epoch(epoch)\n self.path_collector.end_epoch(epoch)\n self.train_buffer.end_epoch(epoch)\n\n logger.record_dict(_get_epoch_timings())\n logger.record_tabular('Epoch', epoch)\n\n write_header = True if epoch == 0 else False\n logger.dump_tabular(with_prefix=False, with_timestamp=False,\n write_header=write_header)\n\n def _get_snapshot(self, epoch):\n ''''\n Currently we do not need to get snapt shot\n '''\n snapshot = dict(\n trainer=self.trainer.get_snapshot(),\n )\n\n # What epoch indicates is that at the end of this epoch,\n # The state of the program is snapshot\n # Not to be confused with at the beginning of the epoch\n snapshot['epoch'] = epoch\n\n # Save the state of various rng\n snapshot['global_pkg_rng_state'] = get_global_pkg_rng_state()\n\n return snapshot\n\n def _log_stats(self, epoch):\n logger.log(\"Epoch {} finished\".format(epoch), with_timestamp=True)\n\n \"\"\"\n Trainer\n \"\"\"\n logger.record_dict(self.trainer.get_diagnostics(), prefix='trainer/')\n\n \"\"\"\n Evaluation\n \"\"\"\n logger.record_dict(self.get_evaluation_diagnostics(), prefix='eval/')\n \"\"\"\n Misc\n \"\"\"\n gt.stamp('logging')\n\n def to(self, device):\n for net in self.trainer.networks:\n net.to(device)\n\n\ndef _get_epoch_timings():\n times_itrs = gt.get_times().stamps.itrs\n times = OrderedDict()\n epoch_time = 0\n for key in sorted(times_itrs):\n time = times_itrs[key][-1]\n epoch_time += time\n times['time/{} (s)'.format(key)] = time\n times['time/epoch (s)'] = epoch_time\n times['time/total (s)'] = gt.get_times().total\n return times\n\ndef get_global_pkg_rng_state():\n\n rng = dict()\n\n rng['np_rng_state'] = np.random.get_state()\n rng['t_cpu_rng_state'] = torch.get_rng_state()\n\n if torch.cuda.is_available():\n rng['t_gpu_rng_state'] = torch.cuda.get_rng_state_all()\n\n return rng","sub_path":"no_transition_relabelling/rl_algorithm.py","file_name":"rl_algorithm.py","file_ext":"py","file_size_in_byte":10266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"198695723","text":"from subprocess import check_call, CalledProcessError\n\ndef findSolution(lpFile, solutionFile):\n '''\n Launch the command in windows shell to find the solution of the lp file\n\n :param lpFile: \n :param solutionFile:\n\n :type lpFile:\n :type solutionFile:\n\n :return solutionFile: the file of the solution\n '''\n try:\n check_call([\"glpsol\", \"--cpxlp\", lpFile , \"-o\", solutionFile])\n except CalledProcessError:\n print(\"\\n/!\\ Impossible de lancer la commande pour résoudre le fichier lp /!\\ \\n\")\n exit()\n \n return solutionFile\n\nif __name__ == \"__main__\":\n findSolution(\"test4\", \"soltion8\")","sub_path":"Other files/findSolution.py","file_name":"findSolution.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"604065791","text":"#!/usr/bin/env python3\n\nactual_date_raw = str(input()).split(\" \")\nexpected_date_raw = str(input()).split(\" \")\n\nexpected_date = {'day': int(expected_date_raw[0]), 'month': int(expected_date_raw[1]), 'year': int(expected_date_raw[2])}\nactual_date = {'day': int(actual_date_raw[0]), 'month': int(actual_date_raw[1]), 'year': int(actual_date_raw[2])}\n\nday_diff = actual_date['day'] - expected_date['day']\nmonth_diff = actual_date['month'] - expected_date['month']\nyear_diff = actual_date['year'] - expected_date['year']\n\nif year_diff >= 1:\n print(10000)\nelif year_diff < 0:\n print(0)\nelif month_diff >= 1:\n fine = 500 * month_diff\n print(fine)\nelif day_diff >= 1:\n fine = 15 * day_diff\n print(fine)\nelse:\n print(0)","sub_path":"30-days-of-code-hr-2/day-26/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"436044199","text":"\"\"\"Madgrad optimizer implementation.\"\"\"\nimport tensorflow as tf\n\n\n@tf.keras.utils.register_keras_serializable(package=\"MadGrad\", name=\"MadGrad\")\nclass MadGrad(tf.keras.optimizers.Optimizer):\n r\"\"\"Optimizer that implements the MADGRAD algorithm.\n Args:\n learning_rate: A Tensor or a floating point value. The learning rate.\n momentum: A float value or a constant float tensor. Accelerates in the\n direction of gradient descent and dampens oscillations\n weight_decay: A float value or a constant float tensor. Factor by which\n the weights are decayed\n epsilon: A small constant for numerical stability.\n name: Optional name for the operations created when applying gradients.\n Defaults to `\"Madgrad\"`.\n **kwargs: Keyword arguments. Allowed to be one of\n `\"clipnorm\"` or `\"clipvalue\"`.\n `\"clipnorm\"` (float) clips gradients by norm; `\"clipvalue\"` (float) clips\n gradients by value.\n Usage Example:\n # >>> opt = MadGrad(learning_rate=0.2)\n # >>> var1 = tf.Variable(10.0)\n # >>> loss = lambda: (var1 ** 2) / 2.0\n # >>> step_count = opt.minimize(loss, [var1]).numpy()\n # >>> \"{:.1f}\".format(var1.numpy())\n 9.3\n Reference:\n - [Aaron Defazio and Samy Jelassi, 2021](https://arxiv.org/abs/2101.11075).\n \"\"\"\n\n _HAS_AGGREGATE_GRAD = True\n\n def __init__(\n self,\n learning_rate=0.01,\n momentum=0.9,\n weight_decay=0,\n epsilon=1e-6,\n name=\"MadGrad\",\n **kwargs\n ):\n learning_rate = kwargs.get(\"lr\", learning_rate)\n super(MadGrad, self).__init__(name, **kwargs)\n self._set_hyper(\"learning_rate\", kwargs.get(\"lr\", learning_rate))\n self._set_hyper(\"decay\", self._initial_decay)\n self._set_hyper(\"momentum\", momentum)\n self._set_hyper(\"weight_decay\", weight_decay)\n self.epsilon = epsilon if epsilon is not None else tf.keras.backend.epsilon()\n self._first_step = True\n\n def _create_slots(self, var_list):\n for var in var_list:\n self.add_slot(var, \"vk\")\n for var in var_list:\n self.add_slot(var, \"sk\")\n for var in var_list:\n self.add_slot(var, \"x_0\")\n\n def _prepare_local(self, var_device, var_dtype, apply_state):\n momentum = tf.identity(self._get_hyper(\"momentum\", var_dtype))\n weight_decay = tf.identity(self._get_hyper(\"weight_decay\", var_dtype))\n\n apply_state[(var_device, var_dtype)] = dict(\n epsilon=tf.convert_to_tensor(self.epsilon, var_dtype),\n momentum=momentum,\n weight_decay=weight_decay,\n )\n\n def _resource_apply_dense(self, grad, var, apply_state=None):\n return var.assign(\n self._compute_update(self, grad, var, apply_state),\n use_locking=self._use_locking,\n ).op\n\n def _resource_apply_sparse(self, grad, var, apply_state, indices):\n return var.assign(\n self._compute_update(self, grad, var, apply_state, indices),\n use_locking=self._use_locking,\n ).op\n\n def _compute_update(self, grad, var, apply_state, indices=[]):\n var_device, var_dtype = var.device, var.dtype.base_dtype\n device_pair = (var_device, var_dtype)\n coefficients = (apply_state or {}).get(\n device_pair\n ) or self._fallback_apply_state(var_device, var_dtype)\n\n eps = coefficients[\"epsilon\"]\n rho = coefficients[\"momentum\"]\n vk = self.get_slot(var, \"vk\")\n sk = self.get_slot(var, \"sk\")\n x0 = self.get_slot(var, \"x_0\")\n\n lr_t = self._decayed_lr(var_dtype)\n i = tf.cast(self.iterations + 1, var_dtype)\n lbda = lr_t * tf.math.sqrt(i)\n damp = tf.cast(self._get_hyper(\"weight_decay\"), var_dtype)\n grad = tf.cond(\n tf.greater(damp, 0),\n lambda: grad + damp * var,\n lambda: grad,\n )\n if self._first_step:\n x0 = x0.assign(var, use_locking=self._use_locking)\n self._first_step = False\n\n sparse = tf.rank(indices) > 0\n s = tf.cond(\n sparse,\n lambda: self._resource_scatter_add(sk, indices, lbda * grad),\n lambda: sk.assign_add(lbda * grad, use_locking=self._use_locking),\n )\n nu = tf.cond(\n sparse,\n lambda: self._resource_scatter_add(vk, indices, lbda * grad ** 2),\n lambda: vk.assign_add(lbda * grad ** 2, use_locking=self._use_locking),\n )\n inv = tf.pow(nu, (1.0 / 3.0)) + eps\n inv_safe = tf.where(inv >= 0)\n inv_safe = tf.where(inv_safe, inv, tf.ones(inv))\n z = x0 - s / inv_safe\n x = (1 - rho) * var + (rho * z)\n return x\n\n def get_config(self):\n config = super(MadGrad, self).get_config()\n config.update(\n {\n \"learning_rate\": self._serialize_hyperparameter(\"learning_rate\"),\n \"momentum\": self._serialize_hyperparameter(\"momentum\"),\n \"weight_decay\": self._serialize_hyperparameter(\"weight_decay\"),\n \"epsilon\": self.epsilon,\n }\n )\n return config\n","sub_path":"madgrad/madgrad.py","file_name":"madgrad.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"377057030","text":"from unittest.mock import MagicMock\n\nfrom s3mesh.forwarder import MeshToS3Forwarder\n\n\ndef build_forwarder(**kwargs):\n mock_mesh_inbox = kwargs.get(\"mesh_inbox\", MagicMock())\n mock_s3_uploader = kwargs.get(\"s3_uploader\", MagicMock())\n mock_probe = kwargs.get(\"probe\", MagicMock())\n mock_mesh_inbox.read_messages.return_value = kwargs.get(\"incoming_messages\", [])\n mock_mesh_inbox.read_messages.side_effect = kwargs.get(\"read_error\", None)\n mock_mesh_inbox.count_messages.side_effect = kwargs.get(\"count_error\", None)\n mock_mesh_inbox.count_messages.return_value = kwargs.get(\"inbox_message_count\", 0)\n\n return MeshToS3Forwarder(mock_mesh_inbox, mock_s3_uploader, mock_probe)\n","sub_path":"tests/builders/forwarder.py","file_name":"forwarder.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"197641859","text":"# Author: Ivica Nikolic (cube444@gmail.com)\n\nimport argparse\nimport sys\nsys.path.append('./metaheuristics')\nfrom simulated_annealing import *\nfrom genetic_algorithm import *\n\n\n\n# Check dependencies\ntry:\n\timport gurobipy\nexcept:\n\tprint( 'The fitness function for SKINNY is implemented as ILP.\\nThe code uses Intels Gurobi to solve ILP, however, gurobipy library cannot be imported. \\nInstall Gurobi to proceed.\\nExiting...')\n\texit(1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--search\", help=\"Print debug info\", action='store')\n\nargs = parser.parse_args()\nif args.search:\n\n\tif int(args.search) == 1:\n\t\tsimmulated_annealing()\n\telif int(args.search) == 2:\n\t\tgenetic_algorithm()\n\telse:\n\t\tprint('Syntax: \\n\\tpython main.py --search METHOD\\nwhere \\nMETHOD=1 for simulated annealing, \\nMETHOD=2 for genetic algorithm')\t\t\t\n\nelse:\n\tprint('Syntax: \\n\\tpython main.py --search METHOD\\nwhere \\nMETHOD=1 for simulated annealing, \\nMETHOD=2 for genetic algorithm')\t\t\t\n\n","sub_path":"skinny/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"1547943","text":"\"\"\"Tests for user authentication in order to access my API\"\"\"\n\nAPI_PATH_NO_KEY = \"/api/v1/%s\"\nAPI_PATH_WITH_KEY = \"/api/v1/%s?api_key=not_the_right_key\"\nAPI_ENDPOINTS = ['states', 'executive', 'legislator', 'committee']\n\n\ndef test_api_key_is_required(client):\n for i in API_ENDPOINTS:\n res = client.get(API_PATH_NO_KEY % i)\n assert res.status_code == 401\n assert 'Submit an API Key' in res.data\n\n\ndef test_api_key_is_not_authorized(client):\n for i in API_ENDPOINTS:\n res = client.get(API_PATH_WITH_KEY % i)\n assert res.status_code == 401\n assert 'Not Authorized' in res.data\n","sub_path":"tests/test_api_key.py","file_name":"test_api_key.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"464393065","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom convolution import convolution\n\ndef sobel_edge_detection(image, filter):\n new_image_x = convolution(image, filter)\n\n new_image_y = convolution(image, np.flip(filter.T, axis=0))\n\n gradient_magnitude = np.sqrt(np.square(new_image_x) + np.square(new_image_y))\n\n gradient_magnitude *= 255.0 / gradient_magnitude.max()\n\n gradient_direction = np.arctan2(new_image_y, new_image_x)\n\n gradient_direction = np.rad2deg(gradient_direction)\n gradient_direction += 180\n\n return gradient_magnitude, gradient_direction\n","sub_path":"Canny_Edge_Detection_Raspberry/sobel.py","file_name":"sobel.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"85866225","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport os\n\nfrom flask import Blueprint\nfrom flask import request\nfrom flask import url_for\nfrom flask_jwt_extended import create_access_token\n\nfrom app.config.config import DevelopmentConfig\nfrom app.models.users import User\nfrom app.utils import responses as resp\nfrom app.utils.responses import response_with\nfrom app.utils.token import generate_verification_token, confirm_verification_token\n\nuser_routes = Blueprint(\"user_routes\", __name__)\n\n\n@user_routes.route('///', methods=['POST'])\ndef create_user():\n try:\n data = request.get_json()\n if User.find_by_email(data['email']) is not None or User.find_by_username(data['username']) is not None:\n return response_with(resp.INVALID_INPUT_422)\n data['password'] = User.generate_hash(data['password'])\n token = generate_verification_token(data['email'])\n verification_email = url_for('user_routes.verify_email', token=token, _external=True)\n result = {'db_insert': str(User.create(data)), 'verification_email': verification_email}\n return response_with(resp.SUCCESS_201, value={'result': result})\n except Exception as e:\n print(e)\n return response_with(resp.INVALID_INPUT_422)\n\n\n@user_routes.route('/confirm//', methods=['GET'])\ndef verify_email(token):\n try:\n email = confirm_verification_token(token)\n except Exception as e:\n return response_with(resp.UNAUTHORIZED_401)\n user = User.find_by_email(email=email)\n if user['is_verified']:\n return response_with(resp.INVALID_INPUT_422)\n else:\n user['is_verified'] = True\n User.update_field(user, 'is_verified', True)\n return response_with(resp.SUCCESS_200, value={'message': 'E-mail verified, you can proceed to login now.'})\n\n\n@user_routes.route('/dev-login/', methods=['POST'])\ndef authenticate_dev_user():\n try:\n data = request.get_json()\n current_user = {}\n if data.get('email'):\n current_user = User.find_by_email(data['email'])\n elif data.get('username'):\n current_user = User.find_by_username(data['username'])\n if not current_user:\n return response_with(resp.SERVER_ERROR_404)\n if current_user and not current_user['is_verified']:\n return response_with(resp.BAD_REQUEST_400)\n if User.verify_hash(data['password'], current_user['password']):\n # JWT_ACCESS_TOKEN_EXPIRES en desarrollo el token no expira.\n access_token = create_access_token(identity=current_user['username'], expires_delta=False)\n return response_with(resp.SUCCESS_200,\n value={'message': 'Logged in as admin', \"access_token\": access_token})\n else:\n return response_with(resp.UNAUTHORIZED_401)\n except Exception as e:\n print(e)\n return response_with(resp.INVALID_INPUT_422)\n\n\n@user_routes.route('/login/', methods=['POST'])\ndef authenticate_user():\n try:\n data = request.get_json()\n current_user = {}\n if data.get('email'):\n current_user = User.find_by_email(data['email'])\n elif data.get('username'):\n current_user = User.find_by_username(data['username'])\n if not current_user:\n return response_with(resp.SERVER_ERROR_404)\n if current_user and not current_user['is_verified']:\n return response_with(resp.BAD_REQUEST_400)\n if User.verify_hash(data['password'], current_user['password']):\n # JWT_ACCESS_TOKEN_EXPIRES = 15 minutos por defecto\n expires = datetime.timedelta(\n minutes=int(os.environ.get('JWT_ACCESS_TOKEN_EXPIRES', DevelopmentConfig.JWT_ACCESS_TOKEN_EXPIRES)))\n access_token = create_access_token(identity=current_user['username'], expires_delta=expires)\n return response_with(resp.SUCCESS_200,\n value={'message': 'Logged in as admin', \"access_token\": access_token})\n else:\n return response_with(resp.UNAUTHORIZED_401)\n except Exception as e:\n print(e)\n return response_with(resp.INVALID_INPUT_422)\n","sub_path":"app/routes/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"514091261","text":"#!/usr/bin/python\n\n###################################################################################################\n#\n# pyral.query_builder - module to build Rally WSAPI compliant query clause\n#\n###################################################################################################\n\n__version__ = (1, 5, 2)\n\nimport re\nimport types\nimport six\nfrom six.moves.urllib.parse import quote\n\n###################################################################################################\n\nclass RallyUrlBuilder(object):\n \"\"\"\n An instance of this class is used to collect information needed to construct a\n valid URL that can be issued in a REST Request to Rally.\n The sequence of use is to obtain a RallyUrlBuilder for a named entity, \n provide qualifying criteria, augments, scoping criteria and any provision \n for a pretty response, and then call build to return the resulting resource URL.\n An instance can be re-used (for the same entity) by simply re-calling the \n specification methods with differing values and then re-calling the build method.\n \"\"\"\n parts = ['fetch', 'query', 'order', \n 'workspace', 'project', 'projectScopeUp', 'projectScopeDown', \n 'pagesize', 'start', 'pretty'\n ]\n\n def __init__(self, entity):\n self.entity = entity\n\n def qualify(self, fetch, query, order, pagesize, startIndex):\n self.fetch = fetch\n self.query = query\n self.order = order\n self.pagesize = pagesize\n self.startIndex = startIndex\n self.workspace = None\n self.project = None\n self.scopeUp = None\n self.scopeDown = None\n self.pretty = False\n \n\n def build(self, pretty=None):\n if pretty:\n self.pretty = True\n \n resource = \"{0}?\".format(self.entity)\n\n qualifiers = ['fetch=%s' % self.fetch]\n if self.query:\n##\n## print(\"RallyQueryFormatter raw query: %s\" % self.query)\n##\n query_string = RallyQueryFormatter.parenGroups(self.query)\n##\n## print(\"query_string: |query=(%s)|\" % query_string)\n##\n qualifiers.append(\"query=(%s)\" % query_string)\n if self.order:\n qualifiers.append(\"order=%s\" % quote(self.order))\n if self.workspace:\n qualifiers.append(self.workspace)\n if self.project:\n qualifiers.append(self.project)\n if self.scopeUp:\n qualifiers.append(self.scopeUp)\n if self.scopeDown:\n qualifiers.append(self.scopeDown)\n\n qualifiers.append('pagesize=%s' % self.pagesize)\n qualifiers.append('start=%s' % self.startIndex)\n\n if self.pretty:\n qualifiers.append('pretty=true')\n\n resource += \"&\".join(qualifiers)\n##\n## print(\"RallyUrlBuilder.build: resource= %s\" % resource)\n##\n return resource\n\n def augmentWorkspace(self, augments, workspace_ref):\n wksp_augment = [aug for aug in augments if aug.startswith('workspace=')]\n self.workspace = \"workspace=%s\" % workspace_ref\n if wksp_augment:\n self.workspace = wksp_augment[0]\n\n def augmentProject(self, augments, project_ref):\n proj_augment = [aug for aug in augments if aug.startswith('project=')]\n self.project = \"project=%s\" % project_ref\n if proj_augment:\n self.project = proj_augment[0]\n\n def augmentScoping(self, augments):\n scopeUp = [aug for aug in augments if aug.startswith('projectScopeUp=')]\n if scopeUp:\n self.scopeUp = scopeUp[0]\n scopeDown = [aug for aug in augments if aug.startswith('projectScopeDown=')]\n if scopeDown:\n self.scopeDown = scopeDown[0]\n\n def beautifyResponse(self):\n self.pretty = True\n\n##################################################################################################\n\nclass RallyQueryFormatter(object):\n CONJUNCTIONS = ['and', 'AND', 'or', 'OR']\n CONJUNCTION_PATT = re.compile(r'\\s+(AND|OR)\\s+', re.I | re.M)\n ATTR_IDENTIFIER = r'[\\w\\.]+[a-zA-Z0-9]' # gotta be word-like possibly separated by '.' chars\n RELATIONSHIP = r'=|!=|>|<|>=|<=|contains|!contains'\n ATTR_VALUE = r'\"[^\"]+\"|[^ ]+' # double quoted value or has no leading, embedded or trailing spaces\n QUERY_CRITERIA_PATTERN = re.compile(r'^(%s) (%s) (%s)$' % (ATTR_IDENTIFIER, RELATIONSHIP, ATTR_VALUE), re.M)\n\n @staticmethod\n def parenGroups(criteria):\n \"\"\"\n Keep in mind that Rally WSAPI only supports a binary expression of (x) op (y)\n as in \"(foo) and (bar)\"\n or (foo) and ((bar) and (egg)) \n Note that Rally doesn't handle (x and y and z) directly.\n Look at the criteria to see if there are any parens other than begin and end \n if the only parens are at begin and end, strip them and subject the criteria to our\n clause grouper and binary expression confabulator. \n Otherwise, we'll naively assume the caller knows what they are doing, ie., they are \n aware of the binary expression requirement.\n \"\"\"\n def _encode(condition):\n \"\"\"\n if cond has pattern of 'thing relation value', then urllib.quote it and return it\n if cond has pattern of '(thing relation value)', then urllib.quote content inside parens\n then pass that result enclosed in parens back to the caller\n \"\"\"\n first_last = \"%s%s\" % (condition[0], condition[-1])\n if first_last == \"()\":\n url_encoded = quote(condition)\n else:\n url_encoded = '(%s)' % quote(condition)\n\n # replace the %xx encodings for '=', '(', ')', '!', and double quote characters\n readable_encoded = url_encoded.replace(\"%3D\", '=')\n readable_encoded = readable_encoded.replace(\"%22\", '\"')\n readable_encoded = readable_encoded.replace(\"%28\", '(')\n readable_encoded = readable_encoded.replace(\"%29\", ')')\n readable_encoded = readable_encoded.replace(\"%21\", '!')\n return readable_encoded\n##\n## print(\"RallyQueryFormatter.parenGroups criteria parm: |%s|\" % repr(criteria))\n##\n \n if type(criteria) in [list, tuple]:\n # by fiat (and until requested by a paying customer), we assume the criteria expressions are AND'ed\n #conditions = [_encode(expression) for expression in criteria] \n conditions = [expression for expression in criteria] \n criteria = \" AND \".join(conditions)\n##\n## print(\"RallyQueryFormatter: criteria is sequence type resulting in |%s|\" % criteria)\n##\n\n if type(criteria) == dict: \n expressions = []\n for field, value in list(criteria.items()):\n # have to enclose string value in double quotes, otherwise turn whatever the value is into a string\n tval = '\"%s\"' % value if type(value) == bytes else '%s' % value\n expression = ('%s = %s' % (field, tval))\n if len(criteria) == 1:\n return expression.replace(' ', '%20')\n expressions.append(expression)\n criteria = \" AND \".join(expressions)\n\n # if the caller has a simple query in the form \"(something relation a_value)\"\n # then return the query as is (after stripping off the surrounding parens)\n if criteria.count('(') == 1 and criteria.count(')') == 1 and \\\n criteria.strip()[0] == '(' and criteria.strip()[-1] == ')':\n return criteria.strip()[1:-1].replace(' ', '%20')\n \n # if caller has more than one opening paren, summarily return the query \n # after stripping off the opening paren at the start of the string and the \n # closing parent at the end of the string\n # The assumption is that the caller has correctly done the parenthesized grouping\n # to end up in a binary form but we strip off the enclosing parens because the \n # caller (RallyUrlBuilder) will be immediately supplying them after the return from here.\n if criteria.count('(') > 1:\n stripped_and_plugged = criteria.strip()[1:-1].replace(' ', '%20')\n return stripped_and_plugged\n\n # commented out following substitution for 1.5.0, as later a call to quote(criteria ...)\n # ends up url-encoding the %26 resulting a a value of %2526 which goofs things up on the back-end in Rally\n #criteria = criteria.replace('&', '%26')\n parts = RallyQueryFormatter.CONJUNCTION_PATT.split(criteria.strip())\n # adjust parts for range condition presence, coalesce parts components that have a sequence of\n # 'foo between value1', 'and', 'value2' into 'foo between value1 and value2',\n adjusted_parts = []\n temp = parts[:]\n while temp:\n if len(temp) > 2:\n if 'between ' in temp[0].lower() and temp[1].lower() == 'and' and temp[2] and ' ' not in temp[2]:\n range_part = f'{temp[0]} {temp[1]} {temp[2]}'\n adjusted_parts.append(range_part)\n conj = temp[1][:]\n temp = temp[3:] if len(temp) > 3 else []\n # and take out 1 'and' or 'AND' conjunction from conjunctions\n continue\n adjusted_parts.append(temp.pop(0))\n parts = adjusted_parts\n\n##\n## print(\"RallyQueryFormatter parts: %s\" % repr(parts))\n##\n # if no CONJUNCTION is in parts, use the condition as is (simple case)\n # OR if the criteria looks like subset query or a range query\n conjunctions = [p for p in parts if p in RallyQueryFormatter.CONJUNCTIONS]\n #if not conjunctions or re.search(r'!?between .+\\s+and\\s+', criteria, flags=re.I):\n if not conjunctions and re.search(r'^[\\w\\.0-9]+\\s+!?between .+\\s+and\\s+.+$', criteria, flags=re.I):\n attr_ident = r'[\\w\\.]+[a-zA-Z0-9]'\n # Is this a subset expression, foo in baz,korn or foo !in burgers,fries,toast\n mo = re.search(r'^(%s)\\s+(!?in)\\s+(.+)$' % attr_ident, criteria, flags=re.I)\n if mo:\n attr_name, cond, values = mo.group(1), mo.group(2), mo.group(3)\n # Rally WSAPI supports attr_name in value1,value2,... directly but not so with !in\n if cond.lower() == '!in': # we must construct an OR'ed express with != for each listed value\n # Rally WSAPI supports attr_name in value1,value2,... directly but not so with !in\n criteria = RallyQueryFormatter.constructSubsetExpression(attr_name, cond, values)\n else:\n # Is this a range expression, someDate between today and nextYear\n mo = re.search(r'^(%s)\\s+(!?between)\\s+(.+)\\s+and\\s+(.+)$' % attr_ident, criteria, flags=re.I)\n if mo:\n attr_name, cond, lesser, greater = mo.group(1), mo.group(2), mo.group(3), mo.group(4)\n criteria = RallyQueryFormatter.constructRangefulExpression(attr_name, cond, lesser, greater)\n\n expression = quote(criteria.strip()).replace('%28', '(').replace('%29', ')')\n return expression\n\n parts = RallyQueryFormatter.validatePartsSyntax(parts)\n binary_expression = quote(parts.pop())\n while parts:\n item = parts.pop()\n if item in RallyQueryFormatter.CONJUNCTIONS:\n conj = item\n binary_expression = \"%s (%s)\" % (conj, binary_expression)\n else:\n cond = quote(item)\n binary_expression = \"(%s) %s\" % (cond, binary_expression)\n\n encoded_parened_expression = binary_expression.replace('%28', '(').replace('%29', ')')\n##\n## print(\"RallyQueryFormatter.encoded_parened_expression: |{0}|\".format(encoded_parened_expression))\n## print(\"=============================================================\")\n##\n final_expression = encoded_parened_expression.replace(' ', '%20')\n return final_expression\n\n @staticmethod\n def validatePartsSyntax(parts):\n attr_ident = r'[\\w\\.]+[a-zA-Z0-9]'\n relationship = r'=|!=|>|<|>=|<=|contains|!contains'\n attr_value = r'\"[^\"]+\"|[^\" ]+'\n criteria_pattern = re.compile(r'^(%s) (%s) (%s)$' % (attr_ident, relationship, attr_value))\n quoted_value_pattern = re.compile(r'^(%s) (%s) (\"[^\"]+\")$' % (attr_ident, relationship))\n unquoted_value_pattern = re.compile(r'^(%s) (%s) ([^\"].+[^\"])$' % (attr_ident, relationship))\n subset_pattern = re.compile(r'^(%s)\\s+(!?in)\\s+(.+)$' % attr_ident, flags=re.I)\n range_pattern = re.compile(r'^(%s)\\s+(!?between)\\s+(.+)\\s+and\\s+(.+)$' % attr_ident, flags=re.I)\n\n valid_parts = []\n front = \"\"\n while parts:\n part = \"%s%s\" % (front, parts.pop(0))\n\n mo = subset_pattern.match(part)\n if mo:\n attr_name, cond, values = mo.group(1), mo.group(2), mo.group(3)\n # Rally WSAPI supports attr_name in value1,value2,... directly, but not so with !in\n if cond.lower() == 'in':\n valid_parts.append(part)\n else: # we must construct an OR'ed express with != for each listed value\n criteria = RallyQueryFormatter.constructSubsetExpression(attr_name, cond, values)\n valid_parts.append(criteria)\n continue\n\n mo = range_pattern.match(part)\n if mo:\n attr_name, cond, lesser, greater = mo.group(1), mo.group(2), mo.group(3), mo.group(4)\n criteria = RallyQueryFormatter.constructRangefulExpression(attr_name, cond, lesser, greater)\n valid_parts.append(criteria)\n continue\n\n if criteria_pattern.match(part):\n valid_parts.append(part)\n elif quoted_value_pattern.match(part):\n valid_parts.append(part)\n elif unquoted_value_pattern.match(part):\n wordles = part.split(' ', 2)\n recast_part = '%s %s \"%s\"' % tuple(wordles)\n valid_parts.append(recast_part)\n else:\n if re.match(r'^(AND|OR)$', part, re.I):\n valid_parts.append(part)\n else:\n front = part + \" \"\n\n if not valid_parts:\n raise Exception(\"Invalid query expression syntax in: %s\" % (\" \".join(parts)))\n \n return valid_parts\n\n #\n # subset and range related ops for building queries\n #\n @staticmethod\n def constructSubsetExpression(field, relation, values):\n \"\"\"\n intended for use when a subset operator (in or !in) is in play\n State in Defined, Accepted, Relased\n needs an ORed expression ((f = D OR f = A) OR ((f = R)))\n State !in Working, Fixed, Testing\n needs an ANDed expression ((f != W AND f != F) AND ((f != T)))\n \"\"\"\n operator, conjunction = \"=\", 'OR'\n if relation.lower() == '!in':\n operator = \"!=\"\n conjunction = 'AND'\n if isinstance(values, str):\n if values.count(',') == 0: # no commas equal only 1 value considered, put it in a list\n values = [values]\n else:\n values = [item.lstrip().rstrip() for item in values.split(',')]\n if len(values) == 1:\n return f'{field} {operator} \"{values[0]}\"'\n val1, val2 = values[:2]\n binary_expression = f'({field} {operator} \"{val1}\") {conjunction} ({field} {operator} \"{val2}\")'\n for value in values[2:]:\n binary_expression = f'({binary_expression}) {conjunction} ({field} {operator} \"{value}\")'\n return binary_expression\n\n @staticmethod\n def constructRangefulExpression(attr_name, cond, lesser, greater):\n \"\"\"\n intended for use when a range operator (between or !between) is in play\n DevPhase between 2021-05-23 and 2021-07-09\n needs a single ANDed expression ((dp >= d1) AND (dp <= d1)))\n DevPhase !between 2021-12-19 and 2022-01-03\n needs a single ORed expression ((dp < d1) OR (dp > d1)))\n \"\"\"\n rlns = ['>=', '<='] if cond.lower() == 'between' else ['<', '>']\n conjunction= 'AND' if cond.lower() == 'between' else 'OR'\n lcond = '%s %s %s' % (attr_name, rlns[0], lesser)\n gcond = '%s %s %s' % (attr_name, rlns[1], greater)\n expression = \"(%s) %s (%s)\" % (lcond, conjunction, gcond)\n return expression\n\n##################################################################################################\n","sub_path":"pyral/query_builder.py","file_name":"query_builder.py","file_ext":"py","file_size_in_byte":16918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"570784061","text":"from django.shortcuts import render, redirect\nfrom django.core.mail import send_mail\nfrom django.views import View\nfrom product.models import Category\nfrom cart.models import *\nfrom order.models import Order\n\ncart = {}\n\n\nclass CartController(View):\n def get(self, request):\n category = Category.objects.filter(active=1)\n quantity = 0\n try:\n cart = request.session['cart']\n\n for key, value in cart.items():\n quantity += int(value['quantity'])\n\n total = 0\n if len(cart) > 0:\n for key, value in cart.items():\n if int(value['sale']) > 0:\n total += int(value['sale']) * int(value['quantity'])\n else:\n total += int(value['price']) * int(value['quantity'])\n return render(request, 'cart.html', {\n 'category': category,\n 'cart_quantity': quantity,\n 'total': total,\n })\n else:\n return render(request, 'empty_cart.html', {\n 'category': category,\n 'cart_quantity': quantity\n })\n except:\n return render(request, 'empty_cart.html', {\n 'category': category,\n 'cart_quantity': quantity\n })\n\n def add_cart(request):\n if request.is_ajax():\n id = request.POST['id']\n num = request.POST['quantity']\n product = Product.objects.get(id=id)\n if id in cart.keys():\n item = {\n 'name': product.title,\n 'price': product.price,\n 'sale': product.sale,\n 'quantity': int(cart[id]['quantity']) + int(num)\n }\n else:\n item = {\n 'name': product.title,\n 'price': product.price,\n 'sale': product.sale,\n 'quantity': num\n }\n\n cart[id] = item\n\n request.session['cart'] = cart\n\n return render(request, 'cart.html')\n\n def update_cart(request):\n if request.is_ajax():\n id = request.POST['id']\n num = request.POST['quantity']\n product = Product.objects.get(id=id)\n if id in cart.keys():\n item = {\n 'name': product.title,\n 'price': product.price,\n 'sale': product.sale,\n 'quantity': num\n }\n\n cart[id] = item\n request.session['cart'] = cart\n\n return render(request, 'cart.html')\n\n def remove_cart(request):\n if request.is_ajax():\n id = request.POST['id']\n if id in cart.keys():\n del cart[id]\n\n request.session['cart'] = cart\n\n return render(request, 'cart.html')\n\n\nclass CheckoutController(View):\n def get(self, request):\n category = Category.objects.filter(active=1)\n return render(request, 'checkout.html', {\n 'category': category\n })\n\n\nclass PaymentController(View):\n def get(self, request):\n category = Category.objects.filter(active=1)\n\n quantity = 0\n total = 0\n for key, value in cart.items():\n quantity += int(value['quantity'])\n if int(value['sale']) > 0:\n total += int(value['sale']) * int(value['quantity'])\n else:\n total += int(value['price']) * int(value['quantity'])\n\n return render(request, 'payment.html', {\n 'category': category,\n 'cart_quantity': quantity,\n 'total': total\n })\n\n def post(request):\n name = request.POST['Name']\n address = request.POST['Address']\n email = request.POST['Email']\n note = request.POST['Note']\n\n lst = []\n\n c = Cart()\n total = 0\n for key, value in cart.items():\n if int(value['sale']) > 0:\n total += int(value['sale']) * int(value['quantity'])\n else:\n total += int(value['price']) * int(value['quantity'])\n lst.append(value['name'] + ' - ' + str(value['quantity']))\n\n c.user = name\n c.total = total\n c.save()\n\n i = Cart.objects.last()\n for key, value in cart.items():\n item = CartItem()\n item.title = i.user\n item.product_id = int(key)\n item.quantity = value['quantity']\n if int(value['sale']) > 0:\n\n item.price = int(value['sale'])\n else:\n item.price = int(value['price'])\n item.save()\n\n order = Order()\n order.user = i.user\n order.product = lst\n order.ship_address = address\n order.description = note\n order.save()\n\n\n message = 'Xin chào {0}, đơn hàng của bạn đã được đặt thành công.\\nCác món bạn đã đặt là {1}.\\nTổng giá trị đơn hàng là {2} vnđ (chưa bao gồm phí vận chuyển).\\nĐịa chỉ giao hàng: {3}.\\nCảm ơn quí khách đã sử dụng dịch vụ.'.format(name, lst, total, address)\n\n send_mail(\n 'New Coffee',\n message,\n 'newcoffee138hadac@gmail.com',\n [email]\n )\n\n cart.clear()\n request.session['cart'] = cart\n\n return redirect('home:index')\n\n","sub_path":"cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"302879392","text":"\ndef findEndPoint(num, dict):\n halt = False\n orig = num\n while not halt:\n if num == 1:\n dict[orig] = num\n return 1\n if num == 89:\n dict[orig] = num\n return 89\n if num in dict:\n dict[orig] = dict[num]\n return dict[num]\n \n temp = 0\n for ch in str(num):\n temp += int(ch)**2\n num = temp\n\ndef main():\n dict = {}\n\n answer = 0\n for num in range(1,10000000):\n check = findEndPoint(num, dict)\n if check == 89:\n answer +=1\n\n print(answer)\n\nmain()\n\n","sub_path":"Python/euler92/euler92/euler92.py","file_name":"euler92.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"162337725","text":"from app1.models import *\nfrom app1.util.utils import *\n\ndef updateTeachPlan(request):\n '''\n get:\n http://127.0.0.1:8000/app1/updateTeachPlan?tpno=001&credit=7.0&teach_date=2011-08-22&evaluation_method=考查\n post:\n http://127.0.0.1:8000/app1/updateTeachPlan\n '''\n try:\n if(request.method=='POST'):\n teadata=json.loads(request.body)\n data=teadata[\"data\"]\n for item in data:\n # tpid=request.GET.get(\"tpno\")\n # cr=request.GET.get(\"credit\")\n # te=request.GET.get(\"teach_date\")\n # ev=request.GET.get(\"evaluation_method\")\n\n tpid=item[\"tpno\"]\n cr=item[\"credit\"]\n te=item[\"teach_date\"]\n ev=item[\"evaluation_method\"]\n\n result=TeachPlan.objects.filter(tpno=tpid).update(credit=cr,teach_date=te,evaluation_method=ev)\n\n result=TeachPlan.objects.all().values(\"tpno\",\"credit\",\"teach_date\",\"evaluation_method\",\"department__dno\",\"department__dname\",\"course__cno\",\"course__cname\",\"teacher__tno\",\"teacher__tname\")\n return showJsonresult(result)\n except Exception as e:\n response={}\n response['msg']=str(e)\n response['err_num']=1\n return showJsonerror(response) ","sub_path":"day08/django/app1/dateview/updateTeachPlan.py","file_name":"updateTeachPlan.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"314745005","text":"# Copyright (c) 2009-2019 The Regents of the University of Michigan\n# This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.\n\nR\"\"\" Pair potentials.\n\nGenerally, pair forces are short range and are summed over all non-bonded particles\nwithin a certain cutoff radius of each particle. Any number of pair forces\ncan be defined in a single simulation. The net force on each particle due to\nall types of pair forces is summed.\n\nPair forces require that parameters be set for each unique type pair. Coefficients\nare set through the aid of the :py:class:`coeff` class. To set these coefficients, specify\na pair force and save it in a variable::\n\n my_force = pair.some_pair_force(arguments...)\n\nThen the coefficients can be set using the saved variable::\n\n my_force.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n my_force.pair_coeff.set('A', 'B', epsilon=1.0, sigma=2.0)\n my_force.pair_coeff.set('B', 'B', epsilon=2.0, sigma=1.0)\n\nThis example set the parameters *epsilon* and *sigma*\n(which are used in :py:class:`lj`). Different pair forces require that different\ncoefficients are set. Check the documentation of each to see the definition\nof the coefficients.\n\"\"\"\n\nfrom hoomd import _hoomd\nfrom hoomd.md import _md\nfrom hoomd.md import force;\nfrom hoomd.md import nlist as nl # to avoid naming conflicts\nimport hoomd;\n\nimport math;\nimport sys;\nimport json;\nfrom collections import OrderedDict\n\nclass coeff:\n R\"\"\" Define pair coefficients\n\n All pair forces use :py:class:`coeff` to specify the coefficients between different\n pairs of particles indexed by type. The set of pair coefficients is a symmetric\n matrix defined over all possible pairs of particle types.\n\n There are two ways to set the coefficients for a particular pair force.\n The first way is to save the pair force in a variable and call :py:meth:`set()` directly.\n\n The second method is to build the :py:class:`coeff` class first and then assign it to the\n pair force. There are some advantages to this method in that you could specify a\n complicated set of pair coefficients in a separate python file and import it into\n your job script.\n\n Example (**force_field.py**)::\n\n from hoomd import md\n my_coeffs = md.pair.coeff();\n my_force.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n my_force.pair_coeff.set('A', 'B', epsilon=1.0, sigma=2.0)\n my_force.pair_coeff.set('B', 'B', epsilon=2.0, sigma=1.0)\n\n Example job script::\n\n from hoomd import md\n import force_field\n\n .....\n my_force = md.pair.some_pair_force(arguments...)\n my_force.pair_coeff = force_field.my_coeffs\n\n \"\"\"\n\n ## \\internal\n # \\brief Initializes the class\n # \\details\n # The main task to be performed during initialization is just to init some variables\n # \\param self Python required class instance variable\n def __init__(self):\n self.values = {};\n self.default_coeff = {}\n\n ## \\internal\n # \\brief Return a compact representation of the pair coefficients\n def get_metadata(self):\n # return list for easy serialization\n l = []\n for (a,b) in self.values:\n item = OrderedDict()\n item['typei'] = a\n item['typej'] = b\n for coeff in self.values[(a,b)]:\n item[coeff] = self.values[(a,b)][coeff]\n l.append(item)\n return l\n\n ## \\var values\n # \\internal\n # \\brief Contains the matrix of set values in a dictionary\n\n ## \\var default_coeff\n # \\internal\n # \\brief default_coeff['coeff'] lists the default value for \\a coeff, if it is set\n\n ## \\internal\n # \\brief Sets a default value for a given coefficient\n # \\details\n # \\param name Name of the coefficient to for which to set the default\n # \\param value Default value to set\n #\n # Some coefficients have reasonable default values and the user should not be burdened with typing them in\n # all the time. set_default_coeff() sets\n def set_default_coeff(self, name, value):\n self.default_coeff[name] = value;\n\n def set(self, a, b, **coeffs):\n R\"\"\" Sets parameters for one type pair.\n\n Args:\n a (str): First particle type in the pair (or a list of type names)\n b (str): Second particle type in the pair (or a list of type names)\n coeffs: Named coefficients (see below for examples)\n\n Calling :py:meth:`set()` results in one or more parameters being set for a single type pair\n or set of type pairs.\n Particle types are identified by name, and parameters are also added by name.\n Which parameters you need to specify depends on the pair force you are setting\n these coefficients for, see the corresponding documentation.\n\n All possible type pairs as defined in the simulation box must be specified before\n executing :py:class:`hoomd.run()`. You will receive an error if you fail to do so. It is not an error,\n however, to specify coefficients for particle types that do not exist in the simulation.\n This can be useful in defining a force field for many different types of particles even\n when some simulations only include a subset.\n\n There is no need to specify coefficients for both pairs 'A', 'B' and 'B', 'A'. Specifying\n only one is sufficient.\n\n To set the same coefficients between many particle types, provide a list of type names instead of a single\n one. All pairs between the two lists will be set to the same parameters.\n\n Examples::\n\n coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n coeff.set('B', 'B', epsilon=2.0, sigma=1.0)\n coeff.set('A', 'B', epsilon=1.5, sigma=1.0)\n coeff.set(['A', 'B', 'C', 'D'], 'F', epsilon=2.0)\n coeff.set(['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], epsilon=1.0)\n\n system = init.read_xml('init.xml')\n coeff.set(system.particles.types, system.particles.types, epsilon=2.0)\n coeff.set('A', system.particles.types, epsilon=1.2)\n\n Note:\n Single parameters can be updated. If both epsilon and sigma have already been\n set for a type pair, then executing ``coeff.set('A', 'B', epsilon=1.1)`` will update\n the value of epsilon and leave sigma as it was previously set.\n\n Some pair potentials assign default values to certain parameters. If the default setting for a given coefficient\n (as documented in the respective pair command) is not set explicitly, the default will be used.\n\n \"\"\"\n hoomd.util.print_status_line();\n\n # listify the inputs\n a = hoomd.util.listify(a)\n b = hoomd.util.listify(b)\n\n for ai in a:\n for bi in b:\n self.set_single(ai, bi, coeffs);\n\n ## \\internal\n # \\brief Sets a single parameter\n def set_single(self, a, b, coeffs):\n a = str(a);\n b = str(b);\n\n # create the pair if it hasn't been created it\n if (not (a,b) in self.values) and (not (b,a) in self.values):\n self.values[(a,b)] = {};\n\n # Find the pair to update\n if (a,b) in self.values:\n cur_pair = (a,b);\n elif (b,a) in self.values:\n cur_pair = (b,a);\n else:\n hoomd.context.msg.error(\"Bug detected in pair.coeff. Please report\\n\");\n raise RuntimeError(\"Error setting pair coeff\");\n\n # update each of the values provided\n if len(coeffs) == 0:\n hoomd.context.msg.error(\"No coefficients specified\\n\");\n for name, val in coeffs.items():\n self.values[cur_pair][name] = val;\n\n # set the default values\n for name, val in self.default_coeff.items():\n # don't override a coeff if it is already set\n if not name in self.values[cur_pair]:\n self.values[cur_pair][name] = val;\n\n ## \\internal\n # \\brief Verifies set parameters form a full matrix with all values set\n # \\details\n # \\param self Python required self variable\n # \\param required_coeffs list of required variables\n #\n # This can only be run after the system has been initialized\n def verify(self, required_coeffs):\n # first, check that the system has been initialized\n if not hoomd.init.is_initialized():\n hoomd.context.msg.error(\"Cannot verify pair coefficients before initialization\\n\");\n raise RuntimeError('Error verifying pair coefficients');\n\n # get a list of types from the particle data\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n valid = True;\n # loop over all possible pairs and verify that all required variables are set\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n a = type_list[i];\n b = type_list[j];\n\n # find which half of the pair is set\n if (a,b) in self.values:\n cur_pair = (a,b);\n elif (b,a) in self.values:\n cur_pair = (b,a);\n else:\n hoomd.context.msg.error(\"Type pair \" + str((a,b)) + \" not found in pair coeff\\n\");\n valid = False;\n continue;\n\n # verify that all required values are set by counting the matches\n count = 0;\n for coeff_name in self.values[cur_pair].keys():\n if not coeff_name in required_coeffs:\n hoomd.context.msg.notice(2, \"Notice: Possible typo? Pair coeff \" + str(coeff_name) + \" is specified for pair \" + str((a,b)) + \\\n \", but is not used by the pair force\\n\");\n else:\n count += 1;\n\n if count != len(required_coeffs):\n hoomd.context.msg.error(\"Type pair \" + str((a,b)) + \" is missing required coefficients\\n\");\n valid = False;\n\n\n return valid;\n\n ## \\internal\n # \\brief Try to get whether a single pair coefficient\n # \\detail\n # \\param a First name in the type pair\n # \\param b Second name in the type pair\n # \\param coeff_name Coefficient to get\n def get(self,a,b,coeff_name):\n if (a,b) in self.values:\n cur_pair = (a,b);\n elif (b,a) in self.values:\n cur_pair = (b,a);\n else:\n return None;\n\n if coeff_name in self.values[cur_pair]:\n return self.values[cur_pair][coeff_name];\n else:\n return None;\n\nclass pair(force._force):\n R\"\"\" Common pair potential documentation.\n\n Users should not invoke :py:class:`pair` directly. It is a base command that provides common\n features to all standard pair forces. Common documentation for all pair potentials is documented here.\n\n All pair force commands specify that a given potential energy and force be computed on all non-excluded particle\n pairs in the system within a short range cutoff distance :math:`r_{\\mathrm{cut}}`.\n\n The force :math:`\\vec{F}` applied between each pair of particles is:\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n \\vec{F} = & -\\nabla V(r) & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n where :math:`\\vec{r}` is the vector pointing from one particle to the other in the pair, and :math:`V(r)` is\n chosen by a mode switch (see :py:meth:`set_params()`):\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V(r) = & V_{\\mathrm{pair}}(r) & \\mathrm{mode\\ is\\ no\\_shift} \\\\\n = & V_{\\mathrm{pair}}(r) - V_{\\mathrm{pair}}(r_{\\mathrm{cut}}) & \\mathrm{mode\\ is\\ shift} \\\\\n = & S(r) \\cdot V_{\\mathrm{pair}}(r) & \\mathrm{mode\\ is\\ xplor\\ and\\ } r_{\\mathrm{on}} < r_{\\mathrm{cut}} \\\\\n = & V_{\\mathrm{pair}}(r) - V_{\\mathrm{pair}}(r_{\\mathrm{cut}}) & \\mathrm{mode\\ is\\ xplor\\ and\\ } r_{\\mathrm{on}} \\ge r_{\\mathrm{cut}}\n \\end{eqnarray*}\n\n :math:`S(r)` is the XPLOR smoothing function:\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n S(r) = & 1 & r < r_{\\mathrm{on}} \\\\\n = & \\frac{(r_{\\mathrm{cut}}^2 - r^2)^2 \\cdot (r_{\\mathrm{cut}}^2 + 2r^2 -\n 3r_{\\mathrm{on}}^2)}{(r_{\\mathrm{cut}}^2 - r_{\\mathrm{on}}^2)^3}\n & r_{\\mathrm{on}} \\le r \\le r_{\\mathrm{cut}} \\\\\n = & 0 & r > r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n and :math:`V_{\\mathrm{pair}}(r)` is the specific pair potential chosen by the respective command.\n\n Enabling the XPLOR smoothing function :math:`S(r)` results in both the potential energy and the force going smoothly\n to 0 at :math:`r = r_{\\mathrm{cut}}`, reducing the rate of energy drift in long simulations.\n :math:`r_{\\mathrm{on}}` controls the point at which the smoothing starts, so it can be set to only slightly modify\n the tail of the potential. It is suggested that you plot your potentials with various values of\n :math:`r_{\\mathrm{on}}` in order to find a good balance between a smooth potential function and minimal modification\n of the original :math:`V_{\\mathrm{pair}}(r)`. A good value for the LJ potential is\n :math:`r_{\\mathrm{on}} = 2 \\cdot \\sigma`.\n\n The split smoothing / shifting of the potential when the mode is ``xplor`` is designed for use in mixed WCA / LJ\n systems. The WCA potential and it's first derivative already go smoothly to 0 at the cutoff, so there is no need\n to apply the smoothing function. In such mixed systems, set :math:`r_{\\mathrm{on}}` to a value greater than\n :math:`r_{\\mathrm{cut}}` for those pairs that interact via WCA in order to enable shifting of the WCA potential\n to 0 at the cutoff.\n\n The following coefficients must be set per unique pair of particle types. See :py:mod:`hoomd.md.pair` for information\n on how to set coefficients:\n\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}` - *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n When :math:`r_{\\mathrm{cut}} \\le 0` or is set to False, the particle type pair interaction is excluded from the neighbor\n list. This mechanism can be used in conjunction with multiple neighbor lists to make efficient calculations in systems\n with large size disparity. Functionally, this is equivalent to setting :math:`r_{\\mathrm{cut}} = 0` in the pair force\n because negative :math:`r_{\\mathrm{cut}}` has no physical meaning.\n \"\"\"\n\n ## \\internal\n # \\brief Initialize the pair force\n # \\details\n # The derived class must set\n # - self.cpp_class (the pair class to instantiate)\n # - self.required_coeffs (a list of the coeff names the derived class needs)\n # - self.process_coeffs() (a method that takes in the coeffs and spits out a param struct to use in\n # self.cpp_force.set_params())\n def __init__(self, r_cut, nlist, name=None):\n # initialize the base class\n force._force.__init__(self, name);\n\n # convert r_cut False to a floating point type\n if r_cut is False:\n r_cut = -1.0\n self.global_r_cut = r_cut;\n\n # setup the coefficient matrix\n self.pair_coeff = coeff();\n self.pair_coeff.set_default_coeff('r_cut', self.global_r_cut);\n self.pair_coeff.set_default_coeff('r_on', self.global_r_cut);\n\n # setup the neighbor list\n self.nlist = nlist\n self.nlist.subscribe(lambda:self.get_rcut())\n self.nlist.update_rcut()\n\n def set_params(self, mode=None):\n R\"\"\" Set parameters controlling the way forces are computed.\n\n Args:\n mode (str): (if set) Set the mode with which potentials are handled at the cutoff.\n\n Valid values for *mode* are: \"none\" (the default), \"shift\", and \"xplor\":\n\n - **none** - No shifting is performed and potentials are abruptly cut off\n - **shift** - A constant shift is applied to the entire potential so that it is 0 at the cutoff\n - **xplor** - A smoothing function is applied to gradually decrease both the force and potential to 0 at the\n cutoff when ron < rcut, and shifts the potential to 0 at the cutoff when ron >= rcut.\n\n See :py:class:`pair` for the equations.\n\n Examples::\n\n mypair.set_params(mode=\"shift\")\n mypair.set_params(mode=\"no_shift\")\n mypair.set_params(mode=\"xplor\")\n\n \"\"\"\n hoomd.util.print_status_line();\n\n if mode is not None:\n if mode == \"no_shift\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.no_shift)\n elif mode == \"shift\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.shift)\n elif mode == \"xplor\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.xplor)\n else:\n hoomd.context.msg.error(\"Invalid mode\\n\");\n raise RuntimeError(\"Error changing parameters in pair force\");\n\n def process_coeff(self, coeff):\n hoomd.context.msg.error(\"Bug in hoomd, please report\\n\");\n raise RuntimeError(\"Error processing coefficients\");\n\n def update_coeffs(self):\n coeff_list = self.required_coeffs + [\"r_cut\", \"r_on\"];\n # check that the pair coefficients are valid\n if not self.pair_coeff.verify(coeff_list):\n hoomd.context.msg.error(\"Not all pair coefficients are set\\n\");\n raise RuntimeError(\"Error updating pair coefficients\");\n\n # set all the params\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n # build a dict of the coeffs to pass to process_coeff\n coeff_dict = {};\n for name in coeff_list:\n coeff_dict[name] = self.pair_coeff.get(type_list[i], type_list[j], name);\n\n param = self.process_coeff(coeff_dict);\n self.cpp_force.setParams(i, j, param);\n\n # rcut can now have \"invalid\" C++ values, which we round up to zero\n self.cpp_force.setRcut(i, j, max(coeff_dict['r_cut'], 0.0));\n self.cpp_force.setRon(i, j, max(coeff_dict['r_on'], 0.0));\n\n ## \\internal\n # \\brief Get the maximum r_cut value set for any type pair\n # \\pre update_coeffs must be called before get_max_rcut to verify that the coeffs are set\n def get_max_rcut(self):\n # go through the list of only the active particle types in the sim\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # find the maximum r_cut\n max_rcut = 0.0;\n\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n # get the r_cut value\n r_cut = self.pair_coeff.get(type_list[i], type_list[j], 'r_cut');\n max_rcut = max(max_rcut, r_cut);\n\n return max_rcut;\n\n ## \\internal\n # \\brief Get the r_cut pair dictionary\n # \\returns The rcut(i,j) dict if logging is on, and None if logging is off\n def get_rcut(self):\n if not self.log:\n return None\n\n # go through the list of only the active particle types in the sim\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # update the rcut by pair type\n r_cut_dict = nl.rcut();\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n # get the r_cut value\n r_cut = self.pair_coeff.get(type_list[i], type_list[j], 'r_cut');\n\n if r_cut is not None: # use the defined value\n if r_cut is False: # interaction is turned off\n r_cut_dict.set_pair(type_list[i],type_list[j], -1.0);\n else:\n r_cut_dict.set_pair(type_list[i],type_list[j], r_cut);\n else: # use the global default\n r_cut_dict.set_pair(type_list[i],type_list[j],self.global_r_cut);\n\n return r_cut_dict;\n\n ## \\internal\n # \\brief Return metadata for this pair potential\n def get_metadata(self):\n data = force._force.get_metadata(self)\n\n # make sure all coefficients are set\n self.update_coeffs()\n\n data['pair_coeff'] = self.pair_coeff\n return data\n\n def compute_energy(self, tags1, tags2):\n R\"\"\" Compute the energy between two sets of particles.\n\n Args:\n tags1 (``ndarray``): a numpy array of particle tags in the first group\n tags2 (``ndarray``): a numpy array of particle tags in the second group\n\n .. math::\n\n U = \\sum_{i \\in \\mathrm{tags1}, j \\in \\mathrm{tags2}} V_{ij}(r)\n\n where :math:`V_{ij}(r)` is the pairwise energy between two particles :math:`i` and :math:`j`.\n\n Assumed properties of the sets *tags1* and *tags2* are:\n\n - *tags1* and *tags2* are disjoint\n - all elements in *tags1* and *tags2* are unique\n - *tags1* and *tags2* are contiguous numpy arrays of dtype int32\n\n None of these properties are validated.\n\n Examples::\n\n tags=numpy.linspace(0,N-1,1, dtype=numpy.int32)\n # computes the energy between even and odd particles\n U = mypair.compute_energy(tags1=numpy.array(tags[0:N:2]), tags2=numpy.array(tags[1:N:2]))\n\n \"\"\"\n # future versions could use np functions to test the assumptions above and raise an error if they occur.\n return self.cpp_force.computeEnergyBetweenSets(tags1, tags2);\n\n def _connect_gsd_shape_spec(self, gsd):\n # This is an internal method, and should not be called directly. See gsd.dump_shape() instead\n if isinstance(gsd, hoomd.dump.gsd) and hasattr(self.cpp_force, \"connectGSDShapeSpec\"):\n self.cpp_force.connectGSDShapeSpec(gsd.cpp_analyzer);\n else:\n raise NotImplementedError(\"GSD Schema is not implemented for {}\".format(self.__class__.__name__));\n\n def get_type_shapes(self):\n \"\"\"Get all the types of shapes in the current simulation.\n\n Since this behaves differently for different types of shapes, the\n default behavior just raises an exception. Subclasses can override this\n to properly return.\n \"\"\"\n raise NotImplementedError(\n \"You are using a shape type that is not implemented! \"\n \"If you want it, please modify the \"\n \"hoomd.hpmc.integrate.mode_hpmc.get_type_shapes function.\")\n\n def _return_type_shapes(self):\n type_shapes = self.cpp_force.getTypeShapesPy();\n ret = [ json.loads(json_string) for json_string in type_shapes ];\n return ret;\n\nclass lj(pair):\n R\"\"\" Lennard-Jones pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`lj` specifies that a Lennard-Jones pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{LJ}}(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} -\n \\alpha \\left( \\frac{\\sigma}{r} \\right)^{6} \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`\\alpha` - *alpha* (unitless) - *optional*: defaults to 1.0\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n lj = pair.lj(r_cut=3.0, nlist=nl)\n lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n lj.pair_coeff.set('A', 'B', epsilon=2.0, sigma=1.0, alpha=0.5, r_cut=3.0, r_on=2.0);\n lj.pair_coeff.set('B', 'B', epsilon=1.0, sigma=1.0, r_cut=2**(1.0/6.0), r_on=2.0);\n lj.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=1.5, sigma=2.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairLJ(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairLJ;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairLJGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairLJGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'alpha'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 6.0);\n return _hoomd.make_scalar2(lj1, lj2);\n\nclass gauss(pair):\n R\"\"\" Gaussian pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`gauss` specifies that a Gaussian pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{gauss}}(r) = & \\varepsilon \\exp \\left[ -\\frac{1}{2}\\left( \\frac{r}{\\sigma} \\right)^2 \\right]\n & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n gauss = pair.gauss(r_cut=3.0, nlist=nl)\n gauss.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n gauss.pair_coeff.set('A', 'B', epsilon=2.0, sigma=1.0, r_cut=3.0, r_on=2.0);\n gauss.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=3.0, sigma=0.5)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairGauss(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairGauss;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairGaussGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairGaussGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma'];\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n\n return _hoomd.make_scalar2(epsilon, sigma);\n\nclass slj(pair):\n R\"\"\" Shifted Lennard-Jones pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n d_max (float): Maximum diameter particles in the simulation will have (in distance units)\n\n :py:class:`slj` specifies that a shifted Lennard-Jones type pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{SLJ}}(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r - \\Delta} \\right)^{12} -\n \\left( \\frac{\\sigma}{r - \\Delta} \\right)^{6} \\right] & r < (r_{\\mathrm{cut}} + \\Delta) \\\\\n = & 0 & r \\ge (r_{\\mathrm{cut}} + \\Delta) \\\\\n \\end{eqnarray*}\n\n where :math:`\\Delta = (d_i + d_j)/2 - 1` and :math:`d_i` is the diameter of particle :math:`i`.\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - *optional*: defaults to 1.0\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n .. attention::\n Due to the way that pair.slj modifies the cutoff criteria, a shift_mode of *xplor* is not supported.\n\n The actual cutoff radius for pair.slj is shifted by the diameter of two particles interacting. Thus to determine\n the maximum possible actual r_cut in simulation\n pair.slj must know the maximum diameter of all the particles over the entire run, *d_max* .\n This value is either determined automatically from the initialization or can be set by the user and can be\n modified between runs with :py:meth:`hoomd.md.nlist.nlist.set_params()`. In most cases, the correct value can be\n identified automatically.\n\n The specified value of *d_max* will be used to properly determine the neighbor lists during the following\n :py:func:`hoomd.run()` commands. If not specified, :py:class:`slj` will set d_max to the largest diameter\n in particle data at the time it is initialized.\n\n If particle diameters change after initialization, it is **imperative** that *d_max* be the largest\n diameter that any particle will attain at any time during the following :py:func:`hoomd.run()` commands.\n If *d_max* is smaller than it should be, some particles will effectively have a smaller value of *r_cut*\n then was set and the simulation will be incorrect. *d_max* can be changed between runs by calling\n :py:meth:`hoomd.md.nlist.nlist.set_params()`.\n\n Example::\n\n nl = nlist.cell()\n slj = pair.slj(r_cut=3.0, nlist=nl, d_max = 2.0)\n slj.pair_coeff.set('A', 'A', epsilon=1.0)\n slj.pair_coeff.set('A', 'B', epsilon=2.0, r_cut=3.0);\n slj.pair_coeff.set('B', 'B', epsilon=1.0, r_cut=2**(1.0/6.0));\n slj.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=2.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, d_max=None, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # update the neighbor list\n if d_max is None :\n sysdef = hoomd.context.current.system_definition;\n d_max = sysdef.getParticleData().getMaxDiameter()\n hoomd.context.msg.notice(2, \"Notice: slj set d_max=\" + str(d_max) + \"\\n\");\n\n # SLJ requires diameter shifting to be on\n self.nlist.cpp_nlist.setDiameterShift(True);\n self.nlist.cpp_nlist.setMaximumDiameter(d_max);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairSLJ(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairSLJ;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairSLJGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairSLJGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'alpha'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 6.0);\n return _hoomd.make_scalar2(lj1, lj2);\n\n def set_params(self, mode=None):\n R\"\"\" Set parameters controlling the way forces are computed.\n\n See :py:meth:`pair.set_params()`.\n\n Note:\n **xplor** is not a valid setting for :py:class:`slj`.\n\n \"\"\"\n hoomd.util.print_status_line();\n\n if mode == \"xplor\":\n hoomd.context.msg.error(\"XPLOR is smoothing is not supported with slj\\n\");\n raise RuntimeError(\"Error changing parameters in pair force\");\n\n pair.set_params(self, mode=mode);\n\nclass yukawa(pair):\n R\"\"\" Yukawa pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`yukawa` specifies that a Yukawa pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{yukawa}}(r) = & \\varepsilon \\frac{ \\exp \\left( -\\kappa r \\right) }{r} & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\kappa` - *kappa* (in units of 1/distance)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n yukawa = pair.lj(r_cut=3.0, nlist=nl)\n yukawa.pair_coeff.set('A', 'A', epsilon=1.0, kappa=1.0)\n yukawa.pair_coeff.set('A', 'B', epsilon=2.0, kappa=0.5, r_cut=3.0, r_on=2.0);\n yukawa.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=0.5, kappa=3.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairYukawa(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairYukawa;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairYukawaGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairYukawaGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'kappa'];\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n kappa = coeff['kappa'];\n\n return _hoomd.make_scalar2(epsilon, kappa);\n\nclass ewald(pair):\n R\"\"\" Ewald pair potential.\n\n :py:class:`ewald` specifies that a Ewald pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{ewald}}(r) = & q_i q_j \\left[\\mathrm{erfc}\\left(\\kappa r + \\frac{\\alpha}{2\\kappa}\\right) \\exp(\\alpha r)+\n \\mathrm{erfc}\\left(\\kappa r - \\frac{\\alpha}{2 \\kappa}\\right) \\exp(-\\alpha r)\\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n The Ewald potential is designed to be used in conjunction with :py:class:`hoomd.md.charge.pppm`.\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\kappa` - *kappa* (Splitting parameter, in 1/distance units)\n - :math:`\\alpha` - *alpha* (Debye screening length, in 1/distance units)\n .. versionadded:: 2.1\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n\n Example::\n\n nl = nlist.cell()\n ewald = pair.ewald(r_cut=3.0, nlist=nl)\n ewald.pair_coeff.set('A', 'A', kappa=1.0)\n ewald.pair_coeff.set('A', 'A', kappa=1.0, alpha=1.5)\n ewald.pair_coeff.set('A', 'B', kappa=1.0, r_cut=3.0, r_on=2.0);\n\n Warning:\n **DO NOT** use in conjunction with :py:class:`hoomd.md.charge.pppm`. It automatically creates and configures\n :py:class:`ewald` for you.\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairEwald(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairEwald;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairEwaldGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairEwaldGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['kappa','alpha'];\n self.pair_coeff.set_default_coeff('alpha', 0.0);\n\n def process_coeff(self, coeff):\n kappa = coeff['kappa'];\n alpha = coeff['alpha'];\n\n return _hoomd.make_scalar2(kappa, alpha)\n\n def set_params(self, coeff):\n \"\"\" :py:class:`ewald` has no energy shift modes \"\"\"\n\n raise RuntimeError('Not implemented for DPD Conservative');\n return;\n\ndef _table_eval(r, rmin, rmax, V, F, width):\n dr = (rmax - rmin) / float(width-1);\n i = int(round((r - rmin)/dr))\n return (V[i], F[i])\n\nclass table(force._force):\n R\"\"\" Tabulated pair potential.\n\n Args:\n width (int): Number of points to use to interpolate V and F.\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list (default of None automatically creates a global cell-list based neighbor list)\n name (str): Name of the force instance\n\n :py:class:`table` specifies that a tabulated pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n The force :math:`\\vec{F}` is (in force units):\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n \\vec{F}(\\vec{r}) = & 0 & r < r_{\\mathrm{min}} \\\\\n = & F_{\\mathrm{user}}(r)\\hat{r} & r_{\\mathrm{min}} \\le r < r_{\\mathrm{max}} \\\\\n = & 0 & r \\ge r_{\\mathrm{max}} \\\\\n \\end{eqnarray*}\n\n and the potential :math:`V(r)` is (in energy units)\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V(r) = & 0 & r < r_{\\mathrm{min}} \\\\\n = & V_{\\mathrm{user}}(r) & r_{\\mathrm{min}} \\le r < r_{\\mathrm{max}} \\\\\n = & 0 & r \\ge r_{\\mathrm{max}} \\\\\n \\end{eqnarray*}\n\n where :math:`\\vec{r}` is the vector pointing from one particle to the other in the pair.\n\n :math:`F_{\\mathrm{user}}(r)` and :math:`V_{\\mathrm{user}}(r)` are evaluated on *width* grid points between\n :math:`r_{\\mathrm{min}}` and :math:`r_{\\mathrm{max}}`. Values are interpolated linearly between grid points.\n For correctness, you must specify the force defined by: :math:`F = -\\frac{\\partial V}{\\partial r}`.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`V_{\\mathrm{user}}(r)` and :math:`F_{\\mathrm{user}}(r)` - evaluated by ``func`` (see example)\n - coefficients passed to ``func`` - *coeff* (see example)\n - :math:`_{\\mathrm{min}}` - *rmin* (in distance units)\n - :math:`_{\\mathrm{max}}` - *rmax* (in distance units)\n\n .. rubric:: Set table from a given function\n\n When you have a functional form for V and F, you can enter that\n directly into python. :py:class:`table` will evaluate the given function over *width* points between\n *rmin* and *rmax* and use the resulting values in the table::\n\n def lj(r, rmin, rmax, epsilon, sigma):\n V = 4 * epsilon * ( (sigma / r)**12 - (sigma / r)**6);\n F = 4 * epsilon / r * ( 12 * (sigma / r)**12 - 6 * (sigma / r)**6);\n return (V, F)\n\n nl = nlist.cell()\n table = pair.table(width=1000, nlist=nl)\n table.pair_coeff.set('A', 'A', func=lj, rmin=0.8, rmax=3.0, coeff=dict(epsilon=1.5, sigma=1.0))\n table.pair_coeff.set('A', 'B', func=lj, rmin=0.8, rmax=3.0, coeff=dict(epsilon=2.0, sigma=1.2))\n table.pair_coeff.set('B', 'B', func=lj, rmin=0.8, rmax=3.0, coeff=dict(epsilon=0.5, sigma=1.0))\n\n .. rubric:: Set a table from a file\n\n When you have no function for for *V* or *F*, or you otherwise have the data listed in a file,\n :py:class:`table` can use the given values directly. You must first specify the number of rows\n in your tables when initializing pair.table. Then use :py:meth:`set_from_file()` to read the file::\n\n nl = nlist.cell()\n table = pair.table(width=1000, nlist=nl)\n table.set_from_file('A', 'A', filename='table_AA.dat')\n table.set_from_file('A', 'B', filename='table_AB.dat')\n table.set_from_file('B', 'B', filename='table_BB.dat')\n\n Note:\n For potentials that diverge near r=0, make sure to set *rmin* to a reasonable value. If a potential does\n not diverge near r=0, then a setting of *rmin=0* is valid.\n\n \"\"\"\n def __init__(self, width, nlist, name=None):\n hoomd.util.print_status_line();\n\n # initialize the base class\n force._force.__init__(self, name);\n\n # setup the coefficient matrix\n self.pair_coeff = coeff();\n\n self.nlist = nlist\n self.nlist.subscribe(lambda:self.get_rcut())\n self.nlist.update_rcut()\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.TablePotential(hoomd.context.current.system_definition, self.nlist.cpp_nlist, int(width), self.name);\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.TablePotentialGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, int(width), self.name);\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # stash the width for later use\n self.width = width;\n\n def update_pair_table(self, typei, typej, func, rmin, rmax, coeff):\n # allocate arrays to store V and F\n Vtable = _hoomd.std_vector_scalar();\n Ftable = _hoomd.std_vector_scalar();\n\n # calculate dr\n dr = (rmax - rmin) / float(self.width-1);\n\n # evaluate each point of the function\n for i in range(0, self.width):\n r = rmin + dr * i;\n (V,F) = func(r, rmin, rmax, **coeff);\n\n # fill out the tables\n Vtable.append(V);\n Ftable.append(F);\n\n # pass the tables on to the underlying cpp compute\n self.cpp_force.setTable(typei, typej, Vtable, Ftable, rmin, rmax);\n\n ## \\internal\n # \\brief Get the r_cut pair dictionary\n # \\returns rcut(i,j) dict if logging is on, and None otherwise\n def get_rcut(self):\n if not self.log:\n return None\n\n # go through the list of only the active particle types in the sim\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # update the rcut by pair type\n r_cut_dict = nl.rcut();\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n # get the r_cut value\n rmax = self.pair_coeff.get(type_list[i], type_list[j], 'rmax');\n r_cut_dict.set_pair(type_list[i],type_list[j], rmax);\n\n return r_cut_dict;\n\n def get_max_rcut(self):\n # loop only over current particle types\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # find the maximum rmax to update the neighbor list with\n maxrmax = 0.0;\n\n # loop through all of the unique type pairs and find the maximum rmax\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n rmax = self.pair_coeff.get(type_list[i], type_list[j], \"rmax\");\n maxrmax = max(maxrmax, rmax);\n\n return maxrmax;\n\n def update_coeffs(self):\n # check that the pair coefficients are valid\n if not self.pair_coeff.verify([\"func\", \"rmin\", \"rmax\", \"coeff\"]):\n hoomd.context.msg.error(\"Not all pair coefficients are set for pair.table\\n\");\n raise RuntimeError(\"Error updating pair coefficients\");\n\n # set all the params\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n # loop through all of the unique type pairs and evaluate the table\n for i in range(0,ntypes):\n for j in range(i,ntypes):\n func = self.pair_coeff.get(type_list[i], type_list[j], \"func\");\n rmin = self.pair_coeff.get(type_list[i], type_list[j], \"rmin\");\n rmax = self.pair_coeff.get(type_list[i], type_list[j], \"rmax\");\n coeff = self.pair_coeff.get(type_list[i], type_list[j], \"coeff\");\n\n self.update_pair_table(i, j, func, rmin, rmax, coeff);\n\n def set_from_file(self, a, b, filename):\n R\"\"\" Set a pair interaction from a file.\n\n Args:\n a (str): Name of type A in pair\n b (str): Name of type B in pair\n filename (str): Name of the file to read\n\n The provided file specifies V and F at equally spaced r values.\n\n Example::\n\n #r V F\n 1.0 2.0 -3.0\n 1.1 3.0 -4.0\n 1.2 2.0 -3.0\n 1.3 1.0 -2.0\n 1.4 0.0 -1.0\n 1.5 -1.0 0.0\n\n The first r value sets *rmin*, the last sets *rmax*. Any line with # as the first non-whitespace character is\n is treated as a comment. The *r* values must monotonically increase and be equally spaced. The table is read\n directly into the grid points used to evaluate :math:`F_{\\mathrm{user}}(r)` and :math:`_{\\mathrm{user}}(r)`.\n \"\"\"\n hoomd.util.print_status_line();\n\n # open the file\n f = open(filename);\n\n r_table = [];\n V_table = [];\n F_table = [];\n\n # read in lines from the file\n for line in f.readlines():\n line = line.strip();\n\n # skip comment lines\n if line[0] == '#':\n continue;\n\n # split out the columns\n cols = line.split();\n values = [float(f) for f in cols];\n\n # validate the input\n if len(values) != 3:\n hoomd.context.msg.error(\"pair.table: file must have exactly 3 columns\\n\");\n raise RuntimeError(\"Error reading table file\");\n\n # append to the tables\n r_table.append(values[0]);\n V_table.append(values[1]);\n F_table.append(values[2]);\n\n # validate input\n if self.width != len(r_table):\n hoomd.context.msg.error(\"pair.table: file must have exactly \" + str(self.width) + \" rows\\n\");\n raise RuntimeError(\"Error reading table file\");\n\n # extract rmin and rmax\n rmin_table = r_table[0];\n rmax_table = r_table[-1];\n\n # check for even spacing\n dr = (rmax_table - rmin_table) / float(self.width-1);\n for i in range(0,self.width):\n r = rmin_table + dr * i;\n if math.fabs(r - r_table[i]) > 1e-3:\n hoomd.context.msg.error(\"pair.table: r must be monotonically increasing and evenly spaced\\n\");\n raise RuntimeError(\"Error reading table file\");\n\n hoomd.util.quiet_status();\n self.pair_coeff.set(a, b, func=_table_eval, rmin=rmin_table, rmax=rmax_table, coeff=dict(V=V_table, F=F_table, width=self.width))\n hoomd.util.unquiet_status();\n\nclass morse(pair):\n R\"\"\" Morse pair potential.\n\n :py:class:`morse` specifies that a Morse pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{morse}}(r) = & D_0 \\left[ \\exp \\left(-2\\alpha\\left(r-r_0\\right)\\right) -2\\exp \\left(-\\alpha\\left(r-r_0\\right)\\right) \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`D_0` - *D0*, depth of the potential at its minimum (in energy units)\n - :math:`\\alpha` - *alpha*, controls the width of the potential well (in units of 1/distance)\n - :math:`r_0` - *r0*, position of the minimum (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n morse = pair.morse(r_cut=3.0, nlist=nl)\n morse.pair_coeff.set('A', 'A', D0=1.0, alpha=3.0, r0=1.0)\n morse.pair_coeff.set('A', 'B', D0=1.0, alpha=3.0, r0=1.0, r_cut=3.0, r_on=2.0);\n morse.pair_coeff.set(['A', 'B'], ['C', 'D'], D0=1.0, alpha=3.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairMorse(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMorse;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairMorseGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMorseGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['D0', 'alpha', 'r0'];\n\n def process_coeff(self, coeff):\n D0 = coeff['D0'];\n alpha = coeff['alpha'];\n r0 = coeff['r0']\n\n return _hoomd.make_scalar4(D0, alpha, r0, 0.0);\n\nclass dpd(pair):\n R\"\"\" Dissipative Particle Dynamics.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n kT (:py:mod:`hoomd.variant` or :py:obj:`float`): Temperature of thermostat (in energy units).\n seed (int): seed for the PRNG in the DPD thermostat.\n name (str): Name of the force instance.\n\n :py:class:`dpd` specifies that a DPD pair force should be applied between every\n non-excluded particle pair in the simulation, including an interaction potential,\n pairwise drag force, and pairwise random force. See `Groot and Warren 1997 `_.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n F = F_{\\mathrm{C}}(r) + F_{\\mathrm{R,ij}}(r_{ij}) + F_{\\mathrm{D,ij}}(v_{ij}) \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n F_{\\mathrm{C}}(r) = & A \\cdot w(r_{ij}) \\\\\n F_{\\mathrm{R, ij}}(r_{ij}) = & - \\theta_{ij}\\sqrt{3} \\sqrt{\\frac{2k_b\\gamma T}{\\Delta t}}\\cdot w(r_{ij}) \\\\\n F_{\\mathrm{D, ij}}(r_{ij}) = & - \\gamma w^2(r_{ij})\\left( \\hat r_{ij} \\circ v_{ij} \\right) \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n w(r_{ij}) = &\\left( 1 - r/r_{\\mathrm{cut}} \\right) & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n where :math:`\\hat r_{ij}` is a normalized vector from particle i to particle j, :math:`v_{ij} = v_i - v_j`,\n and :math:`\\theta_{ij}` is a uniformly distributed random number in the range [-1, 1].\n\n :py:class:`dpd` generates random numbers by hashing together the particle tags in the pair, the user seed,\n and the current time step index.\n\n .. attention::\n\n Change the seed if you reset the simulation time step to 0. If you keep the same seed, the simulation\n will continue with the same sequence of random numbers used previously and may cause unphysical correlations.\n\n For MPI runs: all ranks other than 0 ignore the seed input and use the value of rank 0.\n\n `C. L. Phillips et. al. 2011 `_ describes the DPD implementation\n details in HOOMD-blue. Cite it if you utilize the DPD functionality in your work.\n\n :py:class:`dpd` does not implement and energy shift / smoothing modes due to the function of the force.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`A` - *A* (in force units)\n - :math:`\\gamma` - *gamma* (in units of force/velocity)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n To use the DPD thermostat, an :py:class:`hoomd.md.integrate.nve` integrator must be applied to the system and\n the user must specify a temperature. Use of the dpd thermostat pair force with other integrators will result\n in unphysical behavior. To use pair.dpd with a different conservative potential than :math:`F_C`,\n set A to zero and define the conservative pair potential separately. Note that DPD thermostats\n are often defined in terms of :math:`\\sigma` where :math:`\\sigma = \\sqrt{2k_b\\gamma T}`.\n\n Example::\n\n nl = nlist.cell()\n dpd = pair.dpd(r_cut=1.0, nlist=nl, kT=1.0, seed=0)\n dpd.pair_coeff.set('A', 'A', A=25.0, gamma = 4.5)\n dpd.pair_coeff.set('A', 'B', A=40.0, gamma = 4.5)\n dpd.pair_coeff.set('B', 'B', A=25.0, gamma = 4.5)\n dpd.pair_coeff.set(['A', 'B'], ['C', 'D'], A=12.0, gamma = 1.2)\n dpd.set_params(kT = 1.0)\n integrate.mode_standard(dt=0.02)\n integrate.nve(group=group.all())\n\n \"\"\"\n def __init__(self, r_cut, nlist, kT, seed, name=None):\n hoomd.util.print_status_line();\n\n # register the citation\n c = hoomd.cite.article(cite_key='phillips2011',\n author=['C L Phillips', 'J A Anderson', 'S C Glotzer'],\n title='Pseudo-random number generation for Brownian Dynamics and Dissipative Particle Dynamics simulations on GPU devices',\n journal='Journal of Computational Physics',\n volume=230,\n number=19,\n pages='7191--7201',\n month='Aug',\n year='2011',\n doi='10.1016/j.jcp.2011.05.021',\n feature='DPD')\n hoomd.cite._ensure_global_bib().add(c)\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairDPDThermoDPD(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDThermoDPD;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairDPDThermoDPDGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDThermoDPDGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['A', 'gamma'];\n\n # set the seed for dpd thermostat\n self.cpp_force.setSeed(seed);\n\n # set the temperature\n # setup the variant inputs\n kT = hoomd.variant._setup_variant_input(kT);\n self.cpp_force.setT(kT.cpp_variant);\n\n def set_params(self, kT=None):\n R\"\"\" Changes parameters.\n\n Args:\n kT (:py:mod:`hoomd.variant` or :py:obj:`float`): Temperature of thermostat (in energy units).\n\n Example::\n\n dpd.set_params(kT=2.0)\n \"\"\"\n hoomd.util.print_status_line();\n self.check_initialization();\n\n # change the parameters\n if kT is not None:\n # setup the variant inputs\n kT = hoomd.variant._setup_variant_input(kT);\n self.cpp_force.setT(kT.cpp_variant);\n\n def process_coeff(self, coeff):\n a = coeff['A'];\n gamma = coeff['gamma'];\n return _hoomd.make_scalar2(a, gamma);\n\nclass dpd_conservative(pair):\n R\"\"\" DPD Conservative pair force.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`dpd_conservative` specifies the conservative part of the DPD pair potential should be applied between\n every non-excluded particle pair in the simulation. No thermostat (e.g. Drag Force and Random Force) is applied,\n as is in :py:class:`dpd`.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{DPD-C}}(r) = & A \\cdot \\left( r_{\\mathrm{cut}} - r \\right)\n - \\frac{1}{2} \\cdot \\frac{A}{r_{\\mathrm{cut}}} \\cdot \\left(r_{\\mathrm{cut}}^2 - r^2 \\right)\n & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n\n :py:class:`dpd_conservative` does not implement and energy shift / smoothing modes due to the function of the force.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`A` - *A* (in force units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n dpdc = pair.dpd_conservative(r_cut=3.0, nlist=nl)\n dpdc.pair_coeff.set('A', 'A', A=1.0)\n dpdc.pair_coeff.set('A', 'B', A=2.0, r_cut = 1.0)\n dpdc.pair_coeff.set('B', 'B', A=1.0)\n dpdc.pair_coeff.set(['A', 'B'], ['C', 'D'], A=5.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # register the citation\n c = hoomd.cite.article(cite_key='phillips2011',\n author=['C L Phillips', 'J A Anderson', 'S C Glotzer'],\n title='Pseudo-random number generation for Brownian Dynamics and Dissipative Particle Dynamics simulations on GPU devices',\n journal='Journal of Computational Physics',\n volume=230,\n number=19,\n pages='7191--7201',\n month='Aug',\n year='2011',\n doi='10.1016/j.jcp.2011.05.021',\n feature='DPD')\n hoomd.cite._ensure_global_bib().add(c)\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairDPD(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPD;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairDPDGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['A'];\n\n\n def process_coeff(self, coeff):\n a = coeff['A'];\n gamma = 0;\n return _hoomd.make_scalar2(a, gamma);\n\n def set_params(self, coeff):\n \"\"\" :py:class:`dpd_conservative` has no energy shift modes \"\"\"\n\n raise RuntimeError('Not implemented for DPD Conservative');\n return;\n\nclass dpdlj(pair):\n R\"\"\" Dissipative Particle Dynamics with a LJ conservative force\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n kT (:py:mod:`hoomd.variant` or :py:obj:`float`): Temperature of thermostat (in energy units).\n seed (int): seed for the PRNG in the DPD thermostat.\n name (str): Name of the force instance.\n\n :py:class:`dpdlj` specifies that a DPD thermostat and a Lennard-Jones pair potential should be applied between\n every non-excluded particle pair in the simulation.\n\n `C. L. Phillips et. al. 2011 `_ describes the DPD implementation\n details in HOOMD-blue. Cite it if you utilize the DPD functionality in your work.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n F = F_{\\mathrm{C}}(r) + F_{\\mathrm{R,ij}}(r_{ij}) + F_{\\mathrm{D,ij}}(v_{ij}) \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n F_{\\mathrm{C}}(r) = & \\partial V_{\\mathrm{LJ}} / \\partial r \\\\\n F_{\\mathrm{R, ij}}(r_{ij}) = & - \\theta_{ij}\\sqrt{3} \\sqrt{\\frac{2k_b\\gamma T}{\\Delta t}}\\cdot w(r_{ij}) \\\\\n F_{\\mathrm{D, ij}}(r_{ij}) = & - \\gamma w^2(r_{ij})\\left( \\hat r_{ij} \\circ v_{ij} \\right) \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{LJ}}(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} -\n \\alpha \\left( \\frac{\\sigma}{r} \\right)^{6} \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n w(r_{ij}) = &\\left( 1 - r/r_{\\mathrm{cut}} \\right) & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n where :math:`\\hat r_{ij}` is a normalized vector from particle i to particle j, :math:`v_{ij} = v_i - v_j`,\n and :math:`\\theta_{ij}` is a uniformly distributed random number in the range [-1, 1].\n\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`\\alpha` - *alpha* (unitless)\n - *optional*: defaults to 1.0\n - :math:`\\gamma` - *gamma* (in units of force/velocity)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n To use the DPD thermostat, an :py:class:`hoomd.md.integrate.nve` integrator must be applied to the system and\n the user must specify a temperature. Use of the dpd thermostat pair force with other integrators will result\n in unphysical behavior.\n\n Example::\n\n nl = nlist.cell()\n dpdlj = pair.dpdlj(r_cut=2.5, nlist=nl, kT=1.0, seed=0)\n dpdlj.pair_coeff.set('A', 'A', epsilon=1.0, sigma = 1.0, gamma = 4.5)\n dpdlj.pair_coeff.set('A', 'B', epsilon=0.0, sigma = 1.0 gamma = 4.5)\n dpdlj.pair_coeff.set('B', 'B', epsilon=1.0, sigma = 1.0 gamma = 4.5, r_cut = 2.0**(1.0/6.0))\n dpdlj.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon = 3.0,sigma=1.0, gamma = 1.2)\n dpdlj.set_params(T = 1.0)\n integrate.mode_standard(dt=0.005)\n integrate.nve(group=group.all())\n\n \"\"\"\n\n def __init__(self, r_cut, nlist, kT, seed, name=None):\n hoomd.util.print_status_line();\n\n # register the citation\n c = hoomd.cite.article(cite_key='phillips2011',\n author=['C L Phillips', 'J A Anderson', 'S C Glotzer'],\n title='Pseudo-random number generation for Brownian Dynamics and Dissipative Particle Dynamics simulations on GPU devices',\n journal='Journal of Computational Physics',\n volume=230,\n number=19,\n pages='7191--7201',\n month='Aug',\n year='2011',\n doi='10.1016/j.jcp.2011.05.021',\n feature='DPD')\n hoomd.cite._ensure_global_bib().add(c)\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairDPDLJThermoDPD(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDLJThermoDPD;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairDPDLJThermoDPDGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDPDLJThermoDPDGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon','sigma', 'alpha', 'gamma'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n\n # set the seed for dpdlj thermostat\n self.cpp_force.setSeed(seed);\n\n # set the temperature\n # setup the variant inputs\n kT = hoomd.variant._setup_variant_input(kT);\n self.cpp_force.setT(kT.cpp_variant);\n\n def set_params(self, kT=None, mode=None):\n R\"\"\" Changes parameters.\n\n Args:\n T (:py:mod:`hoomd.variant` or :py:obj:`float`): Temperature (if set) (in energy units)\n mode (str): energy shift/smoothing mode (default noshift).\n\n Examples::\n\n dpdlj.set_params(kT=variant.linear_interp(points = [(0, 1.0), (1e5, 2.0)]))\n dpdlj.set_params(kT=2.0, mode=\"shift\")\n\n \"\"\"\n hoomd.util.print_status_line();\n self.check_initialization();\n\n # change the parameters\n if kT is not None:\n # setup the variant inputs\n kT = hoomd.variant._setup_variant_input(kT);\n self.cpp_force.setT(kT.cpp_variant);\n\n if mode is not None:\n if mode == \"xplor\":\n hoomd.context.msg.error(\"XPLOR is smoothing is not supported with pair.dpdlj\\n\");\n raise RuntimeError(\"Error changing parameters in pair force\");\n\n #use the inherited set_params\n pair.set_params(self, mode=mode)\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n gamma = coeff['gamma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 6.0);\n return _hoomd.make_scalar4(lj1, lj2, gamma, 0.0);\n\nclass force_shifted_lj(pair):\n R\"\"\" Force-shifted Lennard-Jones pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`force_shifted_lj` specifies that a modified Lennard-Jones pair force should be applied between\n non-excluded particle pair in the simulation. The force differs from the one calculated by :py:class:`lj`\n by the subtraction of the value of the force at :math:`r_{\\mathrm{cut}}`, such that the force smoothly goes\n to zero at the cut-off. The potential is modified by a linear function. This potential can be used as a substitute\n for :py:class:`lj`, when the exact analytical form of the latter is not required but a smaller cut-off radius is\n desired for computational efficiency. See `Toxvaerd et. al. 2011 `_\n for a discussion of this potential.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} -\n \\alpha \\left( \\frac{\\sigma}{r} \\right)^{6} \\right] + \\Delta V(r) & r < r_{\\mathrm{cut}}\\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n .. math::\n\n \\Delta V(r) = -(r - r_{\\mathrm{cut}}) \\frac{\\partial V_{\\mathrm{LJ}}}{\\partial r}(r_{\\mathrm{cut}})\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`\\alpha` - *alpha* (unitless) - *optional*: defaults to 1.0\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n fslj = pair.force_shifted_lj(r_cut=1.5, nlist=nl)\n fslj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairForceShiftedLJ(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairForceShiftedLJ;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairForceShiftedLJGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairForceShiftedLJGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'alpha'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 6.0);\n return _hoomd.make_scalar2(lj1, lj2);\n\nclass moliere(pair):\n R\"\"\" Moliere pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`moliere` specifies that a Moliere type pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{Moliere}}(r) = & \\frac{Z_i Z_j e^2}{4 \\pi \\epsilon_0 r_{ij}} \\left[ 0.35 \\exp \\left( -0.3 \\frac{r_{ij}}{a_F} \\right) + 0.55 \\exp \\left( -1.2 \\frac{r_{ij}}{a_F} \\right) + 0.10 \\exp \\left( -6.0 \\frac{r_{ij}}{a_F} \\right) \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r > r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`Z_i` - *Z_i* - Atomic number of species i (unitless)\n - :math:`Z_j` - *Z_j* - Atomic number of species j (unitless)\n - :math:`e` - *elementary_charge* - The elementary charge (in charge units)\n - :math:`a_0` - *a_0* - The Bohr radius (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n moliere = pair.moliere(r_cut = 3.0, nlist=nl)\n moliere.pair_coeff.set('A', 'B', Z_i = 54.0, Z_j = 7.0, elementary_charge = 1.0, a_0 = 1.0);\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairMoliere(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMoliere;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairMoliereGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMoliereGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['Z_i', 'Z_j', 'elementary_charge', 'a_0'];\n self.pair_coeff.set_default_coeff('elementary_charge', 1.0);\n self.pair_coeff.set_default_coeff('a_0', 1.0);\n\n def process_coeff(self, coeff):\n Z_i = coeff['Z_i'];\n Z_j = coeff['Z_j'];\n elementary_charge = coeff['elementary_charge'];\n a_0 = coeff['a_0'];\n\n Zsq = Z_i * Z_j * elementary_charge * elementary_charge;\n if (not (Z_i == 0)) or (not (Z_j == 0)):\n aF = 0.8853 * a_0 / math.pow(math.sqrt(Z_i) + math.sqrt(Z_j), 2.0 / 3.0);\n else:\n aF = 1.0;\n return _hoomd.make_scalar2(Zsq, aF);\n\nclass zbl(pair):\n R\"\"\" ZBL pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`zbl` specifies that a Ziegler-Biersack-Littmark pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{ZBL}}(r) = & \\frac{Z_i Z_j e^2}{4 \\pi \\epsilon_0 r_{ij}} \\left[ 0.1818 \\exp \\left( -3.2 \\frac{r_{ij}}{a_F} \\right) + 0.5099 \\exp \\left( -0.9423 \\frac{r_{ij}}{a_F} \\right) + 0.2802 \\exp \\left( -0.4029 \\frac{r_{ij}}{a_F} \\right) + 0.02817 \\exp \\left( -0.2016 \\frac{r_{ij}}{a_F} \\right) \\right], & r < r_{\\mathrm{cut}} \\\\\n = & 0, & r > r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`Z_i` - *Z_i* - Atomic number of species i (unitless)\n - :math:`Z_j` - *Z_j* - Atomic number of species j (unitless)\n - :math:`e` - *elementary_charge* - The elementary charge (in charge units)\n - :math:`a_0` - *a_0* - The Bohr radius (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n zbl = pair.zbl(r_cut = 3.0, nlist=nl)\n zbl.pair_coeff.set('A', 'B', Z_i = 54.0, Z_j = 7.0, elementary_charge = 1.0, a_0 = 1.0);\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairZBL(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairZBL;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairZBLGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairZBLGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['Z_i', 'Z_j', 'elementary_charge', 'a_0'];\n self.pair_coeff.set_default_coeff('elementary_charge', 1.0);\n self.pair_coeff.set_default_coeff('a_0', 1.0);\n\n def process_coeff(self, coeff):\n Z_i = coeff['Z_i'];\n Z_j = coeff['Z_j'];\n elementary_charge = coeff['elementary_charge'];\n a_0 = coeff['a_0'];\n\n Zsq = Z_i * Z_j * elementary_charge * elementary_charge;\n if (not (Z_i == 0)) or (not (Z_j == 0)):\n aF = 0.88534 * a_0 / ( math.pow( Z_i, 0.23 ) + math.pow( Z_j, 0.23 ) );\n else:\n aF = 1.0;\n return _hoomd.make_scalar2(Zsq, aF);\n\n def set_params(self, coeff):\n \"\"\" :py:class:`zbl` has no energy shift modes \"\"\"\n\n raise RuntimeError('Not implemented for DPD Conservative');\n return;\n\nclass tersoff(pair):\n R\"\"\" Tersoff Potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`tersoff` specifies that the Tersoff three-body potential should be applied to every\n non-bonded particle pair in the simulation. Despite the fact that the Tersoff potential accounts\n for the effects of third bodies, it is included in the pair potentials because the species of the\n third body is irrelevant. It can thus use type-pair parameters similar to those of the pair potentials.\n\n The Tersoff potential is a bond-order potential based on the Morse potential that accounts for the weakening of\n individual bonds with increasing coordination number. It does this by computing a modifier to the\n attractive term of the potential. The modifier contains the effects of third-bodies on the bond\n energies. The potential also includes a smoothing function around the cutoff. The smoothing function\n used in this work is exponential in nature as opposed to the sinusoid used by Tersoff. The exponential\n function provides continuity up (I believe) the second derivative.\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # this potential cannot handle a half neighbor list\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialTersoff(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialTersoff;\n else:\n self.cpp_force = _md.PotentialTersoffGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialTersoffGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficients\n self.required_coeffs = ['cutoff_thickness', 'C1', 'C2', 'lambda1', 'lambda2', 'dimer_r', 'n', 'gamma', 'lambda3', 'c', 'd', 'm', 'alpha']\n self.pair_coeff.set_default_coeff('cutoff_thickness', 0.2);\n self.pair_coeff.set_default_coeff('dimer_r', 1.5);\n self.pair_coeff.set_default_coeff('C1', 1.0);\n self.pair_coeff.set_default_coeff('C2', 1.0);\n self.pair_coeff.set_default_coeff('lambda1', 2.0);\n self.pair_coeff.set_default_coeff('lambda2', 1.0);\n self.pair_coeff.set_default_coeff('lambda3', 0.0);\n self.pair_coeff.set_default_coeff('n', 0.0);\n self.pair_coeff.set_default_coeff('m', 0.0);\n self.pair_coeff.set_default_coeff('c', 0.0);\n self.pair_coeff.set_default_coeff('d', 1.0);\n self.pair_coeff.set_default_coeff('gamma', 0.0);\n self.pair_coeff.set_default_coeff('alpha', 3.0);\n\n def process_coeff(self, coeff):\n cutoff_d = coeff['cutoff_thickness'];\n C1 = coeff['C1'];\n C2 = coeff['C2'];\n lambda1 = coeff['lambda1'];\n lambda2 = coeff['lambda2'];\n dimer_r = coeff['dimer_r'];\n n = coeff['n'];\n gamma = coeff['gamma'];\n lambda3 = coeff['lambda3'];\n c = coeff['c'];\n d = coeff['d'];\n m = coeff['m'];\n alpha = coeff['alpha'];\n\n gamman = math.pow(gamma, n);\n c2 = c * c;\n d2 = d * d;\n lambda3_cube = lambda3 * lambda3 * lambda3;\n\n tersoff_coeffs = _hoomd.make_scalar2(C1, C2);\n exp_consts = _hoomd.make_scalar2(lambda1, lambda2);\n ang_consts = _hoomd.make_scalar3(c2, d2, m);\n\n return _md.make_tersoff_params(cutoff_d, tersoff_coeffs, exp_consts, dimer_r, n, gamman, lambda3_cube, ang_consts, alpha);\n\n\nclass revcross(pair):\n R\"\"\" Reversible crosslinker three-body potential to model bond swaps.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`revcross` specifies that the revcross three-body potential should be applied to every\n non-bonded particle pair in the simulation. Despite the fact that the revcross potential accounts\n for the effects of third bodies, it is included in the pair potentials because its is actually just a\n combination of two body potential terms. It can thus use type-pair parameters similar to those of the pair potentials.\n\n The revcross potential has been described in detail in `S. Ciarella and W.G. Ellenbroek 2019 `_. It is based on a generalized-Lennard-Jones pairwise\n attraction to form bonds between interacting particless:\n\n .. math::\n :nowrap:\n\n \\begin{equation}\n V_{ij}(r) = 4 \\varepsilon \\left[ \\left( \\dfrac{ \\sigma}{r_{ij}} \\right) ^{2n}- \\left( \\dfrac{ \\sigma}{r_{ij}} \\right)^{n} \\right] \\qquad r r_{min}~.\\\\\n \\end{cases}\n \\end{equation}\n\n .. attention::\n\n The revcross potential models an asymmetric interaction between two different chemical moieties that can form a reversible bond. \n\tThis requires the definition of (at least) two different types of particles.\n\tA reversible bond is only possible between two different species, otherwise :math:` v^{\\left( 3b \\right)}_{ijk}` would prevent any bond.\n\tIn our example we then set the interactions for types A and B with ``potRevC.pair_coeff.set(['A','B'],['A','B'],sigma=0.0,n=0,epsilon=0,lambda3=0)`` and the only non-zero energy only between the different types ``potRevC.pair_coeff.set('A','B',sigma=1,n=100,epsilon=100,lambda3=1) ``. \n\tNotice that the number of the minoritary species corresponds to the maximum number of bonds.\n \n\n This three-body term also tunes the energy required for a bond swap through the coefficient: \n - :math:`\\lambda` - *lambda3* (unitless)\n in `S. Ciarella and W.G. Ellenbroek 2019 `_ is explained that setting :math:`\\lambda=1` corresponds to no energy requirement to initiate bond swap, while this\n energy barrier scales roughly as :math:`\\beta \\Delta E_\\text{sw} =\\beta \\varepsilon(\\lambda-1)`.\n\n Note:\n\n Choosing :math:`\\lambda=1` pushes the system towards clusterization because the three-body term is not enough to\n compensate the energy of multiple bonds, so it may cause unphysical situations. \n \n\n Example::\n\n nl = md.nlist.cell()\n potBondSwap = md.pair.revcross(r_cut=1.3,nlist=nl)\n potBondSwap.pair_coeff.set(['A','B'],['A','B'],sigma=0,n=0,epsilon=0,lambda3=0)\n\t# a bond can be made only between A-B and not A-A or B-B\n potBondSwap.pair_coeff.set('A','B',sigma=1,n=100,epsilon=10,lambda3=1)\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # this potential cannot handle a half neighbor list\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialRevCross(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialRevCross;\n else:\n self.cpp_force = _md.PotentialRevCrossGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialRevCrossGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficients\n self.required_coeffs = ['sigma', 'n', 'epsilon', 'lambda3']\n self.pair_coeff.set_default_coeff('sigma', 2.);\n self.pair_coeff.set_default_coeff('n', 1.0);\n self.pair_coeff.set_default_coeff('epsilon', 1.0);\n self.pair_coeff.set_default_coeff('lambda3', 1.0);\n\n def process_coeff(self, coeff):\n sigma = coeff['sigma'];\n n = coeff['n'];\n epsilon = coeff['epsilon'];\n lambda3 = coeff['lambda3'];\n\n return _md.make_revcross_params(sigma, n, epsilon, lambda3);\n\n\n\nclass mie(pair):\n R\"\"\" Mie pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`mie` specifies that a Mie pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{mie}}(r) = & \\left( \\frac{n}{n-m} \\right) {\\left( \\frac{n}{m} \\right)}^{\\frac{m}{n-m}} \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{n} -\n \\left( \\frac{\\sigma}{r} \\right)^{m} \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`n` - *n* (unitless)\n - :math:`m` - *m* (unitless)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n mie = pair.mie(r_cut=3.0, nlist=nl)\n mie.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0, n=12, m=6)\n mie.pair_coeff.set('A', 'B', epsilon=2.0, sigma=1.0, n=14, m=7, r_cut=3.0, r_on=2.0);\n mie.pair_coeff.set('B', 'B', epsilon=1.0, sigma=1.0, n=15.1, m=6.5, r_cut=2**(1.0/6.0), r_on=2.0);\n mie.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=1.5, sigma=2.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairMie(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMie;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairMieGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairMieGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'n', 'm'];\n\n def process_coeff(self, coeff):\n epsilon = float(coeff['epsilon']);\n sigma = float(coeff['sigma']);\n n = float(coeff['n']);\n m = float(coeff['m']);\n\n mie1 = epsilon * math.pow(sigma, n) * (n/(n-m)) * math.pow(n/m,m/(n-m));\n mie2 = epsilon * math.pow(sigma, m) * (n/(n-m)) * math.pow(n/m,m/(n-m));\n mie3 = n\n mie4 = m\n return _hoomd.make_scalar4(mie1, mie2, mie3, mie4);\n\n\nclass _shape_dict(dict):\n \"\"\"Simple dictionary subclass to improve handling of anisotropic potential\n shape information.\"\"\"\n def __getitem__(self, key):\n try:\n return super(_shape_dict, self).__getitem__(key)\n except KeyError as e:\n raise KeyError(\"No shape parameters specified for particle type {}!\".format(key)) from e\n\n\nclass ai_pair(pair):\n R\"\"\"Generic anisotropic pair potential.\n\n Users should not instantiate :py:class:`ai_pair` directly. It is a base class that\n provides common features to all anisotropic pair forces. Rather than repeating all of that documentation in a\n dozen different places, it is collected here.\n\n All anisotropic pair potential commands specify that a given potential energy, force and torque be computed\n on all non-excluded particle pairs in the system within a short range cutoff distance :math:`r_{\\mathrm{cut}}`.\n The interaction energy, forces and torque depend on the inter-particle separation\n :math:`\\vec r` and on the orientations :math:`\\vec q_i`, :math:`q_j`, of the particles.\n \"\"\"\n\n ## \\internal\n # \\brief Initialize the pair force\n # \\details\n # The derived class must set\n # - self.cpp_class (the pair class to instantiate)\n # - self.required_coeffs (a list of the coeff names the derived class needs)\n # - self.process_coeffs() (a method that takes in the coeffs and spits out a param struct to use in\n # self.cpp_force.set_params())\n def __init__(self, r_cut, nlist, name=None):\n # initialize the base class\n force._force.__init__(self, name);\n\n self.global_r_cut = r_cut;\n\n # setup the coefficient matrix\n self.pair_coeff = coeff();\n self.pair_coeff.set_default_coeff('r_cut', self.global_r_cut);\n\n # setup the neighbor list\n self.nlist = nlist\n self.nlist.subscribe(lambda:self.get_rcut())\n self.nlist.update_rcut()\n\n self._shape = _shape_dict()\n\n def set_params(self, mode=None):\n R\"\"\"Set parameters controlling the way forces are computed.\n\n Args:\n mode (str): (if set) Set the mode with which potentials are handled at the cutoff\n\n valid values for mode are: \"none\" (the default) and \"shift\":\n\n - *none* - No shifting is performed and potentials are abruptly cut off\n - *shift* - A constant shift is applied to the entire potential so that it is 0 at the cutoff\n\n Examples::\n\n mypair.set_params(mode=\"shift\")\n mypair.set_params(mode=\"no_shift\")\n\n \"\"\"\n hoomd.util.print_status_line();\n\n if mode is not None:\n if mode == \"no_shift\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.no_shift)\n elif mode == \"shift\":\n self.cpp_force.setShiftMode(self.cpp_class.energyShiftMode.shift)\n else:\n hoomd.context.msg.error(\"Invalid mode\\n\");\n raise RuntimeError(\"Error changing parameters in pair force\");\n\n @property\n def shape(self):\n R\"\"\"Get or set shape parameters per type.\n\n In addition to any pair-specific parameters required to characterize a\n pair potential, individual particles that have anisotropic interactions\n may also have their own shapes that affect the potentials. General\n anisotropic pair potentials may set per-particle shapes using this\n method.\n \"\"\"\n return self._shape\n\n def update_coeffs(self):\n coeff_list = self.required_coeffs + [\"r_cut\"];\n # check that the pair coefficients are valid\n if not self.pair_coeff.verify(coeff_list):\n hoomd.context.msg.error(\"Not all pair coefficients are set\\n\");\n raise RuntimeError(\"Error updating pair coefficients\");\n\n # set all the params\n ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes();\n type_list = [];\n for i in range(0,ntypes):\n type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i));\n\n for i in range(0,ntypes):\n self._set_cpp_shape(i, type_list[i])\n\n for j in range(i,ntypes):\n # build a dict of the coeffs to pass to process_coeff\n coeff_dict = {}\n for name in coeff_list:\n coeff_dict[name] = self.pair_coeff.get(type_list[i], type_list[j], name);\n\n param = self.process_coeff(coeff_dict);\n self.cpp_force.setParams(i, j, param);\n self.cpp_force.setRcut(i, j, coeff_dict['r_cut']);\n\n def _set_cpp_shape(self, type_id, type_name):\n \"\"\"Update shape information in C++.\n\n This method must be implemented by subclasses to generate the\n appropriate shape structure. The default behavior is to do nothing.\"\"\"\n pass\n\nclass gb(ai_pair):\n R\"\"\" Gay-Berne anisotropic pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`gb` computes the Gay-Berne potential between anisotropic particles.\n\n This version of the Gay-Berne potential supports identical pairs of uniaxial ellipsoids,\n with orientation-independent energy-well depth.\n\n The interaction energy for this anisotropic pair potential is\n (`Allen et. al. 2006 `_):\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{GB}}(\\vec r, \\vec e_i, \\vec e_j) = & 4 \\varepsilon \\left[ \\zeta^{-12} -\n \\zeta^{-6} \\right] & \\zeta < \\zeta_{\\mathrm{cut}} \\\\\n = & 0 & \\zeta \\ge \\zeta_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n .. math::\n\n \\zeta = \\left(\\frac{r-\\sigma+\\sigma_{\\mathrm{min}}}{\\sigma_{\\mathrm{min}}}\\right)\n\n \\sigma^{-2} = \\frac{1}{2} \\hat{\\vec{r}}\\cdot\\vec{H^{-1}}\\cdot\\hat{\\vec{r}}\n\n \\vec{H} = 2 \\ell_\\perp^2 \\vec{1} + (\\ell_\\parallel^2 - \\ell_\\perp^2) (\\vec{e_i} \\otimes \\vec{e_i} + \\vec{e_j} \\otimes \\vec{e_j})\n\n with :math:`\\sigma_{\\mathrm{min}} = 2 \\min(\\ell_\\perp, \\ell_\\parallel)`.\n\n The cut-off parameter :math:`r_{\\mathrm{cut}}` is defined for two particles oriented parallel along\n the **long** axis, i.e.\n :math:`\\zeta_{\\mathrm{cut}} = \\left(\\frac{r-\\sigma_{\\mathrm{max}} + \\sigma_{\\mathrm{min}}}{\\sigma_{\\mathrm{min}}}\\right)`\n where :math:`\\sigma_{\\mathrm{max}} = 2 \\max(\\ell_\\perp, \\ell_\\parallel)` .\n\n The quantities :math:`\\ell_\\parallel` and :math:`\\ell_\\perp` denote the semi-axis lengths parallel\n and perpendicular to particle orientation.\n\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\ell_\\perp` - *lperp* (in distance units)\n - :math:`\\ell_\\parallel` - *lpar* (in distance units)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n gb = pair.gb(r_cut=2.5, nlist=nl)\n gb.pair_coeff.set('A', 'A', epsilon=1.0, lperp=0.45, lpar=0.5)\n gb.pair_coeff.set('A', 'B', epsilon=2.0, lperp=0.45, lpar=0.5, r_cut=2**(1.0/6.0));\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n ai_pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.AnisoPotentialPairGB(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.AnisoPotentialPairGB;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.AnisoPotentialPairGBGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.AnisoPotentialPairGBGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'lperp', 'lpar'];\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n lperp = coeff['lperp'];\n lpar = coeff['lpar'];\n\n return _md.make_pair_gb_params(epsilon, lperp, lpar);\n\n def get_type_shapes(self):\n \"\"\"Get all the types of shapes in the current simulation.\n\n Example:\n\n >>> my_gb.get_type_shapes()\n [{'type': 'Ellipsoid', 'a': 1.0, 'b': 1.0, 'c': 1.5}]\n\n Returns:\n A list of dictionaries, one for each particle type in the system.\n \"\"\"\n return super(ai_pair, self)._return_type_shapes();\n\nclass dipole(ai_pair):\n R\"\"\" Screened dipole-dipole interactions.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`dipole` computes the (screened) interaction between pairs of\n particles with dipoles and electrostatic charges. The total energy\n computed is:\n\n .. math::\n\n U_{dipole} = U_{dd} + U_{de} + U_{ee}\n\n U_{dd} = A e^{-\\kappa r} \\left(\\frac{\\vec{\\mu_i}\\cdot\\vec{\\mu_j}}{r^3} - 3\\frac{(\\vec{\\mu_i}\\cdot \\vec{r_{ji}})(\\vec{\\mu_j}\\cdot \\vec{r_{ji}})}{r^5}\\right)\n\n U_{de} = A e^{-\\kappa r} \\left(\\frac{(\\vec{\\mu_j}\\cdot \\vec{r_{ji}})q_i}{r^3} - \\frac{(\\vec{\\mu_i}\\cdot \\vec{r_{ji}})q_j}{r^3}\\right)\n\n U_{ee} = A e^{-\\kappa r} \\frac{q_i q_j}{r}\n\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n :py:class:`dipole` does not implement and energy shift / smoothing modes due to the function of the force.\n\n The following coefficients must be set per unique pair of particle types:\n\n - mu - magnitude of :math:`\\vec{\\mu} = \\mu (1, 0, 0)` in the particle local reference frame\n - A - electrostatic energy scale :math:`A` (default value 1.0)\n - kappa - inverse screening length :math:`\\kappa`\n\n Example::\n\n # A/A interact only with screened electrostatics\n dipole.pair_coeff.set('A', 'A', mu=0.0, A=1.0, kappa=1.0)\n dipole.pair_coeff.set('A', 'B', mu=0.5, kappa=1.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n ## tell the base class how we operate\n\n # initialize the base class\n ai_pair.__init__(self, r_cut, nlist, name);\n\n ## create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.AnisoPotentialPairDipole(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.AnisoPotentialPairDipole;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.AnisoPotentialPairDipoleGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.AnisoPotentialPairDipoleGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n ## setup the coefficient options\n self.required_coeffs = ['mu', 'A', 'kappa'];\n\n self.pair_coeff.set_default_coeff('A', 1.0)\n\n def process_coeff(self, coeff):\n mu = float(coeff['mu']);\n A = float(coeff['A']);\n kappa = float(coeff['kappa']);\n\n return _md.make_pair_dipole_params(mu, A, kappa);\n\n def set_params(self, *args, **kwargs):\n \"\"\" :py:class:`dipole` has no energy shift modes \"\"\"\n\n raise RuntimeError('Not implemented for dipole');\n return;\n\n\nclass reaction_field(pair):\n R\"\"\" Onsager reaction field pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`reaction_field` specifies that an Onsager reaction field pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n Reaction field electrostatics is an approximation to the screened electrostatic interaction,\n which assumes that the medium can be treated as an electrostatic continuum of dielectric\n constant :math:`\\epsilon_{RF}` outside the cutoff sphere of radius :math:`r_{\\mathrm{cut}}`.\n See: `Barker et. al. 1973 `_.\n\n .. math::\n\n V_{\\mathrm{RF}}(r) = \\varepsilon \\left[ \\frac{1}{r} +\n \\frac{(\\epsilon_{RF}-1) r^2}{(2 \\epsilon_{RF} + 1) r_c^3} \\right]\n\n By default, the reaction field potential does not require charge or diameter to be set. Two parameters,\n :math:`\\varepsilon` and :math:`\\epsilon_{RF}` are needed. If :math:`epsilon_{RF}` is specified as zero,\n it will represent infinity.\n\n If *use_charge* is set to True, the following formula is evaluated instead:\n .. math::\n\n V_{\\mathrm{RF}}(r) = q_i q_j \\varepsilon \\left[ \\frac{1}{r} +\n \\frac{(\\epsilon_{RF}-1) r^2}{(2 \\epsilon_{RF} + 1) r_c^3} \\right]\n\n where :math:`q_i` and :math:`q_j` are the charges of the particle pair.\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in units of energy*distance)\n - :math:`\\epsilon_{RF}` - *eps_rf* (dimensionless)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in units of distance)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}` - *r_on* (in units of distance)\n - *optional*: defaults to the global r_cut specified in the pair command\n - *use_charge* (boolean), evaluate potential using particle charges\n - *optional*: defaults to False\n\n .. versionadded:: 2.1\n\n\n Example::\n\n nl = nlist.cell()\n reaction_field = pair.reaction_field(r_cut=3.0, nlist=nl)\n reaction_field.pair_coeff.set('A', 'A', epsilon=1.0, eps_rf=1.0)\n reaction_field.pair_coeff.set('A', 'B', epsilon=-1.0, eps_rf=0.0)\n reaction_field.pair_coeff.set('B', 'B', epsilon=1.0, eps_rf=0.0)\n reaction_field.pair_coeff.set(system.particles.types, system.particles.types, epsilon=1.0, eps_rf=0.0, use_charge=True)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairReactionField(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairReactionField;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairReactionFieldGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairReactionFieldGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'eps_rf', 'use_charge'];\n self.pair_coeff.set_default_coeff('use_charge', False)\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n eps_rf = coeff['eps_rf'];\n use_charge = coeff['use_charge']\n\n return _hoomd.make_scalar3(epsilon, eps_rf, _hoomd.int_as_scalar(int(use_charge)));\n\nclass DLVO(pair):\n R\"\"\" DLVO colloidal interaction\n\n :py:class:`DLVO` specifies that a DLVO dispersion and electrostatic interaction should be\n applied between every non-excluded particle pair in the simulation.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n d_max (float): Maximum diameter particles in the simulation will have (in distance units)\n\n :py:class:`DLVO` evaluates the forces for the pair potential\n .. math::\n\n V_{\\mathrm{DLVO}}(r) = & - \\frac{A}{6} \\left[\n \\frac{2a_1a_2}{r^2 - (a_1+a_2)^2} + \\frac{2a_1a_2}{r^2 - (a_1-a_2)^2}\n + \\log \\left( \\frac{r^2 - (a_1+a_2)^2}{r^2 - (a_1+a_2)^2} \\right) \\right]\n + \\frac{a_1 a_2}{a_1+a_2} Z e^{-\\kappa(r - (a_1+a_2))} & r < (r_{\\mathrm{cut}} + \\Delta)\n = & 0 & r \\ge (r_{\\mathrm{cut}} + \\Delta)\n\n where math:`a_i` is the radius of particle :math:`i`, :math:`\\Delta = (d_i + d_j)/2` and\n :math:`d_i` is the diameter of particle :math:`i`.\n\n The first term corresponds to the attractive van der Waals interaction with A being the Hamaker constant,\n the second term to the repulsive double-layer interaction between two spherical surfaces with Z proportional\n to the surface electric potential.\n\n See Israelachvili 2011, pp. 317.\n\n The DLVO potential does not need charge, but does need diameter. See :py:class:`slj` for an explanation\n on how diameters are handled in the neighbor lists.\n\n Due to the way that DLVO modifies the cutoff condition, it will not function properly with the\n xplor shifting mode. See :py:class:`pair` for details on how forces are calculated and the available energy\n shifting and smoothing modes.\n\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in units of energy*distance)\n - :math:`\\kappa` - *kappa* (in units of 1/distance)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in units of distance)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}` - *r_on* (in units of distance)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n .. versionadded:: 2.2\n\n Example::\n\n nl = nlist.cell()\n DLVO.pair_coeff.set('A', 'A', epsilon=1.0, kappa=1.0)\n DLVO.pair_coeff.set('A', 'B', epsilon=2.0, kappa=0.5, r_cut=3.0, r_on=2.0);\n DLVO.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=0.5, kappa=3.0)\n \"\"\"\n def __init__(self, r_cut, nlist, d_max=None, name=None):\n hoomd.util.print_status_line();\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # update the neighbor list\n if d_max is None :\n sysdef = hoomd.context.current.system_definition;\n d_max = sysdef.getParticleData().getMaxDiameter()\n hoomd.context.msg.notice(2, \"Notice: DLVO set d_max=\" + str(d_max) + \"\\n\");\n\n # SLJ requires diameter shifting to be on\n self.nlist.cpp_nlist.setDiameterShift(True);\n self.nlist.cpp_nlist.setMaximumDiameter(d_max);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairDLVO(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDLVO;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairDLVOGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairDLVOGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['kappa', 'Z', 'A'];\n\n def process_coeff(self, coeff):\n Z = coeff['Z'];\n kappa = coeff['kappa'];\n A = coeff['A'];\n\n return _hoomd.make_scalar3(kappa, Z, A);\n\nclass square_density(pair):\n R\"\"\" Soft potential for simulating a van-der-Waals liquid\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`square_density` specifies that the three-body potential should be applied to every\n non-bonded particle pair in the simulation, that is harmonic in the local density.\n\n The self energy per particle takes the form\n\n .. math:: \\Psi^{ex} = B (\\rho - A)^2\n\n which gives a pair-wise additive, three-body force\n\n .. math:: \\vec{f}_{ij} = \\left( B (n_i - A) + B (n_j - A) \\right) w'_{ij} \\vec{e}_{ij}\n\n Here, :math:`w_{ij}` is a quadratic, normalized weighting function,\n\n .. math:: w(x) = \\frac{15}{2 \\pi r_{c,\\mathrm{weight}}^3} (1-r/r_{c,\\mathrm{weight}})^2\n\n The local density at the location of particle *i* is defined as\n\n .. math:: n_i = \\sum\\limits_{j\\neq i} w_{ij}\\left(\\big| \\vec r_i - \\vec r_j \\big|\\right)\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`A` - *A* (in units of volume^-1) - mean density (*default*: 0)\n - :math:`B` - *B* (in units of energy*volume^2) - coefficient of the harmonic density term\n\n Example::\n\n nl = nlist.cell()\n sqd = pair.van_der_waals(r_cut=3.0, nlist=nl)\n sqd.pair_coeff.set('A', 'A', A=0.1)\n sqd.pair_coeff.set('A', 'A', B=1.0)\n\n For further details regarding this multibody potential, see\n\n Warning:\n Currently HOOMD does not support reverse force communication between MPI domains on the GPU.\n Since reverse force communication is required for the calculation of multi-body potentials, attempting to use the\n square_density potential on the GPU with MPI will result in an error.\n\n [1] P. B. Warren, \"Vapor-liquid coexistence in many-body dissipative particle dynamics\"\n Phys. Rev. E. Stat. Nonlin. Soft Matter Phys., vol. 68, no. 6 Pt 2, p. 066702, 2003.\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # this potential cannot handle a half neighbor list\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialSquareDensity(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialSquareDensity;\n else:\n self.cpp_force = _md.PotentialSquareDensityGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialSquareDensityGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficients\n self.required_coeffs = ['A','B']\n self.pair_coeff.set_default_coeff('A', 0.0)\n\n def process_coeff(self, coeff):\n return _hoomd.make_scalar2(coeff['A'],coeff['B'])\n\n\nclass buckingham(pair):\n R\"\"\" Buckingham pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`buckingham` specifies that a Buckingham pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{Buckingham}}(r) = & A \\exp\\left(-\\frac{r}{\\rho}\\right) -\n \\frac{C}{r^6} & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`A` - *A* (in energy units)\n - :math:`\\rho` - *rho* (in distance units)\n - :math:`C` - *C* (in energy * distance**6 units )\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n .. versionadded:: 2.2\n .. versionchanged:: 2.2\n\n Example::\n\n nl = nlist.cell()\n buck = pair.buckingham(r_cut=3.0, nlist=nl)\n buck.pair_coeff.set('A', 'A', A=1.0, rho=1.0, C=1.0)\n buck.pair_coeff.set('A', 'B', A=2.0, rho=1.0, C=1.0, r_cut=3.0, r_on=2.0);\n buck.pair_coeff.set('B', 'B', A=1.0, rho=1.0, C=1.0, r_cut=2**(1.0/6.0), r_on=2.0);\n buck.pair_coeff.set(['A', 'B'], ['C', 'D'], A=1.5, rho=2.0, C=1.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairBuckingham(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairBuckingham;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairBuckinghamGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairBuckinghamGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['A', 'rho', 'C'];\n\n def process_coeff(self, coeff):\n A = coeff['A'];\n rho = coeff['rho'];\n C = coeff['C'];\n\n return _hoomd.make_scalar4(A, rho, C, 0.0);\n\n\nclass lj1208(pair):\n R\"\"\" Lennard-Jones 12-8 pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`lj1208` specifies that a Lennard-Jones pair potential should be applied between every\n non-excluded particle pair in the simulation.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{LJ}}(r) = & 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} -\n \\alpha \\left( \\frac{\\sigma}{r} \\right)^{8} \\right] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`\\varepsilon` - *epsilon* (in energy units)\n - :math:`\\sigma` - *sigma* (in distance units)\n - :math:`\\alpha` - *alpha* (unitless) - *optional*: defaults to 1.0\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n .. versionadded:: 2.2\n .. versionchanged:: 2.2\n\n Example::\n\n nl = nlist.cell()\n lj1208 = pair.lj1208(r_cut=3.0, nlist=nl)\n lj1208.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)\n lj1208.pair_coeff.set('A', 'B', epsilon=2.0, sigma=1.0, alpha=0.5, r_cut=3.0, r_on=2.0);\n lj1208.pair_coeff.set('B', 'B', epsilon=1.0, sigma=1.0, r_cut=2**(1.0/6.0), r_on=2.0);\n lj1208.pair_coeff.set(['A', 'B'], ['C', 'D'], epsilon=1.5, sigma=2.0)\n\n \"\"\"\n def __init__(self, r_cut, nlist, name=None):\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairLJ1208(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairLJ1208;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairLJ1208GPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairLJ1208GPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficient options\n self.required_coeffs = ['epsilon', 'sigma', 'alpha'];\n self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n epsilon = coeff['epsilon'];\n sigma = coeff['sigma'];\n alpha = coeff['alpha'];\n\n lj1 = 4.0 * epsilon * math.pow(sigma, 12.0);\n lj2 = alpha * 4.0 * epsilon * math.pow(sigma, 8.0);\n return _hoomd.make_scalar2(lj1, lj2);\n\nclass fourier(pair):\n R\"\"\" Fourier pair potential.\n\n Args:\n r_cut (float): Default cutoff radius (in distance units).\n nlist (:py:mod:`hoomd.md.nlist`): Neighbor list\n name (str): Name of the force instance.\n\n :py:class:`fourier` specifies that a fourier series form potential.\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray*}\n V_{\\mathrm{Fourier}}(r) = & \\frac{1}{r^{12}} + \\frac{1}{r^2}\\sum_{n=1}^4 [a_n cos(\\frac{n \\pi r}{r_{cut}}) + b_n sin(\\frac{n \\pi r}{r_{cut}})] & r < r_{\\mathrm{cut}} \\\\\n = & 0 & r \\ge r_{\\mathrm{cut}} \\\\\n \\end{eqnarray*}\n\n where:\n \\begin{eqnarray*}\n a_1 = \\sum_{n=2}^4 (-1)^n a_n cos(\\frac{n \\pi r}{r_{cut}})\n \\end{eqnarray*}\n\n \\begin{eqnarray*}\n b_1 = \\sum_{n=2}^4 n (-1)^n b_n cos(\\frac{n \\pi r}{r_{cut}})\n \\end{eqnarray*}\n\n is calculated to enforce close to zero value at r_cut.\n\n See :py:class:`pair` for details on how forces are calculated and the available energy shifting and smoothing modes.\n Use :py:meth:`pair_coeff.set ` to set potential coefficients.\n\n The following coefficients must be set per unique pair of particle types:\n\n - :math:`a` - *a* (array of 3 values corresponding to a2, a3 and a4 in the Fourier series, unitless)\n - :math:`a` - *b* (array of 3 values corresponding to b2, b3 and b4 in the Fourier series, unitless)\n - :math:`r_{\\mathrm{cut}}` - *r_cut* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n - :math:`r_{\\mathrm{on}}`- *r_on* (in distance units)\n - *optional*: defaults to the global r_cut specified in the pair command\n\n Example::\n\n nl = nlist.cell()\n fourier = pair.fourier(r_cut=3.0, nlist=nl)\n fourier.pair_coeff.set('A', 'A', a=[a2,a3,a4], b=[b2,b3,b4])\n \"\"\"\n\n def __init__(self, r_cut, nlist, name=None):\n\n hoomd.util.print_status_line();\n\n # tell the base class how we operate\n\n # initialize the base class\n pair.__init__(self, r_cut, nlist, name);\n\n # create the c++ mirror class\n if not hoomd.context.exec_conf.isCUDAEnabled():\n self.cpp_force = _md.PotentialPairFourier(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairFourier;\n else:\n self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full);\n self.cpp_force = _md.PotentialPairFourierGPU(hoomd.context.current.system_definition, self.nlist.cpp_nlist, self.name);\n self.cpp_class = _md.PotentialPairFourierGPU;\n\n hoomd.context.current.system.addCompute(self.cpp_force, self.force_name);\n\n # setup the coefficent options\n\n self.required_coeffs = ['fourier_a','fourier_b'];\n # self.pair_coeff.set_default_coeff('alpha', 1.0);\n\n def process_coeff(self, coeff):\n fourier_a = coeff['fourier_a'];\n fourier_b = coeff['fourier_b'];\n\n return _md.make_pair_fourier_params(fourier_a,fourier_b);\n","sub_path":"hoomd/md/pair.py","file_name":"pair.py","file_ext":"py","file_size_in_byte":128672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"343756841","text":"# Copyright 2019-2021 Jitsuin, 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# This is API SAMPLE CODE, not for production use.\n\n\"\"\"Create an event for an asset given url to Archivist and user Token.\n\nThe module contains four functions: main, create_asset, create_event and fetch_event.\nMain function parses in a url to the Archivist and a token, which is a user authorization.\nThe main function would initialize an archivist connection using the url and\nthe token, called \"aconn\", then call create_assets and pass in \"aconn\" and\ncreate_assets will build create_asset, which is a archivist connection function\nto create a new asset for the archivist through archivist connection. The main funciton then\ncalls create_event and pass in \"aconn\" and the created asset to create a new event for the asset.\nMain function calls fetch_event and pass in \"aconn\" and the identity of the event to get the event.\n\"\"\"\n\nfrom archivist.archivist import Archivist\n\n\ndef create_event(arch, asset):\n \"\"\"Create an event for the passed-in asset.\n\n Args:\n arch: archivist connection.\n asset: an asset created using aconn\n\n Returns:\n new_event: a new event for the asset.\n \"\"\"\n # props can be defined for different behaviours and the attributes associated with\n # different behaviours are also different. More details can be found here:\n # https://jitsuin-archivist.readthedocs.io/en/latest/assetv2/index.html\n props = {\n \"operation\": \"Record\",\n # This event is used to record evidence, more behaviour explanation can be found here:\n # https://jitsuin-archivist.readthedocs.io/en/latest/assetv2/index.html\n \"behaviour\": \"RecordEvidence\",\n # Optional Client-claimed time at which the maintenance was performed\n \"timestamp_declared\": \"2019-11-27T14:44:19Z\",\n # Optional Client-claimed identity of person performing the operation\n \"principal_declared\": {\n \"issuer\": \"idp.synsation.io/1234\",\n \"subject\": \"phil.b\",\n \"email\": \"phil.b@synsation.io\",\n },\n }\n attrs = {\n # Required Details of the RecordEvidence request\n \"arc_description\": \"Safety conformance approved for version 1.6.\",\n # Required The evidence to be retained in the asset history\n \"arc_evidence\": \"DVA Conformance Report attached\",\n # Example Client can add any additional information in further attributes,\n # including free text or attachments\n \"conformance_report\": \"blobs/e2a1d16c-03cd-45a1-8cd0-690831df1273\",\n }\n\n return arch.events.create(asset[\"identity\"], props=props, attrs=attrs)\n\n\ndef create_asset(arch):\n \"\"\"Create an asset using Archivist Connection.\n\n Args:\n arch: archivist connection.\n\n Returns:\n newasset: a new asset created.\n \"\"\"\n attrs = {\n \"arc_display_name\": \"display_name\", # Asset's display name in the user interface\n \"arc_description\": \"display_description\", # Asset's description in the user interface\n \"arc_display_type\": \"desplay_type\", # Arc_display_type is a free text field\n # allowing the creator of\n # an asset to specify the asset\n # type or class. Be careful when setting this:\n # assets are grouped by type and\n # sharing policies can be\n # configured to share assets based on\n # their arc_display_type.\n # So a mistake here can result in asset data being\n # under- or over-shared.\n \"some_custom_attribute\": \"value\" # You can add any custom value as long as\n # it does not start with arc_\n }\n behaviours = [\n \"Attachments\",\n \"Firmware\",\n \"LocationUpdate\",\n \"Maintenance\",\n \"RecordEvidence\",\n ]\n\n # The first argument is the behaviours of the asset\n # The second argument is the attributes of the asset\n # The third argument is wait for confirmation:\n # If @confirm@ is True then this function will not\n # return until the asset is confirmed on the blockchain and ready\n # to accept events (or an error occurs)\n # After an asset is submitted to the blockchain (submitted),\n # it will be in the \"Pending\" status.\n # Once it is added to the blockchain, the status will be changed to \"Confirmed\"\n return arch.assets.create(behaviours, attrs, confirm=True)\n\n\ndef main():\n \"\"\"Main function of create event.\n\n Parse in user input of url and auth token and use them to\n create an example archivist connection and create an asset.\n The main function then uses the asset to create an event for\n the asset and fetch the event.\n \"\"\"\n with open(\".auth_token\", mode=\"r\") as tokenfile:\n authtoken = tokenfile.read().strip()\n\n # Initialize connection to Archivist\n arch = Archivist(\n \"https://soak-0-avid.engineering-k8s-stage-2.dev.wild.jitsuin.io\",\n auth=authtoken,\n )\n # Create a new asset\n new_asset = create_asset(arch)\n # Create a new event\n new_event = create_event(arch, new_asset)\n # Fetch the event\n unused_event = arch.events.read(new_event[\"identity\"])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/create_event/create_event.py","file_name":"create_event.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"84218015","text":"\"\"\"\nThe year is divided into four seasons: spring, summer, fall and winter. While the\nexact dates that the seasons change vary a little bit from year to year because of the\nway that the calendar is constructed.\n\nCreate a program that reads a month and day from the user. The user will enter\nthe name of the month as a string, followed by the day within the month as an\ninteger. Then your program should display the season associated with the date\nthat was entered.\n\"\"\"\n\nSPRING = \"March 20\"\nSUMMER = \"June 21\"\nFALL = \"September 22\"\nWINTER = \"December 21\"\n\nmonth = input(\"Enter the name of the month: \")\nday = int(input(\"Enter the day number: \"))\nseason = ''\n\nif month == \"January\" or month == \"February\":\n season = \"Winter\"\nelif month == \"March\":\n if day < 20:\n season = \"Winter\"\n else:\n season = \"Spring\"\nelif month == \"April\" or month == \"May\":\n season = \"Spring\"\nelif month == \"June\":\n if day < 21:\n season = \"Spring\"\n else:\n season = \"Summer\"\nelif month == \"July\" or month == \"August\":\n season = \"Summer\"\nelif month == \"September\":\n if day < 22:\n season = \"Summer\"\n else:\n season = \"Fall\"\nelif month == \"October\" or month == \"November\":\n season = \"Fall\"\nelif month == \"December\":\n if day < 21:\n season = \"Fall\"\n else:\n season = \"Winter\"\n\nprint(month, day, \"is in\", season)","sub_path":"2 If Statements/46_season_from_month_and_day.py","file_name":"46_season_from_month_and_day.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"205152188","text":"import subprocess\nimport traceback\nfrom subprocess import CalledProcessError\nimport os\nimport logging\nimport sys\nimport smtplib\nimport signal\nfrom types import SimpleNamespace\nimport importlib.util\nimport re\nimport fileinput\nimport contextlib\nfrom io import BytesIO\nimport tarfile\nimport shutil\n\nimport requests\n\nfrom nicelogger import enable_pretty_logging\nfrom htmlutils import parse_document_from_requests\nfrom myutils import at_dir\nfrom mailutils import assemble_mail\nimport archpkg\n\nUserAgent = 'lilac/0.1 (package auto-build bot, by lilydjwg)'\n\ns = requests.Session()\ns.headers['User-Agent'] = UserAgent\nlogger = logging.getLogger(__name__)\nSPECIAL_FILES = ('package.list', 'lilac.py', '.gitignore')\nEMPTY_COMMIT = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'\n_g = SimpleNamespace()\nbuild_output = None\nPYPI_URL = 'https://pypi.python.org/pypi/%s/json'\n\n# to be override\nAUR_REPO_DIR = '/tmp'\nMAILTAG = 'lilac'\n\ndef smtp_connect():\n s = smtplib.SMTP()\n s.connect()\n return s\n\ndef send_error_report(name, *, msg=None, exc=None, subject=None):\n # exc_info used as such needs Python 3.5+\n logger.error('%s\\n\\n%s', subject, msg, exc_info=exc)\n\nclass Dependency:\n _CACHE = {}\n\n @classmethod\n def get(cls, topdir, what):\n if isinstance(what, tuple):\n pkgbase, pkgname = what\n else:\n pkgbase = pkgname = what\n\n key = pkgbase, pkgname\n if key not in cls._CACHE:\n cls._CACHE[key] = cls(topdir, pkgbase, pkgname)\n return cls._CACHE[key]\n\n def __init__(self, topdir, pkgbase, pkgname):\n self.pkgbase = pkgbase\n self.pkgname = pkgname\n self.directory = os.path.join(topdir, pkgbase)\n\n def resolve(self):\n try:\n return self._find_local_package()\n except FileNotFoundError:\n return None\n\n def _find_local_package(self):\n with at_dir(self.directory):\n fnames = [x for x in os.listdir() if x.endswith('.pkg.tar.xz')]\n pkgs = []\n for x in fnames:\n info = archpkg.PkgNameInfo.parseFilename(x)\n if info.name == self.pkgname:\n pkgs.append(x)\n\n if len(pkgs) == 1:\n return os.path.abspath(pkgs[0])\n elif not pkgs:\n raise FileNotFoundError\n else:\n ret = sorted(\n pkgs, reverse=True, key=lambda n: os.stat(n).st_mtime)[0]\n return os.path.abspath(ret)\n\nclass MissingDependencies(Exception):\n def __init__(self, pkgs):\n self.deps = pkgs\n\nclass BuildPrefixError(Exception):\n def __init__(self, build_prefix):\n self.build_prefix = build_prefix\n\nclass AurDownloadError(Exception):\n def __init__(self, pkgname):\n self.pkgname = pkgname\n\ndef download_official_pkgbuild(name):\n url = 'https://www.archlinux.org/packages/search/json/?name=' + name\n logger.info('download PKGBUILD for %s.', name)\n info = s.get(url).json()\n r = [r for r in info['results'] if r['repo'] != 'testing'][0]\n repo = r['repo']\n arch = r['arch']\n if repo in ('core', 'extra'):\n gitrepo = 'packages'\n else:\n gitrepo = 'community'\n pkgbase = [r['pkgbase'] for r in info['results'] if r['repo'] != 'testing'][0]\n\n tree_url = 'https://projects.archlinux.org/svntogit/%s.git/tree/repos/%s-%s?h=packages/%s' % (\n gitrepo, repo, arch, pkgbase)\n doc = parse_document_from_requests(tree_url, s)\n blobs = doc.xpath('//div[@class=\"content\"]//td/a[contains(concat(\" \", normalize-space(@class), \" \"), \" ls-blob \")]')\n files = [x.text for x in blobs]\n for filename in files:\n blob_url = 'https://projects.archlinux.org/svntogit/%s.git/plain/repos/%s-%s/%s?h=packages/%s' % (\n gitrepo, repo, arch, filename, pkgbase)\n with open(filename, 'wb') as f:\n logger.debug('download file %s.', filename)\n data = s.get(blob_url).content\n f.write(data)\n return files\n\ndef try_aur_url(name):\n aur4url = 'https://aur.archlinux.org/cgit/aur.git/snapshot/{name}.tar.gz'\n templates = [aur4url]\n urls = [url.format(first_two=name[:2], name=name) for url in templates]\n for url in urls:\n response = s.get(url)\n if response.status_code == 200:\n logger.debug(\"downloaded aur tarball '%s' from url '%s'\", name, url)\n return response.content\n logger.error(\"failed to find aur url for '%s'\", name)\n raise AurDownloadError(name)\n\ndef download_aur_pkgbuild(name):\n content = BytesIO(try_aur_url(name))\n files = []\n with tarfile.open(name=name+\".tar.gz\", mode=\"r:gz\", fileobj=content) as tarf:\n for tarinfo in tarf:\n basename, remain = os.path.split(tarinfo.name)\n if basename == '':\n continue\n if remain in ('.AURINFO', '.SRCINFO', '.gitignore'):\n continue\n tarinfo.name = remain\n tarf.extract(tarinfo)\n files.append(remain)\n return files\n\ndef get_pypi_info(name):\n return s.get(PYPI_URL % name).json()\n\ndef get_pkgver_and_pkgrel():\n pkgrel = None\n pkgver = None\n with open('PKGBUILD') as f:\n for l in f:\n if l.startswith('pkgrel='):\n pkgrel = float(l.rstrip().split('=', 1)[-1].strip('\\'\"'))\n if int(pkgrel) == pkgrel:\n pkgrel = int(pkgrel)\n elif l.startswith('pkgver='):\n pkgver = l.rstrip().split('=', 1)[-1]\n return pkgver, pkgrel\n\ndef update_pkgrel(rel=None):\n with open('PKGBUILD') as f:\n pkgbuild = f.read()\n\n def replacer(m):\n nonlocal rel\n if rel is None:\n rel = int(float(m.group(1))) + 1\n return str(rel)\n\n pkgbuild = re.sub(r'''(?<=^pkgrel=)['\"]?([\\d.])+['\"]?''', replacer, pkgbuild, count=1, flags=re.MULTILINE)\n with open('PKGBUILD', 'w') as f:\n f.write(pkgbuild)\n logger.info('pkgrel updated to %s', rel)\n\ndef find_maintainer(me, file='*'):\n cmd = [\n \"git\", \"log\", \"--format=%H %an <%ae>\", \"--\", file,\n ]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)\n\n try:\n while True:\n line = p.stdout.readline()\n commit, author = line.rstrip().split(None, 1)\n if me not in author:\n return author\n finally:\n p.terminate()\n\ndef sendmail(to, from_, subject, msg):\n s = smtp_connect()\n if len(msg) > 5 * 1024 ** 2:\n msg = msg[:1024 ** 2] + '\\n\\n日志过长,省略ing……\\n\\n' + msg[-1024 ** 2:]\n msg = assemble_mail('[%s] %s' % (MAILTAG, subject), to, from_, text=msg)\n s.send_message(msg)\n s.quit()\n\ndef get_changed_packages(revisions, U=None):\n cmd = [\"git\", \"diff\", \"--name-only\", revisions]\n r = run_cmd(cmd).splitlines()\n ret = {x.split('/', 1)[0] for x in r}\n if U is not None:\n ret &= U\n return ret\n\ndef pkgrel_changed(revisions, pkgname):\n cmd = [\"git\", \"diff\", \"-p\", revisions, '--', pkgname + '/PKGBUILD']\n r = run_cmd(cmd, silent=True).splitlines()\n return any(x.startswith('+pkgrel=') for x in r)\n\ndef clean_directory():\n '''clean all PKGBUILD and related files'''\n files = run_cmd(['git', 'ls-files']).splitlines()\n logger.info('clean directory')\n ret = []\n for f in files:\n if f in SPECIAL_FILES:\n continue\n try:\n logger.debug('unlink file %s', f)\n os.unlink(f)\n ret.append(f)\n except FileNotFoundError:\n pass\n return ret\n\ndef git_rm_files(files):\n if files:\n run_cmd(['git', 'rm', '--cached', '--'] + files)\n\ndef git_add_files(files):\n if isinstance(files, str):\n files = [files]\n try:\n run_cmd(['git', 'add', '--'] + files)\n except CalledProcessError:\n # on error, there may be a partial add, e.g. some files are ignored\n run_cmd(['git', 'reset', '--'] + files)\n raise\n\ndef git_commit(*, check_status=True):\n if check_status:\n ret = [x for x in\n run_cmd([\"git\", \"status\", \"-s\", \".\"]).splitlines()\n if x.split(None, 1)[0] != '??']\n if not ret:\n return\n\n run_cmd(['git', 'commit', '-m', 'auto update for package %s' % (\n os.path.split(os.getcwd())[1])])\n\ndef git_pull():\n output = run_cmd(['git', 'pull', '--no-edit'])\n return 'up-to-date' not in output\n\ndef git_reset_hard():\n run_cmd(['git', 'reset', '--hard'])\n\ndef git_push():\n while True:\n try:\n run_cmd(['git', 'push'])\n break\n except CalledProcessError as e:\n if 'non-fast-forward' in e.output or 'fetch first' in e.output:\n run_cmd([\"git\", \"pull\", \"--rebase\"])\n else:\n raise\n\ndef git_last_commit(ref=None):\n cmd = ['git', 'log', '-1', '--format=%H']\n if ref:\n cmd.append(ref)\n return run_cmd(cmd).strip()\n\ndef aur_pre_build(name=None, *, do_vcs_update=True):\n if os.path.exists('PKGBUILD'):\n pkgver, pkgrel = get_pkgver_and_pkgrel()\n else:\n pkgver = None\n\n _g.aur_pre_files = clean_directory()\n if name is None:\n name = os.path.basename(os.getcwd())\n _g.aur_building_files = download_aur_pkgbuild(name)\n\n new_pkgver, new_pkgrel = get_pkgver_and_pkgrel()\n if pkgver and pkgver == new_pkgver:\n # change to larger pkgrel\n update_pkgrel(max(pkgrel, new_pkgrel))\n\n if do_vcs_update and name.endswith(('-git', '-hg', '-svn', '-bzr')):\n vcs_update()\n # recheck after sync, because AUR pkgver may lag behind\n new_pkgver, new_pkgrel = get_pkgver_and_pkgrel()\n if pkgver and pkgver == new_pkgver:\n update_pkgrel(max(pkgrel, new_pkgrel))\n\ndef vcs_update():\n # clean up the old source tree\n shutil.rmtree('src', ignore_errors=True)\n run_cmd(['makepkg', '-od'], use_pty=True)\n\ndef aur_post_build():\n git_rm_files(_g.aur_pre_files)\n git_add_files(_g.aur_building_files)\n output = run_cmd([\"git\", \"status\", \"-s\", \".\"]).strip()\n if output:\n git_commit()\n del _g.aur_pre_files, _g.aur_building_files\n\ndef pypi_pre_build(depends=None, python2=False, pypi_name=None, arch=None,\n makedepends=None, depends_setuptools=True,\n provides=None,\n optdepends=None, license=None,\n ):\n if os.path.exists('PKGBUILD'):\n pkgver, pkgrel = get_pkgver_and_pkgrel()\n else:\n pkgver = None\n\n pkgname = os.path.basename(os.getcwd())\n if pypi_name is None:\n pypi_name = pkgname.split('-', 1)[-1]\n pkgbuild = run_cmd(['pypi2pkgbuild', pypi_name], silent=True)\n\n if depends_setuptools:\n if depends is None:\n depends = ['python-setuptools']\n else:\n depends.append('python-setuptools')\n elif makedepends is None:\n makedepends = ['python-setuptools']\n elif makedepends:\n makedepends.append('python-setuptools')\n\n pkgbuild = re.sub(r'^pkgname=.*', f'pkgname={pkgname}',\n pkgbuild, flags=re.MULTILINE)\n\n if license:\n pkgbuild = re.sub(r'^license=.*', f'license=({license})',\n pkgbuild, flags=re.MULTILINE)\n\n if depends:\n pkgbuild = pkgbuild.replace(\n \"depends=('python')\",\n \"depends=('python' %s)\" % ' '.join(f\"'{x}'\" for x in depends))\n\n if makedepends:\n pkgbuild = pkgbuild.replace(\n '\\nsource=',\n '\\nmakedepends=(%s)\\nsource=' %\n ' '.join(\"'%s'\" % x for x in makedepends))\n\n if optdepends:\n pkgbuild = pkgbuild.replace(\n '\\nsource=',\n '\\noptdepends=(%s)\\nsource=' %\n ' '.join(\"'%s'\" % x for x in optdepends))\n\n if provides:\n pkgbuild = pkgbuild.replace(\n '\\nsource=',\n '\\nprovides=(%s)\\nsource=' %\n ' '.join(\"'%s'\" % x for x in provides))\n\n if python2:\n pkgbuild = re.sub(r'\\bpython3?(?!\\.)', 'python2', pkgbuild)\n if arch is not None:\n pkgbuild = pkgbuild.replace(\n \"arch=('any')\",\n \"arch=(%s)\" % ' '.join(\"'%s'\" % x for x in arch))\n with open('PKGBUILD', 'w') as f:\n f.write(pkgbuild)\n\n new_pkgver = get_pkgver_and_pkgrel()[0]\n if pkgver and pkgver == new_pkgver:\n # change pkgrel to what specified in PKGBUILD\n update_pkgrel(pkgrel)\n\ndef pypi_post_build():\n git_add_files('PKGBUILD')\n git_commit()\n\ndef lilac_build(repodir, build_prefix=None, oldver=None, newver=None, accept_noupdate=False, depends=(), bindmounts=()):\n with load_lilac() as mod:\n run_cmd([\"sh\", \"-c\", \"rm -f -- *.pkg.tar.xz *.pkg.tar.xz.sig *.src.tar.gz\"])\n success = False\n\n global build_output\n # reset in case no one cleans it up\n build_output = None\n\n try:\n if not hasattr(mod, '_G'):\n # fill nvchecker result unless already filled (e.g. by hand)\n mod._G = SimpleNamespace(oldver = oldver, newver = newver)\n if hasattr(mod, 'pre_build'):\n logger.debug('accept_noupdate=%r, oldver=%r, newver=%r', accept_noupdate, oldver, newver)\n mod.pre_build()\n recv_gpg_keys()\n\n need_build_first = set()\n\n build_prefix = build_prefix or mod.build_prefix\n if not isinstance(build_prefix, str) or 'i686' in build_prefix:\n raise BuildPrefixError(build_prefix)\n\n depend_packages = []\n for x in depends:\n p = x.resolve()\n if p is None:\n need_build_first.add(x.pkgbase)\n else:\n depend_packages.append(p)\n if need_build_first:\n raise MissingDependencies(need_build_first)\n\n makechrootpkg_args = []\n if hasattr(mod, 'makechrootpkg_args'):\n makechrootpkg_args = mod.makechrootpkg_args\n\n call_build_cmd(build_prefix, depend_packages, bindmounts, makechrootpkg_args)\n pkgs = [x for x in os.listdir() if x.endswith('.pkg.tar.xz')]\n if not pkgs:\n raise Exception('no package built')\n if hasattr(mod, 'post_build'):\n mod.post_build()\n success = True\n finally:\n if hasattr(mod, 'post_build_always'):\n mod.post_build_always(success=success)\n\ndef call_build_cmd(tag, depends, bindmounts=(), makechrootpkg_args=[]):\n global build_output\n if tag == 'makepkg':\n cmd = ['makepkg', '--holdver']\n else:\n cmd = ['%s-build' % tag, '--']\n\n if depends:\n for x in depends:\n cmd += ['-I', x]\n\n if bindmounts:\n for x in bindmounts:\n cmd += ['-d', x]\n\n cmd.extend(makechrootpkg_args)\n cmd.extend(['--', '--holdver'])\n\n # NOTE that Ctrl-C here may not succeed\n build_output = run_cmd(cmd, use_pty=True)\n build_output = build_output.replace('\\r\\n', '\\n')\n build_output = re.sub(r'.*\\r', '', build_output)\n\ndef single_main(build_prefix='makepkg'):\n prepend_self_path()\n enable_pretty_logging('DEBUG')\n lilac_build(\n build_prefix = build_prefix,\n repodir = os.path.dirname(\n os.path.dirname(sys.modules['__main__'].__file__)),\n accept_noupdate = True,\n )\n\ndef prepend_self_path():\n mydir = os.path.realpath(os.path.dirname(__file__))\n path = os.environ['PATH']\n os.environ['PATH'] = mydir + os.pathsep + path\n\ndef run_cmd(cmd, *, use_pty=False, silent=False):\n logger.debug('running %r, %susing pty,%s showing output', cmd,\n '' if use_pty else 'not ',\n ' not' if silent else '')\n if use_pty:\n rfd, stdout = os.openpty()\n stdin = stdout\n # for fd leakage\n logger.debug('pty master fd=%d, slave fd=%d.', rfd, stdout)\n else:\n stdin = subprocess.DEVNULL\n stdout = subprocess.PIPE\n\n exited = False\n def child_exited(signum, sigframe):\n nonlocal exited\n exited = True\n old_hdl = signal.signal(signal.SIGCHLD, child_exited)\n\n p = subprocess.Popen(cmd, stdin = stdin, stdout = stdout, stderr = subprocess.STDOUT)\n if use_pty:\n os.close(stdout)\n else:\n rfd = p.stdout.fileno()\n out = []\n\n while True:\n try:\n r = os.read(rfd, 4096)\n if not r:\n if exited:\n break\n else:\n continue\n except InterruptedError:\n continue\n except OSError as e:\n if e.errno == 5: # Input/output error: no clients run\n break\n else:\n raise\n r = r.replace(b'\\x0f', b'') # ^O\n if not silent:\n sys.stderr.buffer.write(r)\n out.append(r)\n\n code = p.wait()\n if use_pty:\n os.close(rfd)\n if old_hdl is not None:\n signal.signal(signal.SIGCHLD, old_hdl)\n\n out = b''.join(out)\n out = out.decode('utf-8', errors='replace')\n if code != 0:\n raise CalledProcessError(code, cmd, out)\n return out\n\ndef edit_file(filename):\n with fileinput.input(files=(filename,), inplace=True) as f:\n for line in f:\n yield line.rstrip('\\n')\n\ndef recv_gpg_keys():\n run_cmd(['recv_gpg_keys'])\n\n@contextlib.contextmanager\ndef load_lilac():\n try:\n spec = importlib.util.spec_from_file_location('lilac.py', 'lilac.py')\n mod = spec.loader.load_module()\n yield mod\n finally:\n try:\n del sys.modules['lilac.py']\n except KeyError:\n pass\n\ndef _update_aur_repo_real(pkgname):\n aurpath = os.path.join(AUR_REPO_DIR, pkgname)\n if not os.path.isdir(aurpath):\n logger.info('cloning AUR repo: %s', aurpath)\n with at_dir(AUR_REPO_DIR):\n run_cmd(['git', 'clone', 'aur@aur.archlinux.org:%s.git' % pkgname])\n else:\n with at_dir(aurpath):\n git_reset_hard()\n git_pull()\n\n logger.info('copying files to AUR repo: %s', aurpath)\n files = run_cmd(['git', 'ls-files']).splitlines()\n for f in files:\n if f in SPECIAL_FILES:\n continue\n logger.debug('copying file %s', f)\n shutil.copy(f, aurpath)\n\n with at_dir(aurpath):\n run_cmd(['mksrcinfo'])\n run_cmd(['git', 'add', '.'])\n run_cmd(['git', 'commit', '-m', 'update by lilac'])\n run_cmd(['git', 'push'])\n\ndef update_aur_repo():\n pkgname = os.path.basename(os.getcwd())\n try:\n _update_aur_repo_real(pkgname)\n except CalledProcessError as e:\n tb = traceback.format_exc()\n send_error_report(\n pkgname,\n exc = (e, tb),\n subject = '[lilac] 提交软件包 %s 到 AUR 时出错',\n )\n\ndef kill_child_processes():\n pids = subprocess.check_output(\n ['pid_children', str(os.getpid())]\n ).decode().split()\n for pid in pids:\n try:\n os.kill(int(pid), signal.SIGKILL)\n except OSError:\n pass\n\ndef is_nodejs_thing():\n with open('PKGBUILD') as f:\n data = f.read()\n return 'nodejs' in data and 'npm' in data\n\ndef update_pkgver_and_pkgrel(newver):\n pkgver, pkgrel = get_pkgver_and_pkgrel()\n\n for line in edit_file('PKGBUILD'):\n if line.startswith('pkgver=') and pkgver != newver:\n line = f'pkgver={newver}'\n elif line.startswith('pkgrel='):\n if pkgver != newver:\n line = 'pkgrel=1'\n else:\n line = f'pkgrel={int(pkgrel)+1}'\n\n print(line)\n\n run_cmd([\"updpkgsums\"])\n","sub_path":"lilaclib.py","file_name":"lilaclib.py","file_ext":"py","file_size_in_byte":17830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"22489124","text":"\"\"\"ロギングモジュール\nアプリケーション内のログ設定を定義するモジュール\nアプリケーションのログは必ずここのロガーを通してロギングする必要がある\n\"\"\"\nimport logging\nimport sys\n\nfrom domain.enums.core_enums import LogLevel\n\nfrom core.config import CoreSettings\n\nsettings = CoreSettings()\n\n# ------------------------\n# ログフォーマット定義\n# ------------------------\nAPP_LOG_FORMAT = \"Level:%(levelname)s\\tType:CoreApiApp\\tTime:%(asctime)s\\tFile:%(pathname)s\\tMessage:%(message)s\"\nACCESS_LOG_FORMAT = \"Level:%(levelname)s\\tType:CoreApiAccess\\tTime:%(asctime)s\\tProcessTime:%(process_time)s\\tClient:%(client_addr)s\\tMethod:%(method)s\\tPath:%(path)s\\tQuery:%(query)s\\tStatusCode:%(status_code)s\"\nJSON_LOG_FORMAT = \"Level:%(levelname)s\\tType:%(type)s\\tTime:%(asctime)s\\tMessage:%(message)s\"\n\n\ndef create_app_logger(log_name: str) -> logging.Logger:\n \"\"\"アプリケーションロガー作成関数\n アプリケーションロガーを作成する\n Args:\n log_name: ロガー名\n Returns:\n logging.Logger: ロガー\n \"\"\"\n\n return _create_logger(\n log_name=log_name,\n log_format=APP_LOG_FORMAT\n )\n\n\ndef create_access_logger() -> logging.Logger:\n \"\"\"アクセスロガー作成関数\n\n Returns:\n logging.Logger: ロガー\n \"\"\"\n return _create_logger(\n log_name=\"access_logger\",\n log_format=ACCESS_LOG_FORMAT\n )\n\n\ndef create_json_logger() -> logging.Logger:\n \"\"\"JSON形式のログメッセージを出力するロガー作成関数\n\n Returns:\n logging.Logger: ロガー\n \"\"\"\n return _create_logger(\n log_name=\"json_logger\",\n log_format=JSON_LOG_FORMAT\n )\n\n\ndef _create_logger(log_name: str, log_format: str) -> logging.Logger:\n \"\"\"ロガー作成関数\n ロガーを作成する\n Args:\n log_name: ロガー��\n log_format: ログフォーマット\n Returns:\n logging.Logger: ロガー\n \"\"\"\n # ロガーの作成\n log = logging.getLogger(log_name)\n\n # ログレベルの設定\n if settings.api_log_level == LogLevel.INFO:\n log.setLevel(logging.INFO)\n elif settings.api_log_level == LogLevel.DEBUG:\n log.setLevel(logging.DEBUG)\n\n # 標準出力に出力\n handler = logging.StreamHandler(stream=sys.stdout)\n # LTSV形式で出力\n formatter = logging.Formatter(log_format)\n handler.setFormatter(formatter)\n log.addHandler(handler)\n\n # プロパゲートしない\n log.propagate = False\n\n return log\n\n\n# ------------------------\n# 名前付きロガー定義\n# ------------------------\nACCESS_LOGGER = create_access_logger()\nJSON_LOGGER = create_json_logger()\n","sub_path":"src/app/core/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"333893244","text":"import random\n\n\nclass Word(object):\n counter = 0\n descendants = {}\n\n def __init__(self, counter, descendants):\n self.counter = counter\n self.descendants = descendants\n\n\ndef get_random_word(d):\n keys = list(d.keys())\n index = random.randint(0, len(keys) - 1)\n return keys[index]\n\n\ndef get_next_word(word):\n if len(word.descendants) == 0:\n return None\n\n rand = random.randint(1, 99)\n prob = 0\n\n for key, value in word.descendants.items():\n prob += (value / word.counter) * 100\n\n if rand <= prob:\n return key\n\n return None\n\n\ndef generate():\n # text = input(\"Enter text: \")\n text = \"Только такая цель позволяет человеку прожить свою жизнь с достоинством и получить настоящую радость. Да, радость! Подумайте: если человек ставит себе задачей увеличивать в жизни добро, приносить людям счастье, какие неудачи могут его постигнуть? Не тому помочь? Но много ли людей не нуждаются в помощи?\"\n # k = int(input(\"Enter k: \"))\n k = 7\n # stop = int(input(\"Enter length to stop: \"))\n stop = 1000\n\n words = {}\n\n for x in range(0, len(text)):\n key = text[x:x + k]\n next_key = text[x + k:x + k + k]\n\n word = words.setdefault(key, Word(0, {}))\n word.counter += 1\n\n word.descendants.setdefault(next_key, 0)\n word.descendants[next_key] += 1\n\n next_key = get_random_word(words)\n\n while stop > 0:\n yield next_key\n\n word = words[next_key]\n next_key = get_next_word(word) or get_random_word(words)\n stop -= len(next_key)\n\n\nif __name__ == '__main__':\n for text in generate():\n print(text, end='')\n\n print()\n","sub_path":"BDA/delirium.py","file_name":"delirium.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"109254123","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 24 13:29:54 2020\r\n\r\n@author: viktorwu02\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.basemap import Basemap\r\nfrom shapely.geometry import Point\r\nfrom shapely.geometry import Polygon\r\n\r\n \r\nfrom netCDF4 import Dataset\r\n\r\nfor year in range(2000,2020):\r\n\r\n file = 'MODIS_2000_2019/' + year + '/Greenland_Reflectivity_' + year + '_5km_C6.nc'\r\n#file = 'MODIS_2000_2019/2012/Greenland_Reflectivity_2012_5km_C6.nc'\r\n nc = Dataset(file,'r')\r\n \r\n### To calculate the cumulative slush-days\r\n \r\n for day in range(1,366):\r\n \r\n albedos = nc.variables[\"albedo\"][day]\r\n icemask = nc.variables[\"icemask\"]\r\n dem = nc.variables[\"dem\"]\r\n lats = nc.variables['lat'][:]\r\n lons = nc.variables['lon'][:]\r\n mod_lons = lons + 360\r\n cumulative_slush = np.zeros((561,301))\r\n \r\n (rows,cols) = np.shape(dem)\r\n for r in range(1,rows-1):\r\n for c in range(1,cols-1):\r\n temp_window = albedos[r-1:r+2,c-1:c+2]\r\n mean = np.sum(temp_window)/9\r\n temp_list = []\r\n \r\n for cell in np.nditer(temp_window, op_flags=['readwrite']):\r\n variance = (cell - mean)**2\r\n temp_list.append(variance)\r\n st_deviation = math.sqrt(sum(temp_list)/9)\r\n \r\n \r\n if st_deviation >= 0.05 and icemask[r,c] == 1: \r\n cumulative_slush[r,c] += 1\r\n \r\n### To classify one image\r\n \r\nfile = 'MODIS_2000_2019/2012/Greenland_Reflectivity_2012_5km_C6.nc' \r\nnc = Dataset(file,'r')\r\n \r\nalbedos = nc.variables[\"albedo\"][day]\r\nicemask = nc.variables[\"icemask\"]\r\ndem = nc.variables[\"dem\"]\r\nlats = nc.variables['lat'][:]\r\nlons = nc.variables['lon'][:]\r\nmod_lons = lons + 360\r\nslush_ice = np.zeros((561,301))\r\n \r\n(rows,cols) = np.shape(dem)\r\nfor r in range(1,rows-1):\r\n for c in range(1,cols-1):\r\n temp_window = albedos[r-1:r+2,c-1:c+2]\r\n mean = np.sum(temp_window)/9\r\n temp_list = []\r\n \r\n for cell in np.nditer(temp_window, op_flags=['readwrite']):\r\n variance = (cell - mean)**2\r\n temp_list.append(variance)\r\n st_deviation = math.sqrt(sum(temp_list)/9)\r\n\r\n if st_deviation >= 0.05 and icemask[r,c] == 1 and cumulative_slush[r,c] < 2800: \r\n slush_ice[r,c] = 1\r\n elif icemask[r,c] != 1 and albedos[r,c] > 0:\r\n slush_ice[r,c] = 3\r\n elif icemask[r,c] != 1:\r\n slush_ice[r,c] = -1 \r\n else: \r\n slush_ice[r,c] = 2\r\n\r\n\r\n\r\n### To count pixels in drainage systems \r\n\r\n#if st_deviation >= 0.05 and icemask[r,c] == 1 and slush_hotspot[r,c] < 2800 and Polygon(polyname).contains(Point(lats[r,c],mod_lons[r,c])): \r\n \r\n#pixlist21.append(len(slush_list))\r\n#topelev21.append(np.percentile(slush_list,90))\r\n\r\n\r\n\r\n \r\n \r\n \r\n#slush_ice = np.flipud(slush_ice)\r\n\r\n #slush_list.append(slush_ice)\r\n\r\n\r\n\r\n\r\n\r\n#plot one\r\n\r\n#from matplotlib.colors import from_levels_and_colors\r\n#cmap, norm = from_levels_and_colors([-1,1,2,3,4],['white','orangered','azure','silver'])\r\n#fig = plt.figure(figsize=(8, 6))\r\n#m = Basemap(projection='lcc', resolution='l',\r\n# width=2E6, height=3E6, lat_0=72, lon_0=-37,)\r\n#mplot = m.pcolormesh(lons, lats, slush_ice,latlon=True, cmap=cmap, norm=norm)\r\n#mplot = m.drawparallels(np.arange(-80.,81.,10.),labels=[True,False,True,False])\r\n#mplot = m.drawmeridians(np.arange(-180.,181.,20.),labels=[False,False,False,True])\r\n#plt.clim(-1, 4)\r\n#plt.title('Slush on GrIS')\r\n#plt.colorbar; \r\n\r\n\r\n\r\n \r\n# To create output\r\n\r\n#header = \"ncols {}\\n\".format(slush_ice.shape[1])\r\n#header += \"nrows {}\\n\".format(slush_ice.shape[0])\r\n#header += \"xllcorner -440510.18862\\n\"\r\n#header += \"yllcorner -3467275.427575\\n\"\r\n#header += \"cellsize 5000\\n\"\r\n#header += \"NODATA_value -9999\"\r\n\r\n#np.savetxt(\"slush2019\"+\"_thresh8_5_wtr\"+\".asc\",slush_ice, header=header, fmt=\"%1.2f\", comments='')\r\n\r\n\r\n\r\n\r\n\r\n\r\n##### To load polygons\r\n \r\n#with open('GrnDrainageSystems_Ekholm.txt', 'r') as f:\r\n\r\n # data = f.readlines() # Reading all data\r\n \r\n # Removing header\r\n # idx = 0\r\n # while not 'END OF HEADER' in data[idx]:\r\n # print(data[idx]) # If you want to print the header\r\n # idx += 1\r\n \r\n # Extracting the first point of the first polygon\r\n # Needs to start at idx+1 since not incrementing after found end of header\r\n # tempLine = data[idx+1] # Current coordinate\r\n # print(tempLine.split(' '))\r\n # tempPoint = tempLine.strip().split(' ') # Removing leading (and ending) spaces and splitting\r\n # indices that gives:\r\n # code, latitude, longitude:\r\n # [0],[6],[11]\r\n \r\n #Extracting the point of each polygon\r\n # tempPolyID = float(tempPoint[0])\r\n #\r\n # polyList.append((float(tempPoint[6]), float(tempPoint[11])))\r\n # tempPolyList is a list with polygon ID followed by a series of tuples with lat,lon coordinates for that polygon\r\n \r\n \r\n \r\n \r\n # Start looping over the data.\r\n # for i in range(idx+2, len(data)):\r\n # tempLine = data[i] # Current coordinate\r\n # tempPoint = tempLine.strip().split(' ') # Removing leading (and ending) spaces and splitting\r\n \r\n # if float(tempPoint[0]) == tempPolyID: # Not recommended to use == for float....\r\n # New point of current polygon \r\n # polyList.append((float(tempPoint[6]), float(tempPoint[11])))\r\n # else:\r\n # New polygon\r\n # tempPolyID = float(tempPoint[0])\r\n # polyList.append(tempPolyID)\r\n # polyList.append((float(tempPoint[6]), float(tempPoint[11])))\r\n\r\n\r\n\r\n##########################\r\n\r\n\r\n#fig = plt.figure(figsize=(8, 6))\r\n#cmap = plt.get_cmap('rainbow')\r\n#cmap.set_under('white') \r\n#m = Basemap(projection='lcc', resolution='l',\r\n# width=2E6, height=3E6, lat_0=72, lon_0=-37,)\r\n#mplot = m.pcolormesh(lons, lats, slush_hotspot, vmin= 0.5, cmap=cmap, latlon=True)\r\n#mplot = m.drawparallels(np.arange(-80.,81.,10.),labels=[True,False,True,False])\r\n#mplot = m.drawmeridians(np.arange(-180.,181.,20.),labels=[False,False,False,True])\r\n#mplot = m.drawcoastlines()\r\n#plt.title('Cumulative slush-days')\r\n#plt.colorbar;\r\n \r\n","sub_path":"detect_slush_on_greenland.py","file_name":"detect_slush_on_greenland.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"5976834","text":"# Feature selection (mordred)\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\n\n# This is the output from the rdkit descriptor calculator tool on Galaxy\nfilename1 = \"molecular-descriptors-mordred.tabular\"\n\n# This is the initial dataset that contains a list of compounds \\\n# (in SMILES format) and a label in the last column (0 or 1) which \\\n# indicates if the compound is active against the estrogen nuclear receptor\nfilename2 = \"er-data.smi\"\n\n# Import data into a pandas dataframe\np_df1 = pd.read_csv(filename1, sep='\\t', dtype='O')\np_df2 = pd.read_csv(filename2, sep='\\t', dtype='O')\n\n# Keep only columns that represent features i.e the molecular descriptors\nX = p_df1\ny = p_df2['label']\n\n\n# np.reshape(y, (X.shape[0], 1))\n# Change the datatype of the features to float and the labels to int\nX = X.astype(\"float32\")\ny = y.astype(\"int32\")\n\n# Replace inf to nan\nX = X.replace([np.inf], np.nan)\ny = y.replace([np.inf], np.nan)\n\n# Convert nan values to 0\nX.fillna(value=0, inplace=True)\ny.fillna(value=0, inplace=True)\n\n\n# Apply SelectKBest class to extract top n best features\nbestfeatures = SelectKBest(score_func=f_classif, k=20)\n\n# Apply ExtraTreesClassifier class to get ranking of the features\n#bestfeatures = ExtraTreesClassifier()\n\nfit = bestfeatures.fit(X, y)\n\nscores = pd.DataFrame(fit.scores_)\n#scores = pd.DataFrame(fit.feature_importances_)\ncolumns = pd.DataFrame(X.columns)\n\n# Concat two dataframes\nfeature_scores = pd.concat([columns, scores], axis=1)\nfeature_scores.columns = ['Feature', 'Score']\nn_largest = feature_scores.nlargest(20, 'Score')\nprint(n_largest)\nfeatures = n_largest['Feature'].values.tolist()\n\n# Extract selected features out of the dataset.\nX = X[features]\n\n# Separate data into train and test\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, shuffle=True)\n\nfile_names = ['X_train', 'X_test', 'y_train', 'y_test']\ndatasets = [X_train, X_test, y_train, y_test]\n\n# Convert the train and test sets to csv files\nfor dataset, file_name in zip(datasets, file_names):\n dataset.to_csv(file_name, sep='\\t', header=None, index=False)\n\n\n# Fit the training data on a random forest classifier\nrForest = RandomForestClassifier(min_samples_leaf=15, n_estimators=250, max_depth=20, random_state=0)\nrForest.fit(X_train, y_train)\n\nscore = rForest.score(X_test, y_test)\nprint(\"Quality of the model: \" + str(score))\n","sub_path":"featureSelection-mordred.py","file_name":"featureSelection-mordred.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"232799113","text":"class Fraccion():\n def __init__(self,num, denom = None):\n self.num = num\n if denom is not None:\n self.denom = denom\n else:\n self.denom = 1\n\n def sumar(self,otro):\n denominador = self.denom*otro.denom\n numerador = (self.num*otro.denom)+(otro.num*self.denom)\n\n return numerador,denominador\n\n def restar(self,otro):\n denominador = self.denom*otro.denom\n numerador = (self.num*otro.denom)-(otro.num*self.denom)\n\n return numerador,denominador\n\n def multiplicar(self,otro):\n numerador = self.num * otro.num\n denominador = self.denom * otro.denom\n\n return numerador,denominador\n\n def dividir(self,otro):\n numerador = self.num * otro.denom\n denominador = self.denom * otro.num\n\n return numerador,denominador\n\nclass TestFraccion():\n def test_sumar(self):\n\n f1 = Fraccion(2,3)\n f2 = Fraccion(5,6)\n\n suma = f1.sumar(f2) #3/2\n return suma\n\n def test_restar(self):\n\n f1 = Fraccion(7,5)\n f2 = Fraccion(8,9)\n\n resta = f1.restar(f2) #23/45\n return resta\n\n def test_multiplicar(self):\n\n f1 = Fraccion(5,3)\n f2 = Fraccion(9)\n\n multiplicacion = f1.multiplicar(f2) #15/1\n return multiplicacion\n\n def test_dividir(self):\n\n f1 = Fraccion(6,1)\n f2 = Fraccion(9)\n\n division = f1.dividir(f2) #2/3\n return division\n\ntest = TestFraccion()\nprint(test.test_sumar())\nprint(test.test_restar())\nprint(test.test_multiplicar())\nprint(test.test_dividir())\n\n\n\n","sub_path":"class_Fraccion.py","file_name":"class_Fraccion.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"224338991","text":"# -*- coding: cp936 -*-\nimport pythoncom\nimport pyHook\nimport time\nimport win32api\nimport os\nimport re\n\n\ndef getDomin(dirName):\n domain = dirName.split(\"_\")\n # print(\"dddddddddddddddddddddddddddddd:\"+str(domain))\n for i in reversed(domain):\n if ((i.replace(\"\\n\", \"\") in firstClassDomain) or (i.replace(\"\\n\", \"\") in conturyDomain)):\n pass\n else:\n return i\n\ndef writeToSave(date,fsaveToPath):#把输入保存到指定文件,fsaveToPath为文件描述符,https为带保存数据,可能为str,也可能为list\n #print(date)\n if(type(date) is type(\"\")):\n fsaveToPath.write(str(date).replace(\"\\n\",\"\") + \"\\n\")\n return 1\n for i in date:\n fsaveToPath.write(str(i).replace(\"\\n\",\"\") + \"\\n\")\n return 2\n\ndef main():\n visitedList=[]\n firstDir = os.listdir(dirPath)\n for second in firstDir:\n secondDir = os.listdir(dirPath + \"\\\\\" + second)\n for i in secondDir:\n visitedList.append(getDomin(i))\n print(writeToSave(visitedList,open(visitedDomainZL,\"a\")))\n\ndef getDomin(url):\n temp=url.split(\"/\")\n if(len(temp)<=2):\n return None\n temp2=temp[2].split(\"?\")[0]\n temp3=temp2.split(\"#\")[0]\n domain=temp3.split(\".\")\n #print(\"dddddddddddddddddddddddddddddd:\"+str(domain))\n for i in reversed(domain):\n if((i.replace(\"\\n\",\"\") in firstClassDomain) or (i.replace(\"\\n\",\"\") in conturyDomain)):\n pass\n else:\n return i\n\ndef test():\n pass\n\ndef jdtxt():\n lis = []\n pattern=\"aaaaaabbb\"\n rr=re.compile(pattern)\n num=0\n with open(r\"D:\\APP-data\\Pycharm\\Level_unauthorized\\url\\url2.txt\", 'r+') as fp:\n for i in fp.readlines():\n if(re.search(rr,i)!=None):\n num=1\n if(num==1):\n lis.append(i)\n print (lis)\n os.remove(r\"D:\\APP-data\\Pycharm\\Level_unauthorized\\url\\url2.txt\")\n with open(r\"D:\\APP-data\\Pycharm\\Level_unauthorized\\url\\url2.txt\", 'a+')as f:\n for i in lis[1:]:\n #print (i)\n f.write(i)\n\nif __name__ == \"__main__\":\n firstClassDomain = (\"biz\", \"com\", \"edu\", \"gov\", \"info\", \"int\", \"mil\", \"name\", \"net\", \"org\", \"pro\", \"xxx\",\n \"aero\", \"cat\", \"coop\", \"jobs\", \"museum\", \"travel\", \"mobi\", \"asia\", \"tel\", \"arpa\", \"root\",\n \"post\")\n conturyDomain = (\"cn\", \"de\",\"uk\", \"us\", \"jp\", \"fr\", \"eg\", \"eu\", \"br\")\n dirPath = r\"E:\\pic\"\n visitedDomainZL = r\"D:\\APP-data\\Pycharm\\Level_unauthorized\\url\\VDZL.txt\"\n\n #main()\n #test()\n #jdtxt()\n print(getDomin(\"http://ckadk.lskdjf.com#?#fjdk=qkjw&ajskdj=KJk\"))","sub_path":"level_unauthorized/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"222791307","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2013-2014 DNAnexus, Inc.\n#\n# This file is part of dx-toolkit (DNAnexus platform client libraries).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# 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\nfrom __future__ import print_function\n\nimport dxpy\nimport json\nimport string\nimport random\nimport sys\nimport argparse\nimport os\n\n# to find the magic library\nimport magic\nimport subprocess\n\ndef id_generator(size=10, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))\n\ndef unpack(input):\n m = magic.Magic()\n\n # determine compression format\n try:\n file_type = m.from_file(input)\n except Exception as e:\n raise dxpy.AppError(\"Error while identifying compression format: \" + str(e))\n \n # if we find a tar file throw a program error telling the user to unpack it\n if file_type == 'application/x-tar':\n raise dxpy.AppError(\"App does not support tar files. Please unpack.\")\n\n # since we haven't returned, the file is compressed. Determine what program to use to uncompress\n uncomp_util = None\n if file_type == 'XZ compressed data':\n uncomp_util = 'xzcat'\n elif file_type[:21] == 'bzip2 compressed data':\n uncomp_util = 'bzcat'\n elif file_type[:20] == 'gzip compressed data':\n uncomp_util = 'zcat'\n elif file_type == 'POSIX tar archive (GNU)' or 'tar' in file_type:\n raise dxpy.AppError(\"Found a tar archive. Please untar your sequences before importing\")\n else:\n # just return input filename since it's already uncompressed\n return input\n\n if uncomp_util != None: \n # bzcat does not support -t. Use non streaming decompressors for testing input\n test_util = None\n if uncomp_util == 'xzcat':\n test_util = 'xz'\n elif uncomp_util == 'bzcat':\n test_util = 'bzip2'\n elif uncomp_util == 'zcat':\n test_util = 'gzip'\n\n try:\n subprocess.check_call(\" \".join([test_util, \"-t\", input]), shell=True)\n except subprocess.CalledProcessError:\n raise dxpy.AppError(\"File failed integrity check by \"+uncomp_util+\". Compressed file is corrupted.\")\n\n # with that in hand, unzip file. If we find a tar archive then exit with error.\n try:\n with subprocess.Popen([uncomp_util, input], stdout=subprocess.PIPE).stdout as pipe:\n line = pipe.next()\n uncomp_type = m.from_buffer(line)\n except Exception as e:\n raise dxpy.AppError(\"Error detecting file format after decompression: \" + str(e))\n\n if uncomp_type == 'POSIX tar archive (GNU)' or 'tar' in uncomp_type:\n raise dxpy.AppError(\"Found a tar archive after decompression. Please untar your files before importing\")\n elif 'ASCII text' not in uncomp_type:\n raise dxpy.AppError(\"After decompression found file type other than plain text\")\n \n try:\n out_name = id_generator()\n subprocess.check_call(\" \".join([uncomp_util, \"--stdout\", input, \">\", out_name]), shell=True)\n return out_name\n except subprocess.CalledProcessError as e:\n raise dxpy.AppError(\"Unable to open compressed input for reading: \" + str(e))\n\ndef detect_type(bed_file):\n delimiter = find_delimiter(bed_file)\n with open(bed_file, 'rU') as bf:\n header=\"\"\n while \"track\" not in header:\n header=bf.readline()\n # if this isn't a browser line either then there isn't a header\n if \"browser\" not in header:\n break\n if \"type=bedDetail\" in header:\n print(\"File is a BED detail file\", file=sys.stderr)\n return {\"type\": \"bedDetail\", \"delimiter\": delimiter}\n \n num_cols = find_num_columns(bed_file, delimiter)\n if num_cols >= 12:\n return {\"type\": \"genes\", \"delimiter\": delimiter}\n else:\n return {\"type\": \"spans\", \"delimiter\": delimiter}\n \n# takes the whole bed file and splits into separate files for each track contained in it\n\ndef split_on_track(bed_file):\n files = []\n current_filename = id_generator()\n # open bed file\n with open(bed_file, 'rU') as bf:\n curr_file = open(current_filename, \"w\")\n line = bf.readline()\n if line.startswith(\"browser\"):\n line = bf.readline()\n curr_file.write(line)\n line = bf.readline()\n while True:\n if line.startswith(\"track\"):\n # close and save our last track as a new file\n curr_file.close()\n files.append(current_filename)\n # open a new file for the next track\n current_filename = id_generator()\n curr_file = open(current_filename, \"w\")\n elif line == \"\":\n curr_file.close()\n files.append(current_filename)\n break\n \n curr_file.write(line)\n line = bf.readline()\n\n return files\n\ndef find_num_columns(bed_file, delimiter=\"\\t\"):\n num_cols = 0\n\n with open(bed_file, \"rU\") as bf:\n line = bf.readline()\n while line != \"\":\n if line.startswith(\"track\"):\n line = bf.readline()\n line = line.split(delimiter)\n if len(line) > num_cols:\n num_cols = len(line)\n line = bf.readline()\n\n print(\"Found num cols: \" + str(num_cols), file=sys.stderr)\n return num_cols\n\ndef find_delimiter(bed_file):\n with open(bed_file, \"rU\") as bf: \n line = bf.readline()\n if line.startswith(\"track\"):\n line = bf.readline()\n tab_split = line.split(\"\\t\")\n \n if len(tab_split) >= 3: \n print(\"Bed file is tab delimited\", file=sys.stderr)\n return \"\\t\"\n else: \n space_split = line.split()\n if len(space_split) < 3: \n raise dxpy.AppError(\"File is not a valid bed file (neither space delimited nor tab delimited)\")\n print(\"Bed file is space delimited\", file=sys.stderr)\n return \" \"\n \ndef import_spans(bed_file, table_name, ref_id, file_id, additional_types, property_keys, property_values, tags, isBedDetail, delimiter=\"\\t\"):\n num_cols = find_num_columns(bed_file, delimiter)\n\n # if this is a bedDetail file we should treat the last two columns separately\n if isBedDetail:\n num_cols -= 2\n \n possible_columns = [(\"chr\", \"string\"),\n (\"lo\", \"int32\"),\n (\"hi\", \"int32\"),\n (\"name\", \"string\"),\n (\"score\", \"float\"),\n (\"strand\", \"string\"),\n (\"thick_start\", \"int32\"),\n (\"thick_end\", \"int32\"),\n (\"item_rgb\", \"string\")]\n\n bedDetail_columns = [(\"bedDetail_ID\", \"string\"),\n (\"bedDetail_desc\", \"string\")]\n\n possible_default_row = [\"\", 0, 0, \"\", 0, \".\", 0, 0, \"\"]\n\n columns = possible_columns[:num_cols]\n\n if isBedDetail:\n columns.extend(bedDetail_columns)\n\n if num_cols > len(columns):\n for i in range(len(columns), num_cols):\n columns.append((\"BED_column_\"+str(i+1), \"string\"))\n possible_default_row.append(\"\")\n\n default_row = possible_default_row[:num_cols]\n\n if isBedDetail:\n default_row.extend([\"\",\"\"])\n\n column_descs = [dxpy.DXGTable.make_column_desc(name, type) for name, type in columns]\n \n indices = [dxpy.DXGTable.genomic_range_index(\"chr\",\"lo\",\"hi\", 'gri')]\n for c in columns:\n if \"name\" in c:\n indices.append(dxpy.DXGTable.lexicographic_index([\n dxpy.DXGTable.lexicographic_index_column(\"name\", True, False),\n dxpy.DXGTable.lexicographic_index_column(\"chr\"),\n dxpy.DXGTable.lexicographic_index_column(\"lo\"),\n dxpy.DXGTable.lexicographic_index_column(\"hi\")], \"search\"))\n break\n \n with open(bed_file, 'rU') as bed, dxpy.new_dxgtable(column_descs, indices=indices, mode='w') as span:\n details = {\"original_contigset\": dxpy.dxlink(ref_id)}\n if file_id != None:\n details[\"original_file\"] = dxpy.dxlink(file_id)\n if len(property_keys) != len(property_values):\n raise dxpy.AppError(\"Expected each provided property to have a corresponding value.\")\n for i in range(len(property_keys)):\n details[property_keys[i]] = property_values[i] \n \n span.set_details(details)\n\n span.add_types([\"Spans\", \"gri\"])\n span.rename(table_name)\n\n for line in bed:\n row = list(default_row)\n\n if line.startswith(\"track\"):\n details = span.get_details()\n details['track'] = line\n span.set_details(details)\n continue\n line = line.rstrip(\"\\n\")\n line = line.split(delimiter)\n if isBedDetail:\n # only the first 4 columns are guaranteed to be defined by UCSC\n validate_line(line[:4])\n # save last two fields separately\n bedDetailFields = line[-2:]\n line = line[:-2] \n else: \n validate_line(line[:num_cols])\n \n # check to see if this is a weird line\n if len(line) == 0:\n break\n if len(line) < 3:\n raise dxpy.AppError(\"Line: \"+\"\\t\".join(line)+\" in BED file contains less than the minimum 3 columns. Invalid BED file.\")\n\n try:\n row[0] = line[0]\n row[1] = int(line[1])\n row[2] = int(line[2])\n row[3] = line[3]\n # dashes are sometimes used when field is invalid\n if line[4] == \"-\" or line[4] == \".\":\n line[4] = 0\n row[4] = float(line[4])\n row[5] = line[5]\n # dashes are sometimes used when field is invalid\n if line[6] == \"-\" or line[6] == \".\":\n line[6] = 0\n row[6] = int(line[6])\n # dashes are sometimes used when field is invalid\n if line[7] == \"-\" or line[7] == \".\":\n line[7] = 0\n row[7] = int(line[7])\n row[8] = line[8]\n\n # an index error would come from having fewer columns in a row, which we should handle ok\n except IndexError:\n pass\n # value error when fields are messed up and string gets converted to int, etc. Throw these out.\n except ValueError:\n continue\n \n if isBedDetail:\n # add these in at the end if we have a bedDetail file\n row[num_cols] = bedDetailFields[0]\n row[num_cols+1] = bedDetailFields[1]\n \n span.add_row(row)\n\n span.flush()\n\n return dxpy.dxlink(span.get_id())\n\n\n##########named spans###############END\n\ndef generate_gene_row(line, block_size, block_start, span_type, default_row, parent_id, span_id):\n row = list(default_row)\n\n try:\n # chr\n row[0] = line[0]\n\n # lo\n row[1] = int(line[1])\n # if we're a child, add our offset\n if parent_id != -1:\n row[1] += block_start\n\n # hi\n # if we're a child, just add size to our start\n if parent_id != -1:\n row[2] = row[1] + block_size\n else:\n row[2] = int(line[2]) \n\n # name\n row[3] = line[3]\n\n # span_id\n row[4] = span_id\n\n # type\n row[5] = span_type\n\n # strand\n row[6] = line[5]\n\n # is_coding\n if span_type == \"CDS\":\n row[7] = True\n elif \"UTR\" in span_type:\n row[7] = False\n else:\n row[7] = False\n\n # parent_id\n row[8] = parent_id\n\n # frame\n row[9] = -1\n\n # description\n row[10] = \"\\t\".join(line[12:])\n # BED files have no description?\n\n # a misformed line can have string columns where they should be int\n except ValueError:\n return None\n # if missing columns then also throw out the line\n except IndexError:\n return None\n\n return row\n\n\ndef import_genes(bed_file, table_name, ref_id, file_id, additional_types, property_keys, property_values, tags, delimiter=\"\\t\"):\n # implement BED importing from this format:\n # http://genome.ucsc.edu/FAQ/FAQformat.html#format1\n\n columns = [(\"chr\", \"string\"),\n (\"lo\", \"int32\"),\n (\"hi\", \"int32\"),\n (\"name\", \"string\"),\n (\"span_id\", \"int32\"),\n (\"type\", \"string\"),\n (\"strand\", \"string\"),\n (\"is_coding\", \"boolean\"),\n (\"parent_id\", \"int32\"),\n (\"frame\", \"int16\"),\n (\"description\", \"string\")]\n\n column_descs = [dxpy.DXGTable.make_column_desc(name, type) for name, type in columns]\n \n indices = [dxpy.DXGTable.genomic_range_index(\"chr\",\"lo\",\"hi\", 'gri'), \n dxpy.DXGTable.lexicographic_index([\n dxpy.DXGTable.lexicographic_index_column(\"name\", True, False),\n dxpy.DXGTable.lexicographic_index_column(\"chr\"),\n dxpy.DXGTable.lexicographic_index_column(\"lo\"),\n dxpy.DXGTable.lexicographic_index_column(\"hi\"),\n dxpy.DXGTable.lexicographic_index_column(\"type\")], \"search\")]\n\n default_row = [\"\", 0, 0, \"\", -1, \"\", \".\", False, -1, -1, \"\"]\n\n with open(bed_file, 'rU') as bed, dxpy.new_dxgtable(column_descs, indices=indices, mode='w') as span:\n span_table_id = span.get_id()\n\n details = {\"original_contigset\": dxpy.dxlink(ref_id)}\n if file_id != None:\n details[\"original_file\"] = dxpy.dxlink(file_id)\n if len(property_keys) != len(property_values):\n raise dxpy.AppError(\"Expected each provided property to have a corresponding value.\")\n for i in range(len(property_keys)):\n details[property_keys[i]] = property_values[i]\n span.set_details(details)\n\n span.add_types([\"gri\", \"Genes\"])\n span.rename(table_name)\n\n current_span_id = 0\n\n # where the parsing magic happens\n for line in bed:\n if line.startswith(\"track\"):\n details = span.get_details()\n details['track'] = line\n span.set_details(details)\n continue\n line = line.rstrip(\"\\n\")\n row = list(default_row)\n line = line.split(delimiter)\n validate_line(line)\n if len(line) < 12:\n raise dxpy.AppError(\"Line: \"+\"\\t\".join(line)+\" in gene model-like BED file contains less than 12 columns. Invalid BED file.\")\n\n # add parent gene track\n row = generate_gene_row(line, 0, 0, \"transcript\", default_row, -1, current_span_id)\n if row != None:\n span.add_row(row)\n current_parent_id = current_span_id\n current_span_id += 1 \n \n # add all children\n blockCount = int(line[9])\n line[10] = line[10].rstrip(\",\").split(\",\")\n blockSizes = [int(line[10][n]) for n in range(blockCount)]\n line[11] = line[11].rstrip(\",\").split(\",\")\n blockStarts = [int(line[11][n]) for n in range(blockCount)]\n\n gene_lo = int(line[1])\n gene_hi = int(line[2])\n\n # set thick* to be within the gene if outside\n thickStart = min(max(int(line[6]), gene_lo), gene_hi)\n thickEnd = max(min(int(line[7]), gene_hi), gene_lo)\n \n for i in range(blockCount):\n # look to thickStart and thickEnd to get information about the type of this region\n # if thick* are the same or cover the whole transcript then we ignore them\n # else, we partition the exons into CDS and UTR based on their boundaries\n if thickStart == thickEnd or (thickStart == gene_lo and thickEnd == gene_hi):\n span.add_row(generate_gene_row(line, \n blockSizes[i], \n blockStarts[i], \n \"exon\", \n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n else:\n exon_lo = int(line[1])+blockStarts[i]\n exon_hi = int(exon_lo+blockSizes[i])\n\n # we're all UTR if we enter either of these\n if (exon_hi <= thickStart and line[5] == '+') or (exon_lo >= thickEnd and line[5] == '-'):\n span.add_row(generate_gene_row(line, \n blockSizes[i], \n blockStarts[i], \n \"5' UTR\", \n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n elif (exon_hi <= thickStart and line[5] == '-') or (exon_lo >= thickEnd and line[5] == '+'):\n span.add_row(generate_gene_row(line, \n blockSizes[i], \n blockStarts[i], \n \"3' UTR\", \n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n\n # if this is true then we overlap CDS partially or completely\n elif (exon_lo < thickEnd and exon_hi > thickStart):\n # entirely contained\n if exon_lo >= thickStart and exon_hi <= thickEnd:\n span.add_row(generate_gene_row(line, \n blockSizes[i], \n blockStarts[i], \n \"CDS\", \n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n else:\n # left portion is UTR\n if exon_lo < thickStart:\n if line[5] == '+':\n UTR_type = \"5' UTR\"\n else:\n UTR_type = \"3' UTR\"\n UTR_size = (min(blockSizes[i], thickStart - exon_lo))\n span.add_row(generate_gene_row(line, \n UTR_size, \n blockStarts[i], \n UTR_type,\n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n\n # CDS portion\n CDS_size = blockSizes[i] - (max(exon_lo, thickStart) - exon_lo)\n CDS_size -= (exon_hi - min(exon_hi, thickEnd))\n CDS_start = (max(exon_lo, thickStart) - exon_lo) + blockStarts[i]\n span.add_row(generate_gene_row(line, \n CDS_size, \n CDS_start, \n \"CDS\",\n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n\n # right portion is UTR\n if exon_hi > thickEnd:\n if line[5] == '+':\n UTR_type = \"3' UTR\"\n else:\n UTR_type = \"5' UTR\"\n UTR_size = (min(blockSizes[i], exon_hi - thickEnd))\n UTR_start = blockStarts[i] + thickEnd - exon_lo\n span.add_row(generate_gene_row(line, \n UTR_size, \n UTR_start, \n UTR_type,\n default_row, \n current_parent_id, \n current_span_id))\n current_span_id += 1\n\n return dxpy.dxlink(span.get_id())\n\n\nparser = argparse.ArgumentParser(description='Import a local BED file as a Spans or Genes object. If multiple tracks exist in the BED file, one object will be created for each.')\nparser.add_argument('filename', help='local filename to import')\nparser.add_argument('reference', help='ID of ContigSet object (reference) that this BED file annotates')\nparser.add_argument('--file_id', default=None, help='the DNAnexus file-id of the original file. If provided, a link to this id will be added in the type details')\nparser.add_argument('--additional_type', default=[], action='append', help='This will be added to the list of object types (in addition to the type \\\"Spans\\\", or \\\"Genes\\\" which is added automatically)')\nparser.add_argument('--property_key', default=[], action='append', help='The keys in key-value pairs that will be added to the details of the object. The nth property key will be paired with the nth property value. The number of keys must equal the number of values provided')\nparser.add_argument('--property_value', default=[], action='append', help='The values in key-value pairs that will be added to the details of the object. The nth property key will be paired with the nth property value. The number of keys must equal the number of values provided')\nparser.add_argument('--tag', default=[], action='append', help='\"A set of tags (string labels) that will be added to the resulting Variants table object. (You can use tags and properties to better describe and organize your data)')\n\n\ndef import_BED(**args):\n if len(args) == 0:\n cmd_line_args = parser.parse_args(sys.argv[1:])\n args['filename'] = cmd_line_args.filename\n args['reference'] = cmd_line_args.reference\n args['file_id'] = cmd_line_args.file_id\n args['additional_type'] = cmd_line_args.additional_type\n args['property_key'] = cmd_line_args.property_key\n args['property_value'] = cmd_line_args.property_value\n args['tag'] = cmd_line_args.tag\n\n bed_filename = args['filename']\n reference = args['reference']\n file_id = args['file_id']\n additional_types = args['additional_type']\n property_keys = args['property_key']\n property_values = args['property_value']\n tags = args['tag']\n\n job_outputs = []\n # uncompresses file if necessary. Returns new filename\n bed_filename_uncomp = unpack( bed_filename )\n\n current_file = 1\n\n for import_filename in split_on_track(bed_filename_uncomp):\n try:\n bed_basename = os.path.basename(bed_filename)\n except:\n bed_basename = bed_filename\n if current_file == 1:\n name = bed_basename\n else:\n name = bed_basename+\"_\"+str(current_file)\n current_file += 1\n bed_type = detect_type(import_filename)[\"type\"]\n delimiter = detect_type(import_filename)[\"delimiter\"]\n\n print(\"Bed type is : \" + bed_type, file=sys.stderr)\n if bed_type == \"genes\":\n print(\"Importing as Genes Type\", file=sys.stderr)\n job_outputs.append(import_genes(import_filename, name, reference, file_id, additional_types, property_keys, property_values, tags, delimiter))\n elif bed_type == \"spans\" or bed_type == \"bedDetail\":\n print(\"Importing as Spans Type\", file=sys.stderr)\n if bed_type == \"bedDetail\":\n print(\"input file is in 'bedDetails' format...\", file=sys.stderr)\n bedDetail=True\n else:\n bedDetail=False\n job_outputs.append(import_spans(import_filename, name, reference, file_id, additional_types, property_keys, property_values, tags, bedDetail, delimiter))\n else:\n raise dxpy.AppError(\"Unable to determine type of BED file\")\n\n subprocess.check_call(\" \".join([\"rm\", import_filename]), shell=True)\n\n if(bed_filename != bed_filename_uncomp):\n subprocess.check_call(\" \".join([\"rm\", bed_filename_uncomp]), shell=True)\n\n print(json.dumps(job_outputs))\n return job_outputs\n\ndef validate_line(line):\n line_str = \"\\t\".join(line)\n entries = list(line)\n \n if len(entries) > 1:\n try:\n if int(entries[1]) < 0:\n raise dxpy.AppError(\"The start position for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[1]))\n except ValueError:\n raise dxpy.AppError(\"One of the start values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[1]))\n \n if len(entries) > 2: \n try:\n if int(entries[2]) < 0:\n raise dxpy.AppError(\"The end position for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[2]))\n except ValueError:\n raise dxpy.AppError(\"One of the end values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[2]))\n \n if len(entries) > 4: \n try:\n if entries[4] != \".\" and entries[4] != \"-\":\n float(entries[4])\n except ValueError:\n raise dxpy.AppError(\"One of the score values for one entry could not be translated to a number. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[4]))\n \n if len(entries) > 5:\n if entries[5] != \"+\" and entries[5] != \"-\" and entries[5] != \".\":\n raise dxpy.AppError(\"The strand indicated for an element was not \\\"+\\\", \\\"-\\\", or \\\".\\\"\" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[5]))\n \n if len(entries) > 6:\n try:\n if entries[6] != \".\" and entries[6] != \"-\":\n if int(entries[6]) < 0:\n raise dxpy.AppError(\"The thickStart position for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[6]))\n except ValueError:\n raise dxpy.AppError(\"One of the thickStart values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[6]))\n \n if len(entries) > 7: \n try:\n if entries[7] != \".\" and entries[7] != \"-\":\n if int(entries[7]) < 0:\n raise dxpy.AppError(\"The thickEnd position for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[7]))\n except ValueError:\n raise dxpy.AppError(\"One of the thickEnd values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[7]))\n \n if len(entries) > 9:\n try:\n if int(entries[9]) < 0:\n raise dxpy.AppError(\"The number of exons (blockCount) for one entry was unexpectedly negative. \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[9]))\n except ValueError:\n raise dxpy.AppError(\"One of the thickEnd values could not be translated to an integer. \" + \"\\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[9]))\n \n if len(entries) > 10: \n try:\n entries[10] = entries[10].rstrip(\",\").split(\",\")\n blockStarts = [int(entries[10][n]) for n in range(int(entries[9]))]\n except:\n raise dxpy.AppError(\"Could not parse the blockSizes entry as a comma-separated list of integers \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[10]))\n \n if len(entries) > 11:\n try:\n entries[11] = entries[11].rstrip(\",\").split(\",\")\n blockStarts = [int(entries[11][n]) for n in range(int(entries[9]))]\n except:\n raise dxpy.AppError(\"Could not parse the blockStarts entry as a comma-separated list of integers \\nOffending line_str: \" + line_str + \"\\nOffending value: \" + str(entries[11]))\n\n\ndef main(**args):\n import_BED(**args)\n\nif __name__ == '__main__':\n import_BED()\n","sub_path":"src/python/dxpy/scripts/dx_bed_to_spans.py","file_name":"dx_bed_to_spans.py","file_ext":"py","file_size_in_byte":31038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"580490568","text":"import pygame\nfrom pygame.locals import *\n\n\nclass Block(pygame.sprite.Sprite):\n def __init__(self, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.PINK = (0, 200, 0)\n self.image = pygame.Surface((32,32))\n self.image.fill(self.PINK)\n self.image.convert()\n self.rect = pygame.Rect(x, y, 32, 32)","sub_path":"block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"397563020","text":"import joblib\nimport numpy as np\nimport pandas as pd\nimport uvicorn\n\nfrom fastapi import status\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\nfrom app.app import *\n\napp = FastAPI()\n\ntopic_data = pd.read_csv(\"data/topic_data.csv\")\n\n@app.get(\"/\")\ndef hello():\n return {\"message\":\"Hello Sherlock\"}\n\n@app.get('/top_10_clusters')\nasync def top_10_clusters():\n top_10_labels = [0, 3, 2, 5, 34, 33, 18, 22, 12, 41]\n LDA_model = joblib.load('models/LDA_models_50.pkl')\n \n results = [str(top_10_words(LDA_model, label)) for label in top_10_labels]\n res = \"-\".join(results)\n return res\n\n@app.get('/get_score')\nasync def get_score(text: str):\n scores = calculate_score(text)\n res = str(list(scores.values())).strip('[]')\n return res\n\n@app.get('/similar_tickets')\nasync def similar_tickets(label: int, nb_tickets: int):\n return topic_data[topic_data.topic == label][:nb_tickets][['Number', 'Description']]\n\n@app.get('/LDA_predict')\nasync def LDA_predict(model_name: str, data: str):\n embedded_data = preprocess(data)\n LDA_model = joblib.load('models/LDA_models_50.pkl')\n prediction = LDA_model.transform(embedded_data).argmax(axis=1)[0]\n \n top10Words = top_10_words(LDA_model, prediction)\n top10Words = ' '.join(top10Words)\n \n result = str(prediction) + \" - \" + top10Words\n\n return result\n\n\n@app.get('/predict')\nasync def predict(model_name: str, data: str):\n embedded_data = preprocess(data)\n embedded_data = np.atleast_2d(embedded_data)\n \n model = joblib.load('models/{}'.format(model_name))\n \n prediction = str(model.predict(embedded_data)[0])\n \n \n return prediction\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=8000, reload=True)\n\n\"\"\"\nTo cover:\n- possible return types: not nympy array, etc\n\"\"\"","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"30208432","text":"import pytest\n\nfrom .common import simple_ok_check, simple_nok_check\n\n\ndef test_max_file_lines_ok():\n code = \"\\n\".join([\"tool\"] * 1000)\n simple_ok_check(code)\n\n\ndef test_max_file_lines_nok():\n code = \"\\n\".join([\"tool\"] * 1001)\n simple_nok_check(code, \"max-file-lines\", 1001)\n\n\n# fmt: off\n@pytest.mark.parametrize('code', [\n\"\"\"\n#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\"\"\",\n])\ndef test_max_line_length_ok(code):\n simple_ok_check(code)\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"\n#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\"\"\",\n])\ndef test_max_line_length_nok(code):\n simple_nok_check(code, 'max-line-length')\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"\nfunc foo():\n var x\n\n\n\"\"\",\n\"\"\"\nfunc foo():\n pass\n\"\"\",\n\"\"\"\nfunc foo():\n\tx.bar()\n\"\"\",\n])\ndef test_trailing_ws_ok(code):\n simple_ok_check(code)\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"func foo():\n pass \n\"\"\",\n\"\"\"func foo():\n pass \n\"\"\",\n\"\"\"func foo():\n pass\t\n\"\"\",\n\"\"\"func foo():\n pass \t \n\"\"\",\n])\ndef test_trailing_ws_nok(code):\n simple_nok_check(code, 'trailing-whitespace')\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"\nfunc foo():\n pass\n\"\"\",\n\"\"\"\nfunc foo():\n\tpass\n\"\"\",\n])\ndef test_mixed_tabs_and_spaces_ok(code):\n simple_ok_check(code)\n\n\n@pytest.mark.parametrize('code', [\n\"\"\"\nclass X:\n func foo():\n \tpass\n\"\"\",\n\"\"\"\nclass X:\n\tfunc foo():\n\t pass\n\"\"\",\n])\ndef test_mixed_tabs_and_spaces_nok(code):\n simple_nok_check(code, 'mixed-tabs-and-spaces', line=4)\n","sub_path":"tests/linter/test_format_checks.py","file_name":"test_format_checks.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"319792351","text":"import socket\nimport time\nimport httplib\nimport json\nfrom urllib import urlencode\nfrom threading import Lock, Event\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom graphite.node import LeafNode, BranchNode\nfrom graphite.readers import FetchInProgress\nfrom graphite.logger import log\nfrom graphite.util import unpickle\nfrom graphite.intervals import IntervalSet, Interval\nfrom graphite import opentsdb\nfrom graphite import tree\n\n\nclass RemoteStore(object):\n lastFailure = 0.0\n available = property(lambda self: time.time() - self.lastFailure > settings.REMOTE_RETRY_DELAY)\n\n def __init__(self, host):\n self.host = host\n\n def find(self, query):\n request = FindRequest(self, query)\n request.send()\n return request\n\n def fail(self):\n self.lastFailure = time.time()\n\n\nclass OpenTSDBRemoteStore(object):\n lastFailure = 0.0\n available = property(lambda self: time.time() - self.lastFailure > settings.REMOTE_RETRY_DELAY)\n\n def __init__(self, host):\n self.host = host\n\n def find(self, query):\n log.info(\"OpenTSDBRemoteStore:find \" + str(query))\n request = OpenTSDBFindRequest(self, query)\n request.send()\n return request\n\n def fail(self):\n self.lastFailure = time.time()\n\n\nclass FindRequest(object):\n __slots__ = ('store', 'query', 'connection',\n 'failed', 'cache_key', 'cached_result')\n\n def __init__(self, store, query):\n self.store = store\n self.query = query\n self.connection = None\n self.failed = False\n\n if query.start_time:\n start = query.start_time - (query.start_time % settings.FIND_CACHE_DURATION)\n else:\n start = \"\"\n\n if query.end_time:\n end = query.end_time - (query.end_time % settings.FIND_CACHE_DURATION)\n else:\n end = \"\"\n\n self.cache_key = \"find:%s:%s:%s:%s\" % (store.host, query.pattern, start, end)\n self.cached_result = None\n\n def send(self):\n log.info(\"FindRequest.send(host=%s, query=%s) called\" % (self.store.host, self.query))\n\n self.cached_result = cache.get(self.cache_key)\n if self.cached_result is not None:\n log.info(\n \"FindRequest(host=%s, query=%s) using cached result\" % (\n self.store.host, self.query)\n )\n return\n\n self.connection = HTTPConnectionWithTimeout(self.store.host)\n self.connection.timeout = settings.REMOTE_FIND_TIMEOUT\n\n query_params = [\n ('local', '1'),\n ('format', 'pickle'),\n ('query', self.query.pattern),\n ]\n if self.query.start_time:\n query_params.append(('from', self.query.start_time))\n\n if self.query.end_time:\n query_params.append(('until', self.query.end_time))\n\n query_string = urlencode(query_params)\n\n try:\n self.connection.request('GET', '/metrics/find/?' + query_string)\n except:\n log.exception(\n \"FindRequest.send(host=%s, query=%s) exception during request\" % (\n self.store.host, self.query)\n )\n self.store.fail()\n self.failed = True\n\n def get_results(self):\n if self.failed:\n return\n\n if self.cached_result is not None:\n results = self.cached_result\n else:\n if self.connection is None:\n self.send()\n\n try:\n response = self.connection.getresponse()\n assert response.status == 200, \"received error response %s - %s\" % (\n response.status, response.reason)\n result_data = response.read()\n results = unpickle.loads(result_data)\n\n except:\n log.exception(\n \"FindRequest.get_results(host=%s, query=%s) exception processing response\" % (\n self.store.host, self.query)\n )\n self.store.fail()\n return\n\n cache.set(self.cache_key, results, settings.FIND_CACHE_DURATION)\n\n for node_info in results:\n if node_info.get('isLeaf'):\n reader = RemoteReader(self.store, node_info, bulk_query=self.query.pattern)\n node = LeafNode(node_info['metric_path'], reader)\n else:\n node = BranchNode(node_info['metric_path'])\n\n node.local = False\n yield node\n\n\nclass OpenTSDBFindRequest(object):\n __slots__ = ('store', 'query')\n\n def __init__(self, store, query):\n self.store = store\n self.query = query\n\n def _query_prefix(self):\n return self.query.pattern\n\n def send(self):\n pass\n\n def get_results(self):\n client = opentsdb.API(self.store.host)\n try:\n results = tree.OpenTSDBMetricsMeta(client).find(self._query_prefix())\n except:\n log.exception(\n \"OpenTSDBFindRequest.get_results(host=%s, query=%s) exception processing response\" % (\n self.store.host, self.query)\n )\n self.store.fail()\n return\n\n # cache.set(self.cache_key, results, settings.FIND_CACHE_DURATION)\n\n log.info(\"RESULTS: \" + str(results))\n for node_info in results:\n if node_info.get('isLeaf'):\n reader = OpenTSDBRemoteReader(self.store, node_info, bulk_query=self.query.pattern)\n node = LeafNode(node_info['metric_path'], reader)\n else:\n node = BranchNode(node_info['metric_path'])\n\n node.local = False\n yield node\n\n\nclass RemoteReader(object):\n __slots__ = ('store', 'metric_path', 'intervals', 'query', 'connection')\n cache_lock = Lock()\n request_cache = {}\n request_locks = {}\n request_times = {}\n\n def __init__(self, store, node_info, bulk_query=None):\n self.store = store\n self.metric_path = node_info['metric_path']\n self.intervals = IntervalSet([Interval(*args) for args in node_info['intervals']])\n self.query = bulk_query or node_info['metric_path']\n self.connection = None\n\n def __repr__(self):\n return '' % (id(self), self.store.host)\n\n def get_intervals(self):\n return self.intervals\n\n def fetch(self, start_time, end_time):\n query_params = [\n ('target', self.query),\n ('format', 'pickle'),\n ('local', '1'),\n ('noCache', '1'),\n ('from', str(int(start_time))),\n ('until', str(int(end_time)))\n ]\n query_string = urlencode(query_params)\n urlpath = '/render/?' + query_string\n url = \"http://%s%s\" % (self.store.host, urlpath)\n\n # Quick cache check up front\n self.clean_cache()\n cached_results = self.request_cache.get(url)\n if cached_results:\n for series in cached_results:\n if series['name'] == self.metric_path:\n time_info = (series['start'], series['end'], series['step'])\n return (time_info, series['values'])\n\n # Synchronize with other RemoteReaders using the same bulk query.\n # Despite our use of thread synchronization primitives, the common\n # case is for synchronizing asynchronous fetch operations within\n # a single thread.\n (request_lock, wait_lock, completion_event) = self.get_request_locks(url)\n\n if request_lock.acquire(False): # we only send the request the first time we're called\n try:\n log.info(\"RemoteReader.request_data :: requesting %s\" % url)\n self.connection = HTTPConnectionWithTimeout(self.store.host)\n self.connection.timeout = settings.REMOTE_FETCH_TIMEOUT\n self.connection.request('GET', urlpath)\n except:\n completion_event.set()\n self.store.fail()\n log.exception(\"Error requesting %s\" % url)\n raise\n\n def wait_for_results():\n if wait_lock.acquire(False): # the FetchInProgress that gets waited on waits for the actual completion\n try:\n response = self.connection.getresponse()\n if response.status != 200:\n raise Exception(\"Error response %d %s from %s\" % (response.status, response.reason, url))\n\n pickled_response = response.read()\n results = unpickle.loads(pickled_response)\n self.cache_lock.acquire()\n self.request_cache[url] = results\n self.cache_lock.release()\n completion_event.set()\n return results\n except:\n completion_event.set()\n self.store.fail()\n log.exception(\"Error requesting %s\" % url)\n raise\n\n else: # otherwise we just wait on the completion_event\n completion_event.wait(settings.REMOTE_FETCH_TIMEOUT)\n cached_results = self.request_cache.get(url)\n if cached_results is None:\n raise Exception(\"Passive remote fetch failed to find cached results\")\n else:\n return cached_results\n\n def extract_my_results():\n for series in wait_for_results():\n if series['name'] == self.metric_path:\n time_info = (series['start'], series['end'], series['step'])\n return (time_info, series['values'])\n\n return FetchInProgress(extract_my_results)\n\n def clean_cache(self):\n self.cache_lock.acquire()\n try:\n if len(self.request_locks) >= settings.REMOTE_READER_CACHE_SIZE_LIMIT:\n log.info(\"RemoteReader.request_data :: clearing old from request_cache and request_locks\")\n now = time.time()\n for url, timestamp in self.request_times.items():\n age = now - timestamp\n if age >= (2 * settings.REMOTE_FETCH_TIMEOUT):\n del self.request_locks[url]\n del self.request_times[url]\n if url in self.request_cache:\n del self.request_cache[url]\n finally:\n self.cache_lock.release()\n\n def get_request_locks(self, url):\n self.cache_lock.acquire()\n try:\n if url not in self.request_locks:\n self.request_locks[url] = (Lock(), Lock(), Event())\n self.request_times[url] = time.time()\n return self.request_locks[url]\n finally:\n self.cache_lock.release()\n\n\nclass OpenTSDBRemoteReader(object):\n __slots__ = ('store', 'metric_path', 'intervals', 'query')\n request_times = {}\n\n def __init__(self, store, node_info, bulk_query=None):\n self.store = store\n self.metric_path = node_info['metric_path']\n self.query = bulk_query or node_info['metric_path']\n\n def __repr__(self):\n return '' % (id(self), self.store.host)\n\n def get_intervals(self):\n return IntervalSet([Interval(float(\"-inf\"), float(\"inf\"))])\n\n def _make_time_info(self, ts):\n dps = ts['dps']\n timestamps = map(int, dps.keys())\n start_time = min(timestamps)\n end_time = max(timestamps)\n step = (end_time - start_time) / len(timestamps)\n return (start_time, end_time, step)\n\n def _make_values(self, ts):\n return [item[1] for item in sorted(ts['dps'].items())]\n\n def fetch(self, start_time, end_time):\n log.info(\"FETCH: \" + str(start_time) + \", \" + str(end_time))\n api = opentsdb.API(self.store.host)\n results = api.query(self.metric_path, start_time, end_time)\n log.info(\"RESULTS: %s\" % str(results)[:100])\n def _extract_my_results():\n for series in results:\n log.info(\"SERIES: %s\" % series.keys())\n if series['metric'] == self.metric_path:\n time_info = self._make_time_info(series)\n data = (time_info, self._make_values(series))\n log.info(\"DATA: \" + str(data)[:400])\n return data\n\n return FetchInProgress(_extract_my_results)\n\n\n# This is a hack to put a timeout in the connect() of an HTTP request.\n# Python 2.6 supports this already, but many Graphite installations\n# are not on 2.6 yet.\n\nclass HTTPConnectionWithTimeout(httplib.HTTPConnection):\n timeout = 30\n\n def connect(self):\n msg = \"getaddrinfo returns an empty list\"\n for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):\n af, socktype, proto, canonname, sa = res\n try:\n self.sock = socket.socket(af, socktype, proto)\n try:\n # default self.timeout is an object() in 2.6\n self.sock.settimeout(float(self.timeout))\n except:\n pass\n self.sock.connect(sa)\n self.sock.settimeout(None)\n except socket.error as e:\n msg = e\n if self.sock:\n self.sock.close()\n self.sock = None\n continue\n break\n if not self.sock:\n raise socket.error(msg)\n","sub_path":"webapp/graphite/remote_storage.py","file_name":"remote_storage.py","file_ext":"py","file_size_in_byte":13560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"391059750","text":"from flask import Blueprint\r\nfrom flask import render_template\r\nfrom flask import redirect\r\nfrom flask import url_for\r\nfrom flask import request\r\nfrom flask import flash\r\n\r\nfrom mdizabela.mod.access import access\r\n\r\nfrom mdizabela.models import db\r\nfrom mdizabela.models import SysUserLevel\r\n\r\nfrom .forms import UpraveniUserLevelForm\r\nfrom .forms import VytvoritUserLevelForm\r\n\r\nmod_user_level = Blueprint('mod_user_level', __name__)\r\n\r\n####\r\n#### přehled uživatelských úrovní\r\n####\r\n@mod_user_level.route('/prehled/', methods=['GET'])\r\n@access('admin')\r\ndef view_user_level():\r\n user_level = SysUserLevel.query.order_by(SysUserLevel.id.asc()).all()\r\n add_user_level_form = VytvoritUserLevelForm()\r\n upraveni_form = UpraveniUserLevelForm()\r\n\r\n return render_template('mod_user_level/prehled_user_level.jinja', pridat_form = add_user_level_form, upraveni_form = upraveni_form, levels = user_level)\r\n\r\n####\r\n#### Přidání nového uživatele\r\n####\r\n@mod_user_level.route('/pridat/', methods=['POST'])\r\n@access('admin')\r\ndef pridat_user_level():\r\n add_user_level_form =VytvoritUserLevelForm(request.form)\r\n\r\n if add_user_level_form.validate():\r\n level_exist = SysUserLevel.query.filter_by(ident=add_user_level_form.ident.data).first()\r\n if not level_exist:\r\n level = SysUserLevel()\r\n level.ident = add_user_level_form.ident.data\r\n level.nazev = add_user_level_form.nazev.data\r\n level.popis = add_user_level_form.popis.data\r\n\r\n db.session.add(level)\r\n db.session.commit()\r\n\r\n flash(f'Level {add_user_level_form.ident.data} byl úspěšně vytvořen.', 'alert-success')\r\n return redirect(url_for('mod_user_level.view_user_level'))\r\n else:\r\n flash(f'Uživatelský level {add_user_level_form.ident.data} již existuje.', 'alert-danger')\r\n return redirect(url_for('mod_user_level.view_user_level'))\r\n else:\r\n for error in add_user_form.errors.values():\r\n for item in error:\r\n flash(f'{item}', 'alert-danger')\r\n return redirect(url_for('mod_user_level.view_prehled_uzivatelu'))\r\n\r\n@mod_user_level.route('/upravit/', methods=['POST'])\r\n@access('admin')\r\ndef upravit_user_level(level_id):\r\n upraveni_form = UpraveniUserLevelForm(request.form)\r\n\r\n if upraveni_form.validate():\r\n level = SysUserLevel.query.filter_by(id = level_id).first()\r\n if level.ident == upraveni_form.ident.data:\r\n if level.nazev != upraveni_form.nazev.data:\r\n level.nazev = upraveni_form.nazev.data\r\n flash(f'Název pro uživatelské oprávnění {level.ident} byl úspěšně změněno na {level.nazev}.', 'alert-success')\r\n\r\n if level.popis != upraveni_form.popis.data:\r\n level.popis = upraveni_form.popis.data\r\n if len(upraveni_form.popis.data) == 0:\r\n flash(f'Popis pro uživatelské oprávnění {level.ident} byl úspěšně smazán.', 'alert-success')\r\n else:\r\n flash(f'Popis pro uživatelské oprávnění {level.ident} byl úspěšně změněno na {level.popis}.', 'alert-success')\r\n\r\n db.session.add(level)\r\n db.session.commit()\r\n\r\n else:\r\n flash(f'Pokus o změnu identifikátoru.', 'alert-danger')\r\n return redirect(url_for('mod_user_level.view_user_level'))\r\n else:\r\n for error in upraveni_form.errors.values():\r\n for item in error:\r\n flash(f'{item}', 'alert-danger')\r\n\r\n return redirect(url_for('mod_user_level.view_user_level'))\r\n","sub_path":"mdizabela/mod/user_level/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"447284176","text":"import numpy as np\r\nfrom collections import defaultdict\r\nfrom scipy.optimize import minimize\r\npd.set_option('display.max_columns', None)\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\ndef optimize_parameter(\r\n data, \r\n start_variance= 20 ** 2, \r\n beta_square = 3 ** 2,\r\n verbose = True,\r\n tolerance = 1e-2,\r\n):\r\n '''Fits the parameters in B-T model.\r\n Args:\r\n winners: The array of winners for each of N contests, of shape [N, 2].\r\n losers: The array of losers for each of N contests, of shape [N, 2].\r\n surface: The array of surfaces for each of N contest, of shape [N, 3].\r\n beta: The uncontral variances of the game\r\n start_variance_1: The initial variance of the surface 1\r\n verbose: Whether or not to print the progress of the optimisation.\r\n tolerance: The tolerance required for the optimisation to successfully terminate.\r\n '''\r\n def fun_to_minimize(theta):\r\n # Constrain\r\n variance = theta \r\n _, discrepancy = calculate_ratings(data = data,start_mean = 1500,start_var = variance ,beta_square = beta_square,k = 0.0001,gamma_q =1/2)\r\n \r\n if verbose:\r\n print('variance: {} ; discrepancy: {}'.format(variance[0],discrepancy[0]))\r\n return discrepancy\r\n \r\n opt_result = minimize(fun_to_minimize,\r\n np.array([start_variance],dtype='float'),\r\n method='Nelder-Mead',\r\n tol=tolerance,)\r\n return (opt_result.success, {'variance':opt_result.x[0]})\r\n","sub_path":"Lin Zhe Ching's Thesis/code/BT_model/optimize_parameter.py","file_name":"optimize_parameter.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"133575298","text":"#!/bin/python\nimport os.path as path\nimport os, re, sys, shutil, zipfile\nfrom distutils.dir_util import copy_tree\n\nORIGINAL_DIRECTORY = path.abspath(path.join(__file__ , \"../..\"))\nWORKING_DIRECTORY = path.abspath(path.join(__file__ , \"../out/miniorange-oauth-client\"))\nAUTOLOAD = path.abspath(path.join(WORKING_DIRECTORY, \"_autoload.php\"))\nSETTINGS = path.abspath(path.join(WORKING_DIRECTORY, \"mo_oauth_settings.php\"))\nBASE_DECREMENTAL = 10\n\n\ndef get_version(file):\n f = open(file)\n string = f.read()\n matched_lines = [line for line in string.split('\\n') if \"VERSION\" in line]\n f.close()\n if len(matched_lines) > 1:\n return false\n return matched_lines[0].split(',')[1].split('\\'')[1].split('_')[1].upper();\n\n\ndef write_version(file):\n f = open(file)\n string = f.read()\n matched_lines = [line for line in string.split('\\n') if \"Version\" in line]\n f.close()\n version = matched_lines[0].split(\"Version\")[1].split(\": \")[1].split(\".\")\n old_version = ''\n for y in version:\n old_version = old_version + y + '.'\n\n new_version = ''\n for x in compute_version(version):\n new_version = new_version + x + \".\"\n\n\n\n new_version = new_version[:-1]\n old_version = old_version[:-1]\n print(\"Old Version: \" + old_version)\n print(\"New Version: \" + new_version)\n f = open(file, \"w\")\n f.write(string.replace(old_version, new_version))\n f.close()\n return new_version\n\n\ndef compute_version(current_version):\n version_to_compute = get_version(AUTOLOAD)\n decremental = BASE_DECREMENTAL\n if version_to_compute == \"ENTERPRISE\":\n decremental = 0\n if version_to_compute == \"PREMIUM\":\n decremental = BASE_DECREMENTAL * 1\n if version_to_compute == \"STANDARD\":\n decremental = BASE_DECREMENTAL * 2\n if version_to_compute == \"FREE\":\n decremental = BASE_DECREMENTAL * 3\n\n current_version[0] = str(int(current_version[0]) - decremental)\n return current_version\n\n\ndef manage_dirs():\n if not os.path.exists(WORKING_DIRECTORY):\n os.makedirs(WORKING_DIRECTORY)\n print(\"Directory \" + WORKING_DIRECTORY + \" Created \")\n else:\n print(\"Directory \" + WORKING_DIRECTORY + \" already exists\")\n\n print(\"Removing entire build dir...\")\n delete_files_from(WORKING_DIRECTORY)\n\n\ndef delete_files_from(folder_path):\n for file_object in os.listdir(folder_path):\n file_object_path = os.path.join(folder_path, file_object)\n if os.path.isfile(file_object_path):\n os.remove(file_object_path)\n else:\n shutil.rmtree(file_object_path)\n\ndef copy_files():\n print(\"Copying files...\")\n copy_tree(path.abspath(path.join(ORIGINAL_DIRECTORY, \"classes\")), path.abspath(path.join(WORKING_DIRECTORY, \"classes\")))\n copy_tree(path.abspath(path.join(ORIGINAL_DIRECTORY, \"resources\")), path.abspath(path.join(WORKING_DIRECTORY, \"resources\")))\n shutil.copy(path.abspath(path.join(ORIGINAL_DIRECTORY, \"mo_oauth_settings.php\")), WORKING_DIRECTORY)\n shutil.copy(path.abspath(path.join(ORIGINAL_DIRECTORY, \"_autoload.php\")), WORKING_DIRECTORY)\n\ndef generate_version():\n basepath = path.abspath(path.join(WORKING_DIRECTORY, \"classes\"))\n version = get_version(AUTOLOAD)\n if version == \"PREMIUM\":\n delete_files_from(path.abspath(path.join(basepath, \"Enterprise\")))\n if version == \"STANDARD\":\n delete_files_from(path.abspath(path.join(basepath, \"Enterprise\")))\n delete_files_from(path.abspath(path.join(basepath, \"Premium\")))\n if version == \"FREE\":\n delete_files_from(path.abspath(path.join(basepath, \"Enterprise\")))\n delete_files_from(path.abspath(path.join(basepath, \"Premium\")))\n delete_files_from(path.abspath(path.join(basepath, \"Standard\")))\n\ndef prepare_plugin(new_version):\n output_filename = 'mo_oauth_client_' + new_version\n shutil.make_archive(output_filename, 'zip', path.abspath(path.join(WORKING_DIRECTORY, \"..\")))\n print(\"Archive Successfully created at: \" + path.abspath(path.join(WORKING_DIRECTORY, output_filename + \".zip\")))\n\nmanage_dirs()\ncopy_files()\ngenerate_version()\nnew_version = write_version(path.abspath(path.join(WORKING_DIRECTORY, \"mo_oauth_settings.php\")))\nzipfile = prepare_plugin(new_version)\n","sub_path":"wp-content/plugins/miniorange-oauth-oidc-single-sign-on/build/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"334582478","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport config\n\nimport tweepy\nimport random\nfrom datetime import datetime\n\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\n\n\nauth = tweepy.OAuthHandler(config.consumer_key, config.consumer_secret)\nauth.set_access_token(config.access_key, config.access_secret)\napi = tweepy.API(auth)\n\n\nmonth_map = {\n '1': 'January',\n '2': 'February',\n '3': 'March',\n '4': 'April',\n '5': 'May',\n '6': 'June',\n '7': 'July',\n '8': 'August',\n '9': 'September',\n '10': 'October',\n '11': 'November',\n '12': 'December'\n}\n\n\nmessages = [\n 'Happy day!',\n 'Have a nice day!',\n 'How\\'s your day going?',\n 'One of the best days of the year!',\n 'Remember to smile today!',\n 'Today is yesterday\\'s tomorrow!',\n 'Today will be tomorrow\\'s yesterday!',\n 'Another day!',\n 'Today is great!',\n 'What\\'s the news today?',\n 'The week\\'s going by so fast! Enjoy today!',\n 'Enjoy your time on this earth. Especially today!',\n 'Make today special!',\n 'Make the most of your day today!',\n 'What will today bring?',\n 'Have a great day!',\n 'What a beautiful day!'\n]\n\n\n# get current date string\ndatetime_now = datetime.now()\n\nmonth_int = datetime_now.strftime('%m')\nmonth_str = month_map[str(int(month_int))]\n\nday_int = datetime_now.strftime('%d')\nday_str = str(int(day_int))\n\n\n# construct wiki url\nwiki_link = 'https://en.wikipedia.org/wiki/' + month_str + '_' + day_str\n\n\n# commit tweet\ntweet_components = [\n random.choice(messages),\n month_str,\n day_str + ':',\n wiki_link\n]\n\napi.update_status(' '.join(tweet_components))\n\n\n\n\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"486778927","text":"# -*- coding: utf-8 -*-\n# import os\n# import log_func as log\n# from log_func import log_log\n\nsettings = {\n # 设置templates路径:\n # 'template_path': os.path.join(os.path.dirname(__file__), \"templates\"),\n\n # 设置静态文件解析路径:\n # 'static_path': os.path.join(os.path.dirname(__file__), \"static\"),\n\n # 设置防跨站请求攻击:默认为False,即不可防御。\n 'xsrf_cookies': False,\n\n # 设置登陆路径,未登陆用户在操作时跳转会用到这个参数:默认为@tornado.web.authenticated\n # 'login_url': \"/login\",\n\n # 设置调试模式:默认为False,即不是调试模式\n 'debug': True,\n\n # 设置cookie密钥:默认为字符串\"secure cookies\"\n 'cookie_secret': \"dskfhisdjklagkfdklag;lkjasdklgjkldsjaklgjkldsfksdklf\",\n\n # 设置是否自动编码:不设置默认为自动编码。\n 'autoescape': None,\n\n # 设置template_loader,可以从独立的路径中导入template:其中your_moudle为自己定义的模块,ZipLoader是tornado.template.BaseLoader的子类\n # 'template_loader': your_moudle.ZipLoader,\n\n # 设置gzip压缩:\n # 'gzip': True,\n\n # 设置静态路径头部:默认是\"/static/\"\n # 'static_url_prefix': \"/mystatic/\",\n\n # 设置静态文件处理类:默认是tornado.web.StaticFileHandler\n # 'static_handler_class': MyStaticFileHandler,\n\n # 设置静态文件的参数:默认为空字典。\n # 'static_handler_args': {\"key1\": \"value1\", \"key2\": \"value2\"},\n\n # 设置日志处理函数\n # 'log_function': log_log\n}\n","sub_path":"celery_test/new_test/tornado_setting.py","file_name":"tornado_setting.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"41938275","text":"__author__ = 'heocon'\nimport dryscrape\nfrom threading import Thread\nimport logging\n\nfilename='data.xml'\narg1='MacBook'\narg2='stuxnet'\nlogfile='file.log'\n\nclass client():\n\n def __init__(self):\n self.data = []\n #self.file={}\n self.file1={}\n self.file2={}\n self.threads = []\n #define logger\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M',\n filename=logfile,\n filemode='a')\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n # set a format which is simpler for console use\n formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n # tell the handler to use this format\n console.setFormatter(formatter)\n # add the handler to the root logger\n logging.getLogger('').addHandler(console)\n # define a Handler which writes INFO messages or higher to the sys.stderr\n\n\n def google(self,arg,savefile):\n #def google(self,arg):\n sess = dryscrape.Session(base_url = 'http://scholar.google.fr')\n logging.info('Visiting in google scholar')\n #print 'Visiting in google scholar'\n sess.visit('/scholar?hl=en&q='+arg)\n content= sess.xpath('//*[@class=\"gs_rs\"]')\n if content==None:\n logging.error('Site is invalid when visiting')\n return -1\n logging.debug('Scrapping content')\n #print 'Scrapping content'\n author=sess.xpath('//*[@class=\"gs_a\"]')\n logging.debug('Scrapping author')\n #print 'Scrapping author'\n title=sess.xpath('//*[@class=\"gs_rt\"]')\n logging.debug('Scrapping title')\n with open(savefile,'a') as f:\n logging.info('Star writing in example.log with google search')\n f.write('\\n')\n f.write('\\n')\n for n in range(0,len(content)-1):\n logging.info('Write in each row %d of google search' %n)\n f.write(' \\n')\n a=self.namespace={\"title\":title[n].text(),\"author\":author[n].text(),\"content\":content[n].text()}\n #self.file1[n] = a\n if a['title']==None:\n logging.error('Site is invalid in google search')\n return -1\n else:\n for key1 in a.keys():\n if key1==None:\n logging.error(\"Site is invalid\")\n exit()\n b=' <'+str(key1)+'>'+str(a[key1])+''+str(key1)+'>\\n'\n f.write(b)\n f.write(' \\n')\n f.write('\\n')\n def amazon(self,arg,savefile):\n #def amazon(self,arg):\n sess=dryscrape.Session(base_url = 'http://www.amazon.com')\n logging.info('Visiting in amazon')\n #print 'Visiting in amazon'\n sess.visit('/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords='+arg)\n\n # save in the dictionary form\n with open(savefile,'a') as f:\n logging.info('Writing in example.log with amazon search')\n f.write('\\n')\n f.write('\\n')\n for i in range(0,15):\n f.write(' \\n')\n a=self.search_amazon(i,sess)\n logging.info('Write in each row %d of amazon search' %i)\n #self.file1[i] = a\n if a['name']==None:\n logging.error(\"Site is invalid in amazon search\")\n return -1\n else:\n for key in a.keys():\n b=' <'+str(key)+'>'+str(a[key])+''+str(key)+'>\\n'\n f.write(b)\n f.write(' \\n')\n f.write('\\n')\n\n\n def search_amazon(self,i,sess):\n name='//li[@id=\"result_'+str(i)+'\\\"]'\n nodes=sess.xpath(name)\n logging.debug('Scrapping item')\n #print 'Scraping item'\n ref=None\n name=None\n price=None\n descrip=None\n otherprice=None\n shipping=None\n star=None\n for node in nodes:\n node2=node.xpath('div/div[2][@class=\"a-row a-spacing-mini\"]')\n if node2==None:\n logging.error('Website is invalid when visiting amazon')\n return -1\n node3=node.xpath('div/div[3][@class=\"a-row a-spacing-mini\"]')\n node4=node.xpath('div/div[4][@class=\"a-row a-spacing-top-mini a-spacing-mini\"]')\n node5=node.xpath('div/div[5][@class=\"a-row a-spacing-none\"]')\n for a in node2:\n a_1=a.xpath('div/a[@href]')\n logging.debug('Scrapping title and link')\n #print 'Scrapping title and link'\n for b in a_1:\n ref=b['href']\n name=b['title']\n if name==None:\n logging.error('Name is invalid')\n return -1\n for a in node3:\n f=a.xpath('div')\n i=len(f)\n logging.debug('Scrapping price, description, and other_price')\n #print 'Scrapping price, description, and other_price'\n a_2=a.xpath('div/a/span[@class=\"a-size-base a-color-price s-price a-text-bold\"]')\n #if a_2==None:\n # logging.error('Price is invalid')\n # return -1\n a_3=a.xpath('div[2]/div/span[@class=\"a-size-small a-color-price\"]')\n #if a_3==None:\n # logging.error('Price is invalid')\n # return -1\n a_4=a.xpath('div['+str(i)+']/a/span[@class=\"a-size-base a-color-price a-text-bold\"]')\n #if a_4==None:\n # logging.error('Price is invalid')\n # return -1\n for b in a_2:\n price=b.text()\n for c in a_3:\n descrip=c.text()\n for d in a_4:\n otherprice=d.text()\n for a in node4:\n logging.debug('Scrapping shipping content')\n #print 'Scrapping shipping content'\n a_5=a.xpath('div/span[@class=\"a-size-small a-color-secondary\"]')\n\n for b in a_5:\n shipping=b.text()\n for a in node5:\n logging.debug('Scrapping star of item')\n #print 'Scrapping star of item'\n star= a.text()\n # save in dictionary form\n self.namespace={'ref':ref,'name':name,'price_new':price,'price_used':otherprice,'description':descrip,'shipping':shipping,'star':star}\n return self.namespace\n #def save_file(self,filename):\n def save_file(self,filename,file):\n with open(filename,'w') as f:\n row=file\n logging.info('Save in example.log')\n #print 'Save in example.log'\n ##row = file\n #f.write('\\n')\n #f.write('\\n')\n #for i in range(0,len(row)-1):\n # f.write(' \\n')\n for key in row.keys():\n if key==None:\n logging.error('Site is invalid')\n exit()\n a=' <'+str(key)+'>'+str(row[key])+''+str(key)+'>\\n'\n f.write(a)\n # f.write(' \\n')\n #f.write('\\n')\n\n\n def go(self):\n #self.google(arg2)\n #self.amazon(arg1)\n t1 = Thread(target=self.google,args=(arg2,filename))\n t2 = Thread(target=self.amazon,args=(arg1,filename))\n\n t1.start()\n t2.start()\n self.threads.append(t1)\n self.threads.append(t2)\n\n [t.join() for t in self.threads]\ndef main():\n a = client()\n a.go()\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n","sub_path":"task_2/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":8034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"255080165","text":"\"\"\"\ntprime.py\n\nA poisitive integer is considered to be a\nT-prime if it has exactly 3 divisors.\n\nThe problem states that you are given an\narray of n positive integers and must determine\nwhether or not they are T-prime\n\"\"\"\ndef brute_force(nums):\n tprimes = []\n for n in nums:\n if _brute_force(n) == True:\n tprimes.append(n)\n return tprimes\n\ndef _brute_force(n):\n divisors = 1\n for i in range(1,n):\n if divisors > 3:\n return False\n if n % i == 0:\n divisors += 1\n \n #This last little bit of logic is because\n #a prime number is an edgecase\n if divisors < 3:\n return False\n return True","sub_path":"Algorithms/tprime.py","file_name":"tprime.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"402783975","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom csv import writer\n\nurl = \"https://www.flipkart.com/mobiles/mi~brand/pr?sid=tyy%2C4io&otracker=nmenu_sub_Electronics_0_Mi&page=1\"\ncurrent = 0\nnext_page = 2\n\nwhile True:\n response = requests.get(url).text\n soup = BeautifulSoup(response, \"html.parser\")\n\n divs = soup.select(\"._1-2Iqu\")\n if not divs:\n break\n\n with open(\"rahul_mi.csv\", \"a\", newline=\"\") as file:\n csv_writer = writer(file)\n if not current:\n csv_writer.writerow([\"Mobile Name\", \"Price\"])\n\n for div in divs:\n mobile_name = div.select(\"._3wU53n\")[0].get_text()\n mobile_price = div.select(\"._1vC4OE\")[0].get_text()[1:]\n # print(f\"{mobile_name} --> {mobile_price}\")\n csv_writer.writerow([mobile_name, mobile_price])\n\n a_tags = soup.select(\"._2Xp0TH\")\n\n for tag in a_tags:\n if not current:\n pass\n else:\n url = f\"https://www.flipkart.com/mobiles/mi~brand/pr?sid=tyy%2C4io&otracker=nmenu_sub_Electronics_0_Mi&page={next_page}\"\n # print(url)\n print(f\"😈 Scarping Done {next_page}😈\")\n next_page += 1\n break\n current += 1\n","sub_path":"Web Scraping with BeautifulSoup/Flipkart Scripting/mi_phone.py","file_name":"mi_phone.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"286575885","text":"def recursion(ten,count = 0):\n if ten == 0 or ten == 1:\n return count\n elif ten % 2 == 0:\n count = count + 1\n ten = ten / 2\n return recursion(ten,count)\n elif ten % 2 == 1:\n count = count + 1\n ten = (ten+1) / 2\n return recursion(ten,count)\ndef tentotwo(ten):\n two = bin(ten)\n two = two[2:]\n while len(two) != 11:#change 11 output#\n two = '0'+two\n return two\ndef manytime(ten):#do recur n+1#\n alldata = 0\n for i in range(0,ten+1):#0~n n+1 time#\n alldata = alldata + recursion(i)#i#\n return alldata#alldata not in for#\nwhile True:\n data = input()\n ten = int(data,2)\n print(tentotwo(manytime(ten)))#many#\n split = input()\n if split == '-1':\n break\n","sub_path":"ds/circuit2.py","file_name":"circuit2.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"312499442","text":"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the PyMVPA package for the\n# copyright and license terms.\n#\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Unit tests for PyMVPA pattern handling\"\"\"\n\nfrom mvpa.datasets.masked import *\nfrom mvpa.misc.exceptions import DatasetError\n\nimport unittest\nimport numpy as N\nimport random\n\nclass MaskedDatasetTests(unittest.TestCase):\n\n def testCreateMaskedDataset(self):\n data = MaskedDataset(samples=[range(5)], labels=1,\n chunks=1)\n # simple sequence has to be a single pattern\n self.failUnlessEqual( data.nsamples, 1)\n # check correct pattern layout (1x5)\n self.failUnless(\n (data.samples == N.array([[0, 1, 2, 3, 4]])).all() )\n\n # check for single label and origin\n self.failUnless( (data.labels == N.array([1])).all() )\n self.failUnless( (data.chunks == N.array([1])).all() )\n\n # now try adding pattern with wrong shape\n self.failUnlessRaises(DatasetError,\n data.__iadd__,\n MaskedDataset(samples=N.ones((2,3)), labels=1,\n chunks=1))\n\n # now add two real patterns\n data += MaskedDataset(samples=N.random.standard_normal((2,5)),\n labels=2, chunks=2)\n self.failUnlessEqual( data.nsamples, 3 )\n self.failUnless( (data.labels == N.array([1,2,2]) ).all() )\n self.failUnless( (data.chunks == N.array([1,2,2]) ).all() )\n\n\n # test unique class labels\n data += MaskedDataset(samples=N.random.standard_normal((2,5)),\n labels=3)\n self.failUnless( (data.uniquelabels == N.array([1,2,3]) ).all() )\n\n # test wrong label length\n self.failUnlessRaises(DatasetError,\n MaskedDataset,\n samples=N.random.standard_normal((4,2,3,4)),\n labels=[1, 2, 3],\n chunks=2)\n\n # test wrong origin length\n self.failUnlessRaises( DatasetError,\n MaskedDataset,\n samples=N.random.standard_normal((4,2,3,4)),\n labels=[1, 2, 3, 4],\n chunks=[2, 2, 2])\n\n\n def testShapeConversion(self):\n data = MaskedDataset(samples=N.arange(24).reshape((2,3,4)),\n labels=1, chunks=1)\n self.failUnlessEqual(data.nsamples, 2)\n self.failUnlessEqual(data.samples.shape, (2,12))\n self.failUnless((data.samples ==\n N.array([range(12),range(12,24)])).all())\n\n\n def testPatternShape(self):\n data = MaskedDataset(samples=N.ones((10,2,3,4)), labels=1, chunks=1)\n self.failUnless(data.samples.shape == (10,24))\n\n\n def testFeature2Coord(self):\n origdata = N.random.standard_normal((10,2,4,3,5))\n data = MaskedDataset( samples=origdata, labels=2, chunks=2 )\n\n def randomCoord(shape):\n return [ random.sample(range(size),1)[0] for size in shape ]\n\n # check 100 random coord2feature transformations\n for i in xrange(100):\n # choose random coord\n c = randomCoord((2,4,3,5))\n # tranform to feature_id\n id = data.mapper.getOutId(c)\n\n # compare data from orig array (selected by coord)\n # and data from pattern array (selected by feature id)\n orig = origdata[:,c[0],c[1],c[2],c[3]]\n pat = data.samples[:, id]\n\n self.failUnless((orig == pat).all())\n\n\n def testCoord2Feature(self):\n origdata = N.random.standard_normal((10,2,4,3,5))\n data = MaskedDataset(samples=origdata, labels=2, chunks=2)\n\n def randomCoord(shape):\n return [ random.sample(range(size),1)[0] for size in shape ]\n\n for id in xrange(data.nfeatures):\n # transform to coordinate\n c = data.mapper.getInId(id)\n self.failUnlessEqual(len(c), 4)\n\n # compare data from orig array (selected by coord)\n # and data from pattern array (selected by feature id)\n orig = origdata[:,c[0],c[1],c[2],c[3]]\n pat = data.samples[:, id]\n\n self.failUnless((orig == pat).all())\n\n\n def testFeatureSelection(self):\n origdata = N.random.standard_normal((10,2,4,3,5))\n data = MaskedDataset(samples=origdata, labels=2, chunks=2)\n\n unmasked = data.samples.copy()\n\n # default must be no mask\n self.failUnless( data.nfeatures == 120 )\n self.failUnless(data.mapper.getOutSize() == 120)\n\n # check that full mask uses all features\n sel = data.selectFeaturesByMask( N.ones((2,4,3,5)) )\n self.failUnless( sel.nfeatures == data.samples.shape[1] )\n self.failUnless( data.nfeatures == 120 )\n\n # check partial array mask\n partial_mask = N.zeros((2,4,3,5), dtype='uint')\n partial_mask[0,0,2,2] = 1\n partial_mask[1,2,2,0] = 1\n\n sel = data.selectFeaturesByMask( partial_mask )\n self.failUnless( sel.nfeatures == 2 )\n self.failUnless( sel.mapper.getMask().shape == (2,4,3,5))\n\n # check that feature selection does not change source data\n self.failUnless(data.nfeatures == 120)\n self.failUnlessEqual(data.mapper.getOutSize(), 120)\n\n # check selection with feature list\n sel = data.selectFeatures([0,37,119])\n self.failUnless(sel.nfeatures == 3)\n\n # check size of the masked patterns\n self.failUnless( sel.samples.shape == (10,3) )\n\n # check that the right features are selected\n self.failUnless( (unmasked[:,[0,37,119]]==sel.samples).all() )\n\n\n def testPatternSelection(self):\n origdata = N.random.standard_normal((10,2,4,3,5))\n data = MaskedDataset(samples=origdata, labels=2, chunks=2)\n\n self.failUnless( data.nsamples == 10 )\n\n # set single pattern to enabled\n sel=data.selectSamples(5)\n self.failUnless( sel.nsamples == 1 )\n self.failUnless( data.nsamples == 10 )\n\n # check duplicate selections\n sel = data.selectSamples([5,5])\n self.failUnless( sel.nsamples == 2 )\n self.failUnless( (sel.samples[0] == sel.samples[1]).all() )\n self.failUnless( len(sel.labels) == 2 )\n self.failUnless( len(sel.chunks) == 2 )\n\n self.failUnless( sel.samples.shape == (2,120) )\n\n def testCombinedPatternAndFeatureMasking(self):\n data = MaskedDataset(\n samples=N.arange( 20 ).reshape( (4,5) ), labels=1, chunks=1 )\n\n self.failUnless( data.nsamples == 4 )\n self.failUnless( data.nfeatures == 5 )\n fsel = data.selectFeatures([1,2])\n fpsel = fsel.selectSamples([0,3])\n self.failUnless( fpsel.nsamples == 2 )\n self.failUnless( fpsel.nfeatures == 2 )\n\n self.failUnless( (fpsel.samples == [[1,2],[16,17]]).all() )\n\n\n def testOrigMaskExtraction(self):\n origdata = N.random.standard_normal((10,2,4,3))\n data = MaskedDataset(samples=origdata, labels=2, chunks=2)\n\n # check with custom mask\n sel = data.selectFeatures([5])\n self.failUnless( sel.samples.shape[1] == 1 )\n origmask = sel.mapper.getMask()\n self.failUnless( origmask[0,1,2] == True )\n self.failUnless( origmask.shape == (2,4,3) )\n\n\n\n def testPatternMerge(self):\n data1 = MaskedDataset(samples=N.ones((5,5,1)), labels=1, chunks=1)\n data2 = MaskedDataset(samples=N.ones((3,5,1)), labels=2, chunks=1)\n\n merged = data1 + data2\n\n self.failUnless(merged.nsamples == 8 )\n self.failUnless((merged.labels == [ 1,1,1,1,1,2,2,2]).all())\n self.failUnless((merged.chunks == [ 1,1,1,1,1,1,1,1]).all())\n\n data1 += data2\n\n self.failUnless(data1.nsamples == 8 )\n self.failUnless((data1.labels == [ 1,1,1,1,1,2,2,2]).all())\n self.failUnless((data1.chunks == [ 1,1,1,1,1,1,1,1]).all())\n\n\n def testLabelRandomizationAndSampling(self):\n data = MaskedDataset(samples=N.ones((5,1)), labels=range(5), chunks=1)\n data += MaskedDataset(samples=N.ones((5,1))+1, labels=range(5), chunks=2)\n data += MaskedDataset(samples=N.ones((5,1))+2, labels=range(5), chunks=3)\n data += MaskedDataset(samples=N.ones((5,1))+3, labels=range(5), chunks=4)\n data += MaskedDataset(samples=N.ones((5,1))+4, labels=range(5), chunks=5)\n self.failUnless( data.samplesperlabel == {0:5, 1:5, 2:5, 3:5, 4:5} )\n\n sample = data.getRandomSamples( 2 )\n self.failUnless( sample.samplesperlabel.values() == [ 2,2,2,2,2 ] )\n\n self.failUnless( (data.uniquechunks == range(1,6)).all() )\n\n # store the old labels\n origlabels = data.labels.copy()\n\n data.permuteLabels(True)\n\n self.failIf( (data.labels == origlabels).all() )\n\n data.permuteLabels(False)\n\n self.failUnless( (data.labels == origlabels).all() )\n\n # now try another object with the same data\n data2 = MaskedDataset(samples=data.samples, labels=data.labels,\n chunks=data.chunks )\n\n # labels are the same as the originals\n self.failUnless( (data2.labels == origlabels).all() )\n\n # now permute in the new object\n data2.permuteLabels( True )\n\n # must not affect the old one\n self.failUnless( (data.labels == origlabels).all() )\n # but only the new one\n self.failIf( (data2.labels == origlabels).all() )\n\n\n def testFeatureMasking(self):\n mask = N.zeros((5,3),dtype='bool')\n mask[2,1] = True; mask[4,0] = True\n data = MaskedDataset(\n samples=N.arange( 60 ).reshape( (4,5,3) ), labels=1, chunks=1,\n mask=mask)\n\n # check simple masking\n self.failUnless( data.nfeatures == 2 )\n self.failUnless( data.mapper.getOutId( (2,1) ) == 0 \n and data.mapper.getOutId( (4,0) ) == 1 )\n self.failUnlessRaises( ValueError, data.mapper.getOutId, (2,3) )\n self.failUnless( data.mapper.getMask().shape == (5,3) )\n self.failUnless( tuple(data.mapper.getInId( 1 )) == (4,0) )\n\n # selection should be idempotent\n self.failUnless(data.selectFeaturesByMask( mask ).nfeatures == data.nfeatures )\n # check that correct feature get selected\n self.failUnless( (data.selectFeatures([1]).samples[:,0] \\\n == N.array([12, 27, 42, 57]) ).all() )\n self.failUnless(tuple( data.selectFeatures([1]).mapper.getInId(0) ) == (4,0) )\n self.failUnless( data.selectFeatures([1]).mapper.getMask().sum() == 1 )\n\n # check sugarings\n # Access to simple attributes and samples\n self.failUnless(N.all(data.I == data.origids))\n self.failUnless(N.all(data.C == data.chunks))\n self.failUnless(N.all(data.L == data.labels))\n self.failUnless(N.all(data.S == data.samples))\n self.failUnless(N.all(data.O == data.mapper.reverse(data.samples)))\n\n # Access to unique attributes\n self.failUnless(N.all(data.UC == data.uniquechunks))\n self.failUnless(N.all(data.UL == data.uniquelabels))\n\n\n# def testROIMasking(self):\n# mask=N.array([i/6 for i in range(60)], dtype='int').reshape(6,10)\n# data = MaskedDataset(\n# N.arange( 180 ).reshape( (3,6,10) ), 1, 1, mask=mask )\n#\n# self.failIf( data.mapper.getMask().dtype == 'bool' )\n# # check that the 0 masked features get cut\n# self.failUnless( data.nfeatures == 54 )\n# self.failUnless( (data.samples[:,0] == [6,66,126]).all() )\n# self.failUnless( data.mapper.getMask().shape == (6,10) )\n#\n# featsel = data.selectFeatures([19])\n# self.failUnless( (data.samples[:,19] == featsel.samples[:,0]).all() )\n#\n# # check single ROI selection works\n# roisel = data.selectFeaturesByGroup([4])\n# self.failUnless( (data.samples[:,19] == roisel.samples[:,1]).all() )\n#\n# # check dual ROI selection works (plus keep feature order)\n# roisel = data.selectFeaturesByGroup([6,4])\n# self.failUnless( (data.samples[:,19] == roisel.samples[:,1]).all() )\n# self.failUnless( (data.samples[:,32] == roisel.samples[:,8]).all() )\n#\n# # check if feature coords can be recovered\n# self.failUnless( (roisel.getCoordinate(8) == (3,8)).all() )\n\n\ndef suite():\n return unittest.makeSuite(MaskedDatasetTests)\n\n\nif __name__ == '__main__':\n import runner\n\n","sub_path":"mvpa/tests/test_maskeddataset.py","file_name":"test_maskeddataset.py","file_ext":"py","file_size_in_byte":12807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"186732842","text":"# -*- coding: utf-8 -*-\r\nfrom perform.defines import *\r\nfrom perform.object import MagAttackPerform as CustomPerform\r\n\r\n#导表开始\nclass Perform(CustomPerform):\n\tid = 1211\n\tname = \"风雷弹\"\n\ttargetType = PERFORM_TARGET_ENEMY\n\ttargetCount = 1\n\tdamage = lambda self,SLV:SLV*2+20\n\tpower = 60\n\tconsumeList = {\n\t\t\"真气\": lambda SLV:SLV*1.2+20,\n\t}\n\trecoverList = {\n\t\t\"符能\": 10,\n\t}\n\tspeRatio = 100\n\tconfigInfo = {\n\t\t\"治疗\":lambda SLV:SLV*2+20,\n\t\t\"治疗威力\":50,\n\t\t\"目标数\":5,\n\t}\n#导表结束\r\n\r\n\tdef perform(self, att, vicCast):\r\n\t\tCustomPerform.perform(self, att, vicCast)\r\n\t\t\r\n\t\ttargetList = self.getPerformTargetList(att, att, 99)\r\n\t\ttargetList.sort(key=lambda w:w.hp)\r\n\t\ttargetCount = self.configInfo[\"目标数\"]\r\n\t\ttargetList = targetList[:targetCount]\r\n\t\ttargetCount = len(targetList)\r\n\t\tdamRatio = self.calDamageRatio(att, vicCast, vicCast, targetCount)\r\n\t\tfor vic in targetList:\r\n\t\t\tif vic.isDead():\r\n\t\t\t\tcontinue\r\n\t\t\tdp = self.calCure(att, vic, vicCast, damRatio)\r\n\t\t\tvic.addHP(dp, att)\r\n\t\t\t\t\r\n\tdef calCure(self, att, vic, vicCast, damRatio):\r\n\t\tmagDam = int(self.transCode(self.configInfo[\"治疗\"], att, vic))\r\n\t\tpower = self.configInfo[\"治疗威力\"]\r\n\t\tdp = att.calCure(vic, magDam, power, damRatio, self.getAttackType())\r\n\t\treturn dp\r\n\t\t\t\t","sub_path":"logic/perform/school/pf1211.py","file_name":"pf1211.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"506687236","text":"import sys\n \nimport pygame\nfrom pygame.locals import *\n \npygame.init()\n \nfps = 60\nfps_clock = pygame.time.Clock()\n \nwidth, height = 640, 480\nscreen = pygame.display.set_mode((width, height))\n \n# Game loop.\nwhile True:\n screen.fill((0, 0, 0))\n \n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n \n # Update.\n \n # Draw.\n \n pygame.display.flip()\n fps_clock.tick(fps)","sub_path":"pygame/lesson_1.py","file_name":"lesson_1.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"256786200","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.views.generic import RedirectView\nfrom users.views import auth_view\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('shops/', include('shops.urls')),\n path('', RedirectView.as_view(url='login/', permanent=True)),\n]\n\n# Add Django site authentication urls (for, logout, password management) and custom login view\nurlpatterns += [\n path('login/', auth_view, name='custom_login'),\n path('accounts/', include('django.contrib.auth.urls')),\n]\n\n# Url for list of users\nurlpatterns += [\n path('loggedin/', include('users.urls')),\n]\n","sub_path":"django_crud_app/django_crud_app/django_crud_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"117259872","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 21 13:07:56 2015\n\n@author: xiaohu\n\"\"\"\n\nimport requests\nimport datetime\nimport time\nimport re\nimport json\n\ns= requests.Session()\nlogin_url = \"http://www.learning.gov.cn/study/login.php\"\najax_url = \"http://www.learning.gov.cn/study/ajax.php\"\ncourse_url = \"http://www.learning.gov.cn/course/course.php\"\n\n\ndef login():\n data = {'username':'320323197111221058', 'password':'19981226'}\n resp = s.post(login_url, data, allow_redirects=False)\n resp.encoding = 'utf-8'\n print(resp.status_code)\n print(resp.headers)\n print(resp.text)\n if 'profile' in resp.headers['location']:\n return True\n return False\n\ndef list_course():\n r = s.get('http://www.learning.gov.cn/study')\n r.encoding = 'utf-8'\n m = re.findall(r'course.php\\?act=detail&courseid=\\d+', r.text)\n courses = [re.search(r'\\d+', x).group() for x in m]\n print(\"course list: \" + str(courses))\n return courses\n \ndef start_course():\n login()\n delay = 1200000\n for course_id in list_course():\n set_course_session(course_id, delay)\n msg1 = log_course(course_id)\n log_id = msg1['logId']\n err = '0'\n while err != '1' :\n msg = update_time(course_id, log_id)\n err = msg['err']\n if err == '2':\n print(\"重新登录...\")\n while login() == False:\n time.sleep(2)\n set_course_session(course_id, delay)\n log_id = log_course(course_id)['logId']\n elif err == '0':\n time.sleep(60)\n print(\"完成学习: course \" + course_id) \n \ndef set_course_session(course_id, delay):\n data = {'act':'set_course_session', 'courseId':course_id, 'delay':delay}\n r = s.post(ajax_url, data)\n msg = json.loads(r.text)\n print(msg)\n return msg\n \ndef log_course(course_id):\n data = {'act':'insert', 'courseId':course_id}\n print('开始课程学习日志: course ' + course_id)\n r = s.post(ajax_url, data)\n msg = json.loads(r.text)\n print(msg)\n return msg\n\ndef update_time(course_id, log_id):\n err = 0\n msg = ''\n while err==0:\n data = {'act':'update', 'courseId':course_id, 'logId':log_id}\n r = s.post(ajax_url, data)\n msg = json.loads(r.text)\n print(msg)\n err = msg['err']\n return msg\n \n \ndef exit_course(course_id, log_id):\n data = {'act':'exit', 'courseId':course_id, 'logId':log_id}\n r = s.post(ajax_url, data)\n msg = json.loads(r.text)\n print(msg)\n delta = msg['playTime'] if 'playTime' in msg else 0\n total_time = str(datetime.timedelta(seconds=delta))\n print('本次共学习: '+total_time)\n \nif __name__ == '__main__':\n start_course()\n","sub_path":"learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"298549516","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass AlipayOpenLotteryCampSubmitModel(object):\n\n def __init__(self):\n self._env = None\n\n @property\n def env(self):\n return self._env\n\n @env.setter\n def env(self, value):\n self._env = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.env:\n if hasattr(self.env, 'to_alipay_dict'):\n params['env'] = self.env.to_alipay_dict()\n else:\n params['env'] = self.env\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = AlipayOpenLotteryCampSubmitModel()\n if 'env' in d:\n o.env = d['env']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/AlipayOpenLotteryCampSubmitModel.py","file_name":"AlipayOpenLotteryCampSubmitModel.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"38214159","text":"i,j,k =input().split()\nm=int(i)\no=int(j)\np=int(k)\n\nif (m>o and m>p):\n print(m)\nelif(o>p):\n print(o)\nelse:\n print(p)\n","sub_path":"threebigest.py","file_name":"threebigest.py","file_ext":"py","file_size_in_byte":125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"515641334","text":"from random import randint\n\ndef calc_fib(n):\n if (n <= 1):\n return n\n\n return calc_fib(n - 1) + calc_fib(n - 2)\n\ndef calc_fib_2(n):\n arr = [0,1]\n\n for i in range(2, n):\n arrLength = len(arr)\n toAppend = arr[arrLength-1] + arr[arrLength-2]\n arr.append(toAppend)\n\n return arr[n-1] + arr[n-2]\n\nwhile (True):\n random_n = randint(3, 25)\n print('random number: ', random_n)\n\n res1 = calc_fib(random_n)\n res2 = calc_fib_2(random_n)\n\n if res1 != res2:\n print('Wrong answer: ', res1, ' | ', res2)\n break\n else:\n print('OK')\n\n","sub_path":"algo-toolbox/week2_algorithmic_warmup/1_fibonacci_number/stress_test_fibonacci.py","file_name":"stress_test_fibonacci.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"174204551","text":"\"\"\"Operator functions for synaptor DAGs.\"\"\"\nfrom __future__ import annotations\nimport os\nfrom typing import Optional\n\nfrom airflow import DAG\nfrom airflow.utils.weight_rule import WeightRule\nfrom airflow.operators.python import PythonOperator\nfrom airflow.models import Variable, BaseOperator\n\nfrom worker_op import worker_op\nfrom param_default import default_synaptor_image\nfrom igneous_and_cloudvolume import check_queue, upload_json, read_single_file\nfrom slack_message import task_failure_alert, task_done_alert, slack_message\nfrom nglinks import ImageLayer, SegLayer, generate_ng_payload, wrap_payload\nfrom kombu_helper import drain_messages\n\n\n# hard-coding these for now\nMOUNT_POINT = \"/root/.cloudvolume/secrets/\"\nTASK_QUEUE_NAME = \"synaptor\"\n\n\n# Op functions\ndef generate_nglink(\n net_output_path: str,\n seg_path: str,\n workflowtype: str,\n storagedir: str,\n add_synapse_points: str,\n img_path: Optional[str] = None,\n voxelres: Optional[tuple[int, int, int]] = None,\n) -> None:\n \"\"\"Generates a neuroglancer link to view the results.\"\"\"\n layers = [\n ImageLayer(\"network output\", net_output_path),\n SegLayer(\"synaptor segmentation\", seg_path),\n ]\n\n if img_path:\n layers = [ImageLayer(\"image\", img_path)] + layers\n\n payload = generate_ng_payload(layers)\n\n if \"Assignment\" in workflowtype and getboolean(add_synapse_points):\n presyn_pts, postsyn_pts = read_pts(storagedir)\n payload = add_annotation_layer(payload, presyn_pts, postsyn_pts, voxelres)\n\n upload_json(storagedir, \"ng.json\", payload)\n slack_message(wrap_payload(os.path.join(storagedir, \"ng.json\")), broadcast=True)\n\n\ndef getboolean(rawvalue: str) -> bool:\n \"\"\"Simulating configparser.getboolean\"\"\"\n value = rawvalue.lower()\n if value in [True, 1, \"yes\", \"y\", \"true\", \"t\", \"on\"]:\n return True\n elif value in [False, 0, \"no\", \"n\", \"false\", \"f\", \"off\"]:\n return False\n else:\n raise ValueError(f\"unrecognized boolean value: {rawvalue}\")\n\n\ndef read_pts(storagedir: str) -> tuple[list, list]:\n maybe_content = read_single_file(storagedir, \"final_edgelist.df\")\n\n if maybe_content:\n content = maybe_content.decode(\"utf-8\")\n else:\n raise ValueError(\"no edge list found\")\n\n lines = content.split(\"\\n\")\n header, rows = lines[0], lines[1:]\n\n # indices for the columns we want\n colnames = header.split(\",\")\n pre_x_i = colnames.index(\"presyn_x\")\n pre_y_i = colnames.index(\"presyn_y\")\n pre_z_i = colnames.index(\"presyn_z\")\n post_x_i = colnames.index(\"postsyn_x\")\n post_y_i = colnames.index(\"postsyn_y\")\n post_z_i = colnames.index(\"postsyn_z\")\n\n # extracting points\n presyn_pts = list()\n postsyn_pts = list()\n for row in rows:\n if \",\" not in row:\n continue\n\n fields = row.split(\",\")\n presyn_pt = fields[pre_x_i], fields[pre_y_i], fields[pre_z_i]\n postsyn_pt = fields[post_x_i], fields[post_y_i], fields[post_z_i]\n\n presyn_pts.append(list(map(int, presyn_pt)))\n postsyn_pts.append(list(map(int, postsyn_pt)))\n\n return presyn_pts, postsyn_pts\n\n\ndef add_annotation_layer(\n payload: dict, presyn_pts: list, postsyn_pts: list, voxel_res: tuple\n) -> dict:\n annotations = [\n {\n \"pointA\": list(presyn_pt),\n \"pointB\": list(postsyn_pt),\n \"type\": \"line\",\n \"id\": str(index),\n }\n for (index, (presyn_pt, postsyn_pt)) in enumerate(zip(presyn_pts, postsyn_pts))\n ]\n\n annotation_layer = {\n \"type\": \"annotation\",\n \"tool\": \"annotateLine\",\n \"tab\": \"annotations\",\n \"source\": {\n \"url\": \"local://annotations\",\n \"transform\" : {\n \"outputDimensions\": {\n \"x\": [f\"{voxel_res[0]}e-9\", \"m\"],\n \"y\": [f\"{voxel_res[1]}e-9\", \"m\"],\n \"z\": [f\"{voxel_res[2]}e-9\", \"m\"],\n }\n }\n },\n \"annotations\": annotations,\n }\n\n payload[\"layers\"][\"synapses\"] = annotation_layer\n\n return payload\n\n\ndef nglink_op(\n dag: DAG,\n net_output_path: str,\n seg_path: str,\n workflowtype: str,\n storagedir: str,\n add_synapse_points: str,\n img_path: str,\n voxelres: tuple[int, int, int],\n) -> PythonOperator:\n return PythonOperator(\n task_id=\"nglink\",\n python_callable=generate_nglink,\n op_args=(\n net_output_path, seg_path, workflowtype, storagedir, add_synapse_points\n ),\n op_kwargs=dict(img_path=img_path, voxelres=voxelres),\n priority_weight=100000,\n on_failure_callback=task_failure_alert,\n weight_rule=WeightRule.ABSOLUTE,\n queue=\"manager\",\n dag=dag,\n )\n\n\ndef drain_op(\n dag: DAG,\n task_queue_name: Optional[str] = TASK_QUEUE_NAME,\n queue: Optional[str] = \"manager\",\n) -> PythonOperator:\n \"\"\"Drains leftover messages from the RabbitMQ.\"\"\"\n from airflow import configuration as conf\n\n broker_url = conf.get(\"celery\", \"broker_url\")\n\n return PythonOperator(\n task_id=\"drain_messages\",\n python_callable=drain_messages,\n priority_weight=100_000,\n op_args=(broker_url, task_queue_name),\n weight_rule=WeightRule.ABSOLUTE,\n on_failure_callback=task_failure_alert,\n on_success_callback=task_done_alert,\n queue=\"manager\",\n dag=dag,\n )\n\n\ndef manager_op(\n dag: DAG,\n synaptor_task_name: str,\n queue: str = \"manager\",\n image: str = default_synaptor_image,\n) -> BaseOperator:\n \"\"\"An operator fn for running synaptor tasks on the airflow node.\"\"\"\n config_path = os.path.join(MOUNT_POINT, \"synaptor_param.json\")\n command = f\"{synaptor_task_name} {config_path}\"\n\n # these variables will be mounted in the containers\n variables = [\"synaptor_param.json\"]\n\n return worker_op(\n variables=variables,\n mount_point=MOUNT_POINT,\n task_id=synaptor_task_name,\n command=command,\n force_pull=True,\n on_failure_callback=task_failure_alert,\n on_success_callback=task_done_alert,\n image=image,\n priority_weight=100_000,\n weight_rule=WeightRule.ABSOLUTE,\n queue=queue,\n dag=dag,\n )\n\n\ndef generate_op(\n dag: DAG,\n taskname: str,\n op_queue_name: Optional[str] = \"manager\",\n task_queue_name: Optional[str] = TASK_QUEUE_NAME,\n tag: Optional[str] = None,\n image: str = default_synaptor_image,\n) -> BaseOperator:\n \"\"\"Generates tasks to run and adds them to the RabbitMQ.\"\"\"\n from airflow import configuration as conf\n\n broker_url = conf.get(\"celery\", \"broker_url\")\n config_path = os.path.join(MOUNT_POINT, \"synaptor_param.json\")\n\n command = (\n f\"generate {taskname} {config_path}\"\n f\" --queueurl {broker_url}\"\n f\" --queuename {task_queue_name}\"\n )\n\n # these variables will be mounted in the containers\n variables = add_secrets_if_defined([\"synaptor_param.json\"])\n\n task_id = f\"generate_{taskname}\" if tag is None else f\"generate_{taskname}_{tag}\"\n\n return worker_op(\n variables=variables,\n mount_point=MOUNT_POINT,\n task_id=task_id,\n command=command,\n force_pull=True,\n on_failure_callback=task_failure_alert,\n on_success_callback=task_done_alert,\n image=image,\n priority_weight=100_000,\n weight_rule=WeightRule.ABSOLUTE,\n queue=op_queue_name,\n dag=dag,\n )\n\n\ndef synaptor_op(\n dag: DAG,\n i: int,\n op_queue_name: Optional[str] = \"synaptor-cpu\",\n task_queue_name: Optional[str] = TASK_QUEUE_NAME,\n tag: Optional[str] = None,\n use_gpus: Optional[bool] = False,\n image: str = default_synaptor_image,\n) -> BaseOperator:\n \"\"\"Runs a synaptor worker until it receives a self-destruct task.\"\"\"\n from airflow import configuration as conf\n\n broker_url = conf.get(\"celery\", \"broker_url\")\n config_path = os.path.join(MOUNT_POINT, \"synaptor_param.json\")\n\n command = (\n f\"worker --configfilename {config_path}\"\n f\" --queueurl {broker_url} \"\n f\" --queuename {task_queue_name}\"\n \" --lease_seconds 300\"\n )\n\n # these variables will be mounted in the containers\n variables = add_secrets_if_defined([\"synaptor_param.json\"])\n\n task_id = f\"worker_{i}\" if tag is None else f\"worker_{tag}_{i}\"\n\n return worker_op(\n variables=variables,\n mount_point=MOUNT_POINT,\n task_id=task_id,\n command=command,\n use_gpus=use_gpus,\n force_pull=True,\n image=image,\n priority_weight=100_000,\n weight_rule=WeightRule.ABSOLUTE,\n queue=op_queue_name,\n dag=dag,\n # qos='quality of service'\n # this turns of a 5-minute failure timer that can kill nodes between\n # task waves or during database tasks\n qos=False,\n retries=100,\n retry_exponential_backoff=False,\n )\n\n\ndef wait_op(dag: DAG, taskname: str) -> PythonOperator:\n \"\"\"Waits for a task to finish.\"\"\"\n return PythonOperator(\n task_id=f\"wait_for_queue_{taskname}\",\n python_callable=check_queue,\n op_args=(TASK_QUEUE_NAME,),\n priority_weight=100_000,\n weight_rule=WeightRule.ABSOLUTE,\n on_success_callback=task_done_alert,\n queue=\"manager\",\n dag=dag,\n )\n\n\n# Helper functions\ndef add_secrets_if_defined(variables: list[str]) -> list[str]:\n \"\"\"Adds CloudVolume secret files to the mounted variables if defined.\n\n Synaptor still needs to store the google-secret.json file sometimes\n bc it currently uses an old version of gsutil.\n \"\"\"\n maybe_aws = Variable.get(\"aws-secret.json\", None)\n maybe_gcp = Variable.get(\"google-secret.json\", None)\n\n if maybe_aws is not None:\n variables.append(\"aws-secret.json\")\n if maybe_gcp is not None:\n variables.append(\"google-secret.json\")\n\n return variables\n","sub_path":"dags/synaptor_ops.py","file_name":"synaptor_ops.py","file_ext":"py","file_size_in_byte":9909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"600774703","text":"from omsdk.sdkcenum import EnumWrapper\n\nProtocolEnum = EnumWrapper('ProtocolEnum', {\n 'SNMP' : 1,\n 'WSMAN' : 2,\n 'REDFISH' : 3,\n 'REST' : 4,\n 'Other' : 100,\n 'Simulator' : 101\n }).enum_type\n\nProtoMethods = EnumWrapper(\"FST\", {\n \"HuntMode\" : \"HuntMode\",\n \"MergeMode\" : \"MergeMode\"\n}).enum_type\n\nclass ProtoPreference:\n def __init__(self, *args):\n self.orig_protocols = []\n for arg in args:\n self.orig_protocols.append(arg)\n self.orig_mode = ProtoMethods.HuntMode\n self.reset()\n\n def set_mode(self, mode):\n self.mode = mode\n\n def reset(self):\n self.protocols = []\n self.include_flag = []\n for arg in self.orig_protocols:\n self.protocols.append(arg)\n self.include_flag.append(True)\n self.mode = self.orig_mode\n\n def add(self, *protoenums):\n for protoenum in protoenums:\n if not protoenum in self.orig_protocols:\n self.orig_protocols.append(protoenum)\n self.protocols.append(protoenum)\n self.include_flag.append(True)\n\n def clone(self):\n s = ProtoPreference()\n for i in range(0, len(self.protocols)):\n s.protocols.append(self.protocols[i])\n s.include_flag.append(self.include_flag[i])\n s.mode = self.mode\n return s\n\n def copy(self, source):\n # clean all preferences\n for i in range(0, len(self.protocols)):\n self.include_flag[i] = False\n\n # set include flag for all those source protocols\n for j in range(0, len(source.protocols)):\n for i in range(0, len(self.protocols)):\n if self.protocols[i] == source.protocols[j]:\n self.include_flag[i] = source.include_flag[j]\n\n if not source.mode is None:\n self.mode = source.mode\n\n return self\n\n def set_preferred(self, protoenum):\n moveit = []\n for i in range(0, len(self.protocols)):\n if (self.protocols[i] == protoenum):\n moveit.append(i)\n tt2 = []\n tt3 = []\n for i in range(len(moveit), 0, -1):\n tt2.insert(0, self.protocols[moveit[i-1]])\n tt3.insert(0, self.include_flag[moveit[i-1]])\n del self.protocols[moveit[i-1]]\n del self.include_flag[moveit[i-1]]\n self.protocols[0:0] = tt2\n self.include_flag[0:0] = tt3\n\n def exclude(self, *protoenums):\n for i in range(0, len(self.protocols)):\n for protoenum in protoenums:\n if (self.protocols[i] == protoenum):\n self.include_flag[i] = False\n\n def include(self, *protoenums):\n for i in range(0, len(self.protocols)):\n for protoenum in protoenums:\n if (self.protocols[i] == protoenum):\n self.include_flag[i] = True\n\n def include_all(self):\n for i in range(0, len(self.protocols)):\n self.include_flag[i] = True\n\n def include_only(self, *protoenums):\n for i in range(0, len(self.protocols)):\n self.include_flag[i] = False\n\n for i in range(0, len(self.protocols)):\n for protoenum in protoenums:\n if (self.protocols[i] == protoenum):\n self.include_flag[i] = True\n\n def printx(self):\n counter = 0\n for i in range(0, len(self.protocols)):\n counter = counter + 1\n print (str(counter) + \" :\" + str(self.protocols[i]) + \"(\" + str(self.include_flag[i]) + \")\")\n\n","sub_path":"omsdk/sdkprotopref.py","file_name":"sdkprotopref.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"480712630","text":"import distance\nimport numpy as np\nfrom sklearn.model_selection import ShuffleSplit\n\nfrom bpm_lstm.bpm_lstm_model import BPM_LSTM\nfrom bpm_lstm.bpm_lstm_utils import save_results, load_dataset_with_features\nfrom bpm_lstm.next_step.next_step_models import available_models\nfrom bpm_lstm.next_step.next_step_utils import build_train_test_datasets, discretize_softmax\n\n\n# noinspection PyAttributeOutsideInit\nclass BPM_LSTM_NEXT_STEP(BPM_LSTM):\n def __init__(self, log_name, log_filepath, write_logs, model_name='new_model_v1', output_filepath='../outputs',\n logs_filepath='logs/', validation_split=0.2, test_split=0.1, test_prefix_size=5, epochs=300):\n super().__init__(log_name, log_filepath, model_name, write_logs, output_filepath,\n logs_filepath, validation_split, test_split, test_prefix_size, epochs)\n self._model_type = 'next_step'\n self._results_filepath = '/'.join(\n [self._output_filepath, self._model_type, self._model_name, self._log_name, ''])\n\n def _evaluate_model_test(self):\n test_scores = [[], []]\n\n for sample, additional_features in zip(self._X_test[0], self._X_test[1]):\n predicted_trace = np.expand_dims(np.zeros(sample.shape), 0)\n predicted_trace[:, :self._test_prefix_size] = sample[:self._test_prefix_size:]\n\n for i in range(self._test_prefix_size, self._X_train[0].shape[1]):\n activity_id, resource_id, time = self._model.predict(\n [predicted_trace, np.expand_dims(additional_features, 0)])\n activity_id = discretize_softmax(activity_id)\n resource_id = discretize_softmax(resource_id)\n predicted_trace[:, i] = np.concatenate([activity_id, resource_id, time], axis=-1)\n\n sample_activity = np.argmax(sample[:, :self._max_activity_id + 1], 1)\n sample_activity_string = ''.join(str(e) for e in sample_activity.tolist())\n\n predicted_activity = np.argmax(predicted_trace[:, :, :self._max_activity_id + 1], 2)[0]\n predicted_activity_string = ''.join(str(e) for e in predicted_activity.tolist())\n\n sample_resource = np.argmax(\n sample[:, self._max_activity_id + 1:self._max_activity_id + self._max_resource_id + 2], 1)\n sample_resource_string = ''.join(str(e) for e in sample_resource.tolist())\n\n predicted_resource = np.argmax(\n predicted_trace[:, :, self._max_activity_id + 1:self._max_activity_id + self._max_resource_id + 2], 2)[\n 0]\n predicted_resource_string = ''.join(str(e) for e in predicted_resource.tolist())\n\n sample_time = sample[:, -1]\n predicted_time = predicted_trace[:, :, -1][0]\n\n test_scores[0].append((1 - distance.nlevenshtein(sample_activity_string, predicted_activity_string)))\n test_scores[1].append((1 - distance.nlevenshtein(sample_resource_string, predicted_resource_string)))\n\n test_scores = np.array(test_scores)\n return np.mean(test_scores, -1)\n\n def train(self, folds):\n dataset, additional_features, self._max_activity_id, self._max_resource_id = load_dataset_with_features(\n self._log_filepath, shuffle=True)\n\n (self._X_train, self._Y_train), self._X_test = build_train_test_datasets(\n dataset,\n additional_features,\n self._max_activity_id,\n self._max_resource_id,\n self._test_split)\n\n kfold = ShuffleSplit(n_splits=folds, test_size=0.2)\n model_scores = {'validation': [],\n 'test': []}\n\n fold = 0\n for train_indexes, validation_indexes in kfold.split(self._X_train[0]):\n checkpoint_filepath = self._create_checkpoints_path(fold)\n log_path = self._create_logs_path(fold)\n\n self._model = available_models[self._model_name](self._X_train, self._max_activity_id,\n self._max_resource_id)\n history = self._train_model(checkpoint_filepath, log_path, train_indexes, validation_indexes)\n validation_scores = history.history\n model_scores['validation'].append(\n (validation_scores['val_activity_id_categorical_accuracy'][-1],\n validation_scores['val_resource_id_categorical_accuracy'][-1],\n validation_scores['val_time_mean_squared_error'][-1]))\n\n test_scores = self._evaluate_model_test()\n model_scores['test'].append(test_scores)\n\n fold += 1\n model_scores['validation'] = np.array(model_scores['validation'])\n model_scores['test'] = np.array(model_scores['test'])\n\n save_results(self._results_filepath, model_scores)\n","sub_path":"src/bpm_lstm/next_step/next_step_model.py","file_name":"next_step_model.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"160059309","text":"import sys\r\nimport os\r\nimport argparse\r\nimport codecs\r\n\r\ntotallines = 0\r\nfiles = None\r\ncl = None\r\ncb = None \r\ncc = None\r\ncw = None\r\n\r\ndef parseargs():\r\n global cl\r\n global cb\r\n global cc\r\n global cw\r\n global files\r\n parser = argparse.ArgumentParser(description = \"wc\", prog = \"wc\")\r\n parser.add_argument(\"-c\", dest = \"bytes\", help = \"Print byte count\", action = \"store_false\")\r\n parser.add_argument(\"-m\", dest = \"chars\", help = \"Print char count\", action = \"store_false\")\r\n parser.add_argument(\"-w\", dest = \"words\", help = \"Print word count\", action = \"store_false\")\r\n parser.add_argument(\"-l\", dest = \"lines\", help = \"Print line count\", action = \"store_false\")\r\n parser.add_argument(\"files\", metavar = \"files\", nargs = '+', default = sys.stdin)\r\n res = parser.parse_args()\r\n# for x in res: print(x)\r\n cb = res.bytes\r\n cc = res.chars\r\n cw = res.words\r\n cl = res.lines\r\n files = res.files\r\n\r\ndef process(fin):\r\n ffin = None\r\n try:\r\n ffin = open(fin, 'r')\r\n except:\r\n sys.stderr.write(\"error while opening file \" + fin + \"\\n\")\r\n return None, None, None, None\r\n nbytes = os.stat(fin).st_size\r\n rlines = ffin.readlines()\r\n lines = len(rlines)\r\n words = 0\r\n chars = 0\r\n for x in rlines:\r\n x = x.split()\r\n words += len(x)\r\n for y in x:\r\n chars += len(y)\r\n return nbytes, chars, words, lines\r\n\r\nparseargs()\r\nif files == sys.stdin:\r\n process(sys.stdin)\r\nelse:\r\n for x in files:\r\n b, c, w, l = process(x)\r\n if b == None:\r\n continue\r\n totallines += l\r\n print(\"In file\", x,)\r\n if cb: print(\"\\tBytes:\", b)\r\n if cc: print(\"\\tChars:\", c)\r\n if cw: print(\"\\tWords:\", w)\r\n if cl: print(\"\\tLines:\", w)\r\nprint(\"Total Lines: \", totallines)","sub_path":"practice_python/wc.py","file_name":"wc.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"75660584","text":"from itertools import islice\nimport sys\nimport os\nimport json\nimport time\nimport csv\n\nfrom dateutil import parser\nfrom pyspark import SparkContext, SparkConf\n\n\nDATA_TYPE_INTEGER = 0\nDATA_TYPE_REAL = 1\nDATA_TYPE_DATETIME = 2\nDATA_TYPE_TEXT = 3\n\n\ndef inspect_type(cell):\n try:\n value = long(cell)\n except:\n try:\n value = float(cell)\n except:\n try:\n value = parser.parse(cell).replace(tzinfo=None)\n except:\n return DATA_TYPE_TEXT, cell\n return DATA_TYPE_DATETIME, value\n return DATA_TYPE_REAL, value\n return DATA_TYPE_INTEGER, value\n\n\ndef map_column(cell):\n type_name, value = inspect_type(cell)\n return cell, type_name, value\n\n\ninput_file = sys.argv[1]\noutput_dir = sys.argv[2]\n\n\nos.system('mkdir -p %s' % output_dir)\n\nsc = SparkContext()\nsc.setLogLevel(\"ERROR\")\n\nfor line in open(input_file):\n start = time.time()\n input_file = '/user/hm74/NYCOpenData/%s' % line.strip()\n dataset_name = input_file.split('/')[-1]\n output_file = '%s/%s.json' % (output_dir, dataset_name)\n output = {\n 'dataset_name': dataset_name,\n 'columns': [],\n 'key_column_candidates': [],\n }\n\n print('Processing %s ...' % dataset_name)\n\n rdd = sc.textFile(input_file)\n rdd = rdd.mapPartitions(lambda x: csv.reader(x, delimiter=\"\\t\"))\n column_names = rdd.first()\n print('columns[%d]' % len(column_names))\n rdd = rdd.mapPartitionsWithIndex(lambda idx, it: islice(it, 1, None) if idx == 0 else it)\n number_all = rdd.count()\n\n for i, column_name in enumerate(column_names):\n print('%d/%d' % (i+1, len(column_names)))\n rdd_col = rdd.map(lambda x: x[i])\n print('%d/%d - all count' % (i+1, len(column_names)))\n print('%d/%d - non empty count' % (i+1, len(column_names)))\n number_non_empty_cells = rdd_col.filter(lambda x: x != '').count()\n number_empty_cells = number_all - number_non_empty_cells\n print('%d/%d - value2cnt' % (i+1, len(column_names)))\n rdd_value2cnt = rdd_col.map(lambda x: (x, 1)).reduceByKey(lambda a, b: a + b)\n number_distinct_values = rdd_value2cnt.count()\n print('%d/%d - frequent_values' % (i+1, len(column_names)))\n frequent_values = rdd_value2cnt.sortBy(lambda x: x[1], False).keys().take(5)\n\n data_types = []\n print('%d/%d - map column' % (i+1, len(column_names)))\n rdd_cell_dtype_value = rdd_col.map(map_column)\n\n # INTEGER (LONG)\n print('%d/%d - checking type of INTEGER (LONG) ...' % (i+1, len(column_names)))\n rdd_int = rdd_cell_dtype_value.filter(lambda x: x[1] == DATA_TYPE_INTEGER)\\\n .map(lambda x: x[2])\n count = rdd_int.count()\n if (count > 0):\n data_types.append({\n 'type': 'INTEGER (LONG)',\n 'count': count,\n 'max_value': rdd_int.max(),\n 'min_value': rdd_int.min(),\n 'mean': rdd_int.mean(),\n 'stddev': rdd_int.stdev(),\n })\n if count == number_all and count == number_distinct_values:\n output['key_column_candidates'].append(column_name)\n\n\n # REAL\n print('%d/%d - checking type of REAL ...' % (i+1, len(column_names)))\n rdd_real = rdd_cell_dtype_value.filter(lambda x: x[1] == DATA_TYPE_REAL)\\\n .map(lambda x: x[2])\n count = rdd_real.count()\n if (count > 0):\n data_types.append({\n 'type': 'REAL',\n 'count': count,\n 'max_value': rdd_real.max(),\n 'min_value': rdd_real.min(),\n 'mean': rdd_real.mean(),\n 'stddev': rdd_real.stdev(),\n })\n\n\n # DATE/TIME\n print('%d/%d - checking type of DATE/TIME ...' % (i+1, len(column_names)))\n rdd_datetime = rdd_cell_dtype_value.filter(lambda x: x[1] == DATA_TYPE_DATETIME)\\\n .map(lambda x: (x[0], x[2]))\n count = rdd_datetime.count()\n if (count > 0):\n data_types.append({\n 'type': 'DATE/TIME',\n 'count': count,\n 'max_value': rdd_datetime.max(key=lambda x: x[1])[0],\n 'min_value': rdd_datetime.min(key=lambda x: x[1])[0],\n })\n if count == number_all and count == number_distinct_values:\n output['key_column_candidates'].append(column_name)\n\n # TEXT\n print('%d/%d - checking type of TEXT ...' % (i+1, len(column_names)))\n rdd_text_len = rdd_cell_dtype_value.filter(lambda x: x[1] == DATA_TYPE_TEXT)\\\n .map(lambda x: (x[2], len(x[2])))\n count = rdd_text_len.count()\n if (count > 0):\n rdd_text_len_uniq = rdd_text_len.distinct()\n data_types.append({\n 'type': 'REAL',\n 'count': count,\n 'shortest_values': rdd_text_len_uniq.sortBy(lambda x: x[1]).keys().take(5),\n 'longest_values': rdd_text_len_uniq.sortBy(lambda x: x[1], False).keys().take(5),\n 'average_length': rdd_text_len_uniq.map(lambda x: x[1]).mean(),\n })\n\n output['columns'].append({\n 'column_name': column_name,\n 'number_non_empty_cells': number_non_empty_cells,\n 'number_empty_cells': number_empty_cells,\n 'number_distinct_values': number_distinct_values,\n 'frequent_values': frequent_values,\n 'data_types': data_types,\n })\n\n with open(output_file, 'w') as fout:\n fout.write(json.dumps(output, indent=4))\n\n print('%s: time cost %d seconds' % (dataset_name, time.time() - start))\n","sub_path":"Section A/group17/task1/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":5724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"416023950","text":"KEY_MOD_LCTRL = 0x1D\nKEY_MOD_LSHIFT = 0x2A\nKEY_MOD_LALT = 0x38\n\nKEY_CAPSLOCK = 0x3A # Keyboard Caps Lock\n\n\n\nKEY_NONE = 0x00 \nKEY_A = 0x1E # Keyboard a and A\nKEY_B = 0x30 # Keyboard b and B\nKEY_C = 0x2E # Keyboard c and C\nKEY_D = 0x20 # Keyboard d and D\nKEY_E = 0x12 # Keyboard e and E\nKEY_F = 0x21 # Keyboard f and F\nKEY_G = 0x22 # Keyboard g and G\nKEY_H = 0x23 # Keyboard h and H\nKEY_I = 0x17 # Keyboard i and I\nKEY_J = 0x24 # Keyboard j and J\nKEY_K = 0x25 # KeyboardK andK\nKEY_L = 0x26 # Keyboard l and L\nKEY_M = 0x32 # Keyboard m and M\nKEY_N = 0x31 # Keyboard n and N\nKEY_O = 0x18 # Keyboard o and O\nKEY_P = 0x19 # Keyboard p and P\nKEY_Q = 0x10 # Keyboard q and Q\nKEY_R = 0x13 # Keyboard r and R\nKEY_S = 0x1F # Keyboard s and S\nKEY_T = 0x14 # Keyboard t and T\nKEY_U = 0x16 # Keyboard u and U\nKEY_V = 0x2F # Keyboard v and V\nKEY_W = 0x11 # Keyboard w and W\nKEY_X = 0x2D # Keyboard x and X\nKEY_Y = 0x15 # Keyboard y and Y\nKEY_Z = 0x2C # Keyboard z and Z\n\nKEY_1 = 0x02 # Keyboard 1 and !\nKEY_2 = 0x03 # Keyboard 2 and @\nKEY_3 = 0x04 # Keyboard 3 and #\nKEY_4 = 0x05 # Keyboard 4 and $\nKEY_5 = 0x06 # Keyboard 5 and %\nKEY_6 = 0x07 # Keyboard 6 and ^\nKEY_7 = 0x08 # Keyboard 7 and &\nKEY_8 = 0x09 # Keyboard 8 and *\nKEY_9 = 0x0A # Keyboard 9 and (\nKEY_0 = 0x0B # Keyboard 0 and )\n\nKEY_ENTER = 0x1C # Keyboard Return (ENTER)\nKEY_ESC = 0x01 # Keyboard ESCAPE\nKEY_BACKSPACE = 0x0E # Keyboard DELETE (Backspace)\nKEY_TAB = 0x0F # Keyboard Tab\nKEY_SPACE = 0x39 # Keyboard Spacebar\nKEY_MINUS = 0x0C # Keyboard - and _\nKEY_EQUAL = 0x0D # Keyboard = and +\nKEY_LEFTBRACE = 0x1A # Keyboard [ and {\nKEY_RIGHTBRACE = 0x1B # Keyboard ] and }\nKEY_BACKSLASH = 0x2B # Keyboard \\ and |\nKEY_TILDE = 0x29 # Keyboard Non-US # and ~\nKEY_SEMICOLON = 0x27 # Keyboard ; and :\nKEY_APOSTROPHE = 0x28 # Keyboard ' and \"\nKEY_GRAVE = 0x29 # Keyboard ` and ~\nKEY_COMMA = 0x33 # Keyboard , and <\nKEY_DOT = 0x34 # Keyboard . and >\nKEY_SLASH = 0x35 # Keyboard / and ?\n\nKEY_F1 = 0x3B # Keyboard F1\nKEY_F2 = 0x3C # Keyboard F2\nKEY_F3 = 0x3D # Keyboard F3\nKEY_F4 = 0x3E # Keyboard F4\nKEY_F5 = 0x3F # Keyboard F5\nKEY_F6 = 0x40 # Keyboard F6\nKEY_F7 = 0x41 # Keyboard F7\nKEY_F8 = 0x42 # Keyboard F8\nKEY_F9 = 0x43 # Keyboard F9\nKEY_F10 = 0x44 # Keyboard F10\nKEY_F11 = 0x85 # Keyboard F11\nKEY_F12 = 0x86 # Keyboard F12\n\n\nKEY_KP1 = 0x4F # Keypad 1 and End\nKEY_KP2 = 0x50 # Keypad 2 and Down Arrow\nKEY_KP3 = 0x51 # Keypad 3 and PageDn\nKEY_KP4 = 0x4B # Keypad 4 and Left Arrow\nKEY_KP5 = 0x4C # Keypad 5\nKEY_KP6 = 0x4D # Keypad 6 and Right Arrow\nKEY_KP7 = 0x47 # Keypad 7 and Home\nKEY_KP8 = 0x48 # Keypad 8 and Up Arrow\nKEY_KP9 = 0x49 # Keypad 9 and Page Up\nKEY_KP0 = 0x52 # Keypad 0 and Insert\nKEY_KPDOT = 0x53 # Keypad . and Delete\n\n########################################################\n## not done\n\nKEY_MOD_RCTRL = 0x10##nd\nKEY_MOD_RSHIFT = 0x36##nd\nKEY_MOD_RALT = 0x40##nd\nKEY_SYSRQ = 0x46 # Keyboard Print Screen\nKEY_SCROLLLOCK = 0x47 # Keyboard Scroll Lock\nKEY_PAUSE = 0x48 # Keyboard Pause\nKEY_INSERT = 0x49 # Keyboard Insert\nKEY_HOME = 0x4a # Keyboard Home\nKEY_PAGEUP = 0x4b # Keyboard Page Up\nKEY_DELETE = 0x4c # Keyboard Delete Forward\nKEY_END = 0x4d # Keyboard End\nKEY_PAGEDOWN = 0x4e # Keyboard Page Down\nKEY_RIGHT = 0x4f # Keyboard Right Arrow\nKEY_LEFT = 0x50 # Keyboard Left Arrow\nKEY_DOWN = 0x51 # Keyboard Down Arrow\nKEY_UP = 0x52 # Keyboard Up Arrow\n\nKEY_NUMLOCK = 0x45 # Keyboard Num Lock and Clear\nKEY_KPSLASH = 0x54 # Keypad /\nKEY_KPASTERISK = 0x37 # Keypad *\nKEY_KPMINUS = 0x4A # Keypad -\nKEY_KPPLUS = 0x4E # Keypad +\nKEY_KPENTER = 0x58 # Keypad ENTER\n\n\nKEY_102ND = 0x64 # Keyboard Non-US \\ and |\nKEY_COMPOSE = 0x65 # Keyboard Application\nKEY_POWER = 0x66 # Keyboard Power\nKEY_KPEQUAL = 0x67 # Keypad =\n\nKEY_F13 = 0x68 # Keyboard F13\nKEY_F14 = 0x69 # Keyboard F14\nKEY_F15 = 0x6a # Keyboard F15\nKEY_F16 = 0x6b # Keyboard F16\nKEY_F17 = 0x6c # Keyboard F17\nKEY_F18 = 0x6d # Keyboard F18\nKEY_F19 = 0x6e # Keyboard F19\nKEY_F20 = 0x6f # Keyboard F20\nKEY_F21 = 0x70 # Keyboard F21\nKEY_F22 = 0x71 # Keyboard F22\nKEY_F23 = 0x72 # Keyboard F23\nKEY_F24 = 0x73 # Keyboard F24\n\nKEY_OPEN = 0x74 # Keyboard Execute\nKEY_HELP = 0x75 # Keyboard Help\nKEY_PROPS = 0x76 # Keyboard Menu\nKEY_FRONT = 0x77 # Keyboard Select\nKEY_STOP = 0x78 # Keyboard Stop\nKEY_AGAIN = 0x79 # Keyboard Again\nKEY_UNDO = 0x7a # Keyboard Undo\nKEY_CUT = 0x7b # Keyboard Cut\nKEY_COPY = 0x7c # Keyboard Copy\nKEY_PASTE = 0x7d # Keyboard Paste\nKEY_FIND = 0x7e # Keyboard Find\nKEY_MUTE = 0x7f # Keyboard Mute\nKEY_VOLUMEUP = 0x80 # Keyboard Volume Up\nKEY_VOLUMEDOWN = 0x81 # Keyboard Volume Down\nKEY_KPCOMMA = 0x85 # Keypad Comma\nKEY_RO = 0x87 # Keyboard International1\nKEY_KATAKANAHIRAGANA = 0x88 # Keyboard International2\nKEY_YEN = 0x89 # Keyboard International3\nKEY_HENKAN = 0x8a # Keyboard International4\nKEY_MUHENKAN = 0x8b # Keyboard International5\nKEY_KPJPCOMMA = 0x8c # Keyboard International6\nKEY_HANGEUL = 0x90 # Keyboard LANG1\nKEY_HANJA = 0x91 # Keyboard LANG2\nKEY_KATAKANA = 0x92 # Keyboard LANG3\nKEY_HIRAGANA = 0x93 # Keyboard LANG4\nKEY_ZENKAKUHANKAKU = 0x94 # Keyboard LANG5\nKEY_KPLEFTPAREN = 0xb6 # Keypad (\nKEY_KPRIGHTPAREN = 0xb7 # Keypad )\n\nKEY_LEFTCTRL = 0xe0 # Keyboard Left Control\nKEY_LEFTSHIFT = 0xe1 # Keyboard Left Shift\nKEY_LEFTALT = 0xe2 # Keyboard Left Alt\nKEY_LEFTMETA = 0xe3 # Keyboard Left GUI\nKEY_RIGHTCTRL = 0xe4 # Keyboard Right Control\nKEY_RIGHTSHIFT = 0xe5 # Keyboard Right Shift\nKEY_RIGHTALT = 0xe6 # Keyboard Right Alt\nKEY_RIGHTMETA = 0xe7 # Keyboard Right GUI\n\nKEY_MEDIA_PLAYPAUSE = 0xe8\nKEY_MEDIA_STOPCD = 0xe9\nKEY_MEDIA_PREVIOUSSONG = 0xea\nKEY_MEDIA_NEXTSONG = 0xeb\nKEY_MEDIA_EJECTCD = 0xec\nKEY_MEDIA_VOLUMEUP = 0xed\nKEY_MEDIA_VOLUMEDOWN = 0xee\nKEY_MEDIA_MUTE = 0xef\nKEY_MEDIA_WWW = 0xf0\nKEY_MEDIA_BACK = 0xf1\nKEY_MEDIA_FORWARD = 0xf2\nKEY_MEDIA_STOP = 0xf3\nKEY_MEDIA_FIND = 0xf4\nKEY_MEDIA_SCROLLUP = 0xf5\nKEY_MEDIA_SCROLLDOWN = 0xf6\nKEY_MEDIA_EDIT = 0xf7\nKEY_MEDIA_SLEEP = 0xf8\nKEY_MEDIA_COFFEE = 0xf9\nKEY_MEDIA_REFRESH = 0xfa\nKEY_MEDIA_CALC = 0xfb\n\n#endif # USB_HID_KEYS\n","sub_path":"FINAL/keys.py","file_name":"keys.py","file_ext":"py","file_size_in_byte":5941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"225465429","text":"import requests\nfrom bs4 import BeautifulSoup as bs\nimport csv\n\nBase_url = 'https://u24.ru/news/city/?p=0'\n\nheaders = {'accept': '*/*',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'}\n\n\ndef U24_parse(Base_url, headers):\n news = []\n session = requests.Session()\n request = session.get(Base_url, headers=headers)\n if request.status_code == 200:\n soup = bs(request.content, 'lxml')\n divs = soup.find_all('div', attrs={'class': 'col-sm-9'})\n for div in divs:\n title = div.find('div', attrs={'class': 'title'}).text\n href = 'https://u24.ru' + div.find('a')['href']\n text = div.find('a', attrs={'class': 'txt'}).text\n date = div.find('div', attrs={'class': 'newsdate'}).text\n divs_img = soup.find_all ('div', attrs = {'class': 'col-sm-3'})\n for div in divs_img:\n img = div.find ('img')[ 'src' ]\n news.append({\n 'title': title,\n 'href': href,\n 'text ': text ,\n 'date': date,\n 'img': img\n })\n else:\n print('Error')\n return news\n\n\ndef files_writer(news):\n with open('parsed_news.csv', 'w') as file:\n a_pen = csv.writer(file)\n a_pen.writerow((\"Новость\", \"URL\", \"Загаловок\", \"Фото\", \"Дата\"))\n for new in news:\n a_pen.writerow((new['title'], new['href'], new['text '], new['img'], new['date']))\n\nnews = U24_parse(Base_url, headers)\nfiles_writer(news)\n","sub_path":"U24_official.py","file_name":"U24_official.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"15180542","text":"from __future__ import print_function\nimport os\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n# The GPU id to use, usually either \"0\" or \"1\"\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n# supress annoying TF messages at the beginning\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nimport tensorflow as tf\n\nimport tensorflow.keras, os, DataBaseManager, time, math\nfrom tensorflow.keras.layers import Dense, Flatten, BatchNormalization, Dropout, Activation, Concatenate\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, MaxPooling1D, AveragePooling2D, Reshape, Input, UpSampling2D, Conv1D, Lambda\nfrom tensorflow.keras import backend as K\nimport numpy as np\nfrom numpy.random import seed\nimport Utilities as utils\nfrom shutil import copy2\nimport sys\nimport MaskedMLP\nimport ActiveMaskedMLP\n\nprint(\"TF version: \", tf.__version__)\nprint(\"TF.keras version: \", tensorflow.keras.__version__)\n\nnp.set_printoptions(threshold=sys.maxsize)\n\n\n###############################################################################################\n# set memory constraints\n###############################################################################################\ndef get_session(gpu_fraction=0.80):\n gpu_options = tf.compat.v1.GPUOptions(allow_growth=True)\n # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction, allow_growth=True)\n return tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(gpu_options=gpu_options))\n\n\ntf.compat.v1.keras.backend.set_session(get_session())\n\nbatch_size = 60000\nepochs = 1\nlearning_rate = 0.001\n\nsaveToDisk = True\ncurrentFileName = os.path.basename(__file__).replace(\".py\", \"\")\nrunName = currentFileName + \"_\" + utils.DateToString()\ndirNameDefault = \"./Outputs/\" + runName + \"/\"\nworkingDir = os.getcwd()\nntraindata = 60000\nntestdata = 10000\n\nnp.random.seed(None)\n\n\n# myseed = np.random.randint(0, 100)\n# myseed=17\n# myseed =9503629\n\n# from tensorflow.keras.layers import Layer\n\ndef makeSharedLayerCNN(inputshape, nclasses, name=None):\n input_img = Input(shape=inputshape)\n\n L1 = Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=inputshape)(input_img)\n L1 = BatchNormalization()(L1)\n L1 = Dropout(0.3)(L1)\n\n conv1 = Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu')\n\n L2 = conv1(L1)\n L3 = conv1(L2)\n L4 = conv1(L3)\n L5 = conv1(L4)\n L6 = conv1(L5)\n L6 = BatchNormalization()(L6)\n\n L7 = MaxPooling2D(pool_size=(2, 2))(L6)\n conv2 = Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu')\n\n L8 = conv2(L7)\n L9 = conv2(L8)\n L10 = conv2(L9)\n L11 = conv2(L10)\n L12 = conv2(L11)\n L12 = BatchNormalization()(L12)\n\n L13 = Flatten()(L12)\n\n D = Dense(512, activation='relu')(L13)\n D = Dropout(0.2)(D)\n classes = Dense(nclasses, activation='softmax')(D)\n\n model = Model(input_img, classes)\n model.compile(loss='categorical_crossentropy',\n optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1e-6),\n metrics=['accuracy'])\n\n return model\n\n\ndef makeSahredLayersdMLP(fullarch):\n inputshape = fullarch[0]\n outshape = fullarch[-1]\n\n input_img = Input(shape=(inputshape,))\n\n # add the first hidden layer and connect it to the input\n t0 = Dense(100, 'relu')\n L1 = t0(input_img)\n\n # method 1\n # t1 = Dense(100, 'relu')\n # L2 = t1(L1)\n # L3 = t1(L2)\n # L4 = t1(L3)\n # L5 = t1(L4)\n\n # method 2\n # L2=Dense(100, 'relu')(L1)\n # L3=Dense(100, 'relu')(L2)\n # L4=Dense(100, 'relu')(L3)\n # L5=Dense(100, 'relu')(L4)\n\n # method 3\n L5 = Dense(100, 'relu')(L1)\n\n # here is the last layer, connected to the one before\n # (either the ones from the loop or the one before\n LN = Dense(outshape, 'softmax')(L5)\n\n # define the model, connecting the input to the last layer (LN)\n model = Model(input_img, LN)\n\n # set a network name\n import uuid\n ID = uuid.uuid4().hex\n\n model._name = \"FC\" + a2s(fullarch) + \"_ID\" + ID[len(ID) - 7:]\n\n model.compile(loss='categorical_crossentropy',\n optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1e-6),\n metrics=['accuracy'])\n\n return model\n\n\ndef makeMLP(inputshape, outshape, arch, name, opt, loss):\n model = Sequential(name=name)\n\n model.add(Dense(arch[0], activation='relu', input_dim=inputshape))\n\n if len(arch) != 0:\n for i in range(1, len(arch)):\n model.add(Dense(arch[i], activation='relu'))\n\n model.add(Dense(outshape, activation='softmax', input_dim=inputshape))\n\n model.compile(loss=loss,\n optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1e-6),\n metrics=['accuracy'])\n\n return model\n\n\ndef MakeAverageImageForClass(X, Y):\n averages = []\n\n for c in range(0, 10):\n # get all images of class c\n index_c = np.argmax(Y, axis=1) == c\n\n img_c = X[index_c,]\n\n avg_img_c = np.mean(img_c, axis=0)\n\n averages.append(avg_img_c)\n\n return averages\n\n\ndef RealTo3D(a):\n if len(a.shape) != 2:\n return a\n c = np.expand_dims(a, axis=2)\n\n pad_up = 1\n pad_dn = 1\n c = np.pad(c, ((0, 0), (0, 0), (pad_up, pad_dn)), 'constant', constant_values=(0, 0))\n\n # find indices where the values are <0\n lt0 = (a < 0)\n eq0 = (a == 0)\n\n c[eq0, 0] = 1 # blue\n c[lt0, 1] = 0 # green\n c[lt0, 2] = -a[lt0] # red\n\n return c\n\n\ndef SetMaskToONe(full_arch):\n masks = []\n dense_arch = full_arch[1:-1]\n inputsize = full_arch[0]\n nclasses = full_arch[-1]\n\n c = 1\n\n if len(dense_arch) == 0:\n m = c * np.ones((inputsize, nclasses), dtype=np.float32)\n # m[:m.shape[0] // 2, :m.shape[1] // 2] = 0\n masks.append(m)\n else:\n m = c * np.ones((inputsize, dense_arch[0]), dtype=np.float32)\n # m = np.random.normal(0, 0.005, (inputsize, dense_arch[0]))\n # m = np.random.randint(0, 3, (inputsize, dense_arch[0]))\n # m[:m.shape[0] // 2, :m.shape[1] // 2] = 0\n masks.append(m)\n\n for t in range(1, len(dense_arch)):\n m = c * np.ones((dense_arch[t - 1], dense_arch[t]), dtype=np.float32)\n # m = np.random.normal(0, 0.005, (dense_arch[t - 1], dense_arch[t]))\n # m = np.random.randint(0, 3, (dense_arch[t - 1], dense_arch[t]))\n # m[:m.shape[0] // 2, :m.shape[1] // 2] = 0\n masks.append(m)\n\n m = c * np.ones((dense_arch[-1], nclasses), dtype=np.float32)\n # m = np.random.normal(0, 0.005, (dense_arch[-1], nclasses))\n # m = np.random.randint(0, 3, (dense_arch[-1], nclasses))\n # m[:m.shape[0] // 2, :m.shape[1] // 2] = 0\n masks.append(m)\n\n return masks\n\n\n#\n# class MyLayer(Layer):\n#\n# def __init__(self, output_dim, weight_mask, activation, seed, **kwargs):\n# self.output_dim = output_dim\n# self.mask = weight_mask\n# self.seed = seed\n# self.activation = activation\n#\n# super(MyLayer, self).__init__(**kwargs)\n#\n# def build(self, input_shape):\n# ki = tensorflow.keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=self.seed)\n#\n# self.kernel = self.add_weight(name='kernel',\n# shape=(input_shape.as_list()[1], self.output_dim),\n# initializer=ki,\n# trainable=True)\n#\n# # bi = tensorflow.keras.initializers.zeros()\n# # self.bias = self.add_weight(name='bias',\n# # shape=(self.output_dim,),\n# # initializer=ki,\n# # trainable=True)\n#\n# super(MyLayer, self).build(input_shape) # Be sure to call this at the end\n#\n# def call(self, x):\n# act = K.dot(x, self.kernel * self.mask) # + self.bias\n#\n# if 'relu' in self.activation:\n# act = tensorflow.keras.activations.relu(act)\n#\n# if 'softmax' in self.activation:\n# act = tensorflow.keras.activations.softmax(act)\n#\n# return act\n#\n# def compute_output_shape(self, input_shape):\n# return (input_shape.as_list()[1], self.output_dim)\n#\n# def get_weights(self):\n# w = super(MyLayer, self).get_weights()\n# return w * self.mask\n#\n# def get_seed(self):\n# return self.seed\n#\n# def set_weights(self, weights):\n# super(MyLayer, self).set_weights(weights)\n\ndef RetrainWithMask(myseed, old_weights, fullarch, pruneamount, epochs, data):\n new_weights, masks = SetWeightsToZeroPerLayer(old_weights, pruneamount)\n net = MaskedMLP.makeMaskedMLP(fullarch, masks, myseed)\n\n # Xtrain, Ytrain, Xtest, Ytest = data\n # net.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=epochs, verbose=0, shuffle=True, validation_data=(Xtest, Ytest))\n\n if epochs != 0:\n net.fit(data[0], data[1], batch_size=batch_size, epochs=epochs, verbose=0, shuffle=True, validation_data=(data[2], data[3]))\n\n return net\n\n\ndef a2s(a):\n if len(a) == 0:\n return \"0_\"\n\n s = \"\"\n for i in range(len(a) - 1):\n s += str(a[i]) + \"_\"\n\n s += str(a[-1])\n\n return s\n\n\ndef ToArray(W):\n bag = []\n for i in range(0, len(W)):\n w = W[i].reshape(-1)\n bag.extend(w)\n\n B = np.asarray(bag)\n\n return B\n\n\ndef CalculateThreshold(a, p):\n # sort array\n s = np.sort(np.abs(a))\n\n # we know that the i-th element is larger than the ones below\n i = int(p * (a.shape[0] - 1))\n t = s[i]\n\n # print(\"threshold:\", t)\n\n return t\n\n\ndef SetWeightsToZeroPerLayer(net_weights, p):\n new_weights = net_weights.copy()\n masks = net_weights.copy()\n\n for l in range(0, len(net_weights)):\n # for l in range(0, 1):\n # make a copy of the current layer weights, including biases\n layerw = net_weights[l]\n # if len(layerw.shape)<2:\n # continue\n\n # print(type(masks[l]))\n\n masks[l] = np.zeros_like(masks[l])\n\n threshold = CalculateThreshold(ToArray(layerw), p)\n # mn = (ToArray(layerw)).mean()\n\n # set all weights and biases to zero\n # new_weights[l] = mn * np.ones_like(layerw)\n new_weights[l] = np.zeros_like(layerw)\n\n # get indices of the weight which are larger than threshold\n indices = np.abs(layerw) > threshold\n\n # set net_weights[indices] to the values of layerw\n new_weights[l][indices] = layerw[indices]\n masks[l][indices] = 1\n\n return new_weights, masks\n\n\ndef SetWeightsToZeroGlobally(net_weights, p):\n new_weights = net_weights.copy()\n masks = net_weights.copy()\n\n threshold = CalculateThreshold(ToArray(new_weights), p)\n\n for l in range(0, len(net_weights)):\n # for l in range(0, 1):\n # make a copy of the current layer weights, including biases\n layerw = net_weights[l]\n # if len(layerw.shape)<2:\n # continue\n\n # print(type(masks[l]))\n\n masks[l] = np.zeros_like(masks[l])\n\n # mn = (ToArray(layerw)).mean()\n\n # set all weights and biases to zero\n # new_weights[l] = mn * np.ones_like(layerw)\n new_weights[l] = np.zeros_like(layerw)\n\n # get indices of the weight which are larger than threshold\n indices = np.abs(layerw) > threshold\n\n # set net_weights[indices] to the values of layerw\n new_weights[l][indices] = layerw[indices]\n masks[l][indices] = 1\n\n return new_weights, masks\n\n\ndef MaskWeights(old_weights, mask):\n new_weights = old_weights.copy()\n\n for l in range(0, len(old_weights)):\n new_weights[l] = old_weights[l] * mask[l]\n\n return new_weights\n\n\ndef DrawWeights(name, net_weights):\n import cv2\n\n for l in range(0, len(net_weights)):\n layerw = net_weights[l].copy()\n if len(layerw.shape) > 1:\n # layerw -= layerw.min()\n layerw = np.abs(layerw)\n layerw /= layerw.max()\n cv2.imshow(name + str(l), layerw)\n cv2.waitKey(1)\n\n cv2.waitKey(-1)\n return 0\n\n\n#\n# def makeMaskedMLP(inputshape, outshape, arch, masks, seed):\n# input_img = Input(shape=(inputshape,))\n#\n# # if there are no hidden layers then add just\n# # the last layer connected to the input (input_img)\n# if len(arch) == 0:\n# # e = np.random.randint(0, 2, (inputshape, outshape))\n# # e = np.ones(inputshape, outshape)\n# # e[:e.shape[0] // 2, :e.shape[1] // 2] = 0\n# LN = MyLayer(outshape, masks[0], 'softmax', seed)(input_img)\n#\n# # if there are hidden layers then\n# else:\n# # add the first hidden layer and connect it to the input\n# # e = np.random.randint(0, 2, (inputshape, arch[0]))\n# # e = np.ones((inputshape, arch[0]))\n# # e[:e.shape[0] // 2, :e.shape[1] // 2] = 0\n# Li = MyLayer(arch[0], masks[0], 'relu', seed)(input_img)\n#\n# # add the rest of the hidden layers (if any) and connect\n# # them to the previous ones\n# for i in range(1, len(arch)):\n# # e = np.random.randint(0, 2, (arch[i - 1], arch[i]))\n# # e = np.ones((arch[i - 1], arch[i]))\n# # e[:e.shape[0] // 2, :e.shape[1] // 2] = 0\n# Li = MyLayer(arch[i], masks[i], 'relu', seed)(Li)\n#\n# # here is the last layer, connected to the one before\n# # (either the ones from the loop or the one before\n# # e = np.random.randint(0, 2, (arch[-1], outshape))\n# # e = np.ones((arch[-1], outshape))\n# # e[:e.shape[0] // 2, :e.shape[1] // 2] = 0\n# LN = MyLayer(outshape, masks[-1], 'softmax', seed)(Li)\n#\n# # define the model, connecting the input to the last layer (LN)\n# model = Model(input_img, LN)\n#\n# # set a network name\n# import uuid\n# ID = uuid.uuid4().hex\n#\n# model._name = \"FC\" + a2s(arch) + \"_10_ID\" + ID[len(ID) - 7:] + \"_S\" + str(seed)\n#\n# model.compile(loss='categorical_crossentropy',\n# optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1e-6),\n# metrics=['accuracy'])\n#\n# return model\n#\n\n\ndef customstopping(model, X, Y):\n \"\"\"\n :param model:\n :param X: traindata\n :param Y: train labels\n :return: to stop or not to stop\n \"\"\"\n\n loss, acc = model.evaluate(X, Y, verbose=0)\n prediction = model.predict(X)\n\n epsilon = np.finfo(prediction.dtype).eps\n # epsilon=0\n confidences = np.sum(np.log(prediction + epsilon) * (Y), axis=1)\n\n sumlog = -np.sum(confidences)\n size = model.count_params()\n\n print(\"--- Custom stopping ---\")\n print(\" loss \", loss * X.shape[0])\n # print(\" acc \", acc)\n # print(\" size \", size)\n print(\" sumlog \", sumlog)\n\n # if mean - std * 2 < size - mean < mean + std * 2:\n # if size * 1.1 > sumlog2 > size * 0.9:\n # print(sumlog2, size)\n\n # if sumlog2 <= size:\n # print(\"size and sumlog2 are comparable\")\n # return 1\n\n return 0\n\n\ndef VisualizeNetwork(net):\n masks = []\n old_weights = []\n for l in range(1, len(net.layers)):\n m = net.layers[l].get_mask()\n ow = net.layers[l].get_weights()\n masks.append(m)\n old_weights.append(ow)\n print(\"mshape\", m.shape)\n print(\"owshape\", ow.shape)\n\n # print(m.shape)\n\n m = np.swapaxes(masks[0], 0, 1)\n ow = np.swapaxes(old_weights[0], 0, 1)\n ow = ow * m\n # ow = ow - ow.min()\n # ow /= ow.max()\n ow = ow.reshape(-1, 28, 28)\n owcolor = []\n\n for o in range(ow.shape[0]):\n owrgb = RealTo3D(ow[o])\n\n for oo in range(0, 3):\n if owrgb[oo].max() != 0:\n owrgb /= owrgb[oo].std()\n\n owcolor.append(owrgb)\n\n import cv2\n cv2.imshow(\"Weights\" + str(net.name), utils.MakeGridOfImages3D(owcolor))\n cv2.waitKey(1)\n\n return 0\n\n\ndef runmodels(networks, data, n_epochs=None, outputdir=None):\n # trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareMNISTData3D()\n # averages = MakeAverageImageForClass(trainImages, trainLabels)\n # import cv2\n # cv2.imshow(\"averages\", utils.MakeGridOfImages(averages))\n # cv2.waitKey(1)\n\n def InvertMask(masks):\n invertedmask = masks.copy()\n\n for i in range(len(masks)):\n invertedmask[i] = 1 - masks[i]\n\n return invertedmask\n\n if outputdir is None:\n dirName = dirNameDefault\n else:\n dirName = outputdir\n\n if n_epochs is None:\n n_epochs = epochs\n\n if saveToDisk:\n if not os.path.exists(dirName):\n os.makedirs(dirName)\n copy2(currentFileName + \".py\", dirName)\n print(\"data will be saved in \", dirName)\n\n start = time.time()\n\n e = 0\n trainedWeights = {}\n\n ne = 150\n stop = False\n\n # predictions0=\n import localutils\n\n TransitionsTrain = []\n TransitionsTest = []\n\n while e < 1500 and stop == False:\n for net, t in zip(networks, range(0, len(networks))):\n # get train data for network t\n Xtrain = data[t][0]\n Ytrain = data[t][1]\n Xtest = data[t][2]\n Ytest = data[t][3]\n\n # loss, acc = net.evaluate(Xtest, Ytest, verbose=0)\n # print(\"untrained net test accuracy\", acc)\n\n # VisualizeNetwork(net)\n # input()\n\n # pred0Train = net.predict(Xtrain)\n # pred0Test = net.predict(Xtest)\n\n # earlystopping_callback = EarlyStopping(monitor='loss', mode='min', baseline=0.1)\n # tf.keras.callbacks.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=0, verbose=0, mode='auto', baseline=None,\n # restore_best_weights=False)\n # earlystopping_callback=tf.keras.callbacks.EarlyStopping(monitor='loss', mode='max', baseline=0.1)\n fit_history = net.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=1, verbose=2, shuffle=False)\n\n # weights = net.get_weights()\n # print(type(weights))\n # ss=0\n # for w in weights:\n # # print(type(w))\n # print(w.shape)\n # print(w.size)\n # ss+=w.size\n # print(\"ss\",ss)\n # input()\n\n # getmaskandweights = False\n # if getmaskandweights:\n # a = 1\n # W = []\n # M = []\n # for l in range(1, len(net.layers)):\n # w = net.layers[l].get_weights()[0]\n # m = net.layers[l].get_active_mask()\n # print(m)\n # M.append(m)\n # W.append(w)\n\n # pred1Train = net.predict(Xtrain)\n # pred1Test = net.predict(Xtest)\n #\n # transTrain = localutils.AnalizeTransitions(pred0Train, pred1Train, Ytrain)\n # transTest = localutils.AnalizeTransitions(pred0Test, pred1Test, Ytest)\n #\n # TransitionsTrain.append(transTrain)\n # TransitionsTest.append(transTest)\n\n # def TransitionSummary(transition, msg):\n #\n # wws = transition[0, 0, 1]\n # wwo = transition[0, 0, 0]\n # wc = transition[0, 1, :].sum()\n # cw = transition[1, 0, :].sum()\n # cc = transition[1, 1, :].sum()\n #\n # print(msg)\n # print(\" - from wrong->wrong \", wwo, \"(other), \", wws, \"same\")\n # print(\" - from wrong->correct \", wc)\n # print(\" - from correct->wrong \", cw)\n # print(\" - from correct->correct \", cc)\n # print(\"\\n\\n\\n\\n\")\n #\n # return 0\n\n # TransitionSummary(transTrain, \"Train transitions\")\n # TransitionSummary(transTest, \"Test transitions\")\n #\n # print(transTrain.sum())\n # print(transTest.sum())\n\n # continue\n\n W = []\n for l in range(1, len(net.layers)):\n w = net.layers[l].get_weights()[0]\n W.append(w)\n\n # DrawWeights(\"asdfgh\", W)\n # loss, acc = net.evaluate(Xtest, Ytest, verbose=0)\n # print(\"trained net test accuracy \", acc)\n\n if customstopping(model=net, X=Xtrain, Y=Ytrain):\n stop = True\n\n retrainwithmaskweights = False\n if retrainwithmaskweights:\n old_weights = net.get_weights().copy()\n full_arch = localutils.ExtractFullArch(old_weights)\n netseed = localutils.ExtractSeed(net.name)\n new_weights, masks = SetWeightsToZeroGlobally(old_weights, 0.8)\n\n masks_ones = SetMaskToONe(full_arch)\n\n LTHnet = MaskedMLP.makeMaskedMLP(full_arch, masks_ones, netseed)\n # LTHnet.set_weights(masks)\n\n loss, acc = net.evaluate(Xtest, Ytest, verbose=0)\n print(\"pretrain accuracy:\", acc)\n # fit_history = LTHnet.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=ne, verbose=2, shuffle=True, validation_data=(Xtest, Ytest))\n\n # loss, acc = LTHnet.evaluate(Xtest, Ytest, verbose=0)\n # print(\"retrain accuracy:\", acc)\n\n trainnewnetwork = False\n if trainnewnetwork:\n import cv2\n\n old_weights = net.get_weights().copy()\n full_arch = localutils.ExtractFullArch(old_weights)\n\n # full_arch.append(old_weights[0].shape[0])\n # full_arch.append(old_weights[0].shape[1])\n #\n # for i in range(1, len(old_weights)):\n # full_arch.append(old_weights[i].shape[1])\n\n percentages = 0.01 * np.arange(0, 101, 1)\n percentages = 0.01 * np.arange(0, 100, 10)\n # percentages = np.append(percentages, np.arange(1, 11) / 1000 + 0.99)\n netseed = localutils.ExtractSeed(net.name)\n\n print(\"\\n\\nTraining a copy of the first network, masked\")\n for pruneamount in percentages:\n print(\"- pruning by:\", pruneamount)\n\n K.clear_session()\n\n # new_weights, masks = SetWeightsToZeroPerLayer(old_weights, pruneamount)\n new_weights, masks = SetWeightsToZeroGlobally(old_weights, pruneamount)\n LTHnet = MaskedMLP.makeMaskedMLP(full_arch, masks, netseed)\n VisualizeNetwork(LTHnet)\n\n # LTHnet.set_weights(masks)\n # fit_history = LTHnet.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=ne, verbose=2, shuffle=True,validation_data=(Xtest, Ytest))\n\n # masksI = InvertMask(masks)\n # LTHnetI = MaskedMLP.makeMaskedMLP(full_arch, masksI, netseed)\n # loss, acc = LTHnetI.evaluate(Xtest, Ytest, verbose=0)\n # print(\" inverted mask test accuracy\", acc)\n #\n # masks=masksI\n # print(masks[0].shape)\n m = np.swapaxes(masks[0], 0, 1)\n ow = np.swapaxes(old_weights[0], 0, 1)\n\n # print(m.shape)\n # print(ow.shape)\n # ow = ow * m\n # # ow = ow - ow.min()\n # # ow /= ow.max()\n # ow = ow.reshape(-1, 28, 28)\n # owcolor = []\n #\n # for o in range(ow.shape[0]):\n # owrgb = RealTo3D(ow[o])\n #\n # for oo in range(0, 3):\n # if owrgb[oo].max() != 0:\n # owrgb /= owrgb[oo].std()\n #\n # owcolor.append(owrgb)\n\n # # cv2.imshow(\"Masks\" + str(pruneamount), utils.MakeGridOfImages(m.reshape(-1, 28, 28)))\n #\n # # ow3c = RealTo3D(ow)\n #\n # cv2.imshow(\"Weights\" + str(pruneamount), utils.MakeGridOfImages3D(owcolor))\n # cv2.waitKey(1)\n continue\n #\n # # find zero points and replace them with 0.01\n # # for m in masks:\n # # condition = (m == 0)\n # # # print(condition)\n # # m[condition] = 0.001\n # netseed = ExtractSeed(net.name)\n #\n # mlp = MaskedMLP.makeMaskedMLP(full_arch, masks, netseed)\n #\n # # cv2.imshow(\"asdff\" + str(l), utils.MakeGridOfImages(net.layers[1].get_mask().reshape(-1, 28, 28)))\n # # cv2.imshow(\"asdff\" + str(l), utils.MakeGridOfImages(masks[0].reshape(-1, 28, 28)))\n # # cv2.imshow(\"ow\" + str(l), utils.MakeGridOfImages(old_weights[0].reshape(-1, 28, 28)))\n # # cv2.waitKey(1)\n #\n # # for l in range(1, len(mlp.layers)):\n # # m = net.layers[l].get_mask()\n # # print(m.shape)\n # #\n # # cv2.imshow(\"mlp pruned masks\" + str(l), m)\n #\n # print(\"network name:\", mlp.name)\n # print(\"parameters: \", mlp.count_params())\n #\n # loss, acc = mlp.evaluate(Xtest, Ytest, verbose=0)\n # # print(\" test accuracy\", acc)\n #\n # print(\"pruning by: {:1.2f}\".format(pruneamount), \" test accuracy\", acc)\n # mlp.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=ne, verbose=2, shuffle=True)\n\n netseed = localutils.ExtractSeed(net.name)\n # add the network's weights to the dictionary of trained weights\n trainedWeights[netseed] = W\n\n e += 1\n # cv2.waitKey(-1)\n\n # import matplotlib.pyplot as plt\n #\n # # plot the graph of transitions\n #\n # plots = np.zeros((epochs, 5))\n # i = 0\n # labels = []\n # for t in TransitionsTest:\n # wws = t[0, 0, 1]\n # wwo = t[0, 0, 0]\n # wc = t[0, 1, :].sum()\n # cw = t[1, 0, :].sum()\n # cc = t[1, 1, :].sum()\n #\n # plots[i, 0] = wws\n # labels.append(\"wws\")\n #\n # plots[i, 1] = wwo\n # labels.append(\"wwo\")\n #\n # plots[i, 2] = wc\n # labels.append(\"wc\")\n #\n # plots[i, 3] = cw\n # labels.append(\"cw\")\n #\n # plots[i, 4] = cc\n # labels.append(\"cc\")\n #\n # i += 1\n #\n # plt.plot(plots[:,0], label=\"wws\")\n # plt.plot(plots[:,1], label=\"wwo\")\n # plt.plot(plots[:,2], label=\"wc\")\n # plt.plot(plots[:,3], label=\"cw\")\n # plt.plot(plots[:,4], label=\"cc\")\n # plt.legend(fontsize=9)\n # plt.show()\n #\n # input()\n\n # testScores = []\n # for net, t in zip(networks, range(0, len(networks))):\n # Xtest = data[t][2]\n # Ytest = data[t][3]\n # loss, acc = net.evaluate(Xtest, Ytest, verbose=0)\n # testScores.append(acc)\n # print(\"loss \", loss, \" accuracy\", acc)\n #\n # prunenetwork = False\n #\n # if prunenetwork:\n # print(\"clone net test loss: \")\n # pruned_metrics = []\n # # net_clone = tensorflow.keras.models.clone_model(net)\n # #\n # # net_clone.compile(loss='categorical_crossentropy',\n # # optimizer=tensorflow.keras.optimizers.Adam(lr=learning_rate, decay=1.2e-3),\n # # metrics=['accuracy'])\n #\n # net_clone = net\n # old_weights = net.get_weights().copy()\n # old_acc = acc\n #\n # percentages = 0.01 * np.arange(0, 100, 3)\n # percentages = np.append(percentages, np.arange(1, 11) / 1000 + 0.99)\n #\n # print(percentages)\n #\n # # for p in range(0, 101, 1):\n # for p in percentages:\n # new_weights, masks = SetWeightsToZeroPerLayer(old_weights, p)\n # # new_weights = SetWeightsToZeroGlobally(old_weights, p / 100)\n #\n # # print(\"nonzero old_weights\", np.count_nonzero(ToArray(old_weights)))\n # # print(\"nonzero new_weights\", np.count_nonzero(ToArray(new_weights)))\n #\n # net_clone.set_weights(new_weights)\n # # DrawWeights(masks)\n # DrawWeights(new_weights)\n # loss, acc = net_clone.evaluate(Xtest, Ytest, verbose=0)\n # nzow = np.count_nonzero(ToArray(old_weights))\n # nznw = np.count_nonzero(ToArray(new_weights))\n # msg = \"{:3.2f}%: new acc={:1.4f}({:1.5f}), newW/oldW={:.4f}\".format(p * 100, acc, acc / old_acc, nznw / nzow)\n # # msg=\"- %d\"\n # print(msg)\n # # print(\" -\", p, \"%: acc=\", acc, \" new/old = \", acc / old_acc, \"!0-oldW\", nzow, \"!0-newW\", nznw)\n # pruned_metrics.append([loss, acc])\n #\n # print(\"test score: \", testScores)\n #\n\n import pickle\n\n print(\"keys:\", trainedWeights.keys())\n\n if saveToDisk:\n # save the models\n # for net in networks:\n # net.save(dirName + \"Net_\" + net.name)\n\n # save to disk the dictionary for all networks\n file = open(dirName + \"SeedsAndArchitectures.pkl\", \"wb\")\n pickle.dump(trainedWeights, file)\n file.close()\n\n end = time.time()\n print(\" execution time:\", end - start)\n\n return 0\n\n\ndef customtraining(net, data):\n Xtrain = data[0][0]\n Ytrain = data[0][1]\n Xtest = data[0][2]\n Ytest = data[0][3]\n\n # earlystopping_callback = tf.keras.callbacks.EarlyStopping(monitor='loss', mode='min', baseline=0.1)\n # earlystopping_callback = tf.keras.callbacks.EarlyStopping(monitor='loss', mode='min', min_delta=0.0001, verbose=1)\n\n maximumtrainepochs = 3000\n e = 1\n bs = 128\n ajn = 0\n\n M = []\n for l in range(1, len(net.layers)):\n m = net.layers[l].get_mask()[0].reshape(-1)\n M.extend(m)\n\n Ma = np.asarray(M)\n Wj = -np.count_nonzero(Ma)\n # fit_history = net.fit(Xtrain, Ytrain, batch_size=bs, epochs=1000, verbose=2, shuffle=False, callbacks=[earlystopping_callback])\n\n while e < maximumtrainepochs:\n if e < 20:\n bs = 60\n if 100 > e > 20:\n bs = 600\n if e > 100:\n bs = 60000\n\n # fit_history = net.fit(Xtrain, Ytrain, batch_size=bs, epochs=1, verbose=2, shuffle=False, callbacks=[earlystopping_callback])\n fit_history = net.fit(Xtrain, Ytrain, batch_size=bs, epochs=1, verbose=2, shuffle=False) # , callbacks=[earlystopping_callback])\n # print(\"approx sumlog2 \", fit_history.history['loss'][0] * 60000)\n Pj = -fit_history.history['loss'][-1] * Xtrain.shape[0]\n Ajn = Wj + Pj\n\n print(\"epoch\", e)\n print(\" loss*Datasize = \", fit_history.history['loss'][-1] * Xtrain.shape[0])\n print(\" loss = \", fit_history.history['loss'])\n print(\" Ajn = \", Ajn)\n e += 1\n\n return 0\n\n\ndef runmodels2(net, data, n_epochs=None, outputdir=None):\n if outputdir is None:\n dirName = dirNameDefault\n else:\n dirName = outputdir\n\n if n_epochs is None:\n n_epochs = epochs\n\n if saveToDisk:\n if not os.path.exists(dirName):\n os.makedirs(dirName)\n copy2(currentFileName + \".py\", dirName)\n print(\"data will be saved in \", dirName)\n\n start = time.time()\n\n e = 0\n trainedWeights = {}\n\n ne = 150\n stop = False\n\n import localutils\n\n # get train data for network t\n Xtrain = data[0][0]\n Ytrain = data[0][1]\n Xtest = data[0][2]\n Ytest = data[0][3]\n\n # localutils.customtraining2(net, data)\n\n # earlystopping_callback = tf.keras.callbacks.EarlyStopping(monitor='loss', min_delta=0.05)\n Loss = []\n VLoss = []\n batch_size = 1280\n patience = 10\n while e < 1500:\n # fit_history = net.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=1, verbose=2, shuffle=False,validation_data=(Xtest, Ytest)) # , callbacks=[earlystopping_callback])\n fit_history = net.fit(Xtrain, Ytrain, batch_size=batch_size, epochs=1, verbose=2, shuffle=False, validation_data=(Xtest, Ytest))\n # print(\"approx sumlog2 \", fit_history.history['loss'][0] * 60000)\n print(\"epoch\", e)\n # print(fit_history.history['loss'][-1] * batch_size)\n print(fit_history.history['loss'], fit_history.history['val_loss'])\n Loss.append(fit_history.history['loss'])\n VLoss.append(fit_history.history['val_loss'])\n\n if len(Loss) >= 2 * patience:\n vl0 = np.mean(np.asarray(VLoss)[-patience:-patience // 2])\n vl1 = np.mean(np.asarray(VLoss)[-patience // 2:])\n if vl1 > vl0:\n break\n\n # if e % 10 == 0:\n # customstopping(model=net, X=Xtrain, Y=Ytrain)\n\n e += 1\n\n W = []\n for l in range(1, len(net.layers)):\n w = net.layers[l].get_weights()[0]\n W.append(w)\n\n netseed = localutils.ExtractSeed(net.name)\n # add the network's weights to the dictionary of trained weights\n trainedWeights[netseed] = W\n\n import pickle\n\n print(\"keys:\", trainedWeights.keys())\n\n if saveToDisk:\n # save the models\n # for net in networks:\n # net.save(dirName + \"Net_\" + net.name)\n\n # save to disk the dictionary for all networks\n file = open(dirName + \"SeedsAndArchitectures.pkl\", \"wb\")\n pickle.dump(trainedWeights, file)\n file.close()\n\n end = time.time()\n print(\" execution time:\", end - start)\n\n return 0\n\n\ndef MakeModels():\n trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareMNISTData3D()\n # trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareFashionData3D()\n # trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareCIFAR10Data()\n\n # print(\"nonzeros mean\",np.count_nonzero(trainImages,axis=(1,2,3)).mean())\n # print(\"nonzeros std\",np.count_nonzero(trainImages,axis=(1,2,3)).std())\n # print(\"nonzeros min\",np.count_nonzero(trainImages,axis=(1,2,3)).min())\n # print(\"nonzeros max\",np.count_nonzero(trainImages,axis=(1,2,3)).max())\n # input()\n\n # trainImages = (trainImages - trainImages.mean()) / trainImages.std()\n # testImages = (testImages - testImages.mean()) / testImages.std()\n\n (n_examples, sx, sy, nchannels) = trainImages.shape\n\n trainImages_f = trainImages.reshape(-1, sx * sy * nchannels)\n testImages_f = testImages.reshape(-1, sx * sy * nchannels)\n\n NNets = 20\n\n networks = []\n data = []\n\n import uuid\n for i in range(NNets):\n # dense_arch = np.asarray([20])\n # dense_arch = np.append(dense_arch, np.random.randint(20, 25, 3), axis=0)\n # np.random.seed(17)\n # dense_arch = np.random.randint(50, 100, 4)\n # dense_arch = [np.random.randint(290, 310), np.random.randint(90, 110)]\n dense_arch = []\n dense_arch = [300, 100]\n full_arch = [trainImages_f.shape[1]]\n full_arch.extend(dense_arch)\n full_arch.append(nclasses)\n\n masks = SetMaskToONe(full_arch)\n\n # for m in range(len(masks)):\n # print(masks[m])\n # DrawWeights(\"Weights_\", masks)\n\n # for t in range(1, 15):\n # if t % 2 == 1:\n # dense_arch[t] = 28 * 28\n myseed = np.random.randint(0, 123456789)\n # myseed = 24690568\n mlp = MaskedMLP.makeMaskedMLP(full_arch, masks, myseed)\n networks.append(mlp)\n # mlp = makeSahredLayersdMLP(full_arch)\n # activemlp = ActiveMaskedMLP.makeActiveMaskedMLP(full_arch, masks, myseed)\n\n # mlp.set_weights(masks)\n # DrawWeights(\"aldjas\", mlp.get_weights())\n # cnn = makeSharedLayerCNN(trainImages.shape[1:], 10, \"cnn\")\n # networks.append(cnn)\n\n # simeplMLP=makeMLP(full_arch,)\n id = uuid.uuid4().hex\n\n # model_mlp = makeMLP(sx * sy * nchannels, nclasses, dense_arch,\n # name=\"mlp_\" + a2s(dense_arch) + \"_ID\" + id,\n # opt='adam', loss='categorical_crossentropy')\n # networks.append(activemlp)\n\n data.append([trainImages_f, trainLabels, testImages_f, testLabels])\n # data.append([trainImages, trainLabels, testImages, testLabels])\n\n for n in networks:\n n.summary()\n print(\"network name:\", n.name)\n print(\"parameters: \", n.count_params())\n\n print(\"\\n\\n\\n\")\n runmodels2(networks, data, n_epochs=epochs)\n\n return 0\n\n\ndef MakeModel():\n trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareMNISTData3D()\n (n_examples, sx, sy, nchannels) = trainImages.shape\n\n trainImages_f = trainImages.reshape(-1, sx * sy * nchannels)\n testImages_f = testImages.reshape(-1, sx * sy * nchannels)\n\n data = []\n\n import uuid\n dense_arch = []\n dense_arch = [289, 100]\n full_arch = [trainImages_f.shape[1]]\n full_arch.extend(dense_arch)\n full_arch.append(nclasses)\n\n masks = SetMaskToONe(full_arch)\n print(len(masks))\n print(masks[0].shape)\n import localutils\n # masks[0] = localutils.unfoldconvolution(28, 28, 12, 1)\n # masks[1] = localutils.unfoldconvolution(17, 17, 8, 1)\n # input()\n print(\"nonzeromasks:\", np.count_nonzero(ToArray(masks)))\n\n myseed = np.random.randint(0, 123456789)\n myseed = 24690568\n mlp = MaskedMLP.makeMaskedMLP(full_arch, masks, myseed)\n id = uuid.uuid4().hex\n\n data.append([trainImages_f, trainLabels, testImages_f, testLabels])\n # data.append([trainImages, trainLabels, testImages, testLabels])\n\n mlp.summary()\n print(\"network name:\", mlp.name)\n print(\"parameters: \", mlp.count_params())\n print(\"\\n\\n\\n\")\n runmodels2(mlp, data, n_epochs=epochs)\n\n return 0\n\n\ndef main():\n MakeModel()\n\n return 0\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"LotteryTickets/LTH.py","file_name":"LTH.py","file_ext":"py","file_size_in_byte":38368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"107061525","text":"from datetime import datetime\nfrom decimal import Decimal\n\nfrom peewee import fn\n\nfrom cockroachdb.modules.models import Order, OrderLine, Customer\nfrom cockroachdb.modules.transactions.base import BaseTransaction\n\n\nclass DeliveryTransaction(BaseTransaction):\n \"\"\"\n Delivery transaction\n\n Example:\n delivery = DeliveryTransaction(1, 100)\n delivery.run()\n \"\"\"\n\n DISTRICT_ITER_RANGE = [index + 1 for index in range(10)]\n\n def __init__(self, warehouse_id: int, carrier_id: int):\n \"\"\"\n Initiate a transaction for processing customer payment\n :param warehouse_id: warehouse number\n :param carrier_id: carrier identifier\n \"\"\"\n super().__init__()\n self.warehouse_id = warehouse_id\n self.carrier_id = carrier_id\n\n def _execute(self):\n \"\"\"\n Execute new delivery transaction\n :return: None\n \"\"\"\n for district_id in DeliveryTransaction.DISTRICT_ITER_RANGE:\n # Find next available order ID for delivery\n try:\n next_delivery_order: Order = (\n Order.select()\n .where(\n Order.carrier_id.is_null()\n & (Order.warehouse_id == self.warehouse_id)\n & (Order.district_id == district_id)\n )\n .order_by(Order.id)\n .limit(1)\n .get()\n )\n order_id = next_delivery_order.id\n except Order.DoesNotExist:\n continue\n\n if order_id is not None:\n # Retrieve order and order line details\n order_line: OrderLine = (\n OrderLine.select(fn.SUM(OrderLine.amount).alias(\"amount\"))\n .where(\n (OrderLine.warehouse_id == self.warehouse_id)\n & (OrderLine.district_id == district_id)\n & (OrderLine.order_id == order_id)\n )\n .get()\n )\n\n # Update order carrier ID\n Order.update(carrier_id=self.carrier_id).where(\n (Order.warehouse_id == self.warehouse_id)\n & (Order.district_id == district_id)\n & (Order.id == order_id)\n ).execute()\n\n # Update associated order line items\n OrderLine.update(delivery_date=datetime.utcnow()).where(\n (OrderLine.warehouse_id == self.warehouse_id)\n & (OrderLine.district_id == district_id)\n & (OrderLine.order_id == order_id)\n ).execute()\n\n # Update customer balance and delivery count\n Customer.update(\n balance=Customer.balance + Decimal(order_line.amount),\n delivery_count=Customer.delivery_count + 1,\n ).where(\n (Customer.warehouse_id == self.warehouse_id)\n & (Customer.district_id == district_id)\n & (Customer.id == next_delivery_order.customer_id)\n ).execute()\n\n @property\n def transaction_name(self):\n \"\"\"\n Transaction name\n :return: transaction name\n \"\"\"\n return \"delivery\"\n","sub_path":"cockroachdb/modules/transactions/delivery.py","file_name":"delivery.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"111937087","text":"import bs4\nimport re\nimport googlemaps\nimport json\nfrom datetime import datetime\nfrom googletrans import Translator\n\nfp = open(\"2019_7_page_5.html\", encoding =\"utf8\")\nsoup = bs4.BeautifulSoup(fp,'lxml')\naddr = []\naddrt = []\nt = Translator()\n\nfor i in soup.findAll(id = re.compile('^ContentPlaceHolder1_gdvMissingRegistrationdetails_lbllinkedfir')):\n if(i.text.find('रहात्या')==-1 & i.text.find('रहाच्या')==-1 &i.text.find('राहते')==-1 & i.text.find('राहच्या')==-1 & i.text.find('राहत्या')==-1 & i.text.find('रहाते')==-1 ):\n addr.append(i.text)\n\nfp = open(\"db_gen.txt\",\"a\",encoding=\"utf8\")\nfp1 = open(\"dbn_gen.txt\",\"a\",encoding=\"utf8\")\ngmaps = googlemaps.Client(key='AIzaSyBNbSHpD55qfU-m2WbrhoPEEIAHFEIIKVE')\nfor i in addr:\n result = gmaps.geocode(i)\n if (len(result)!=0) :\n lat = result[0][\"geometry\"][\"location\"][\"lat\"]\n lon = result[0][\"geometry\"][\"location\"][\"lng\"]\n fp.write(str(lat) + \" \" + str(lon) + \"\\n\")\n fp1.write(str(lat) + \" \" + str(lon) +\"\\n\" + \" [\" + i +\"]\" + \"\\n\")\nfp.close()\nfp1.close()\n\n\n \n","sub_path":"Data_analysis/db_gen_analysis.py","file_name":"db_gen_analysis.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"180276707","text":"import time\nfrom time import strftime, sleep\nimport subprocess\nimport digitalio\nimport board\nfrom PIL import Image, ImageDraw, ImageFont\nimport adafruit_rgb_display.st7789 as st7789\nimport qwiic_joystick\n\n\n\ncs_pin = digitalio.DigitalInOut(board.CE0)\ndc_pin = digitalio.DigitalInOut(board.D25)\nreset_pin = None\nBAUDRATE = 64000000\nspi = board.SPI()\ndisp = st7789.ST7789(\n spi,\n cs=cs_pin,\n dc=dc_pin,\n rst=reset_pin,\n baudrate=BAUDRATE,\n width=135,\n height=240,\n x_offset=53,\n y_offset=40,\n)\n\n\nheight = disp.width \nwidth = disp.height\nimage = Image.new(\"RGB\", (width, height))\nrotation = 90\n\ndraw = ImageDraw.Draw(image)\ndraw.rectangle((0, 0, width, height), outline=0, fill=(0, 0, 0))\ndisp.image(image, rotation)\n\npadding = -2\ntop = padding\nbottom = height - padding\nx = 0\n\nfont = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\", 18)\n\n# Turn on the backlight\nbacklight = digitalio.DigitalInOut(board.D22)\nbacklight.switch_to_output()\nbacklight.value = True\n\n# Enable the buttons for demo\nbuttonA = digitalio.DigitalInOut(board.D23)\nbuttonB = digitalio.DigitalInOut(board.D24)\n\n# Define default coordination\nx, y = 0, 0\n\n# Enable the joystick\njoystick = qwiic_joystick.QwiicJoystick()\n\nif joystick.is_connected() == False:\n print(\"The Qwiic Joystick device isn't connected to the system. Please check your connection\", \\\n file=sys.stderr)\n\njoystick.begin()\n\nprint(\"Initialized. Firmware Version: %s\" % joystick.get_version())\n\nwhile True:\n # Draw a black filled box to clear the image.\n draw.rectangle((0, 0, width, height), outline=0, fill=0)\n\n #TODO: fill in here. You should be able to look in cli_clock.py and stats.py \n\n # Get current time hour \n hour = int(strftime(\"%H\"))\n\n print(\"X: %d, Y: %d, Button: %d\" % ( \\\n joystick.get_horizontal(), \\\n joystick.get_vertical(), \\\n joystick.get_button()))\n\n time.sleep(0.1)\n\n # Button Push\n # while joystick.get_button() == 0:\n # ma_img = Image.open(\"mawen.jpeg\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n\n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Left\n while 500 < joystick.get_horizontal() <= 600 and joystick.get_vertical() == 0:\n ma_img = Image.open(\"species_icon/human.png\")\n ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n disp.image(ma_img, rotation)\n time.sleep(0.1)\n # Upper Left\n # while joystick.get_horizontal() == 1023 and 0 <= joystick.get_vertical() < 100:\n # ma_img = Image.open(\"2.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Up\n while joystick.get_horizontal() == 1023 and 500 <= joystick.get_vertical() < 600:\n ma_img = Image.open(\"species_icon/pikachu.png\")\n ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n disp.image(ma_img, rotation)\n time.sleep(0.1)\n # Upper Right\n # while joystick.get_horizontal() == 1023 and 1000 <= joystick.get_vertical() < 1024:\n # ma_img = Image.open(\"4.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Right\n while 500 <= joystick.get_horizontal() < 600 and 0 <= joystick.get_vertical() == 1023:\n ma_img = Image.open(\"species_icon/dog.png\")\n ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n disp.image(ma_img, rotation)\n time.sleep(0.1)\n # Lower Right\n # while joystick.get_horizontal() == 0 and 1000 <= joystick.get_vertical() < 1024:\n # ma_img = Image.open(\"6.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Down\n # while joystick.get_horizontal() == 0 and 500 <= joystick.get_vertical() < 600:\n # ma_img = Image.open(\"7.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n # Lower Left\n # while 0 <=joystick.get_horizontal() < 100 and 0 <= joystick.get_vertical() < 100:\n # ma_img = Image.open(\"8.png\")\n # ma_img = ma_img.resize((240, 135), Image.BICUBIC)\n \n # disp.image(ma_img, rotation)\n # time.sleep(0.1)\n\n \n\n\n\n\n # Display image.\n disp.image(image, rotation)\n time.sleep(1)\n","sub_path":"Final Project/translator copy.py","file_name":"translator copy.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"647152098","text":"# -*- coding: utf-8 -*-\n\nimport cv2\nimport sys\nfrom PIL import Image\n\n# camera_idx为视频来源\ndef CatcUsbVideo(windows_name, camera_idx):\n cv2.namedWindow(windows_name)\n\n # 用cap接收视频来源\n cap = cv2.VideoCapture(camera_idx)\n print(camera_idx)\n\n # 获取视频的帧速率fps\n fps = int(cap.get(cv2.CAP_PROP_FPS))\n # 获取视频的宽高\n size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n # 设置视频的解码器\n fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')\n # 获取视频的总帧数\n frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n print('视频详细信息:\\n\\tfps:', fps, '\\n\\t宽、高:', size, '\\n\\t总帧数:', frames, '\\n\\t解码器:', fourcc)\n\n # 告诉openCV使用人脸分类器\n classfier = cv2.CascadeClassifier(\"/home/ylhy/PycharmProjects/untitled/venv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_alt2.xml\")\n\n # 定义一个边框颜色\n color = (0, 255, 0)\n\n s = 0\n # 如果视频能被打开就开始循环\n while cap.isOpened():\n ok, frame = cap.read()\n if not ok:\n print(\"错误\")\n break\n # 将当前视频所循环获取的帧转换为灰度视频进行识别,提高速度\n grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # 开始人脸检测,把处理好的灰度视频传入\n # 1.2为图片缩放比例,3为需要检测的有效点数\n faceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\n # 如果大于0说明检测到了人脸\n if len(faceRects) > 0:\n for faceRects in faceRects:\n x, y, w, h = faceRects\n cv2.rectangle(frame, (x - 10, y - 10),(x + w +10, y + h +10), color, 2)\n s = s + 1\n cv2.imwrite('/home/ylhy/桌面/image_'+str(s)+'.jpg', frame)\n cv2.imshow(windows_name, frame)\n\n c = cv2.waitKey(10)\n if c & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n CatcUsbVideo(\"开始\",'/home/ylhy/桌面/as.mp4')\n","sub_path":"dome.py","file_name":"dome.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"147882568","text":"from collections import deque\n\n\n\"\"\"\nBinary search trees are a data structure that enforce an ordering over\nthe data they store. That ordering in turn makes it a lot more efficient\nat searching for a particular piece of data in the tree.\n\nThis part of the project comprises two days:\n1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`\n on the BSTNode class.\n2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods\n on the BSTNode class.\n\"\"\"\n\n\nclass BSTNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def __repr__(self):\n return f\"{self.value}\"\n\n # Insert the given value into the tree\n def insert(self, value):\n # First we check if the new value is less than the initial instances value\n if value < self.value:\n # We then check if the initial instances left pointer is equal to None\n if self.left is None:\n # If it is we then instantiate a new instance and set the initial instances left pointer to the new instance\n self.left = BSTNode(value)\n else:\n # We hop over the node that the instance is pointing to and insert new node recursively\n self.left.insert(value)\n else:\n # If the value of the instance was greater\n # We then check if the instances right pointer is equal to None\n if self.right is None:\n # If it is we then instantiate a new instance and set the initial instances right pointer to the new instance\n self.right = BSTNode(value)\n else:\n # We hop over the node that the instance is pointing to and insert new node recursively\n self.right.insert(value)\n\n # Return True if the tree contains the value\n # False if it does not\n\n def contains(self, target):\n # If initial instance value is the same as the new value return true\n if self.value is target:\n return True\n # We then decide which direction to traverse down the tree\n # If this is true we go left and check the values\n if self.value > target:\n if self.left is not None:\n return self.left.contains(target)\n # If this is true we go right and check the values\n elif self.value < target:\n if self.right is not None:\n return self.right.contains(target)\n else:\n # If neither of the previous conditions are met we return False\n return False\n\n # Return the maximum value found in the tree\n\n def get_max(self):\n if self.right == None:\n return self.value\n else:\n return self.right.get_max()\n\n # Call the function `fn` on the value of each node\n def for_each(self, fn):\n base = self.value\n if not self.left and not self.right:\n return fn(base)\n if self.left and not self.right:\n return fn(base), self.left.for_each(fn)\n if self.right and not self.left:\n return fn(base), self.right.for_each(fn)\n if self.right and self.left:\n return fn(base), self.right.for_each(fn), self.left.for_each(fn)\n\n # Part 2 -----------------------\n\n # Print all the values in order from low to high\n # Hint: Use a recursive, depth first traversal\n def in_order_print(self, node):\n if node:\n self.in_order_print(node.left)\n print(node.value)\n self.in_order_print(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative breadth first traversal\n\n def bft_print(self, node):\n queue = []\n queue.append(node)\n\n while len(queue) > 0:\n node = queue.pop(0)\n print(node.value)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n\n def dft_print(self, node):\n stack = []\n stack.append(node)\n\n while len(stack) > 0:\n node = stack.pop(-1)\n print(node.value)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n\n # Stretch Goals -------------------------\n # Note: Research may be required\n\n # Print Pre-order recursive DFT\n def pre_order_dft(self, node):\n pass\n\n # Print Post-order recursive DFT\n def post_order_dft(self, node):\n pass\n","sub_path":"binary_search_tree/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"244244441","text":"\"\"\"\nsentry.tagstore.v2.backend\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n:copyright: (c) 2010-2017 by the Sentry Team, see AUTHORS for more details.\n:license: BSD, see LICENSE for more details.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport six\n\nfrom collections import defaultdict\nfrom datetime import timedelta\nfrom django.db import connections, router, IntegrityError, transaction\nfrom django.db.models import Q, Sum\nfrom django.utils import timezone\nfrom operator import or_\nfrom six.moves import reduce\n\nfrom sentry import buffer\nfrom sentry.tagstore import TagKeyStatus\nfrom sentry.tagstore.base import TagStorage\nfrom sentry.utils import db\n\nfrom .models import EventTag, GroupTagKey, GroupTagValue, TagKey, TagValue\n\n\nclass TagStorage(TagStorage):\n \"\"\"\\\n The v2 tagstore backend stores and respects ``environment_id``.\n\n An ``environment_id`` value of ``None`` is used to keep track of the aggregate value across\n all environments.\n \"\"\"\n\n def setup(self):\n self.setup_deletions(\n tagkey_model=TagKey,\n tagvalue_model=TagValue,\n grouptagkey_model=GroupTagKey,\n grouptagvalue_model=GroupTagValue,\n eventtag_model=EventTag,\n )\n\n self.setup_cleanup(\n tagvalue_model=TagValue,\n grouptagvalue_model=GroupTagValue,\n eventtag_model=EventTag,\n )\n\n self.setup_merge(\n grouptagkey_model=GroupTagKey,\n grouptagvalue_model=GroupTagValue,\n )\n\n self.setup_tasks(\n tagkey_model=TagKey,\n )\n\n self.setup_receivers(\n tagvalue_model=TagValue,\n grouptagvalue_model=GroupTagValue,\n )\n\n # TODO(brett): v2-specific receivers for keeping environment aggregates up to date\n\n def create_tag_key(self, project_id, environment_id, key, **kwargs):\n return TagKey.objects.create(\n project_id=project_id,\n environment_id=environment_id,\n key=key,\n **kwargs\n )\n\n def get_or_create_tag_key(self, project_id, environment_id, key, **kwargs):\n return TagKey.objects.get_or_create(\n project_id=project_id,\n environment_id=environment_id,\n key=key,\n **kwargs\n )\n\n def create_tag_value(self, project_id, environment_id, key, value, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n return TagValue.objects.create(\n project_id=project_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n value=value,\n **kwargs\n )\n\n def get_or_create_tag_value(self, project_id, environment_id,\n key, value, key_id=None, **kwargs):\n if key_id is None:\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n key_id = tag_key.id\n\n return TagValue.objects.get_or_create(\n project_id=project_id,\n environment_id=environment_id,\n _key_id=key_id,\n value=value,\n **kwargs\n )\n\n def create_group_tag_key(self, project_id, group_id, environment_id, key, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n return GroupTagKey.objects.create(\n project_id=project_id,\n group_id=group_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n **kwargs\n )\n\n def get_or_create_group_tag_key(self, project_id, group_id, environment_id, key, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n return GroupTagKey.objects.get_or_create(\n project_id=project_id,\n group_id=group_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n **kwargs\n )\n\n def create_group_tag_value(self, project_id, group_id, environment_id, key, value, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n tag_value, _ = self.get_or_create_tag_value(\n project_id, environment_id, key, value, **kwargs)\n\n return GroupTagValue.objects.create(\n project_id=project_id,\n group_id=group_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n _value_id=tag_value.id,\n **kwargs\n )\n\n def get_or_create_group_tag_value(self, project_id, group_id,\n environment_id, key, value, **kwargs):\n tag_key, _ = self.get_or_create_tag_key(\n project_id, environment_id, key, **kwargs)\n\n tag_value, _ = self.get_or_create_tag_value(\n project_id, environment_id, key, value, **kwargs)\n\n return GroupTagValue.objects.get_or_create(\n project_id=project_id,\n group_id=group_id,\n environment_id=environment_id,\n _key_id=tag_key.id,\n _value_id=tag_value.id,\n **kwargs\n )\n\n def create_event_tags(self, project_id, group_id, environment_id, event_id, tags):\n try:\n # don't let a duplicate break the outer transaction\n with transaction.atomic():\n # Tags are bulk inserted because this is an all-or-nothing situation.\n # Either the whole transaction works, or it doesn't. There's no value\n # in a partial success where we'd need to replay half of the rows.\n EventTag.objects.bulk_create([\n EventTag(\n project_id=project_id,\n environment_id=environment_id,\n group_id=group_id,\n event_id=event_id,\n key_id=key_id,\n value_id=value_id,\n )\n for key_id, value_id in tags\n ])\n except IntegrityError:\n pass\n\n def get_tag_key(self, project_id, environment_id, key, status=TagKeyStatus.VISIBLE):\n from sentry.tagstore.exceptions import TagKeyNotFound\n\n qs = TagKey.objects.filter(\n project_id=project_id,\n key=key,\n **self._get_environment_filter(environment_id)\n )\n\n if status is not None:\n qs = qs.filter(status=status)\n\n try:\n return qs.get()\n except TagKey.DoesNotExist:\n raise TagKeyNotFound\n\n def get_tag_keys(self, project_id, environment_id, status=TagKeyStatus.VISIBLE):\n qs = TagKey.objects.filter(\n project_id=project_id,\n **self._get_environment_filter(environment_id)\n )\n\n if status is not None:\n qs = qs.filter(status=status)\n\n return list(qs)\n\n def get_tag_value(self, project_id, environment_id, key, value):\n from sentry.tagstore.exceptions import TagValueNotFound\n\n qs = TagValue.objects.filter(\n project_id=project_id,\n _key__key=key,\n value=value,\n **self._get_environment_filter(environment_id)\n )\n\n try:\n return qs.get()\n except TagValue.DoesNotExist:\n raise TagValueNotFound\n\n def get_tag_values(self, project_id, environment_id, key):\n qs = TagValue.objects.filter(\n project_id=project_id,\n _key__key=key,\n **self._get_environment_filter(environment_id)\n )\n\n return list(qs)\n\n def get_group_tag_key(self, project_id, group_id, environment_id, key):\n from sentry.tagstore.exceptions import GroupTagKeyNotFound\n\n qs = GroupTagKey.objects.filter(\n project_id=project_id,\n group_id=group_id,\n _key__key=key,\n **self._get_environment_filter(environment_id)\n )\n\n try:\n return qs.get()\n except GroupTagKey.DoesNotExist:\n raise GroupTagKeyNotFound\n\n def get_group_tag_keys(self, project_id, group_id, environment_id, limit=None):\n qs = GroupTagKey.objects.filter(\n group_id=group_id,\n **self._get_environment_filter(environment_id)\n )\n\n if limit is not None:\n qs = qs[:limit]\n\n return list(qs)\n\n def get_group_tag_value(self, project_id, group_id, environment_id, key, value):\n from sentry.tagstore.exceptions import GroupTagValueNotFound\n\n qs = GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n _key__key=key,\n _value__value=value,\n **self._get_environment_filter(environment_id)\n )\n\n try:\n return qs.get()\n except GroupTagValue.DoesNotExist:\n raise GroupTagValueNotFound\n\n def get_group_tag_values(self, project_id, group_id, environment_id, key):\n qs = GroupTagValue.objects.filter(\n group_id=group_id,\n _key__key=key,\n **self._get_environment_filter(environment_id)\n )\n\n return list(qs)\n\n def delete_tag_key(self, project_id, key):\n from sentry.tagstore.tasks import delete_tag_key as delete_tag_key_task\n\n tagkeys_qs = TagKey.objects.filter(\n project_id=project_id,\n key=key,\n )\n\n deleted = []\n for tagkey in tagkeys_qs:\n updated = TagKey.objects.filter(\n id=tagkey.id,\n status=TagKeyStatus.VISIBLE,\n ).update(status=TagKeyStatus.PENDING_DELETION)\n\n if updated:\n delete_tag_key_task.delay(object_id=tagkey.id)\n deleted.append(tagkey)\n\n return deleted\n\n def delete_all_group_tag_keys(self, project_id, group_id):\n GroupTagKey.objects.filter(\n project_id=project_id,\n group_id=group_id,\n ).delete()\n\n def delete_all_group_tag_values(self, project_id, group_id):\n GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n ).delete()\n\n def incr_tag_key_values_seen(self, project_id, environment_id, key, count=1):\n buffer.incr(TagKey,\n columns={\n 'values_seen': count,\n },\n filters={\n 'project_id': project_id,\n 'environment_id': environment_id,\n 'key': key,\n })\n\n def incr_tag_value_times_seen(self, project_id, environment_id,\n key, value, extra=None, count=1):\n buffer.incr(TagValue,\n columns={\n 'times_seen': count,\n },\n filters={\n 'project_id': project_id,\n 'environment_id': environment_id,\n 'key': key,\n 'value': value,\n },\n extra=extra)\n\n def incr_group_tag_key_values_seen(self, project_id, group_id, environment_id, key, count=1):\n buffer.incr(GroupTagKey,\n columns={\n 'values_seen': count,\n },\n filters={\n 'project_id': project_id,\n 'group_id': group_id,\n 'environment_id': environment_id,\n 'key': key,\n })\n\n def incr_group_tag_value_times_seen(self, project_id, group_id, environment_id,\n key, value, extra=None, count=1):\n buffer.incr(GroupTagValue,\n columns={\n 'times_seen': count,\n },\n filters={\n 'project_id': project_id,\n 'group_id': group_id,\n 'environment_id': environment_id,\n 'key': key,\n 'value': value,\n },\n extra=extra)\n\n def get_group_event_ids(self, project_id, group_id, environment_id, tags):\n tagkeys = dict(\n TagKey.objects.filter(\n project_id=project_id,\n key__in=tags.keys(),\n status=TagKeyStatus.VISIBLE,\n **self._get_environment_filter(environment_id)\n ).values_list('key', 'id')\n )\n\n tagvalues = {\n (t[1], t[2]): t[0]\n for t in TagValue.objects.filter(\n reduce(or_, (Q(_key__key=k, value=v)\n for k, v in six.iteritems(tags))),\n project_id=project_id,\n **self._get_environment_filter(environment_id)\n ).values_list('id', '_key__key', 'value')\n }\n\n try:\n tag_lookups = [(tagkeys[k], tagvalues[(k, v)])\n for k, v in six.iteritems(tags)]\n # [(1, 10), ...]\n except KeyError:\n # one or more tags were invalid, thus the result should be an empty\n # set\n return []\n\n # Django doesnt support union, so we limit results and try to find\n # reasonable matches\n\n # get initial matches to start the filter\n k, v = tag_lookups.pop()\n matches = list(\n EventTag.objects.filter(\n project_id=project_id,\n group_id=group_id,\n key_id=k,\n value_id=v,\n **self._get_environment_filter(environment_id)\n ).values_list('event_id', flat=True)[:1000]\n )\n\n # for each remaining tag, find matches contained in our\n # existing set, pruning it down each iteration\n for k, v in tag_lookups:\n matches = list(\n EventTag.objects.filter(\n project_id=project_id,\n group_id=group_id,\n event_id__in=matches,\n key_id=k,\n value_id=v,\n **self._get_environment_filter(environment_id)\n ).values_list('event_id', flat=True)[:1000]\n )\n if not matches:\n return []\n\n return matches\n\n def get_groups_user_counts(self, project_id, group_ids, environment_id):\n qs = GroupTagKey.objects.filter(\n project_id=project_id,\n group_id__in=group_ids,\n _key__key='sentry:user',\n **self._get_environment_filter(environment_id)\n )\n\n return defaultdict(int, qs.values_list('group_id', 'values_seen'))\n\n def get_group_tag_value_count(self, project_id, group_id, environment_id, key):\n if db.is_postgres():\n # This doesnt guarantee percentage is accurate, but it does ensure\n # that the query has a maximum cost\n using = router.db_for_read(GroupTagValue)\n cursor = connections[using].cursor()\n cursor.execute(\n \"\"\"\n SELECT SUM(t)\n FROM (\n SELECT times_seen as t\n FROM tagstore_grouptagvalue\n INNER JOIN tagstore_tagkey\n ON (tagstore_grouptagvalue.key_id = tagstore_tagkey.id)\n WHERE tagstore_grouptagvalue.group_id = %s\n AND tagstore_grouptagvalue.environment_id = %s\n AND tagstore_tagkey.key = %s\n ORDER BY last_seen DESC\n LIMIT 10000\n ) as a\n \"\"\", [group_id, environment_id, key]\n )\n return cursor.fetchone()[0] or 0\n\n cutoff = timezone.now() - timedelta(days=7)\n return GroupTagValue.objects.filter(\n group_id=group_id,\n _key__key=key,\n last_seen__gte=cutoff,\n **self._get_environment_filter(environment_id)\n ).aggregate(t=Sum('times_seen'))['t']\n\n def get_top_group_tag_values(self, project_id, group_id, environment_id, key, limit=3):\n if db.is_postgres():\n # This doesnt guarantee percentage is accurate, but it does ensure\n # that the query has a maximum cost\n return list(\n GroupTagValue.objects.raw(\n \"\"\"\n SELECT *\n FROM (\n SELECT tagstore_grouptagvalue.id,\n tagstore_grouptagvalue.project_id,\n tagstore_grouptagvalue.group_id,\n tagstore_grouptagvalue.environment_id,\n tagstore_grouptagvalue.times_seen,\n tagstore_grouptagvalue.key_id,\n tagstore_grouptagvalue.value_id,\n tagstore_grouptagvalue.last_seen,\n tagstore_grouptagvalue.first_seen\n FROM tagstore_grouptagvalue\n INNER JOIN tagstore_tagkey\n ON (tagstore_grouptagvalue.key_id = tagstore_tagkey.id)\n WHERE tagstore_grouptagvalue.group_id = %%s\n AND tagstore_grouptagvalue.environment_id = %%s\n AND tagstore_tagkey.key = %%s\n ORDER BY last_seen DESC\n LIMIT 10000\n ) as a\n ORDER BY times_seen DESC\n LIMIT %d\n \"\"\" % limit, [group_id, environment_id, key]\n )\n )\n\n cutoff = timezone.now() - timedelta(days=7)\n return list(\n GroupTagValue.objects.filter(\n group_id=group_id,\n _key__key=key,\n last_seen__gte=cutoff,\n **self._get_environment_filter(environment_id)\n ).order_by('-times_seen')[:limit]\n )\n\n def get_first_release(self, project_id, group_id):\n try:\n first_release = GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n _key__key__in=('sentry:release', 'release'),\n ).order_by('first_seen')[0]\n except IndexError:\n return None\n else:\n return first_release.value\n\n def get_last_release(self, project_id, group_id):\n try:\n last_release = GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n _key__key__in=('sentry:release', 'release'),\n ).order_by('-last_seen')[0]\n except IndexError:\n return None\n\n return last_release.value\n\n def get_release_tags(self, project_ids, environment_id, versions):\n return list(TagValue.objects.filter(\n project_id__in=project_ids,\n _key__key='sentry:release',\n value__in=versions,\n **self._get_environment_filter(environment_id)\n ))\n\n def get_group_ids_for_users(self, project_ids, event_users, limit=100):\n return list(GroupTagValue.objects.filter(\n project_id__in=project_ids,\n environment_id__isnull=True,\n _key__key='sentry:user',\n _value__value__in=[eu.tag_value for eu in event_users],\n ).order_by('-last_seen').values_list('group_id', flat=True)[:limit])\n\n def get_group_tag_values_for_users(self, event_users, limit=100):\n tag_filters = [\n Q(_value__value=eu.tag_value, project_id=eu.project_id)\n for eu in event_users\n ]\n\n return list(GroupTagValue.objects.filter(\n reduce(or_, tag_filters),\n environment_id__isnull=True,\n _key__key='sentry:user',\n ).order_by('-last_seen')[:limit])\n\n def get_group_ids_for_search_filter(self, project_id, environment_id, tags):\n from sentry.search.base import ANY, EMPTY\n # Django doesnt support union, so we limit results and try to find\n # reasonable matches\n\n # ANY matches should come last since they're the least specific and\n # will provide the largest range of matches\n tag_lookups = sorted(six.iteritems(tags), key=lambda x: x != ANY)\n\n # get initial matches to start the filter\n matches = None\n\n # for each remaining tag, find matches contained in our\n # existing set, pruning it down each iteration\n for k, v in tag_lookups:\n if v is EMPTY:\n return None\n\n elif v != ANY:\n base_qs = GroupTagValue.objects.filter(\n project_id=project_id,\n _key__key=k,\n _value__value=v,\n **self._get_environment_filter(environment_id)\n )\n\n else:\n base_qs = GroupTagValue.objects.filter(\n project_id=project_id,\n _key__key=k,\n **self._get_environment_filter(environment_id)\n ).distinct()\n\n if matches:\n base_qs = base_qs.filter(group_id__in=matches)\n else:\n # restrict matches to only the most recently seen issues\n base_qs = base_qs.order_by('-last_seen')\n\n matches = list(base_qs.values_list('group_id', flat=True)[:1000])\n\n if not matches:\n return None\n\n return matches\n\n def update_group_tag_key_values_seen(self, project_id, group_ids):\n gtk_qs = GroupTagKey.objects.filter(\n project_id=project_id,\n group_id__in=group_ids\n )\n\n for instance in gtk_qs:\n instance.update(\n values_seen=GroupTagValue.objects.filter(\n project_id=instance.project_id,\n group_id=instance.group_id,\n environment_id=instance.environment_id,\n key=instance.key,\n ).count(),\n )\n\n def get_tag_value_qs(self, project_id, environment_id, key, query=None):\n queryset = TagValue.objects.filter(\n project_id=project_id,\n key=key,\n **self._get_environment_filter(environment_id)\n )\n\n if query:\n queryset = queryset.filter(value__contains=query)\n\n return queryset\n\n def get_group_tag_value_qs(self, project_id, group_id, environment_id, key):\n return GroupTagValue.objects.filter(\n project_id=project_id,\n group_id=group_id,\n key=key,\n **self._get_environment_filter(environment_id)\n )\n\n def update_group_for_events(self, project_id, event_ids, destination_id):\n return EventTag.objects.filter(\n project_id=project_id,\n event_id__in=event_ids,\n ).update(group_id=destination_id)\n\n def _get_environment_filter(self, environment_id):\n if environment_id is None:\n return {'environment_id__isnull': True}\n else:\n return {'environment_id': environment_id}\n","sub_path":"src/sentry/tagstore/v2/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":23262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"515340574","text":"import abc\nimport serial # type: ignore\nimport telnetlib\nimport threading\n\nfrom typing import Optional\n\nimport logging\n\nlogging.basicConfig()\n_LOGGER = logging.getLogger(\"nad_receiver.transport\")\n\n\nDEFAULT_TIMEOUT = 1\n\n\nclass NadTransport(abc.ABC):\n @abc.abstractmethod\n def communicate(self, command: str) -> str:\n pass\n\n\nclass SerialPortTransport:\n \"\"\"Transport for NAD protocol over RS-232.\"\"\"\n\n def __init__(self, serial_port: str) -> None:\n \"\"\"Create RS232 connection.\"\"\"\n self.ser = serial.Serial(\n serial_port,\n baudrate=115200,\n timeout=DEFAULT_TIMEOUT,\n write_timeout=DEFAULT_TIMEOUT,\n )\n self.lock = threading.Lock()\n\n def __repr__(self):\n return f\"SerialPortTransport\"\n\n def _open_connection(self) -> None:\n if not self.ser.is_open:\n self.ser.open()\n _LOGGER.debug(\"serial open: %s\", self.ser.is_open)\n\n def communicate(self, command: str) -> str:\n with self.lock:\n self._open_connection()\n\n self.ser.write(f\"\\r{command}\\r\".encode(\"utf-8\"))\n # To get complete messages, always read until we get '\\r'\n # Messages will be of the form '\\rMESSAGE\\r' which\n # pyserial handles nicely\n msg = self.ser.read_until(\"\\r\")\n if not msg.strip(): # discard '\\r' if it was sent\n msg = self.ser.read_until(\"\\r\")\n assert isinstance(msg, bytes)\n return msg.strip().decode()\n\n\nclass TelnetTransport:\n \"\"\"\n Support NAD amplifiers that use telnet for communication.\n Supports all commands from the RS232 base class\n\n Known supported model: Nad T787.\n \"\"\"\n\n def __init__(self, host: str, port: int, timeout: int) -> None:\n \"\"\"Create NADTelnet.\"\"\"\n self.telnet: Optional[telnetlib.Telnet] = None\n self.host = host\n self.port = port\n self.timeout = timeout\n\n def _open_connection(self) -> None:\n if not self.telnet:\n try:\n self.telnet = telnetlib.Telnet(self.host, self.port, 3)\n # Some versions of the firmware report Main.Model=T787.\n # some versions do not, we want to clear that line\n self.telnet.read_until(\"\\n\".encode(), self.timeout)\n # Could raise eg. EOFError, UnicodeError\n except (EOFError, UnicodeError):\n pass\n\n def communicate(self, cmd: str) -> str:\n self._open_connection()\n assert self.telnet\n\n self.telnet.write(f\"\\r{cmd}\\r\".encode())\n msg = self.telnet.read_until(b\"\\r\", self.timeout)\n return msg.strip().decode()\n","sub_path":"nad_receiver/nad_transport.py","file_name":"nad_transport.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"436238173","text":"import tkinter as tk\n\nHEIGHT = 700\nWIDTH = 600\nroot = tk.Tk()\nroot.title(\"App\")\n\ntk.Label(root, text=\"First Name\").grid(row=0)\ntk.Label(root, text=\"Last Name\").grid(row=1)\n\ne1 = tk.Entry(root)\ne2 = tk.Entry(root)\n\ne1.grid(row=0, column=1)\ne2.grid(row=1, column=1)\n\n\nroot.mainloop()","sub_path":"vijay47.py","file_name":"vijay47.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"368685780","text":"\r\nclass ACO():\r\n\t\"\"\"docstring for ACO\"\"\"\r\n\r\n\tdistance_matrix = None\r\n\tcity_count = None\r\n\tparams = {}\r\n\r\n\tants = []\r\n\tpheromone = []\r\n\r\n\tdef __init__(self, distance_matrix, params):\r\n\t\t\"\"\"args - distance matrix\"\"\"\r\n\t\tACO.distance_matrix = distance_matrix\r\n\t\tACO.city_count = len(distance_matrix)\r\n\t\tACO.pheromone = [[0 for i in range(ACO.city_count)] for j in range(ACO.city_count)]\r\n\r\n\t\tsource = 0\r\n\t\tfor i in range(30):\r\n\t\t\tACO.ants.append(Ant(source))\r\n\t\t\tsource += 1\r\n\t\t\tsource = source % ACO.city_count\r\n\r\n\tdef find_route(self):\r\n\t\tprint('finding route')\r\n\r\n\tdef best_route(self):\r\n\t\tprint('the best route is')\r\n\r\n\r\nclass Ant():\r\n\r\n\tdef __init__(self, start_city):\r\n\t\tself.cur_city = start_city\r\n\t\tself.path = [start_city]\r\n\t\tself.tour_length = 0\r\n\r\n\tdef move_to_city(self, city):\r\n\t\tself.path.append(city)\r\n\t\tself.tour_length += ACO.distance_matrix[self.cur_city][city]\r\n\t\tif len(self.path) == ACO.city_count:\r\n\t\t\tself.tour_length += ACO.distance_matrix[self.path[-1]][self.path[0]]\r\n\t\tself.cur_city = city\r\n\r\n\tdef can_move(self):\r\n\t\treturn len(self.path) < ACO.city_count\r\n\r\n\tdef reset(self, city):\r\n\t\tself.cur_city = city\r\n\t\tself.path = [city]\r\n\t\tself.tour_length = 0.\r\n","sub_path":"aco.py","file_name":"aco.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"510401534","text":"import sympy\n\nif __name__ == \"__main__\":\n overall = 600851475143\n largestPrimeFactor = None\n checkNum = 5\n while (checkNum * checkNum) <= overall:\n checkNum = sympy.nextprime(checkNum)\n if overall % checkNum == 0:\n largestPrimeFactor = checkNum\n print(\"Largest prime factor of 600851475143 is: {0}\".format(largestPrimeFactor))\n","sub_path":"python/3_largestPrime.py","file_name":"3_largestPrime.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"562344287","text":"'''\n\nThis module is for tests using a combination of n-grams and other features.\n\nFor n-gram only tests, use ngram-only-tests.py.\n\nFor non n-gram only tests, use non-ngram-only-tests.py.\n\nThe code relating to scikit-learn was adapted from code on the scikit-learn website: https://scikit-learn.org/\n\n'''\nimport numpy as np\nimport sys\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import balanced_accuracy_score\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.feature_extraction.text import CountVectorizer\n\ncorpus = [] # List of sentences in human-readable form (i.e. not in a bag of words representation).\ndocumentClassificationList = [] # Stored as strings - true = formal, false = informal.\nformalityScoreList = [] # Mechanical Turk formality scores.\nnonDocumentData = [] # List of lists, each containing a sentence's attribute data.\ndataFileFieldNames = [] # The field names from the top of the data spreadsheet.\ncorpus = [] # List of sentences in human-readable form (i.e. not in a bag of words representation).\ndocumentClassificationList = [] # Stored as strings - true = formal, false = informal.\nformalityScoreList = [] # Mechanical Turk formality scores.\nnonDocumentData = [] # List of lists, each containing a sentence's attribute data.\ndataFileFieldNames = [] # The field names from the top of the data spreadsheet.\nfieldsToSelectFrom = [] # List of features that the user has not selected for the test.\nchosenFields = [] # List of features that the user has selected for the test.\nfileName = \"new_formality_data.csv\"\n\n\n# Checks if the 'fileName' is the correct file name\ndef checkFileNameCorrect():\n global fileName\n print(\"The default data file name is \", fileName, \"\\n\")\n print(\"If this is the name of the data file you are using, simply press enter\")\n newFileName = input(\"Otherwise, please provide the correct name, and then press enter: \")\n if newFileName != \"\":\n fileName = newFileName\n print(\"\\nThank you. The file name has been changed to:\", fileName)\n else:\n print(\"\\nThank you. You have confirmed that the existing file name is correct:\", fileName)\n\n\n# Checks if file present. Code for this module adapted from:\n# https://stackoverflow.com/questions/5627425/what-is-a-good-way-to-handle-exceptions-when-trying-to-read-a-file-in-python\ndef checkFilePresent():\n try:\n f = open(fileName, 'rb')\n except OSError:\n print(\"\\nFile not found:\", fileName)\n print(\"Please ensure that the data file is in the same folder as the program file.\")\n print(\"Exiting program.\")\n sys.exit()\n\n\n# This function loads the data from the file and stores it in the data structures shown above.\n# It is always the first function to be run.\ndef loadData():\n checkFileNameCorrect() # Asks user is data file name is correct\n checkFilePresent() # Checks if data file is present\n with open(fileName, encoding='utf-8') as inputFile:\n firstLine = inputFile.readline()\n firstLineAsList = firstLine.split(\",\")\n # Copy the data file field names into a global list:\n for items in firstLineAsList:\n dataFileFieldNames.append(items)\n\n # The sentence field is always the final field on the right. Therefore, the sentence index is the number of\n # fields up to and including the one immediately preceding the 'sentence' field.\n sentenceIndex = len(firstLineAsList)-1\n for line in inputFile:\n\n # Searches through the line for commas, character by character. Stops when 'sentenceIndex' number of commas\n # have been encountered.\n # The document is located to the right of the comma corresponding to index 'sentenceIndex'.\n # Everything to the left of that comma is data relating to the document.\n numCommas = 0\n for character in range(len(line)):\n\n # Increments numCommas whenever a comma is encountered in the line.\n if line[character] == \",\":\n numCommas = numCommas + 1\n\n # The code below is run when when the number of commas encountered equals the value of 'sentenceIndex'.\n # When the code below is run, it means that everything on the line to the right of the last comma\n # encountered is part of the sentence, and not attribute data.\n if numCommas == sentenceIndex:\n dataExcludingSentence = line[:character]\n dataExcludingSentenceAsList = dataExcludingSentence.split(\",\")\n nonDocumentData.append(dataExcludingSentenceAsList)\n formalityScore = float(dataExcludingSentenceAsList[2])\n formalityScoreList.append(formalityScore)\n # If mechanical Turk formality score >=4 then formal status = true:\n documentClassificationList.append(formalityScore >= 4)\n documentToAdd = line[character + 1:] # The rest of the current line is comprised of the document\n documentToAdd.replace('\\n', '') # Removes 'next line' symbol \\n from the end of the document\n\n # Puts document into a list of Strings:\n corpus.append(documentToAdd)\n break # returns to the outer 'for' loop, so the next line can be processed.\n inputFile.close()\n print(\"\\nNo of records uploaded: \", len(corpus))\n\n\n# This function performs the machine learning test and outputs a classification prediction result summary.\ndef classificationResults(featureData, classificationLabels, featureDescription):\n\n # The two lines below convert the lists passed into the function to arrays.\n X = np.array(featureData)\n y = np.array(classificationLabels)\n\n # Splits the data into training and testing sets using 5 split k fold:\n skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=12345)\n skf.split(X, y)\n X_train = []\n X_test = []\n y_train = []\n y_test = []\n for train_index, test_index in skf.split(X, y):\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n\n # Fits the data to a model. The model is initially instantiated as SVC so that the definitions of 'classifier' in\n # the 'if' statements below it aren't out of scope of the rest of the module.\n model = SVC(gamma='scale', kernel='linear', probability=True).fit(X_train, y_train)\n if classifier == \"Logistic Regression\":\n model = LogisticRegression(random_state=0, solver='lbfgs',max_iter=1000).fit(X_train, y_train)\n if classifier == \"Multinomial Bayes\":\n model = MultinomialNB().fit(X_train, y_train)\n if classifier == \"Random Forest\":\n model = RandomForestClassifier().fit(X_train, y_train)\n\n # Generates a prediction for each sentence, and stores them in a list called 'predictions'.\n predictions = model.predict(np.array(X_test))\n\n # Calculates true positives, true negatives, false positives and false negatives:\n truePositives = 0\n trueNegatives = 0\n falsePositives = 0\n falseNegatives = 0\n numberInList = 0\n for prediction in predictions:\n\n # Is this a formal sentence which was predicted to be formal?\n if y_test[numberInList] and prediction:\n truePositives = truePositives + 1\n\n # Is this an informal sentence which was predicted to be informal?\n if not y_test[numberInList] and not prediction:\n trueNegatives = trueNegatives + 1\n\n # Is this an informal sentence which was predicted to be formal?\n if not y_test[numberInList] and prediction:\n falsePositives = falsePositives + 1\n\n # Is this a formal sentence which was predicted to be informal?\n if y_test[numberInList] and not prediction:\n falseNegatives = falseNegatives + 1\n numberInList = numberInList + 1\n\n # Performance metrics\n if (truePositives + trueNegatives + falsePositives + falseNegatives) > 0:\n accuracy = (truePositives + trueNegatives) / (truePositives + trueNegatives + falsePositives + falseNegatives)\n else:\n accuracy = 0\n if (truePositives + falsePositives) > 0:\n precision = truePositives / (truePositives + falsePositives)\n else:\n precision = 0\n if (truePositives + falseNegatives) > 0:\n recall = truePositives / (truePositives + falseNegatives)\n else:\n recall = 0\n if (trueNegatives + falsePositives) > 0:\n fallout = falsePositives / (trueNegatives + falsePositives) # 'Fallout' is the same as the false positive rate.\n else:\n fallout = 0\n balAccuracy = balanced_accuracy_score(y_test, predictions)\n\n # Area under roc curve\n y_scores = model.predict_proba(X_test)\n y_scores = y_scores[:, 1]\n rocAreaUnderCurve = roc_auc_score(y_test, y_scores)\n\n # Console output\n print(\"\\nFeature tested:\\n\", featureDescription)\n print(\"Classifier: \" + classifier, \"\\n\")\n print(\"Total predictions: \", numberInList)\n print(\"TRUE POSITIVES: \", truePositives)\n print(\"FALSE POSITIVES: \", falsePositives)\n print(\"TRUE NEGATIVES: \", trueNegatives)\n print(\"FALSE NEGATIVES: \", falseNegatives)\n # Division by zero is illegal, so if the denominator is zero, then 'N/A' is given as the metric's value.\n if accuracy > 0:\n print(\"Accuracy: %3.2f\" % accuracy)\n else:\n print(\"Accuracy: N/A\")\n if precision > 0:\n print(\"Precision: %3.2f\" % precision)\n else:\n print(\"Precision: N/A\")\n if recall > 0:\n print(\"Recall: %3.2f\" % recall)\n else:\n print(\"Recall: N/A\")\n if fallout > 0:\n print(\"False positive rate: %3.2f\" % fallout)\n else:\n print(\"False positive rate: N/A\")\n print(\"AUC: %3.2f\" % rocAreaUnderCurve)\n print(\"Balanced accuracy: %3.2f\" % balAccuracy)\n\n\n# Asks the user what type of n-gram they want to test.\ndef askForType():\n print(\"\\nThe n-gram types are: \")\n print(\"1 - Unigram\")\n print(\"2 - Bigram\")\n print(\"3 - Trigram\")\n print(\"4 - Unigram and bigram combined\")\n print(\"5 - Unigram, bigram and trigram combined\")\n userChoice = input(\"\\nChoose an option by typing a number between 1 and 5 and then pressing 'enter': \")\n if userChoice.isnumeric():\n global nGramType\n userChoice = int(userChoice)\n if userChoice == 1:\n nGramType = \"unigram\"\n return\n if userChoice == 2:\n nGramType = \"bigram\"\n return\n if userChoice == 3:\n nGramType = \"trigram\"\n return\n if userChoice == 4:\n nGramType = \"1, 2 gram\"\n return\n if userChoice == 5:\n nGramType = \"1, 2, 3 gram\"\n return\n else:\n print(\"\\nInvalid selection. Please try again\")\n askForType()\n # If non-numeric value entered:\n else:\n print(\"\\nInvalid selection. Please try again\")\n askForType()\n\n\n# Asks user whether n-gram will be binary, non-binary or TF-IDF representation\ndef askForRepresentation():\n print(\"\\nThe representation options are: \")\n print(\"1 - Binary\")\n print(\"2 - Non-Binary\")\n print(\"3 - TF-IDF\")\n userChoice = input(\"\\nChoose an option by typing a number between 1 and 3 and then pressing 'enter': \")\n if userChoice.isnumeric():\n global representation\n userChoice = int(userChoice)\n if userChoice == 1:\n representation = \"binary\"\n return\n if userChoice == 2:\n representation = \"non-binary\"\n return\n if userChoice == 3:\n representation = \"TF-IDF\"\n return\n else:\n print(\"\\nInvalid selection. Please try again\")\n askForRepresentation()\n # If non-numeric value entered:\n else:\n print(\"\\nInvalid selection. Please try again\")\n askForRepresentation()\n\n\n# Asks the user if they want stop words including in their test\ndef askAboutStopWords():\n print(\"\\nThe stop word options are: \")\n print(\"1 - Include stop words\")\n print(\"2 - No, do not include stop words\")\n userChoice = input(\"\\nChoose an option by typing 1 or 2 and then pressing 'enter': \")\n if userChoice.isnumeric():\n global stops\n userChoice = int(userChoice)\n if userChoice == 1:\n stops = \"with stop words\"\n return\n if userChoice == 2:\n stops = \"without stop words\"\n return\n else:\n print(\"Invalid selection. Please try again\")\n askAboutStopWords()\n # If non-numeric value entered:\n else:\n print(\"\\nInvalid selection. Please try again\")\n askAboutStopWords()\n\n\n# Asks user which classifier to use\ndef askForClassifier():\n print(\"\\nThe classifiers are: \\n1 - Support Vector Machine\\n2 - Logistic Regression\\n3 - Multinomial Bayes\\n\"\n \"4 - Random Forest\")\n classifierChoice = input(\"\\nPlease choose a classifier by typing a number between 1 and 4 and then press 'enter': \")\n if classifierChoice.isnumeric():\n classifierChoice = int(classifierChoice)\n global classifier\n if classifierChoice == 1:\n print(\"You have selected Support Vector Machine\")\n classifier = \"Support Vector Machine\"\n return\n if classifierChoice == 2:\n print(\"You have selected Logistic Regression\")\n classifier = \"Logistic Regression\"\n return\n if classifierChoice == 3:\n print(\"You have selected Multinomial Bayes\")\n classifier = \"Multinomial Bayes\"\n return\n if classifierChoice == 4:\n print(\"You have selected Random Forest\")\n classifier = \"Random Forest\"\n return\n else:\n print(\"\\nThat was not a valid selection. Please try again.\")\n askForClassifier()\n else:\n print(\"\\nThat was not a valid selection. Please try again.\")\n askForClassifier()\n\n\n# Selects the correct vector type to create based on the user's test choices.\ndef setVector(nGramType, representation, stops):\n # UNIGRAMS\n\n # Unigram, binary representation, stop words included.\n if nGramType == \"unigram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(1, 1))\n\n # Unigram, binary representation, stop words excluded.\n if nGramType == \"unigram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(1, 1))\n\n # Unigram, non-binary representation, stop words included.\n if nGramType == \"unigram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(1, 1))\n\n # Unigram, non-binary representation, stop words excluded.\n if nGramType == \"unigram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(1, 1))\n\n # Unigram, TF-IDF representation, stop words included.\n if nGramType == \"unigram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(1, 1))\n\n # Unigram, TF-IDF representation, stop words excluded.\n if nGramType == \"unigram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(1, 1))\n\n # BIGRAMS\n\n # Bigram, binary representation, stop words included.\n if nGramType == \"bigram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(2, 2))\n\n # Bigram, binary representation, stop words excluded.\n if nGramType == \"bigram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(2, 2))\n\n # Bigram, non-binary representation, stop words included.\n if nGramType == \"bigram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(2, 2))\n\n # Bigram, non-binary representation, stop words excluded.\n if nGramType == \"bigram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(2, 2))\n\n # Bigram, TF-IDF representation, stop words included.\n if nGramType == \"bigram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(2, 2))\n\n # Bigram, TF-IDF representation, stop words excluded.\n if nGramType == \"bigram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(2, 2))\n\n # TRIGRAMS\n\n # Trigram, binary representation, stop words included.\n if nGramType == \"trigram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(3, 3))\n\n # Trigram, binary representation, stop words excluded.\n if nGramType == \"trigram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(3, 3))\n\n # Trigram, non-binary representation, stop words included.\n if nGramType == \"trigram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(3, 3))\n\n # Trigram, non-binary representation, stop words excluded.\n if nGramType == \"trigram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(3, 3))\n\n # Trigram, TF-IDF representation, stop words included.\n if nGramType == \"trigram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(3, 3))\n\n # Trigram, TF-IDF representation, stop words excluded.\n if nGramType == \"trigram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(3, 3))\n\n # UNIGRAMS AND BIGRAMS COMBINED\n\n # Unigram and bigram combined, binary representation, stop words included.\n if nGramType == \"1, 2 gram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(1, 2))\n\n # Unigram and bigram combined, binary representation, stop words excluded.\n if nGramType == \"1, 2 gram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(1, 2))\n\n # Unigram and bigram combined, non-binary representation, stop words included.\n if nGramType == \"1, 2 gram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(1, 2))\n\n # Unigram and bigram combined, non-binary representation, stop words excluded.\n if nGramType == \"1, 2 gram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(1, 2))\n\n # Unigram and bigram combined, TF-IDF representation, stop words included.\n if nGramType == \"1, 2 gram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(1, 2))\n\n # Unigram and bigram combined, TF-IDF representation, stop words excluded.\n if nGramType == \"1, 2 gram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(1, 2))\n\n # UNIGRAMS, BIGRAMS AND TRIGRAMS COMBINED\n\n # Unigram, bigram and trigram combined, binary representation, stop words included.\n if nGramType == \"1, 2, 3 gram\" and representation == \"binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=True, ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, binary representation, stop words excluded.\n if nGramType == \"1, 2, 3 gram\" and representation == \"binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=True, stop_words='english', ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, non-binary representation, stop words included.\n if nGramType == \"1, 2, 3 gram\" and representation == \"non-binary\" and stops == \"with stop words\":\n return CountVectorizer(binary=False, ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, non-binary representation, stop words excluded.\n if nGramType == \"1, 2, 3 gram\" and representation == \"non-binary\" and stops == \"without stop words\":\n return CountVectorizer(binary=False, stop_words='english', ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, TF-IDF representation, stop words included.\n if nGramType == \"1, 2, 3 gram\" and representation == \"TF-IDF\" and stops == \"with stop words\":\n return TfidfVectorizer(ngram_range=(1, 3))\n\n # Unigram, bigram and trigram combined, TF-IDF representation, stop words excluded.\n if nGramType == \"1, 2, 3 gram\" and representation == \"TF-IDF\" and stops == \"without stop words\":\n return TfidfVectorizer(stop_words='english', ngram_range=(1, 3))\n\n\n# Puts all non n-gram feature field names into list 'fieldsToSelectFrom', except those that are not feature fields.\ndef createFeatureFieldList():\n nonFeatureFields = ['HIT ID', 'Sentence ID', 'Formality', 'Actual sentence\\n']\n for fieldName in dataFileFieldNames:\n if fieldName not in nonFeatureFields:\n fieldsToSelectFrom.append(fieldName)\n\n\n# Prints a list of fields that are available (excludes fields already selected by the user)\ndef printAvailableFields():\n count = 1\n print(\"\\nYou can add the following features to the test: \\n\")\n for fieldName in fieldsToSelectFrom:\n print(count, \"-\", fieldName)\n count = count + 1\n\n\n# Asks the user to choose the features they want to test. Stores field names in 'chosenFields'.\ndef askForNonNgramFeatures():\n if not fieldsToSelectFrom: # If all the available features have already been selected by the user\n print(\"\\nYou have selected all the available features. You will now be asked to choose a classifier.\")\n if not chosenFields: # If no selections yet made by the user.\n printAvailableFields()\n print(\"\\nNo features have been selected yet\")\n featureChoice = input(\"\\nPlease choose the number of a feature to add: \")\n if featureChoice.isnumeric():\n featureChoice = int(featureChoice)\n\n # If a valid selection is made, adds the field name to chosenFields and removes it from fieldsToSelect.\n if 0 <= featureChoice <= len(fieldsToSelectFrom):\n print(\"\\nYou have just selected: \" + fieldsToSelectFrom[featureChoice - 1])\n chosenFields.append(fieldsToSelectFrom[featureChoice - 1])\n fieldsToSelectFrom.remove(fieldsToSelectFrom[featureChoice - 1])\n askForNonNgramFeatures()\n else:\n print(\"You did not enter a valid number. Please try again.\")\n askForNonNgramFeatures()\n else:\n print(\"You did not enter a number. Please try again.\")\n askForNonNgramFeatures()\n\n # If the user has made at least one selection already\n else:\n print(\"\\nSo far, you have selected the following features: \")\n for fields in chosenFields:\n print(fields)\n printAvailableFields()\n featureChoice = input(\"\\nPlease choose an additional feature and press 'enter'\\nor press C then 'enter' to \"\n \"select your classifier: \")\n if featureChoice.isnumeric():\n featureChoice = int(featureChoice)\n\n # If a valid selection is made, adds the field name to chosenFields and removes it from fieldsToSelect.\n if 0 <= featureChoice <= len(fieldsToSelectFrom):\n print(\"\\nYou have just selected: \" + fieldsToSelectFrom[featureChoice - 1])\n chosenFields.append(fieldsToSelectFrom[featureChoice - 1])\n fieldsToSelectFrom.remove(fieldsToSelectFrom[featureChoice - 1])\n askForNonNgramFeatures()\n else:\n print(\"You did not enter a valid number. Please try again.\")\n askForNonNgramFeatures()\n\n # Pressing 'C' exits the function.\n elif featureChoice == \"C\":\n return\n\n # If neither 'C' nor a number entered:\n else:\n print(\"You did not enter a number. Please try again.\")\n askForNonNgramFeatures()\n\n\n# Creates a human-readable description of the selected features.\ndef nonNGramFeatureDescription():\n featureDesc = \"\"\n count = 0\n for feature in chosenFields:\n count = count + 1\n\n # If the first or only feature\n if count == 1:\n featureDesc = '\\'' + feature + '\\''\n continue\n\n # If not final feature in list of multiple features (but not the first)\n if count != len(chosenFields):\n featureDesc = featureDesc + \", \" + '\\'' + feature + '\\''\n\n # If final feature in list of multiple features\n if count == len(chosenFields):\n featureDesc = featureDesc + \" and \" + '\\'' + feature + '\\''\n return featureDesc\n\n\ndef setParameters():\n # Gets n-gram requirements from user and then puts them into a vector\n askForType()\n askForRepresentation()\n askAboutStopWords()\n\n # Creates vector based on n-gram requirements\n corpusVector = setVector(nGramType, representation, stops)\n fittedCorpusVector = corpusVector.fit_transform(corpus)\n corpusVectorAsArray = fittedCorpusVector.toarray()\n\n\n # Gets non n-gram features from user\n createFeatureFieldList() # Puts all feature field names into list 'fieldsToSelectFrom'.\n askForNonNgramFeatures() # Asks the user to choose the features they want to test. Stores in 'chosenFields'.\n\n # Puts the indexes of the fields relating to the selected non-ngram features into a newly created list,\n # featureIndexList (so that the relevant feature data can later be obtained from list nonDocumentData).\n featureIndexList = []\n for fieldName in chosenFields:\n featureIndex = dataFileFieldNames.index(fieldName)\n featureIndexList.append(featureIndex)\n\n # Produces, for each record, a list of the non n-gram feature data for that record, and stores it in 'list of\n # lists' featuresToTestDataList.\n featuresToTestDataList = []\n for records in nonDocumentData:\n dataThisLine = [] # List of the current line's non n-gram feature data.\n for references in featureIndexList:\n records[references] = float(records[references]) # Float used as all feature data is numeric\n dataThisLine.append(records[references])\n # Add sentence's non n-gram feature data to featuresToTestDataList once it's been extracted to dataThisLine.\n featuresToTestDataList.append(dataThisLine)\n\n # Asks the user which classifier they require\n askForClassifier()\n\n # Console output prior to test being run, to confirm the test details\n nonNGramFeatures = nonNGramFeatureDescription()\n featureDescription = nGramType + \" with \" + representation + \" representation and \" + stops + \\\n \" with the following non n-gram features:\\n\" + nonNGramFeatures\n print(\"\\nTEST SUMMARY\\n\" + \"------------\\n\" + featureDescription)\n print(\"Your classifier is: \", classifier)\n print(\"\\nThe test may take a while. Please be patient.\")\n\n # Appends each line's non-ngram feature data to the end of the n-gram vector, and store in featureData[].\n featureData = []\n recordNum = 0\n for documentBagsOfWords in corpusVectorAsArray:\n featureData.append(np.hstack((documentBagsOfWords, featuresToTestDataList[recordNum])))\n recordNum = recordNum + 1\n # Call function to run the test and display the results\n classificationResults(featureData, documentClassificationList, featureDescription)\n\n\n# FUNCTION CALLS THAT EXECUTE WHENEVER THE PROGRAM IS RUN\nloadData()\nsetParameters()\n","sub_path":"ngram-and-non-ngram-tests-combined.py","file_name":"ngram-and-non-ngram-tests-combined.py","file_ext":"py","file_size_in_byte":28672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"608465246","text":"#!/usr/bin/env python\n\n# Setup module for the Topic Sever\n#\n# March 2016\n\nfrom setuptools import setup\n\n# Read the requirements.txt file (used by Travis CI)\n# ans use for setup's install_requires[] list.\nwith open('requirements.txt') as f:\n required = f.read().splitlines()\n\n# -----------------------------------------------------------------------------\n# setup\n# -----------------------------------------------------------------------------\nsetup(\n\n name='TopicServer',\n version='1.0.5',\n platforms=['any'],\n\n url='https://github.com/JudiciaryPag/TopicServer',\n license='http://www.apache.org/licenses/LICENSE-2.0',\n author='Judiciary Pag',\n author_email='JudiciaryPag@users.noreply.github.com',\n description='A topic-based message server',\n long_description='A simple memory-resident topic-based Twisted message'\n ' server where messages, posted against topics,'\n ' remain until read by subscribers.',\n\n test_suite='server.test',\n\n # Installation dependencies.\n # This ia the list of registered PyPI modules that we use.\n install_requires=required,\n\n # Our packages here.\n # Specific modules can be found in the MANIFEST.in file.\n packages=['client', 'server', 'server.test'],\n\n # Project classification...\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Framework :: Twisted',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards',\n 'Topic :: Internet :: WWW/HTTP :: HTTP Servers'\n ]\n\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"543864910","text":"import numpy as np\nimport pandas as pd\nimport cv2\nimport os\n \ndef write_pred_dataframe(valid_data , pred_coord , folder,file_name , file_col_name ,\n patches_coord=None, write_index = False , is_valid = True ):\n \"\"\"\n Goal: write prediction coordinates to DATAFRAME csv and return the panda dataframe\n\n params:\n valid_data: panda dataframe of validation data. used for giving file name and types\n pred_coord: prediction coordiantes shape [batch_size , 2 * landmark]\n folder: folder to save\n file_name: name of the csv file. When is None, function doesn't save the csv\n patches_coord: lists of coodinates for each patch. [batch_size, n patches] (dtype = list)\n \"\"\"\n # Get the name and view from Valid data\n df_file_names = valid_data.df.drop(valid_data.coords_cols , axis=1 , errors = 'ignore')\n df_file_names = df_file_names.reset_index(drop=True)\n result = pd.DataFrame(pred_coord, columns = valid_data.coords_cols )\n if not os.path.exists(folder):\n os.makedirs(folder)\n \n if is_valid:\n gt_coords = valid_data.df[valid_data.coords_cols].values\n pred_coord[gt_coords==-1] = -1\n \n # Write the polygons in if there is given patches_coord\n # Other wise assign all -1.\n\n # if patches_coord is None:\n # patches_coord = np.ones((result.shape[0], len(valid_data.patches_cols))) * -1 \n # p_result = pd.DataFrame(patches_coord, columns = valid_data.patches_cols)\n\n result = pd.concat([df_file_names,result],axis=1)\n\n if file_name is not None:\n result.to_csv(folder+file_name+\".csv\" , index =write_index)\n return result\n\ndef build_result_dict(result_dict= {},name = None,\n pck = None, mean_pck = None, pck_threshold = None,\n diff_per_pt=None, mean_diff_per_pt = None,\n in_poly = None, mean_in_poly = None,\n iou = None, mean_iou = None,\n precision = None, mean_precision = None,\n pck_50 = None, pck_150 = None, pck_200 = None, pck_300 = None ):\n \"\"\"\n Goals: write value into dictionry, the default value is None\n which the dict can be used into grid searching result.\n \"\"\"\n remove_keys = ['restore_param_file', 'config_name']\n for remove_key in remove_keys:\n if remove_key in result_dict.keys():\n result_dict.pop(remove_key)\n\n result_dict['name'] = name\n result_dict['pck{}'.format(pck_threshold)] = pck\n result_dict['mean_pck'] = mean_pck\n result_dict['diff_per_pt'] = diff_per_pt\n result_dict['mean_diff_per_pt'] = mean_diff_per_pt\n result_dict['in_poly'] = in_poly\n result_dict['mean_in_poly'] = mean_in_poly\n result_dict['iou'] = iou\n result_dict['mean_iou'] = mean_iou\n result_dict['precision'] = precision\n result_dict['mean_precision'] = mean_precision\n\n result_dict['pck_50'] = pck_50\n result_dict['pck_150'] = pck_150\n result_dict['pck_200'] = pck_200\n result_dict['pck_300'] = pck_300\n result_dict = {str(k):str(v) for k,v in result_dict.items()}\n return result_dict\n\n### Heatmap functions:\ndef plot_heatmaps(dir, heatmaps, img, file_name, names = None, img_per_row = 5):\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n results = np.array([], dtype=np.int64).reshape(0, img.shape[1] * img_per_row,3)\n row = np.array([], dtype=np.int64).reshape(img.shape[0],0,3)\n\n for i in range(heatmaps.shape[-1]):\n # Fore every pic\n\n heatmap = heatmaps[...,i:i+1]\n # print(np.min(img_temp),np.max(img_temp))\n heatmap = np.interp(heatmap,[np.min(heatmap),np.max(heatmap)],[0,255]).astype(np.uint8)\n heatmap = cv2.applyColorMap(heatmap,cv2.COLORMAP_JET)\n\n heatmap = cv2.resize(heatmap, dsize=(img.shape[1], img.shape[0]),\n interpolation = cv2.INTER_NEAREST)\n\n dst = cv2.addWeighted(img,0.5,heatmap,0.5,0)\n if names is not None:\n cv2.putText(dst, names[i], (50,50),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (200, 200, 200), 2, cv2.LINE_AA)\n\n if (i+1) % img_per_row !=0:\n row = np.hstack((row, dst))\n else:\n row = np.hstack((row, dst))\n results = np.vstack((results, row))\n row = np.array([], dtype=np.int64).reshape(img.shape[0],0,3)\n if heatmaps.shape[-1] % img_per_row !=0: \n offset = (img_per_row-heatmaps.shape[-1] % img_per_row)\n blank = np.zeros((img.shape[0] , img.shape[1] * offset , 3)).astype(np.uint8)\n\n row = np.hstack((row , blank))\n results = np.vstack((results, row))\n \n cv2.imwrite( os.path.join(dir, \"{}.png\".format(file_name)),results)\n\n\n\ndef save_heatmaps(dir, heatmaps, file_name, pt_names):\n dir = os.path.join(dir, file_name)\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n for i in range(heatmaps.shape[-1]):\n # Fore every pic\n heatmap = heatmaps[...,i:i+1]\n heatmap = np.interp(heatmap,[np.min(heatmap),np.max(heatmap)],[0,255]).astype(np.uint8)\n cv2.imwrite( os.path.join(dir, \"{}.jpg\".format(pt_names[i])),heatmap)\n\n\n### Deprecate ####\n\ndef write_point_result(pred_coord , gt_coords,lm_cnt, params, folder):\n \"\"\"\n Goal: write the evaluation (PCK, pixel difference) on json\n\n params:\n pred_coords: predicted coordinates, shape:[batch , lm_cnt * 2]\n gt_coords: ground-truth coordinates. shape:[batch , lm_cnt * 2]\n lm_cnt: landmark count\n params: hyperparams and config dictionary\n folder: dir for saving the json\n \"\"\"\n\n print(\"deprecated\")\n # if not os.path.exists(folder):\n # os.makedirs(folder)\n # pck_threshold = params['pck_threshold']\n # diff_per_pt ,pck= pck_accuracy(pred_coord , gt_coords, lm_cnt=5 , \n # pck_threshold = params['pck_threshold'],scale = 1)\n # diff_per_pt_all ,pck_all= pck_accuracy(pred_coord , gt_coords, lm_cnt=lm_cnt , \n # pck_threshold = params['pck_threshold'],scale = 1)\n # result = {}\n # result['config'] = get_info_from_params_points(params)\n # result['pck-{}'.format(pck_threshold)] =pck.tolist()\n # result['pixel_diff'] = diff_per_pt.tolist()\n # result['mean_pck-{}'.format(pck_threshold)] =np.mean(pck)\n\n # result['pck_all-{}'.format(pck_threshold)] =pck_all.tolist()\n # result['pixel_diff_all'] = diff_per_pt_all.tolist()\n # result['mean_pck_all-{}'.format(pck_threshold)] =np.mean(pck_all)\n\n # result_name = \"{}_{}.json\".format(str(date.today()) ,params[\"name\"])\n # print(\"write into: \", result_name)\n # f = open(folder+result_name,\"w\")\n # f.write(json.dumps(result ,indent=2 , sort_keys=True))\n # f.close()\n\n### Goal: Get the dictionray from params.\n# Used in write_point_result\ndef get_info_from_params_points(params):\n \"\"\"\n Goal: Get useful properties of the config dictionray.\n \"\"\"\n print(\"deprecated\")\n\n # outputs = {}\n # keys = [\"name\", \"category\" ,\"img_aug\", \"nepochs\" , \"learning_rate\",\"batch_size\",\n # \"decay_step\" , \"decay_step\" , \"dropout_rate\" , \"nlow\" ,\"nstacks\"]\n # for key in keys:\n # assert key in params.keys() , \"No this keys, check the config file\"\n # outputs[key] = params[key]\n # return outputs\n\n\n\ndef write_coord(pred_coords , gt_coords , folder,file_name = \"hg_valid_coords\" ):\n \"\"\"\n deprecated\n Goal: write coords only in csv\n \"\"\"\n print(\"deprecated\")\n # pred_file_name = folder + file_name+\"_pred.csv\"\n # gt_file_name = folder +file_name + \"_gt.csv\"\n # print(\"Save VALID prediction in \"+pred_file_name)\n # print(\"save GROUND TRUTH in \" + gt_file_name)\n # np.savetxt(pred_file_name, pred_coords, delimiter=\",\")\n # np.savetxt(gt_file_name, gt_coords, delimiter=\",\")\n\n\n","sub_path":"util/points_io.py","file_name":"points_io.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"639862986","text":"\"\"\"\r\n6、多窗口切换\r\n窗口的苏醒 handle\r\n\r\n\"\"\"\r\n# coding:utf-8\r\nfrom selenium import webdriver\r\nimport time\r\n\r\ndriver = webdriver.Firefox()\r\ndriver.get(\"http://sz.ganji.com/\")\r\ntime.sleep(1)\r\n\r\ndriver.find_element_by_link_text(\"行政后勤\").click()\r\ntime.sleep(1)\r\n\r\nhandle = driver.current_window_handle # 获取单个handle属性\r\nprint(handle)\r\n\r\nhandlee = driver.window_handles # 获取多个handle属性\r\nprint(handlee)\r\n\r\nhandle_new = handlee[1] # 取新窗口的句柄\r\ndriver.switch_to.window(handle_new) # 切换新窗口\r\nprint(driver.title) # 获取页面的标题\r\n\r\n# 回到第一个窗口上\r\ndriver.switch_to.window(handlee[0])\r\nprint(driver.title)\r\n\r\n\r\ndriver.quit()\r\n","sub_path":"day04/02句柄.py","file_name":"02句柄.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"461031376","text":"import numpy as np\nimport matplotlib.pyplot as plt\n# Plot figures in external window:\nfrom IPython import get_ipython\nget_ipython().run_line_magic('matplotlib', 'qt') \n\nData_tpx3 = np.genfromtxt('shot_19970_W0020_J07-200128-170807-1-0.csv', delimiter=',')\nData_tpx3_cent = np.genfromtxt('shot_19970_W0020_J07-200128-170807-1_cent-0.csv', delimiter=',')\n\ntime_tpx3 = np.array([row[2] for row in Data_tpx3])\ntime_new = time_tpx3 * 25/4096/1e6\ndata_tpx3 = np.array([row[3] for row in Data_tpx3])\ntot_total = np.array([row[4] for row in Data_tpx3_cent])\n\ncol = np.array([row[0] for row in Data_tpx3])\nrow = np.array([row[1] for row in Data_tpx3])\n\n# =============================================================================\n# Plot\n# =============================================================================\n\nfig1 = plt.figure(1)\n\n#plt.plot(time_new, data_tpx3)\n#plt.plot(time_new)\nplt.xlabel(\"t, [ms]\")\nplt.ylabel(\",[-]\")\n\nplt.hist(data_tpx3, 300, (0, 7500), histtype='step')\nToT = np.histogram(data_tpx3, 300, (0, 7500))\n\nfig2 = plt.figure(2)\n\nplt.hist(time_new, 128, (14400, 14600), histtype='step')\n\nfig3 = plt.figure(3)\n\nplt.hist(tot_total, 1000, (0, 25000), histtype='step')\n\nfig4 = plt.figure(4)\nplt.plot(time_new, data_tpx3)\n\n","sub_path":"wtf/Scrappy/tpx3.py","file_name":"tpx3.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"602134721","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 21 18:01:19 2019\n\n@author: mushtu\n\"\"\"\n##Find the minimum first and then its index\nls= [809,834,477,478,307,122,96,102,324,476]\n#min(ls) \nlow = min(ls)\nmin_index = ls.index(low)\nprint (min_index) \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n##Find Remove Find\ndef find_two_smallest(L): \n 'Return a tuple of the indices of the two smallest values in list L.'\n smallest = min(L) \n min1 = L.index(smallest) \n L.remove(smallest) \n next_smallest = min(L) \n min2 = L.index(next_smallest)\n##Insert at index min1 \n L.insert(min1, smallest) \n if min1 <= min2: \n min2 += 1\n return (min1, min2)\n\nL=[809,834,477,478,307,122,96,102,324,476]\nfind_two_smallest(L)\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##Sort, Identify Mins, Get Indices\ndef find_two_smallest(L):\n temp_list = L[:] \n temp_list.sort() \n smallest = temp_list[0] \n next_smallest = temp_list[1] \n min1 = L.index(smallest) \n min2 = L.index(next_smallest) \n return (min1, min2)\nfind_two_smallest(L)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#Walk through the List\ndef find_two_smallest(L): \n# set min1 and min2 to the indices of the smallest and next-smallest \n# values at the beginning of L \n if L[0] < L[1]: \n min1, min2 = 0, 1 \n else: \n min2, min1 = 1, 0\n# examine each value in the list in order \n for i in range(2, len(L)):\n if L[i] < L[min1]: \n min2 = min1 \n min1 = i\n# New second smallest? \n elif L[i] < L[min2]: \n min2 = i\n return (min1, min2)\nfind_two_smallest(L)\n\n","sub_path":"CS1010Fall2019-master/Class Excercises/Problem Solving and Design UM.py","file_name":"Problem Solving and Design UM.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"621877911","text":"import sys\nsys.path = [\"../../deps\"] + sys.path\n\nfrom math import pi, sin, cos\n\nfrom pyglet.gl import *\nfrom pyglet.window import key\nimport pyglet\n\nfrom euclid import *\n\ntry:\n # Try and create a window with multisampling (antialiasing)\n config = Config(sample_buffers=1, samples=4,\n depth_size=16, double_buffer=True,)\n window = pyglet.window.Window(resizable=True, config=config)\nexcept pyglet.window.NoSuchConfigException:\n # Fall back to no multisampling for old hardware\n window = pyglet.window.Window(resizable=True)\n\nkeyboard = key.KeyStateHandler()\nwindow.push_handlers(keyboard)\nwindow.set_exclusive_mouse(True)\n\nlabel = pyglet.text.Label('Hello, torus!',\n font_name='Times New Roman',\n font_size=18,\n x=0, y=0, color=(0,0,0,255),\n anchor_x='left', anchor_y='bottom')\n\nmouse_dxdy = [0, 0]\nsensitivity = 20.0\n\ncamera_pos = Vector3(0, 0, 2)\ncamera_rot = Quaternion()\n\nright = Vector3(1, 0, 0)\nup = Vector3(0, 1, 0)\nforward = Vector3(0, 0, 1)\n\ncamera_right = right.copy()\ncamera_up = up.copy()\n\n@window.event\ndef on_resize(width, height):\n # Override the default on_resize handler to create a 3D projection\n glViewport(0, 0, width, height)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluPerspective(60., width / float(height), .1, 1000.)\n glMatrixMode(GL_MODELVIEW)\n return pyglet.event.EVENT_HANDLED\n\n# does the mouse thang\n@window.event\ndef on_mouse_motion(x, y, dx, dy):\n global camera_rot\n \n mouse_dxdy[0] = (dx / sensitivity)\n mouse_dxdy[1] = -(dy / sensitivity)\n \n # view right/left\n if (dx > 0):\n q = Quaternion.new_rotate_axis( mouse_dxdy[0], camera_up)\n camera_rot = q * camera_rot\n if (dx < 0):\n q = Quaternion.new_rotate_axis( mouse_dxdy[0], camera_up)\n camera_rot = q * camera_rot\n \n # view up/down\n if (dy > 0):\n q = Quaternion.new_rotate_axis( mouse_dxdy[1], camera_right)\n camera_rot = q * camera_rot\n if (dy < 0):\n q = Quaternion.new_rotate_axis( mouse_dxdy[1], camera_right)\n camera_rot = q * camera_rot\n\ndef update(dt):\n # fill types\n if keyboard[key._1]:\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) # solid\n if keyboard[key._2]:\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # wireframe\n if keyboard[key._3]:\n glPolygonMode(GL_FRONT_AND_BACK, GL_POINT) # point\n\n global sensitivity\n\n # sensitivity controls\n if keyboard[key._4]:\n sensitivity -= 1.0 if sensitivity > 5.0 else 0.0\n if keyboard[key._5]:\n sensitivity += 1.0 if sensitivity > 5.0 else 0.0\n \n\n global camera_pos\n global camera_rot\n\n global right\n global up\n global forward\n\n global camera_right\n global camera_up\n\n camera_dir = camera_up.cross(camera_right)\n # camera_dir.normalize()\n\n # movement\n if keyboard[key.S]:\n # camera_dir = camera_up.cross(camera_right)\n # camera_dir.normalize()\n y, x, z = camera_rot.get_euler()\n camera_pos.x -= sin(y)\n camera_pos.y += sin(x)\n camera_pos.z += cos(y)\n # camera_pos -= camera_dir\n if keyboard[key.W]:\n # camera_dir = camera_up.cross(camera_right)\n # camera_dir.normalize()\n y, x, z = camera_rot.get_euler()\n camera_pos.x += sin(y)\n camera_pos.y -= sin(x)\n camera_pos.z -= cos(y)\n # camera_pos += camera_dir\n\n # camera\n if keyboard[key.LEFT]:\n q = Quaternion.new_rotate_axis(-.1, camera_up)\n camera_rot = q * camera_rot\n if keyboard[key.RIGHT]:\n q = Quaternion.new_rotate_axis( .1, camera_up)\n camera_rot = q * camera_rot\n if keyboard[key.UP]:\n q = Quaternion.new_rotate_axis(-.1, camera_right)\n camera_rot = q * camera_rot\n if keyboard[key.DOWN]:\n q = Quaternion.new_rotate_axis( .1, camera_right)\n camera_rot = q * camera_rot\n if keyboard[key.A]:\n camera_dir = camera_up.cross(camera_right)\n q = Quaternion.new_rotate_axis( .1, camera_dir)\n camera_rot = q * camera_rot\n if keyboard[key.D]:\n camera_dir = camera_up.cross(camera_right)\n q = Quaternion.new_rotate_axis(-.1, camera_dir)\n camera_rot = q * camera_rot\n\n y, x, z = tuple(map(lambda x: x*180/pi, camera_rot.get_euler()))\n label.text = \"pitch: %d yaw: %d roll: %d\" % (x,y,z) + \" X: %d Y: %d Z: %d \" % (camera_pos.x, camera_pos.y, camera_pos.z)\n\npyglet.clock.set_fps_limit(30)\npyglet.clock.schedule(update)\n\n@window.event\ndef on_draw():\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glLoadIdentity()\n camera()\n for t in torus:\n t.draw()\n to_ortho()\n label.draw()\n from_ortho()\n\ndef camera():\n angle, axis = camera_rot.get_angle_axis()\n glRotatef(angle*180/pi, axis.x, axis.y, axis.z)\n glTranslated(-camera_pos.x, -camera_pos.y, -camera_pos.z) # translate screen to camera position\n\ndef to_ortho():\n glDisable(GL_DEPTH_TEST)\n glMatrixMode(GL_PROJECTION)\n glPushMatrix()\n glLoadIdentity()\n glOrtho(0, window.width, 0 , window.height, -1, 1)\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\ndef from_ortho():\n glEnable(GL_DEPTH_TEST)\n glMatrixMode(GL_PROJECTION)\n glPopMatrix()\n glMatrixMode(GL_MODELVIEW)\n\ndef setup():\n # One-time GL setup\n glClearColor(1, 1, 1, 1) # rgba (white)\n glColor3f(1, 0, 0) # rgb (red)\n glEnable(GL_DEPTH_TEST)\n glEnable(GL_CULL_FACE)\n\n # Simple light setup. On Windows GL_LIGHT0 is enabled by default,\n # but this is not the case on Linux or Mac, so remember to always\n # include it.\n glEnable(GL_LIGHTING)\n glEnable(GL_LIGHT0)\n glEnable(GL_LIGHT1)\n\n # Define a simple function to create ctypes arrays of floats:\n def vec(*args):\n return (GLfloat * len(args))(*args)\n\n glLightfv(GL_LIGHT0, GL_POSITION, vec(.5, .5, 1, 0)) # xyz homogenous\n glLightfv(GL_LIGHT0, GL_SPECULAR, vec(.5, .5, 1, 1)) # rgba (blue)\n glLightfv(GL_LIGHT0, GL_DIFFUSE, vec(1, 1, 1, 1)) # rgba (white)\n\n glLightfv(GL_LIGHT1, GL_POSITION, vec(1, 0, .5, 0))\n glLightfv(GL_LIGHT1, GL_DIFFUSE, vec(.5, .5, .5, 1))\n glLightfv(GL_LIGHT1, GL_SPECULAR, vec(1, 1, 1, 1))\n\n glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.5, 0, 0.3, 1)) # rgba (purple)\n glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, vec(1, 1, 1, 1)) # rgba (white)\n glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50) # [0-128] with 0 being most shiny\n\nclass Torus(object):\n def __init__(self, radius, inner_radius, slices, inner_slices):\n # Create the vertex and normal arrays.\n vertices = []\n normals = []\n\n u_step = 2 * pi / (slices - 1)\n v_step = 2 * pi / (inner_slices - 1)\n u = 0.\n for i in range(slices):\n cos_u = cos(u)\n sin_u = sin(u)\n v = 0.\n for j in range(inner_slices):\n cos_v = cos(v)\n sin_v = sin(v)\n\n d = (radius + inner_radius * cos_v)\n x = d * cos_u\n y = d * sin_u\n z = inner_radius * sin_v\n\n nx = cos_u * cos_v\n ny = sin_u * cos_v\n nz = sin_v\n\n vertices.extend([x, y, z])\n normals.extend([nx, ny, nz])\n v += v_step\n u += u_step\n\n # Create ctypes arrays of the lists\n vertices = (GLfloat * len(vertices))(*vertices)\n normals = (GLfloat * len(normals))(*normals)\n\n # Create a list of triangle indices.\n indices = []\n for i in range(slices - 1):\n for j in range(inner_slices - 1):\n p = i * inner_slices + j\n indices.extend([p, p + inner_slices, p + inner_slices + 1])\n indices.extend([p, p + inner_slices + 1, p + 1])\n indices = (GLuint * len(indices))(*indices)\n\n # Compile a display list\n self.list = glGenLists(1) # create an array of lists (only one here)\n glNewList(self.list, GL_COMPILE) # only compile list, don't execute it yet\n\n glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) # push context\n\n glEnableClientState(GL_VERTEX_ARRAY) # context can display vertexes\n glEnableClientState(GL_NORMAL_ARRAY) # context can display normals\n glVertexPointer(3, GL_FLOAT, 0, vertices) # array of vertices in 3-space, stride is 0 for non-interleaved arrays\n glNormalPointer(GL_FLOAT, 0, normals) # same as above except normals are always in 3-space\n glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, indices)\n\n glPopClientAttrib() # pop context\n\n glEndList() # end list\n\n def draw(self):\n glCallList(self.list)\n\nsetup()\ntorus = [\n Torus(1.1, 0.2, 100, 50),\n Torus(0.7, 0.2, 75, 40),\n Torus(0.3, 0.2, 50, 30)\n]\n\npyglet.app.run()\n","sub_path":"game/graphics/scripts/rotation.py","file_name":"rotation.py","file_ext":"py","file_size_in_byte":8918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"414206847","text":"import pygame\nimport engine as eng\n# from graphics import *\nfrom itertools import cycle\nimport ipdb\nimport random\n\nDATA_STAGES = {\"raw\": 1, \"crunched\": 2, \"paper\": 3}\nASSET_FOLDER = \"assets/\"\nGRAVITY_VELOCITY = 4 # lets cheat for now\nFLOOR_Y = 580\nPLAYER_SPEED = 20\nPLAYER_THROW_SPEED = eng.Vector(20, -5)\nFOLLOWER_SPEED = PLAYER_SPEED - 3 # just slower than the players\nPATROL_SPEED = 4 # just slower than the players\nJUMP_VELOCITY = -20\nDATA_DEVICE_TIMER = .01\nTIMER_WIDTH = 100\nPLAYER_INTERACT_DIST = 50\nEJECT_SPEED = eng.Vector(20, -20)\nPLAYER_MASH_NUMBER = 10 # the number of times the player has to mash a button to escape\nMEETING_EVENT_HORIZON = 50 # the distance where the player will need to escape\nMEETING_GRAVITAIONAL_SPHERE = 100 # the distance where the player begins to be pulled in\nMEETING_PULL = 5\nMEETING_TIMER = .01\nDEBUG = True\nSTUN_VELOCITY_LOSER = eng.Vector(10, -15)\nSTUN_VELOCITY_WINNER = eng.Vector(5, -10)\nSTUN_WINNER_TIMER = 10\nSTUN_LOSER_TIMER = 20\nLEFT_FRAME_ID = 'l_'\n\n\ndef draw_message(x, bottom, message, window):\n \"\"\"draw text somewhere on the screen\"\"\"\n eng.FONT.set_bold(True)\n font_to_render = eng.FONT.render(str(message), True, (0, 0, 0))\n font_rect = font_to_render.get_rect()\n font_rect.x = x\n font_rect.bottom = bottom\n window.blit(font_to_render, font_rect)\n return font_rect\n\n\ndef draw_timer(game_obj, surface, ascending=True):\n outline_rect = pygame.Rect(0, 0, TIMER_WIDTH, 20)\n outline_rect.centerx = game_obj.rect.centerx\n outline_rect.centery = game_obj.rect.y - outline_rect.height\n timer_rect = pygame.Rect(outline_rect)\n if ascending:\n timer_rect.width = TIMER_WIDTH * game_obj.timer\n else:\n timer_rect.width = 101 - TIMER_WIDTH * game_obj.timer # off by one error fix later\n \n \n\n print(timer_rect.width)\n\n pygame.draw.rect(surface, (255, 0, 255), timer_rect)\n pygame.draw.rect(surface, (128, 0, 128), outline_rect, 1)\n if timer_rect.width == TIMER_WIDTH - 1 or not ascending:\n # TODO: optimize the clearing of the timer if need be\n return outline_rect\n\n\n# TODO: add more things to do\nclass GameObject(object):\n \"\"\"the top level game object. All game objects inherit from this class.\"\"\"\n id = 0\n\n def __init__(self, startx, starty, width, height, obj_id=None):\n self.rect = pygame.Rect((startx, starty, width, height))\n if not obj_id:\n self.id = GameObject.id # assign\n GameObject.id += 1\n else:\n self.id = obj_id\n self.render = True\n self.message_str = None # info that is displayed above the object\n self.to_del = False\n self.physics = False # Does this class need physics? i.e. movement\n self.collision = True # Does this class need collisions\n self.dirt_sprite = True # only draw sprite if dirty\n\n def update(self):\n \"\"\"anything that the object needs to do every frame\"\"\"\n return\n\n def animate(self):\n return\n\n\nclass NetworkedObject(object):\n def __init__(self, attribute_list):\n self.attribute_list = attribute_list\n\n def build_packet(self, accumulator):\n packet = {}\n for attribute in self.attribute_list:\n packet[attribute] = self.__getattribute__(attribute)\n accumulator.append(packet)\n\n def read_packet(self, packet):\n for attribute in self.attribute_list:\n self.__setattr__(attribute, packet[attribute])\n\n\nclass AnimateSpriteObject(object):\n \"\"\"a stand alone object that allows the inherited game object to have animation \n sprites\"\"\"\n\n def __init__(self, animation_dict, des_width, des_height):\n \"\"\"Initilize all the frames of the animated sprite object\n :param animation_dict: a dictionary that is keyed on the name of the animation. The dictionary \n contains a tuple pair, with the name of the file at [0] and the number of frames of the sprite sheet\n at [1][0] for the x and [1][1] for the y. So \n animation_dict[animation_name] -> (sprite_sheet_filename, (sprite_sheet_x, sprite_sheet_y) \n :type animation_dict: dict\n :param des_width: the desired width of each frame \n :type des_width: int\n :param des_height: the desired height of each frame\n :type des_height: int\n \"\"\"\n object.__init__(self)\n frame_dict = {}\n self.animation_frames = {}\n self.sprite_sheets = {}\n for animation_name, (filename, (width, height)) in animation_dict.items():\n self.sprite_sheets[animation_name], self.animation_frames[animation_name] = self._get_frames(\n ASSET_FOLDER + filename, int(width),\n int(height), des_width=des_width,\n des_height=des_height)\n\n # get the left facing sprite\n left_animation = LEFT_FRAME_ID + animation_name\n self.sprite_sheets[left_animation] = pygame.transform.flip(self.sprite_sheets[animation_name], 1, 0)\n self.animation_frames[left_animation] = self.animation_frames[animation_name][::-1]\n\n self.current_animation = 'idle'\n self.current_cycle = cycle(self.animation_frames[self.current_animation])\n self.current_frame = next(self.current_cycle)\n self.animation_time = 3\n self.animation_timer = 0\n self.hold_end_frame = False # set to true for animations where the end should be held (like falling)\n\n def change_animation(self, frame):\n \"\"\"change the frames that player object is currently cycling through.\n :param frame: a key that maps to a list of animation frames in self.animation_frames\n :type frame: str\"\"\"\n if not frame in self.animation_frames:\n frame = 'idle'\n\n self.current_animation = frame # TODO: evaluate if we need this member\n self.current_cycle = cycle(self.animation_frames[self.current_animation])\n\n def reverse_animation(self, direction):\n \"\"\"take the current animation and point it in the other direction specified\n returns new animation name the object needs to change to or None\"\"\"\n is_left = True if LEFT_FRAME_ID in self.current_animation else False\n new_animation = None\n if direction == -1 and not is_left:\n # moving right, but trying to flip to the left\n new_animation = LEFT_FRAME_ID + self.current_animation\n elif direction == 1 and is_left:\n # moving left, but trying to flip right\n new_animation = self.current_animation[len(LEFT_FRAME_ID):]\n return new_animation\n\n\n def animate(self):\n \"\"\"Updates the animation timer goes to next frame in current animation cycle\n after the alloted animation time has passed.\"\"\"\n self.animation_timer += 1\n if self.animation_timer == self.animation_time:\n self.current_frame = next(self.current_cycle)\n self.animation_timer = 0\n\n def draw(self, surface):\n \"\"\"Draws the player object onto surface\n :param surface: the surface to draw the object, typically the window\n :type surface: pygame.Surface\"\"\"\n surface.blit(self.sprite_sheets[self.current_animation], self.rect, area=self.current_frame)\n\n def _get_frames(self, filename, columns, rows, des_width=30, des_height=30):\n \"\"\"returns a new sprite sheet and a list of rectangular coordinates in the\n file that correspond to frames in the file name. It also manipulates the spritesheet \n so each frame will have the des_width and des_height\n :param filename: sprite sheet file\n :type filename: str\n :param columns: the number of columns in the sprite sheet\n :type columns: int\n :param rows: the number of rows in the sprite sheet\n :type rows: int\n :param des_width: the desired width of a single frame\n :type des_width: int\n :param des_height: the desired height of a single frame\n :type des_height: int\"\"\"\n sheet = pygame.image.load(filename)\n sheet_rect = sheet.get_rect()\n sheet_width = columns * des_width\n sheet_height = rows * des_height\n\n sheet = pygame.transform.smoothscale(sheet, (sheet_width, sheet_height))\n sheet_rect = sheet.get_rect()\n frames = []\n for x in range(0, sheet_rect.width, des_width):\n for y in range(0, sheet_rect.height, des_height):\n frames.append(pygame.Rect(x, y, des_width, des_height))\n return sheet, frames\n\n\nclass Constructor(object):\n \"\"\"A special object that contains a reference to the entire game. Inherited\n by classes that need to construct objects in the game world\"\"\"\n\n def __init__(self, game):\n object.__init__(self)\n self.game = game\n\n def add_to_world(self, obj):\n if self.game:\n self.game.added.append(obj)\n else:\n ipdb.set_trace()\n\n\nclass MovableGameObject(GameObject):\n \"\"\"any game object that moves\"\"\"\n\n def __init__(self, startx, starty, width, height, obj_id=None):\n super(MovableGameObject, self).__init__(startx, starty, width, height, obj_id=obj_id)\n self.velocity = eng.Vector(0, 0)\n self.physics = True # most movable game objects need physics\n self.last_rect = self.rect.copy()\n\n def move(self, velocity):\n self.velocity = velocity\n\n def stop(self):\n self.velocity = [0, 0]\n\n def hide_object(self):\n \"\"\"moves turns of physics and rendering for the object\"\"\"\n self.render = False\n self.physics = False\n self.rect.x, self.rect.y = -1000, -1000 # move somewhere far off screen to\n\n def unhide_object(self):\n \"\"\"moves turns of physics and rendering for the object\"\"\"\n self.render = True\n self.physics = True\n\n def respond_to_collision(self, obj, axis=None):\n \"\"\"Contains the callback for the collision between a move able object and the\n object passed in. If the object passed in is the environment (i.e. SimpleScenery)\n it will treate the environment as a wall and stop the object.\n :param obj: object player is colliding with\n :type obj: GameObject\n :param axis: which axis was the player moving along.\n :type axis: String \"\"\"\n if isinstance(obj, BackGroundScenery):\n if axis == 'y':\n self._handle_background_collision(obj)\n return\n if axis == 'x':\n if self.velocity.x > 0:\n self.rect.right = obj.rect.left\n if self.velocity.x < 0:\n self.rect.left = obj.rect.right\n self.velocity.x = 0\n if axis == 'y':\n if self.velocity.y > 0:\n self.rect.bottom = obj.rect.top\n if self.velocity.y < 0:\n self.rect.top = obj.rect.bottom\n self.velocity.y = 0\n\n def _handle_background_collision(self, obj):\n \"\"\"collisions with things that are in the background i.e. things you can\n jump on but walk through\"\"\"\n if self.velocity.y > 0 and self.last_rect.bottom <= obj.rect.top:\n # only collide going down (rember +y = down)\n self.rect.bottom = obj.rect.top\n self.velocity.y = 0 # stop the object\n\n def update(self):\n self.last_rect = self.rect.copy()\n\n\nclass BackGroundScenery(GameObject):\n \"\"\"objects that you can jump on top of but can run through. Think of them as\n in the background that the play jumps up on. For example a platform in mario. \n Doesn't update during gameplay so no need to inherit network object\"\"\"\n\n def __init(self, startx, starty, width, height, obj_id=None):\n super(BackGroundScenery, self).__init__(startx, starty, width, height, obj_id=obj_id)\n\n def draw(self, surface):\n pygame.draw.rect(surface, (128, 0, 128), self.rect, 3)\n\n\nclass SimpleScenery(GameObject):\n \"\"\"Simple SimpleScenery object. Game objects that are just simple shapes\"\"\"\n\n def __init__(self, startx, starty, width, height, color=None, obj_id=None):\n super(SimpleScenery, self).__init__(startx, starty, width, height, obj_id=obj_id)\n self.color = color\n\n def draw(self, surface):\n \"\"\"Draw the simple scenery object\"\"\"\n if self.message_str:\n # message_rect = pygame.Rect(0,0,0,0)\n x = self.rect.centerx\n bottom = self.rect.top - 10\n # message_rect.bottom = self.rect.top - 10\n return draw_message(x, bottom, self.message_str, surface)\n\n\nclass Player(AnimateSpriteObject, MovableGameObject, NetworkedObject):\n def __init__(self, startx, starty, width, height, sprite_sheet=None, color=None, obj_id=None):\n MovableGameObject.__init__(self, startx, starty, width, height, obj_id=obj_id)\n AnimateSpriteObject.__init__(self, sprite_sheet, width, height)\n NetworkedObject.__init__(self, ['rect', 'current_frame', 'current_animation', 'id',\n 'render'])\n self.color = color\n self.rect = pygame.Rect((startx, starty, width, height))\n self.sprite_sheet = sprite_sheet\n self.data = None\n self.direction = 1\n self.moving = False\n self.mash_left = 0\n self.mash_right = 0\n self.interact_dist = PLAYER_INTERACT_DIST # The max distance needed for the player to interact with something\n self.trapped = False\n self.trapper = None # Object trapping the player\n self.mash_left = False\n self.mash_right = False\n self.escape_hit = 0\n self.score = 0\n self.message_str = \"hello\"\n self.movement_event = False # set to true if another object is mucking with the players velocity\n self.escape_mash_number = PLAYER_MASH_NUMBER\n self.stunned_timer = 0\n self.stunned_velocity = eng.Vector(0, 0)\n self.invincible_timer = 0\n self.invincible = False\n self.jumping = False\n self.on_ladder = False\n self.near_ladder = False\n\n\n def jump(self):\n if not self.trapped and not self.stunned_timer and not self.jumping:\n self.velocity.y = JUMP_VELOCITY\n\n def update(self):\n \"\"\"set velocity to be moved by the physics engine\"\"\"\n MovableGameObject.update(self)\n if self.stunned_timer:\n self.stunned_timer -= 1\n # self.velocity.x = self.stunned_velocity.x\n elif not self.movement_event and self.moving and not self.trapped:\n self.velocity.x = self.direction * PLAYER_SPEED\n if self.invincible_timer:\n self.invincible_timer -= 1\n else:\n self.invincible = False\n\n def escape(self, direction):\n \"\"\"mash a button to escape students\"\"\"\n if self.trapped:\n print(\"trying to escape\")\n if direction == 1:\n self.mash_left = True\n elif direction == 2:\n self.mash_right = True\n if self.mash_left and self.mash_right:\n self.mash_left = False\n self.mash_right = False\n self.escape_hit += 1\n if self.escape_hit > self.escape_mash_number:\n self.trapper.un_trap(self)\n self.trapper = None\n self.trapped = False\n self.mash_left = False\n self.mash_right = False\n self.escape_hit = 0\n self.invincible_timer = 60\n self.invincible = True\n\n def write_paper(self):\n return\n\n def move_right(self):\n \"\"\"DEPRICATED: use move(1): sets velocity of player to move right\"\"\"\n self.move(1)\n\n def move_left(self):\n \"\"\"DEPRICATED use move(-1): sets velocity of player to move left\"\"\"\n self.move(-1)\n\n def move(self, direction):\n \"\"\"sets move to the direction passed in\"\"\"\n if self.on_ladder:\n self.do_ladder_things()\n return # Don't move to the side while on ladder\n self.direction = direction\n self.moving = True\n self.change_animation('moving')\n new_animation = self.reverse_animation(direction) # change animation frame if need be\n if new_animation:\n self.change_animation(new_animation)\n\n def stop_right(self):\n \"\"\"sets velocity to 0\"\"\"\n if self.direction == 1:\n self.velocity.x = 0\n self.moving = False\n\n # TODO: why have two methods for stop\n def stop_left(self):\n \"\"\"sets velocity to 0\"\"\"\n if self.direction == -1:\n self.velocity.x = 0\n self.moving = False\n\n def read_packet(self, packet):\n if packet['current_animation'] != self.current_frame:\n self.change_animation(packet['current_animation'])\n super(Player, self).read_packet(packet)\n\n def interact(self, game_objs):\n \"\"\"a catch all function that called when hitting the interact button. It will\n look through the game_objs and if it's with a minimum threshold(self.interact_dist), call specific functions\n based on what the objects are.\n :param game_objs: A list of game objects that the player can potentially interact\n with\n :type game_objs: list of GameObject\"\"\"\n for game_obj in game_objs:\n if isinstance(game_obj, DataDevice):\n if eng.distance(self.rect, game_obj.rect) < self.interact_dist:\n game_obj.interact(self)\n\n def do_ladder_things(game_obj):\n if self.rect.colliderect(game_obj.rect):\n if self.on_ladder:\n self.on_ladder = False\n else:\n self.on_ladder = True\n\n\n\n def draw(self, surface):\n \"\"\"Draws the player object onto surface\n :param surface: the surface to draw the object, typically the window\n :type surface: pygame.Surface\"\"\"\n AnimateSpriteObject.draw(self, surface)\n pygame.draw.rect(surface, (128, 0, 128), self.rect, 1)\n\n def respond_to_collision(self, obj, axis=None):\n \"\"\"Contains the callback for the collision between a player object and a game object passed in. Axis is needed\n for collisions that halt movement\n :param obj: object player is colliding with\n :type obj: GameObject\n :param axis: which axis was the player moving along.\n :type axis: String \"\"\"\n if type(obj) == Data:\n if self.data is None:\n self.data = obj\n self.data.hide_object()\n self.change_animation('hasdata')\n else:\n super(Player, self).respond_to_collision(obj, axis)\n if isinstance(obj, Player) and not self.stunned_timer:\n self.joust_attack(obj)\n if (isinstance(obj, Meeting) or isinstance(obj, Follower)) and not self.trapped:\n # got sucked trapped by something\n obj.trap(self)\n\n def joust_attack(self, other_player):\n \"\"\"The player collided with another, determine who 'won' and properly stun the player\"\"\"\n if self.rect.centery < other_player.rect.centery:\n dominate_player = self\n losing_player = other_player\n elif self.rect.centery > other_player.rect.centery:\n dominate_player = other_player\n losing_player = self\n else:\n return # are currently on the same plane\n # figure out which way the dominate player bumped into the loser were going\n if dominate_player.rect.centerx > losing_player.rect.centerx:\n # hit right side of loser, push to the left\n losing_player.velocity.x = -STUN_VELOCITY_LOSER.x\n dominate_player.velocity.x = STUN_VELOCITY_WINNER.x\n elif dominate_player.rect.centerx < losing_player.rect.centerx:\n losing_player.velocity.x = STUN_VELOCITY_LOSER.x\n dominate_player.velocity.x = -STUN_VELOCITY_WINNER.x\n else:\n # on top of the other player, pick one at random\n modifier = random.randint(0, 1) * 2 - 1\n losing_player.velocity.x = STUN_VELOCITY_LOSER.x * modifier\n dominate_player.velocity.x = STUN_VELOCITY_WINNER.x * -modifier\n\n losing_player.stunned_timer = STUN_LOSER_TIMER\n dominate_player.stunned_timer = STUN_WINNER_TIMER\n dominate_player.velocity.y = STUN_VELOCITY_WINNER.y\n losing_player.velocity.y = STUN_VELOCITY_LOSER.y\n if losing_player.data:\n losing_player.drop_data()\n\n\n def drop_data(self):\n self.throw_data()\n\n def stun_event(self):\n \"\"\" if something is happening the the player, \"\"\"\n\n\n def throw_data(self):\n \"\"\"Through the data that the player is holding\"\"\"\n if self.data:\n if self.moving:\n exit_buff = PLAYER_SPEED # if the player is moving, have to throw the data ahead a frame\n else:\n exit_buff = 0\n if self.direction == -1:\n self.data.rect.right = self.rect.left + (exit_buff * self.direction)\n else:\n self.data.rect.left = self.rect.right + (exit_buff * self.direction)\n\n self.data.velocity.x = self.velocity.x + PLAYER_THROW_SPEED.x * self.direction\n self.data.rect.y = self.rect.y\n self.data.velocity.y = PLAYER_THROW_SPEED.y\n self.data.unhide_object()\n self.data = None\n self.change_animation('moving')\n\n\nclass DataDevice(BackGroundScenery, Constructor, NetworkedObject):\n \"\"\"Devices that are scenery, but output data when interacted with\"\"\"\n\n def __init__(self, startx, starty, width, height, color=None, obj_id=None, game=None):\n BackGroundScenery.__init__(self, startx, starty, width, height, obj_id=obj_id)\n Constructor.__init__(self, game)\n NetworkedObject.__init__(self, ['rect', 'id', 'timer', 'message_str'])\n self.timer = None\n self.color = color\n self.data = None\n self.collision = False # for now, only interaction comes with explicit buttons\n\n def generate_data(self):\n game_obj = Data(20, 20, 40, 40)\n print(game_obj)\n game_obj.rect.centerx = self.rect.centerx\n game_obj.rect.bottom = self.rect.top\n game_obj.velocity.y = random.randint(EJECT_SPEED.y, EJECT_SPEED.y / 2)\n game_obj.velocity.x = random.randint(-EJECT_SPEED.x, EJECT_SPEED.x)\n self.add_to_world(game_obj)\n return game_obj\n\n def interact(self, player, timer=DATA_DEVICE_TIMER):\n if not self.timer: # only allow one timer at a time\n self.timer = timer\n\n\n def draw(self, surface):\n BackGroundScenery.draw(self, surface) # SimpleScenery.draw\n if self.timer:\n outline_rect = pygame.Rect(0, 0, TIMER_WIDTH, 20)\n outline_rect.centerx = self.rect.centerx\n outline_rect.centery = self.rect.y - outline_rect.height\n timer_rect = pygame.Rect(outline_rect)\n timer_rect.width = TIMER_WIDTH * self.timer\n pygame.draw.rect(surface, (255, 0, 255), timer_rect)\n pygame.draw.rect(surface, (128, 0, 128), outline_rect, 1)\n if timer_rect.width == TIMER_WIDTH - 1:\n # TODO: clear timer. Do this by returning the area that needs to be cleared\n return outline_rect\n\n def update(self):\n if self.timer:\n self.timer += DATA_DEVICE_TIMER\n if self.timer >= 1:\n self.generate_data()\n self.timer = None\n\n def respond_to_collision(self, obj, axis=None):\n return\n\n def get_data(self, data):\n self.timer = DATA_DEVICE_TIMER # start timer\n self.data = data\n # TODO: Make a better hide/delete function\n data.rect.x, data.rect.y = (-100, -100)\n data.velocity.x = 0\n data.velocity.y = 0\n\n\nclass DataCruncher(DataDevice):\n \"\"\"Second stage of collecting data\"\"\"\n\n def __init__(self, startx, starty, width, height, accept_stage=1, amount_data_needed=1,\n concurrent_data=1, obj_id=None,\n game=None):\n super(DataCruncher, self).__init__(startx, starty, width, height, obj_id=obj_id, game=None)\n # Constructor.__init__(self, game)\n self.accept_stage = accept_stage\n self.amount_data_needed = amount_data_needed\n self.data_collected = 0\n\n def handle_data(self, game_obj):\n if game_obj.stage == self.accept_stage:\n self.data_collected += 1\n if self.data_collected == self.amount_data_needed:\n self.timer = DATA_DEVICE_TIMER # start timer\n self.message_str = None\n self.data_collected = 0\n else:\n # if there can be more data \n self.message_str = str(self.data_collected) + \"/\" + str(self.amount_data_needed)\n # TODO: THis is wrong, need a destructor \n self.data = game_obj\n self.data.advance_data()\n self.data.hide_object()\n\n def update(self):\n if self.timer:\n self.timer += DATA_DEVICE_TIMER\n if self.timer >= 1:\n self.generate_data()\n self.timer = None\n\n def generate_data(self):\n self.data.rect.centerx = self.rect.centerx\n self.data.rect.bottom = self.rect.top\n self.data.velocity.y = random.randint(EJECT_SPEED.y, EJECT_SPEED.y / 2)\n self.data.velocity.x = random.randint(-EJECT_SPEED.x, EJECT_SPEED.x)\n self.data.unhide_object()\n\n\nclass Desk(DataDevice):\n \"\"\"Where the player will sit and write the paper after collecting data\"\"\"\n\n def __init__(self, startx, starty, width, height, accept_stage=1, obj_id=None,\n game=None):\n super(Desk, self).__init__(startx, starty, width, height, obj_id=obj_id, game=None)\n self.player = None\n\n def update(self):\n if self.player:\n self.player.escape_hit = 0 # Don't allow player to escape\n # player siting at desk, update timer\n if self.timer:\n self.timer += DATA_DEVICE_TIMER\n if self.timer >= 1:\n self.generate_data()\n self.timer = None\n self.player.trapped = False\n self.player = None\n\n def generate_data(self):\n self.data.rect.centerx = self.rect.centerx\n self.data.rect.bottom = self.rect.top\n self.data.velocity.y = random.randint(EJECT_SPEED.y, EJECT_SPEED.y / 2)\n self.data.velocity.x = random.randint(-EJECT_SPEED.x, EJECT_SPEED.x)\n self.data.advance_data()\n self.data.unhide_object()\n\n def interact(self, player, timer=DATA_DEVICE_TIMER):\n if not self.player and player.data:\n # player hasn't interacted yet and has data\n self.player = player\n self.player.trapped = True\n self.player.escape_hit = 0\n self.timer = timer\n self.data = self.player.data\n self.player.data = None\n\n\nclass PublishingHouse(DataCruncher):\n \"\"\"Where the player brings the final paper\"\"\"\n\n def __init__(self, startx, starty, width, height, accept_stage=1, amount_data_needed=1,\n concurrent_data=1, obj_id=None, game=None):\n super(PublishingHouse, self).__init__(startx, starty, width, height, accept_stage=accept_stage,\n amount_data_needed=amount_data_needed, concurrent_data=concurrent_data,\n obj_id=obj_id, game=game)\n\n def generate_data(self):\n # TODO: make a scoring mechanic\n print(\"score\")\n\n\nclass Data(AnimateSpriteObject, MovableGameObject, NetworkedObject):\n def __init__(self, startx, starty, width, height, color=None, sprite_sheet={\"idle\": [\"light_blue.png\", [\"1\", \"1\"]]},\n obj_id=None):\n MovableGameObject.__init__(self, startx, starty, width, height, obj_id=obj_id)\n AnimateSpriteObject.__init__(self, sprite_sheet, width, height)\n NetworkedObject.__init__(self, ['rect', 'current_frame', 'id', 'render', 'stage'])\n self.color = color\n self.sprite_sheet = sprite_sheet\n # TODO: Since we are just giving primitives but want to treat them as a sprite, we have to get creative\n self.sprite_sheet = sprite_sheet\n self.stage = 1\n self.frame = 'idle'\n\n def draw(self, surface):\n super(Data, self).draw(surface) # animatedSpriteObject.draw\n if DEBUG:\n x = self.rect.centerx\n bottom = self.rect.top - 10\n return draw_message(x, bottom, self.stage, surface)\n\n def respond_to_collision(self, obj, axis=None):\n if isinstance(obj, Player):\n obj.respond_to_collision(self)\n elif isinstance(obj, DataCruncher) and self.stage == obj.accept_stage:\n obj.handle_data(self)\n else:\n # TODO: this makes the data go through players\n super(Data, self).respond_to_collision(obj, axis)\n\n def advance_data(self):\n # TODO: hacked for now with no sprite sheet\n self.stage += 1\n\n\nclass Follower(AnimateSpriteObject, MovableGameObject, NetworkedObject):\n \"\"\"a class that follows it's leader\"\"\"\n\n def __init__(self, startx, starty, width, height, color=None, sprite_sheet=None, obj_id=None, site_range=200):\n MovableGameObject.__init__(self, startx, starty, width, height, obj_id=obj_id)\n AnimateSpriteObject.__init__(self, sprite_sheet, width, height)\n NetworkedObject.__init__(self, ['rect', 'current_frame', 'id', 'render'])\n self.color = color\n self.leader = None\n self.velocity = eng.Vector(0, 0)\n self.site = site_range\n # TODO: Since we are just giving primitives but want to treat them as a sprite, we have to get creative\n self.sprite_sheet = sprite_sheet\n\n def trap(self, game_obj):\n if not game_obj.invincible:\n game_obj.trapped = True\n game_obj.trapper = self\n\n def update(self):\n MovableGameObject.update(self)\n if self.leader and eng.distance(self.rect, self.leader.rect) < self.site:\n # figure out which direction to move\n if self.leader.rect.centerx - self.rect.centerx > 0:\n self.velocity.x = FOLLOWER_SPEED # move right\n elif self.leader.rect.centerx - self.rect.centerx < 0:\n self.velocity.x = -FOLLOWER_SPEED # move left\n else:\n self.velocity.x = 0\n elif self.leader:\n self.leader = None\n self.velocity.x = 0\n\n def check_for_leader(self, leader_list):\n self.leader = None\n closest_leader = leader_list[0]\n closest_distance = eng.distance(self.rect, closest_leader.rect)\n for potential_leader in leader_list[1:]:\n distance = eng.distance(self.rect, potential_leader.rect)\n if distance < closest_distance and (not potential_leader.trapped or potential_leader.trapper == self):\n closest_leader = potential_leader\n closest_distance = distance\n if closest_distance < self.site and (not closest_leader.trapped or potential_leader.trapper == self):\n self.leader = closest_leader\n\n def respond_to_collision(self, obj, axis=None):\n if isinstance(obj, Player):\n obj.respond_to_collision(self, axis)\n super(Follower, self).respond_to_collision(obj, axis)\n\n def un_trap(self, game_obj):\n \"\"\"Called after a player has escaped the patrollers grasp\"\"\"\n if self.rect.x < game_obj.rect.x:\n # on the left, push back to the left\n self.velocity.x = -10\n self.velocity.y = -20\n else:\n self.velocity.x = 10\n self.velocity.y = -20\n\n\nclass Patroller(Follower):\n \"\"\"class that patrols it's give x area\"\"\"\n\n def __init__(self, startx, starty, width, height, sprite_sheet=None, obj_id=None, patrol_range=100, site_range=200):\n super(Patroller, self).__init__(startx, starty, width, height, obj_id=obj_id, sprite_sheet=sprite_sheet, site_range=site_range)\n self.patrol_range = patrol_range\n self.reset_patrol()\n self.direction = 1 # scaler to multiple speed by to get direction\n # TODO: Since we are just giving primitives but want to treat them as a sprite, we have to get creative\n self.sprite_sheet = sprite_sheet\n\n def update(self):\n if self.leader:\n super(Patroller, self).update()\n if not self.leader:\n # leader moved out of range, set new start and end patrol to start from the middle\n self.reset_patrol()\n self.do_patrol()\n else:\n self.do_patrol()\n\n def do_patrol(self):\n if self.velocity.x > 0 and self.rect.centerx > self.end_patrol:\n self.direction = -1\n if self.velocity.x < 0 and self.rect.centerx < self.start_patrol:\n self.direction = 1\n self.velocity.x = PATROL_SPEED * self.direction\n\n def reset_patrol(self):\n \"\"\"sets the partrol to be equidistance from the current center\"\"\"\n self.start_patrol = self.rect.centerx - self.patrol_range / 2\n self.end_patrol = self.rect.centerx + self.patrol_range / 2\n self.velocity.x = PATROL_SPEED\n\n\n\nclass Meeting(SimpleScenery, NetworkedObject):\n \"\"\"A meeting trap that will pull the players into at a certain range\"\"\"\n\n def __init__(self, startx, starty, width, height, obj_id=None):\n SimpleScenery.__init__(self, startx, starty, width, height, obj_id=obj_id)\n NetworkedObject.__init__(self, ['rect', 'id', 'timer', 'message_str'])\n self.pulling_player = None\n self.timer = None\n\n def check_player(self, players):\n \"\"\"check if the player is close enough to be pulled in\"\"\"\n if self.timer:\n # cooling down\n return\n\n for player in players:\n distance = eng.distance(self.rect, player.rect)\n\n if eng.distance(self.rect, player.rect) < MEETING_GRAVITAIONAL_SPHERE:\n player.movement_event = True # inform the player that the meeting is in control now!!\n # ipdb.set_trace()\n self.pull_event(player)\n else:\n player.movement_event = False\n\n def pull_event(self, player, **kwargs):\n \"\"\"a function to give the player\"\"\"\n # distance = kwargs['distance']\n distance = eng.distance(self.rect, player.rect)\n if self.rect.x >= player.rect.x:\n # on the right side of it, pull to the right\n if not player.moving or distance < MEETING_EVENT_HORIZON:\n pull_velocity = MEETING_PULL\n else:\n pull_velocity = player.direction * PLAYER_SPEED + MEETING_PULL\n elif self.rect.x < player.rect.x:\n # on the left side of it, pull to the left\n if not player.moving or distance < MEETING_EVENT_HORIZON:\n pull_velocity = -MEETING_PULL\n else:\n pull_velocity = player.direction * PLAYER_SPEED - MEETING_PULL\n player.velocity.x = pull_velocity\n\n def un_trap(self, game_obj):\n \"\"\"Release the mortal from the bonds of responsibility\"\"\"\n self.timer = MEETING_TIMER\n game_obj.movement_event = False\n\n\n def draw(self, surface):\n super(Meeting, self).draw(surface)\n if self.timer:\n return draw_timer(self, surface, False) # draw a descending timer\n\n def trap(self, game_obj):\n if not self.timer:\n game_obj.trapped = True\n game_obj.trapper = self\n\n\n def update(self):\n super(Meeting, self).update()\n if self.timer:\n self.timer += MEETING_TIMER\n if self.timer >= 1:\n self.timer = None\n\n\ndef Portal(GameObject):\n \"\"\"a special object that contains a pointer to another portal object, creating a \n link in gamespace bewteen the two\"\"\"\n\ndef Laddder(GameObject):\n \"\"\"Simple ladder object\"\"\"\n def __init__(self, startx, starty, width, height, obj_id=None):\n super(Laddder, self)\n\n def pull_event(self, player, **kwargs):\n \"\"\"a function to give the player\"\"\"\n # distance = kwargs['distance']\n distance = eng.distance(self.rect, player.rect)\n if self.rect.x >= player.rect.x:\n # on the right side of it, pull to the right\n if not player.moving or distance < MEETING_EVENT_HORIZON:\n pull_velocity = MEETING_PULL\n else:\n pull_velocity = player.direction * PLAYER_SPEED + MEETING_PULL\n elif self.rect.x < player.rect.x:\n # on the left side of it, pull to the left\n if not player.moving or distance < MEETING_EVENT_HORIZON:\n pull_velocity = -MEETING_PULL\n else:\n pull_velocity = player.direction * PLAYER_SPEED - MEETING_PULL\n player.velocity.x = pull_velocity","sub_path":"world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":33878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"197735626","text":"\nfrom app import app\nfrom config import client\nfrom bson.json_util import dumps\nimport random\nimport string\nfrom flask import Flask, jsonify, request, make_response\n\n\ndb = client.Bank\ncol = db.Account\n\n@app.route(\"/api/createuser\",methods=['POST'])\ndef createUser():\n try:\n record = request.get_json()\n id = record.get(\"_id\")\n filter = {\"_id\": id}\n accno = ''.join(random.choices(string.digits, k=8))\n col.insert_one(record)\n col.update_one(filter, {\"$set\":{\"AccountNo \":accno}})\n res = make_response(jsonify({\"Message\": \"Record inserted\", \"Account Number\": accno}), 200)\n return res\n except:\n res = {\n \"Message\":\"Error occurred !\"\n }\n return make_response(jsonify(res),503)\n\n@app.route(\"/api/users\", methods=['GET'])\ndef getUsers():\n try:\n users = col.find()\n res = dumps(users)\n return res\n except:\n res = {\n \"Message\": \"Error occurred !\"\n }\n return make_response(jsonify(res), 503)\n\n@app.route(\"/api/users/\", methods=['GET'])\ndef getSingleUser(accno):\n try:\n user = col.find_one({\"AccountNo \":accno})\n if user:\n res = {\n \"Account Info\": user\n }\n return make_response(jsonify(res), 200)\n else:\n res = {\n \"Message\": \"Account not found!\"\n }\n return make_response(jsonify(res), 404)\n except:\n res = {\n \"Message\": \"Error occurred !\"\n }\n return make_response(jsonify(res), 503)\n\n@app.route(\"/api/update/\", methods=['PUT'])\ndef updateUser(accno):\n try:\n if col.find_one({\"AccountNo \":accno}):\n req = request.get_json()\n print(req)\n filter = {\"AccountNo \":accno}\n for i in req:\n col.update_one(filter, {\"$set\":{i:req[i]}})\n return \"Record updated successfully!\",200\n else:\n res = {\n \"Message\":\"Account not found!\"\n }\n return make_response(jsonify(res), 404)\n except:\n res = {\n \"Message\": \"Error occurred !\"\n }\n return make_response(jsonify(res), 503)\n\n\n@app.route(\"/api/delete/\", methods=[\"DELETE\"])\ndef delete_collection(accno):\n try:\n if col.find_one({\"AccountNo \":accno}):\n query = {\"AccountNo \":accno}\n col.delete_one(query)\n res = make_response(jsonify({\"Message\": \"Record deleted successfully\"}), 200)\n return res\n else:\n res = {\n \"Message\": \"Account not found!\"\n }\n return make_response(jsonify(res), 404)\n except:\n res = {\n \"Message\": \"Error occurred !\"\n }\n return make_response(jsonify(res), 503)\n\n\n","sub_path":"app/userdata.py","file_name":"userdata.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"}
+{"seq_id":"465514314","text":"from __future__ import print_function, division\n\n# WORKING COPY OF SPLAT CODE LIBRARY\n# based on routines developed by:\n# Christian Aganze\n# Daniella Bardalez Gagliuffi\n# Adam Burgasser\n# Caleb Choban\n# Ivanna Escala\n# Aishwarya Iyer\n# Yuhui Jin\n# Michael Lopez\n# Alex Mendez\n# Gretel Mercado\n# Jonathan Parra\n# Maitrayee Sahi\n# Adrian Suarez\n# Melisa Tallis\n# Tomoki Tamiya\n\n#\n# CURRENT STATUS (3/12/2015)\n# URGENT\n# fails when reading in unpublished (online) data\n#\n# LESS URGENT\n# reformat fits files so headers have valid information, and spectra are flux calibrated\n# update information for sources in source database\n# add help sections to all programs\n# plotspectrum => multiplot, multipage files\n# proper SQL search for database\n# have classifybyindex return individual index classifications (e.g., 'full' keyword)\n\n# verify the version is correct\nimport sys\nif sys.version_info.major != 2 and sys.version_info.major != 3:\n raise NameError('\\nSPLAT only works on Python 2.7 and 3.X\\n')\n\n# imports\nimport astropy\nimport base64\nimport copy\nimport matplotlib.pyplot as plt\nimport numpy\nimport os\nimport random\nimport re\nimport requests\nimport scipy\nif sys.version_info.major == 2: # switch for those using python 3\n import string\nimport warnings\n\nfrom astropy.io import fits # for reading in spreadsheet\nfrom astropy.table import Table, join # for reading in table files\nfrom astropy.coordinates import SkyCoord # coordinate conversion\nfrom astropy import units as u # standard units\nfrom astropy import constants as const # physical constants in SI units\nfrom scipy import stats, signal\nfrom scipy.integrate import trapz # for numerical integration\nfrom scipy.interpolate import interp1d\n\n# suppress warnings - probably not an entirely safe approach!\nnumpy.seterr(all='ignore')\nwarnings.simplefilter(\"ignore\")\n#from splat._version import __version__\n\n#set the SPLAT PATH, either from set environment variable or from sys.path\nSPLAT_PATH = './'\nif os.environ.get('SPLAT_PATH') != None:\n SPLAT_PATH = os.environ['SPLAT_PATH']\n# get from PYTHONPATH\nif os.environ.get('PYTHONPATH') != None and SPLAT_PATH == './':\n path = os.environ['PYTHONPATH']\n for i in path.split(':'):\n if 'splat' in i:\n SPLAT_PATH = i\n# get from system path\nif SPLAT_PATH == './':\n checkpath = ['splat' in r for r in sys.path]\n if max(checkpath):\n SPLAT_PATH = sys.path[checkpath.index(max(checkpath))]\n\n# local application/library specific import\n#import bdevopar as splevol\nfrom splat_db import *\nfrom splat_model import *\nfrom splat_plot import *\n#import splat_db\n\n#################### CONSTANTS ####################\nSPLAT_URL = 'http://pono.ucsd.edu/~adam/splat/'\nDATA_FOLDER = '/reference/Spectra/'\n\n# explicitly read in source and spectral databases\nDB_SOURCES = fetchDatabase(splat.DB_SOURCES_FILE)\nDB_SPECTRA = fetchDatabase(splat.DB_SPECTRA_FILE)\n\nmonths = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']\nspex_pixel_scale = 0.15 # spatial scale in arcseconds per pixel\nuspex_pixel_scale = 0.10 # spatial scale in arcseconds per pixel\nspex_wave_range = [0.65,2.45]*u.micron # default wavelength range\nmax_snr = 1000.0 # maximum S/N ratio permitted\nTMPFILENAME = 'splattmpfile'\n\nSPEX_STDFILES = { \\\n 'M0.0': '11335_10505.fits',\\\n 'M1.0': '11364_10806.fits',\\\n 'M2.0': '11181_10187.fits',\\\n 'M3.0': '10823_11422.fits',\\\n 'M4.0': '12004_10444.fits',\\\n 'M5.0': '10829_10104.fits',\\\n 'M6.0': '11182_10188.fits',\\\n 'M7.0': '10822_11283.fits',\\\n 'M8.0': '10824_11423.fits',\\\n 'M9.0': '10821_11058.fits',\\\n 'L0.0': '10107_10315.fits',\\\n 'L1.0': '11072_11527.fits',\\\n 'L2.0': '10600_10957.fits',\\\n 'L3.0': '10592_11111.fits',\\\n 'L4.0': '10675_11572.fits',\\\n 'L5.0': '10351_10583.fits',\\\n 'L6.0': '10375_10696.fits',\\\n 'L7.0': '10678_10105.fits',\\\n 'L8.0': '10115_11254.fits',\\\n 'L9.0': '10268_10237.fits',\\\n 'T0.0': '10771_10871.fits',\\\n 'T1.0': '10767_10591.fits',\\\n 'T2.0': '10017_10945.fits',\\\n 'T3.0': '10034_10874.fits',\\\n 'T4.0': '10143_11632.fits',\\\n 'T5.0': '10021_11106.fits',\\\n 'T6.0': '10200_11236.fits',\\\n 'T7.0': '10159_10513.fits',\\\n 'T8.0': '10126_10349.fits',\\\n 'T9.0': '11536_10509.fits'}\n# EMPTY DICTIONARY\nSPEX_STDS = {}\n\nSPEX_SD_STDFILES = { \\\n 'sdM5.5': '11670_11134.fits',\\\n 'sdM6.0': '10265_10045.fits',\\\n 'sdM7.0': '10197_11074.fits',\\\n 'sdM8.0': '10123_10145.fits',\\\n 'sdM9.5': '10188_10700.fits',\\\n 'sdL0.0': '11972_10248.fits',\\\n 'sdL3.5': '10364_10946.fits',\\\n 'sdL4.0': '10203_11241.fits'}\n# EMPTY DICTIONARY\nSPEX_SD_STDS = {}\n\nSPEX_ESD_STDFILES = { \\\n 'esdM5.0': '10229_10163.fits',\\\n# 'esdM6.5': '_10579.fits',\\\n 'esdM7.0': '10521_10458.fits',\\\n 'esdM8.5': '10278_10400.fits'}\n# EMPTY DICTIONARY\nSPEX_ESD_STDS = {}\n\n\n# filters\nFILTER_FOLDER = '/reference/Filters/'\nFILTERS = { \\\n '2MASS_J': {'file': 'j_2mass.txt', 'description': '2MASS J-band', 'zeropoint': 1594.0}, \\\n '2MASS_H': {'file': 'h_2mass.txt', 'description': '2MASS H-band', 'zeropoint': 1024.0}, \\\n '2MASS_KS': {'file': 'ks_2mass.txt', 'description': '2MASS Ks-band', 'zeropoint': 666.7}, \\\n 'BESSEL_I': {'file': 'bessel_i.txt', 'description': 'Bessel I-band', 'zeropoint': 2405.3}, \\\n 'HAWK_Y': {'file': 'hawk-y.txt', 'description': 'HAWK Y-band', 'zeropoint': 2092.9}, \\\n 'HAWK_J': {'file': 'hawk-j.txt', 'description': 'HAWK J-band', 'zeropoint': 1543.5}, \\\n 'HAWK_H': {'file': 'hawk-h.txt', 'description': 'HAWK H-band', 'zeropoint': 1053.6}, \\\n 'HAWK_H2': {'file': 'hawk-h2.txt', 'description': 'HAWK H2-band', 'zeropoint': 688.8}, \\\n 'HAWK_CH4': {'file': 'hawk-ch4.txt', 'description': 'HAWK CH4-band', 'zeropoint': 1093.4}, \\\n 'HAWK_KS': {'file': 'hawk-ks.txt', 'description': 'HAWK Ks-band', 'zeropoint': 675.3}, \\\n 'HAWK_BRG': {'file': 'hawk-brg.txt', 'description': 'HAWK Brackett Gamma', 'zeropoint': 638.9}, \\\n 'HAWK_NB1060': {'file': 'hawk-nb1060.txt', 'description': 'HAWK Narrow Band 1060', 'zeropoint': 2003.27}, \\\n 'HAWK_NB1190': {'file': 'hawk-nb1190.txt', 'description': 'HAWK Narrow Band 1190', 'zeropoint': 1697.50}, \\\n 'HAWK_NB2090': {'file': 'hawk-nb2090.txt', 'description': 'HAWK Narrow Band 2090', 'zeropoint': 706.68}, \\\n 'FOURSTAR_J': {'file': 'fourstar-j.txt', 'description': 'FOURSTAR J-band', 'zeropoint': 1581.2}, \\\n 'FOURSTAR_J1': {'file': 'fourstar-j1.txt', 'description': 'FOURSTAR J1-band', 'zeropoint': 1978.7}, \\\n 'FOURSTAR_J2': {'file': 'fourstar-j2.txt', 'description': 'FOURSTAR J2-band', 'zeropoint': 1774.5}, \\\n 'FOURSTAR_J3': {'file': 'fourstar-j3.txt', 'description': 'FOURSTAR J3-band', 'zeropoint': 1488.8}, \\\n 'FOURSTAR_H': {'file': 'fourstar-h.txt', 'description': 'FOURSTAR H-band', 'zeropoint': 1054.9}, \\\n 'FOURSTAR_H_SHORT': {'file': 'fourstar-hshort.txt', 'description': 'FOURSTAR H short', 'zeropoint': 1119.1}, \\\n 'FOURSTAR_H_LONG': {'file': 'fourstar-hlong.txt', 'description': 'FOURSTAR H long', 'zeropoint': 980.7}, \\\n 'FOURSTAR_KS': {'file': 'fourstar-j.txt', 'description': 'FOURSTAR Ks-band', 'zeropoint': 675.7}, \\\n 'IRAC_CH1': {'file': 'irac1.txt', 'description': 'IRAC Channel 1 (3.6 micron)', 'zeropoint': 280.9}, \\\n 'IRAC_CH2': {'file': 'irac2.txt', 'description': 'IRAC Channel 2 (4.5 micron)', 'zeropoint': 179.7}, \\\n 'IRAC_CH3': {'file': 'irac3.txt', 'description': 'IRAC Channel 3 (5.8 micron)', 'zeropoint': 115.0}, \\\n 'IRAC_CH4': {'file': 'irac4.txt', 'description': 'IRAC Channel 4 (8.0 micron)', 'zeropoint': 64.13}, \\\n 'MKO_J_ATM': {'file': 'j_atm_mko.txt', 'description': 'MKO J-band + atmosphere', 'zeropoint': 1562.3}, \\\n 'MKO_H_ATM': {'file': 'h_atm_mko.txt', 'description': 'MKO H-band + atmosphere', 'zeropoint': 1045.9}, \\\n 'MKO_K_ATM': {'file': 'k_atm_mko.txt', 'description': 'MKO K-band + atmosphere', 'zeropoint': 647.7}, \\\n 'MKO_J': {'file': 'mko_j.txt', 'description': 'MKO J-band + atmosphere', 'zeropoint': 1562.3}, \\\n 'MKO_H': {'file': 'mko_h.txt', 'description': 'MKO H-band + atmosphere', 'zeropoint': 1045.9}, \\\n 'MKO_K': {'file': 'mko_ks.txt', 'description': 'MKO K-band', 'zeropoint': 647.7}, \\\n 'MKO_KP': {'file': 'mko_kp.txt', 'description': 'MKO Kp-band', 'zeropoint': 693.7}, \\\n 'MKO_LP': {'file': 'mko_lp.txt', 'description': 'MKO Lp-band', 'zeropoint': 248.3}, \\\n 'MKO_MP': {'file': 'mko_mp.txt', 'description': 'MKO Mp-band', 'zeropoint': 164.7}, \\\n 'NICMOS_F090M': {'file': 'nic1_f090m.txt', 'description': 'NICMOS F090M', 'zeropoint': 2255.0}, \\\n 'NICMOS_F095N': {'file': 'nic1_f095n.txt', 'description': 'NICMOS F095N', 'zeropoint': 2044.6}, \\\n 'NICMOS_F097N': {'file': 'nic1_f097n.txt', 'description': 'NICMOS F097N', 'zeropoint': 2275.4}, \\\n 'NICMOS_F108N': {'file': 'nic1_f108n.txt', 'description': 'NICMOS F108N', 'zeropoint': 1937.3}, \\\n 'NICMOS_F110M': {'file': 'nic1_f110m.txt', 'description': 'NICMOS F110M', 'zeropoint': 1871.8}, \\\n 'NICMOS_F110W': {'file': 'nic1_f110w.txt', 'description': 'NICMOS F110W', 'zeropoint': 1768.5}, \\\n 'NICMOS_F113N': {'file': 'nic1_f113n.txt', 'description': 'NICMOS F113N', 'zeropoint': 1821.0}, \\\n 'NICMOS_F140W': {'file': 'nic1_f140w.txt', 'description': 'NICMOS F140W', 'zeropoint': 1277.1}, \\\n 'NICMOS_F145M': {'file': 'nic1_f145m.txt', 'description': 'NICMOS F145M', 'zeropoint': 1242.0}, \\\n 'NICMOS_F160W': {'file': 'nic1_f160w.txt', 'description': 'NICMOS F160W', 'zeropoint': 1071.7}, \\\n 'NICMOS_F164N': {'file': 'nic1_f164n.txt', 'description': 'NICMOS F164N', 'zeropoint': 1003.0}, \\\n 'NICMOS_F165M': {'file': 'nic1_f165m.txt', 'description': 'NICMOS F165M', 'zeropoint': 1023.6}, \\\n 'NICMOS_F166N': {'file': 'nic1_f166n.txt', 'description': 'NICMOS F166N', 'zeropoint': 1047.7}, \\\n 'NICMOS_F170M': {'file': 'nic1_f170m.txt', 'description': 'NICMOS F170M', 'zeropoint': 979.1}, \\\n 'NICMOS_F187N': {'file': 'nic1_f187n.txt', 'description': 'NICMOS F187N', 'zeropoint': 803.7}, \\\n 'NICMOS_F190N': {'file': 'nic1_f190n.txt', 'description': 'NICMOS F190N', 'zeropoint': 836.5}, \\\n 'NIRC2_J': {'file': 'nirc2-j.txt', 'description': 'NIRC2 J-band', 'zeropoint': 1562.7}, \\\n 'NIRC2_H': {'file': 'nirc2-h.txt', 'description': 'NIRC2 H-band', 'zeropoint': 1075.5}, \\\n 'NIRC2_HCONT': {'file': 'nirc2-hcont.txt', 'description': 'NIRC2 H-continuum band', 'zeropoint': 1044.5}, \\\n 'NIRC2_K': {'file': 'nirc2-k.txt', 'description': 'NIRC2 K-band', 'zeropoint': 648.9}, \\\n 'NIRC2_KP': {'file': 'nirc2-kp.txt', 'description': 'NIRC2 Kp-band', 'zeropoint': 689.3}, \\\n 'NIRC2_KS': {'file': 'nirc2-ks.txt', 'description': 'NIRC2 Ks-band', 'zeropoint': 676.2}, \\\n 'NIRC2_KCONT': {'file': 'nirc2-kcont.txt', 'description': 'NIRC2 K continuum-band', 'zeropoint': 605.9}, \\\n 'NIRC2_FE2': {'file': 'nirc2-fe2.txt', 'description': 'WIRC Fe II', 'zeropoint': 1019.7}, \\\n 'NIRC2_LP': {'file': 'nirc2-lp.txt', 'description': 'WIRC Fe II', 'zeropoint': 248.0}, \\\n 'NIRC2_M': {'file': 'nirc2-ms.txt', 'description': 'WIRC Fe II', 'zeropoint': 165.8}, \\\n 'PANSTARRS_I': {'file': 'panstarrs-i.txt', 'description': 'PANSTARRS i-band', 'zeropoint': 2584.6}, \\\n 'PANSTARRS_Z': {'file': 'panstarrs-z.txt', 'description': 'PANSTARRS z-band', 'zeropoint': 2584.6}, \\\n 'PANSTARRS_Y': {'file': 'panstarrs-y.txt', 'description': 'PANSTARRS y-band', 'zeropoint': 2584.6}, \\\n 'UKIDSS_Z': {'file': 'ukidss-z.txt', 'description': 'UKIDSS Z-band', 'zeropoint': 2261.4}, \\\n 'UKIDSS_Y': {'file': 'ukidss-y.txt', 'description': 'UKIDSS Y-band', 'zeropoint': 2057.2}, \\\n 'UKIDSS_J': {'file': 'ukidss-j.txt', 'description': 'UKIDSS J-band', 'zeropoint': 1556.8}, \\\n 'UKIDSS_H': {'file': 'ukidss-h.txt', 'description': 'UKIDSS H-band', 'zeropoint': 1038.3}, \\\n 'UKIDSS_K': {'file': 'ukidss-k.txt', 'description': 'UKIDSS K-band', 'zeropoint': 644.1}, \\\n 'VISTA_Z': {'file': 'vista_z.txt', 'description': 'VISTA Z-band', 'zeropoint': 2263.81}, \\\n 'VISTA_Y': {'file': 'vista_y.txt', 'description': 'VISTA Y-band', 'zeropoint': 2087.32}, \\\n 'VISTA_J': {'file': 'vista_j.txt', 'description': 'VISTA J-band', 'zeropoint': 1554.03}, \\\n 'VISTA_H': {'file': 'vista_h.txt', 'description': 'VISTA H-band', 'zeropoint': 1030.40}, \\\n 'VISTA_KS': {'file': 'vista_ks.txt', 'description': 'VISTA Ks-band', 'zeropoint': 674.83}, \\\n 'WFC3_F127M': {'file': 'wfc3_F127M.txt', 'description': 'WFC3 F127M', 'zeropoint': 2261.3}, \\\n 'WFC3_F139M': {'file': 'wfc3_F139M.txt', 'description': 'WFC3 F139M', 'zeropoint': 2261.3}, \\\n 'WFC3_F164N': {'file': 'wfc3_F164M.txt', 'description': 'WFC3 F164N', 'zeropoint': 2261.3}, \\\n 'WFC3_F167N': {'file': 'wfc3_F160W.txt', 'description': 'WFC3 F160W', 'zeropoint': 2261.3}, \\\n 'WFCAM_Z': {'file': 'wfcam-z.txt', 'description': 'UKIRT WFCAM Z', 'zeropoint': 2261.3}, \\\n 'WFCAM_Y': {'file': 'wfcam-y.txt', 'description': 'UKIRT WFCAM Y', 'zeropoint': 2040.9}, \\\n 'WFCAM_J': {'file': 'wfcam-j.txt', 'description': 'UKIRT WFCAM J', 'zeropoint': 1548.7}, \\\n 'WFCAM_H': {'file': 'wfcam-h.txt', 'description': 'UKIRT WFCAM H', 'zeropoint': 1027.1}, \\\n 'WFCAM_H2': {'file': 'wfcam-h2.txt', 'description': 'UKIRT WFCAM H2', 'zeropoint': 677.1}, \\\n 'WFCAM_BRG': {'file': 'wfcam-brg.txt', 'description': 'UKIRT WFCAM Brackett Gamma', 'zeropoint': 645.5}, \\\n 'WFCAM_K': {'file': 'wfcam-k.txt', 'description': 'UKIRT WFCAM K', 'zeropoint': 630.0}, \\\n 'WIRCAM_Y': {'file': 'wircam-cfht-y.txt', 'description': 'CFHT WIRCAM Y', 'zeropoint': 2073.32}, \\\n 'WIRCAM_J': {'file': 'wircam-cfht-j.txt', 'description': 'CFHT WIRCAM J', 'zeropoint': 1551.01}, \\\n 'WIRCAM_H': {'file': 'wircam-cfht-h.txt', 'description': 'CFHT WIRCAM H', 'zeropoint': 1044.35}, \\\n 'WIRCAM_KS': {'file': 'wircam-cfht-ks.txt', 'description': 'CFHT WIRCAM Ks', 'zeropoint': 674.62}, \\\n 'WIRCAM_KCONT': {'file': 'wircam-cfht-kcont.txt', 'description': 'CFHT WIRCAM K-cont', 'zeropoint': 636.17}, \\\n 'WIRCAM_CH4_OFF': {'file': 'wircam-cfht-ch4s.txt', 'description': 'CFHT WIRCAM CH4-on', 'zeropoint': 987.39}, \\\n 'WIRCAM_CH4_ON': {'file': 'wircam-cfht-ch4l.txt', 'description': 'CFHT WIRCAM CH4-off', 'zeropoint': 1076.31}, \\\n 'WIRC_J': {'file': 'wirc_jcont.txt', 'description': 'WIRC J-cont', 'zeropoint': 0.}, \\\n 'WIRC_H': {'file': 'wirc_hcont.txt', 'description': 'WIRC H-cont', 'zeropoint': 0.}, \\\n 'WIRC_K': {'file': 'wirc_kcont.txt', 'description': 'WIRC K-cont', 'zeropoint': 0.}, \\\n 'WIRC_CO': {'file': 'wirc_co.txt', 'description': 'WIRC CO', 'zeropoint': 0.}, \\\n 'WIRC_CH4S': {'file': 'wirc_ch4s.txt', 'description': 'WIRC CH4S', 'zeropoint': 0.}, \\\n 'WIRC_CH4L': {'file': 'wirc_ch4l.txt', 'description': 'WIRC CH4L', 'zeropoint': 0.}, \\\n 'WIRC_FE2': {'file': 'wirc_feii.txt', 'description': 'WIRC Fe II', 'zeropoint': 0.}, \\\n 'WIRC_BRGAMMA': {'file': 'wirc_brgamma.txt', 'description': 'WIRC H I Brackett Gamma', 'zeropoint': 0.}, \\\n 'WIRC_PABETA': {'file': 'wirc_pabeta.txt', 'description': 'WIRC H I Paschen Beta', 'zeropoint': 0.}, \\\n 'WISE_W1': {'file': 'wise_w1.txt', 'description': 'WISE W1 (3.5 micron)', 'zeropoint': 309.54}, \\\n 'WISE_W2': {'file': 'wise_w2.txt', 'description': 'WISE W2 (4.6 micron)', 'zeropoint': 171.79}, \\\n 'WISE_W3': {'file': 'wise_w3.txt', 'description': 'WISE W3 (13 micron)', 'zeropoint': 31.67}, \\\n 'WISE_W4': {'file': 'wise_w4.txt', 'description': 'WISE W4 (22 micron)', 'zeropoint': 8.363} \\\n }\n\n# Index sets\nindex_sets = ['burgasser','bardalez','tokunaga','reid','geballe','allers','testi','slesnick','mclean','rojas']\n\n# change the command prompt\nsys.ps1 = 'splat> '\n\n#####################################################\n\n\n# helper functions from Alex\ndef lazyprop(fn):\n attr_name = '_lazy_' + fn.__name__\n @property\n def _lazyprop(self):\n if not hasattr(self, attr_name):\n setattr(self, attr_name, fn(self))\n return getattr(self, attr_name)\n return _lazyprop\n\ndef Show(fn):\n def _show(self, *args, **kwargs):\n noplot = kwargs.pop('noplot', False)\n quiet = kwargs.pop('quiet', False)\n tmp = fn(self, *args, **kwargs)\n# if not quiet:\n# self.info()\n# if not noplot:\n# self.plot(**kwargs)\n return tmp\n return _show\n\ndef Copy(fn):\n def _copy(self, *args, **kwargs):\n out = copy.copy(self)\n return fn(out, *args, **kwargs)\n return _copy\n\n\n# define the Spectrum class which contains the relevant information\nclass Spectrum(object):\n '''\n :Description: Primary class for containing spectral and source data for SpeX Prism Library.\n\n :param model:\n :type model: optional, default = False\n :param wlabel: label of wavelength\n :type wlabel: optional, default = 'Wavelength'\n :param wunit: unit in which wavelength is measured\n :type wunit: optional, default = ``u.micron``\n :param wunit_label: label of the unit of wavelength\n :type wunit_label: optional, default = :math:`\\\\mu m`\n :param flabel: label of flux density\n :type flabel: optional, default = :math:`F_\\\\lambda`\n :param fscale: string describing how flux density is scaled\n :type fscale: optional, default = ''\n :param funit: unit in which flux density is measured\n :type funit: optional, default = ``u.erg/(u.cm**2 * u.s * u.micron)``\n :param funit_label: label of the unit of flux density\n :type funit_label: optional, default = :math:`erg\\;cm^{-2} s^{-1} \\\\mu m^{-1}`\n :param resolution:\n :type resolution: optional, default = 150\n :param slitpixelwidth: Width of the slit measured in subpixel values.\n :type slitpixelwidth: optional, default = 3.33\n :param slitwidth: Actual width of the slit, measured in arc seconds. Default value is the ``slitpixelwidth`` multiplied by the spectrograph pixel scale of 0.15 arcseconds.\n :type slitwidth: optional, default = ``slitpixelwidth`` * 0.15\n :param header: header info of the spectrum\n :type header: optional, default = Table()\n :param filename: a string containing the spectrum's filename.\n :type filename: optional, default = ''\n :param file: same as filename\n :type file: optional, default = ''\n :param idkey: spectrum key of the desired spectrum\n :type idkey: optional, default = False\n\n :Example:\n >>> import splat\n >>> sp = splat.Spectrum(filename='myspectrum.fits') # read in a file\n >>> sp = splat.Spectrum('myspectrum.fits') # same\n >>> sp = splat.Spectrum(10002) # read in spectrum with idkey = 10002\n >>> sp = splat.Spectrum(wave=wavearray,flux=fluxarray) # create objects with wavelength & flux arrays\n '''\n\n def __init__(self, *args, **kwargs):\n# some presets\n sdb = False\n self.model = kwargs.get('model',False)\n self.wlabel = kwargs.get('wlabel',r'Wavelength')\n self.wunit = kwargs.get('wunit',u.micron)\n self.wunit_label = kwargs.get('wunit_label',r'$\\mu$m')\n self.flabel = kwargs.get('flabel',r'F$_{\\lambda}$')\n self.fscale = kwargs.get('fscale','')\n self.funit = kwargs.get('funit',u.erg/(u.cm**2 * u.s * u.micron))\n self.funit_label = kwargs.get('funit_label',r'erg~cm$^{-2}$~s$^{-1}$~$\\mu$m$^{-1}$')\n self.resolution = kwargs.get('resolution',150) # default placeholder\n self.slitpixelwidth = kwargs.get('slitwidth',3.33) # default placeholder\n self.slitwidth = self.slitpixelwidth*spex_pixel_scale\n# self.header = kwargs.get('header',fits.PrimaryHDU())\n self.header = kwargs.get('header',{})\n self.filename = kwargs.get('file','')\n self.filename = kwargs.get('filename',self.filename)\n self.idkey = kwargs.get('idkey',False)\n\n# option 1: a filename is given\n if (len(args) > 0):\n if isinstance(args[0],str):\n self.filename = args[0]\n if kwargs.get('file',self.filename) != '':\n self.filename = kwargs.get('file',self.filename)\n if kwargs.get('filename',self.filename) != '':\n self.filename = kwargs.get('filename',self.filename)\n\n# option 2: a spectrum ID is given\n if (len(args) > 0):\n if isinstance(args[0],int):\n self.idkey = args[0]\n\n\n if self.idkey != False:\n# self.idkey = kwargs.get('idkey',self.idkey)\n try:\n sdb = keySpectrum(self.idkey)\n if sdb != False:\n self.filename = sdb['DATA_FILE'][0]\n except:\n print('Warning: problem reading in spectral database, a known problem for Python 3.X')\n elif self.model == False and self.filename != '':\n kwargs['filename']=self.filename\n kwargs['silent']=True\n try:\n t = searchLibrary(**kwargs)\n if len(t) > 0:\n sdb = t\n except:\n print('Warning: problem reading in source or spectral database, a known problem for Python 3.X') \n else:\n sdb = False\n\n# set up folder - by default this is local data directory\n kwargs['folder'] = kwargs.get('folder',SPLAT_PATH+DATA_FOLDER)\n self.simplefilename = os.path.basename(self.filename)\n self.file = self.filename\n self.name = kwargs.get('name',self.simplefilename)\n kwargs['filename'] = self.filename\n\n# option 3: wave and flux are given\n if len(kwargs.get('wave','')) > 0 and len(kwargs.get('flux','')) > 0:\n self.wave = kwargs['wave']\n self.flux = kwargs['flux']\n if len(kwargs.get('noise','')) > 0:\n self.noise = kwargs['noise']\n else:\n self.noise = numpy.array([numpy.nan for i in self.wave])\n\n# read in data from file\n elif self.filename != '':\n try:\n rs = readSpectrum(self.filename,**kwargs)\n self.wave = rs['wave']\n self.flux = rs['flux']\n self.noise = rs['noise']\n self.header = rs['header']\n except:\n raise NameError('\\nCould not load spectral file {:s}, recheck the filename and path'.format(kwargs.get('filename','')))\n\n# empty spectrum vessel (used for copying)\n else:\n self.wave = []\n self.flux = []\n self.noise = []\n\n# process spectral data\n if len(self.wave) > 0:\n# convert to numpy arrays\n self.wave = numpy.array(self.wave)\n self.flux = numpy.array(self.flux)\n self.noise = numpy.array(self.noise)\n# enforce positivity and non-nan\n if (numpy.nanmin(self.flux) < 0):\n self.flux[numpy.where(self.flux < 0)] = 0.\n self.flux[numpy.isnan(self.flux)] = 0.\n# check on noise being too low\n if (numpy.nanmax(self.flux/self.noise) > max_snr):\n self.noise[numpy.where(self.flux/self.noise > max_snr)]=numpy.median(self.noise)\n# convert to astropy quantities with units\n# assuming input is flam in erg/s/cm2/micron\n if ~isinstance(self.wave,astropy.units.quantity.Quantity):\n self.wave = numpy.array(self.wave)*self.wunit\n if ~isinstance(self.flux,astropy.units.quantity.Quantity):\n self.flux = numpy.array(self.flux)*self.funit\n if ~isinstance(self.wave,astropy.units.quantity.Quantity):\n self.noise = numpy.array(self.noise)*self.funit\n# some conversions\n self.flam = self.flux\n self.nu = self.wave.to('Hz',equivalencies=u.spectral())\n self.fnu = self.flux.to('Jy',equivalencies=u.spectral_density(self.wave))\n self.fnu_unit = u.Jansky\n# calculate variance\n self.variance = self.noise**2\n self.dof = numpy.round(len(self.wave)/self.slitpixelwidth)\n# signal to noise\n w = numpy.where(self.flux.value > numpy.median(self.flux.value))\n self.snr = numpy.nanmean(self.flux.value[w]/self.noise.value[w])\n\n# preserve original values\n self.wave_original = copy.deepcopy(self.wave)\n self.flux_original = copy.deepcopy(self.flux)\n self.noise_original = copy.deepcopy(self.noise)\n self.variance_original = copy.deepcopy(self.variance)\n# self.resolution = copy.deepcopy(self.resolution)\n# self.slitpixelwidth = copy.deepcopy(self.slitpixelwidth)\n else:\n print ('Warning: not information provided, creating an empty Spectrum object')\n\n# populate information on source and spectrum from database\n if sdb != False:\n for k in sdb.keys():\n setattr(self,k.lower(),sdb[k][0])\n self.shortname = designationToShortName(self.designation)\n self.date = self.observation_date\n# convert some data into numbers\n kconv = ['ra','dec','julian_date','median_snr','resolution','airmass',\\\n 'jmag','jmag_error','hmag','hmag_error','kmag','kmag_error','source_key']\n for k in kconv:\n try:\n setattr(self,k,float(getattr(self,k)))\n except:\n setattr(self,k,numpy.nan)\n# print(getattr(self,k))\n \n\n# information on model\n if self.model == True:\n self.teff = kwargs.get('teff',numpy.nan)\n self.logg = kwargs.get('logg',numpy.nan)\n self.z = kwargs.get('z',numpy.nan)\n self.fsed = kwargs.get('fsed',numpy.nan)\n self.cld = kwargs.get('cld',numpy.nan)\n self.kzz = kwargs.get('kzz',numpy.nan)\n self.slit = kwargs.get('slit',numpy.nan)\n self.modelset = kwargs.get('set','')\n self.name = self.modelset+' Teff='+str(self.teff)+' logg='+str(self.logg)+' [M/H]='+str(self.z)\n self.fscale = 'Surface'\n\n# populate header \n kconv = ['designation','name','shortname','ra','dec','slitwidth','source_key','data_key','observer',\\\n 'data_reference','discovery_reference','program_pi','program_number','airmass','reduction_spextool_version',\\\n 'reduction_person','reduction_date','observation_date','julian_date','median_snr','resolution','airmass']\n for k in kconv:\n try:\n self.header[k] = getattr(self,k)\n except:\n self.header[k] = ''\n\n self.history = ['Loaded']\n\n\n def __copy__(self):\n s = type(self)()\n s.__dict__.update(self.__dict__)\n return s\n\n# backup version\n def copy(self):\n s = type(self)()\n s.__dict__.update(self.__dict__)\n return s\n\n def __repr__(self):\n '''\n :Purpose: A simple representation of an object is to just give it a name\n '''\n return 'Spectrum of {}'.format(self.name)\n\n def __add__(self,other):\n '''\n :Purpose: Adds two spectra\n :param other: the other spectrum to add to the object\n '''\n sp = self.copy()\n f = interp1d(other.wave,other.flux,bounds_error=False,fill_value=0.)\n n = interp1d(other.wave,other.variance,bounds_error=False,fill_value=numpy.nan)\n sp.flux = numpy.add(self.flux,f(self.wave)*other.funit)\n sp.variance = sp.variance+n(self.wave)*(other.funit**2)\n sp.noise = sp.variance**0.5\n sp.flux_original=sp.flux\n sp.noise_original=sp.noise\n sp.variance_original=sp.variance\n sp.name = self.name+' + '+other.name\n return sp\n\n def __sub__(self,other):\n '''\n :Purpose: Subtracts two spectra\n :param other: the other spectrum to subtract from the object\n '''\n sp = self.copy()\n f = interp1d(other.wave,other.flux,bounds_error=False,fill_value=0.)\n n = interp1d(other.wave,other.variance,bounds_error=False,fill_value=numpy.nan)\n sp.flux = numpy.subtract(self.flux,f(self.wave)*other.funit)\n sp.variance = sp.variance+n(self.wave)*(other.funit**2)\n sp.noise = sp.variance**0.5\n sp.flux_original=sp.flux\n sp.noise_original=sp.noise\n sp.variance_original=sp.variance\n sp.name = self.name+' - '+other.name\n return sp\n\n def __mul__(self,other):\n '''\n :Purpose: Multiplies two spectra\n :param other: the other spectrum to multiply by the object\n '''\n sp = self.copy()\n f = interp1d(other.wave,other.flux,bounds_error=False,fill_value=0.)\n n = interp1d(other.wave,other.variance,bounds_error=False,fill_value=numpy.nan)\n sp.flux = numpy.multiply(self.flux,f(self.wave)*other.funit)\n sp.variance = numpy.multiply(sp.flux**2,(\\\n numpy.divide(self.variance.value,sp.flux.value**2)+numpy.divide(n(self.wave),f(self.wave)**2)))\n sp.noise = sp.variance**0.5\n sp.flux_original=sp.flux\n sp.noise_original=sp.noise\n sp.variance_original=sp.variance\n sp.name = self.name+' x '+other.name\n sp.funit = sp.flux.unit\n return sp\n\n def __div__(self,other):\n '''\n :Purpose: Divides two spectra\n :param other: the other spectrum to divide by the object\n '''\n sp = self.copy()\n f = interp1d(other.wave,other.flux,bounds_error=False,fill_value=0.)\n n = interp1d(other.wave,other.variance,bounds_error=False,fill_value=numpy.nan)\n sp.flux = numpy.divide(self.flux,f(self.wave)*other.funit)\n sp.variance = numpy.multiply(sp.flux**2,(\\\n numpy.divide(self.variance.value,sp.flux.value**2)+numpy.divide(n(self.wave),f(self.wave)**2)))\n sp.noise = sp.variance**0.5\n# clean up infinities\n sp.flux = numpy.where(numpy.absolute(sp.flux) == numpy.inf, numpy.nan, sp.flux)*u.erg/u.erg\n sp.noise = numpy.where(numpy.absolute(sp.noise) == numpy.inf, numpy.nan, sp.noise)*u.erg/u.erg\n sp.variance = numpy.where(numpy.absolute(sp.variance) == numpy.inf, numpy.nan, sp.variance)*u.erg/u.erg\n sp.flux_original=sp.flux\n sp.noise_original=sp.noise\n sp.variance_original=sp.variance\n sp.name = self.name+' / '+other.name\n sp.funit = sp.flux.unit\n return sp\n\n def info(self):\n '''\n :Purpose: Reports some information about this spectrum.\n '''\n if (self.model):\n print('\\n{} model with the following parmeters:'.format(self.modelset))\n print('Teff = {} K'.format(self.teff))\n print('logg = {} cm/s2'.format(self.logg))\n print('z = {}'.format(self.z))\n print('fsed = {}'.format(self.fsed))\n print('cld = {}'.format(self.cld))\n print('kzz = {}'.format(self.kzz))\n print('Smoothed to slit width {} arcseconds\\n'.format(self.slit))\n else:\n# print('\\nSpectrum of {0} observed on {1}'''.format(self.name, self.date))\n text = ['Spectrum of','Observed on','Observed by','at an airmass of','Full source designation is', 'Median S/N =','SPLAT source key is','SPLAT spectrum key is']\n ref = ['name','date','observer','airmass','designation','median_snr','source_key','data_key']\n for i,k in enumerate(ref):\n try:\n if getattr(self,k) != '':\n print('\\t{} {}'.format(text[i],getattr(self,k)))\n except:\n pass\n try:\n bib = getBibTex(self.data_reference)\n print('\\tData published in {}'.format(shortRef(bib)))\n except:\n pass\n# print('\\nPlot spectrum using .plot()')\n return\n\n def flamToFnu(self):\n '''\n :Purpose: Converts flux density from :math:`F_\\\\lambda` to :math:`F_\\\\nu`, the later in Jy\n '''\n self.funit = u.Jy\n self.flabel = 'F_nu'\n self.flux.to(self.funit,equivalencies=u.spectral_density(self.wave))\n self.noise.to(self.funit,equivalencies=u.spectral_density(self.wave))\n return\n\n def fluxCalibrate(self,f,mag,**kwargs):\n '''\n :Purpose: Calibrates spectrum to input magnitude\n '''\n absolute = kwargs.get('absolute',False)\n apparent = kwargs.get('apparent',False)\n self.normalize()\n apmag,apmag_e = filterMag(self,f,**kwargs)\n# NOTE: NEED TO INCORPORATE UNCERTAINTY INTO SPECTRAL UNCERTAINTY\n if (~numpy.isnan(apmag)):\n self.scale(10.**(0.4*(apmag-mag)))\n if (absolute):\n self.fscale = 'Absolute'\n if (apparent):\n self.fscale = 'Apparent'\n return\n\n# determine maximum flux, by default in non telluric regions\n def fluxMax(self,**kwargs):\n '''\n :Purpose: Determines maximum flux of spectrum\n :param maskTelluric: masks telluric regions\n :type maskTelluric: optional, default = True\n '''\n if kwargs.get('maskTelluric',True):\n return numpy.nanmax(self.flux.value[numpy.where(\\\n numpy.logical_or(\\\n numpy.logical_and(self.wave > 0.9*u.micron,self.wave < 1.35*u.micron),\n numpy.logical_and(self.wave > 1.42*u.micron,self.wave < 1.8*u.micron),\n numpy.logical_and(self.wave > 1.92*u.micron,self.wave < 2.3*u.micron)))])*self.funit\n else:\n return numpy.nanmax(self.flux.value[numpy.where(\\\n numpy.logical_and(self.wave > 0.9*u.micron,self.wave < 2.3*u.micron))])*self.funit\n\n def fnuToFlam(self):\n '''\n :Purpose: Converts flux density from :math:`F_\\\\nu` to :math:`F_\\\\lambda`, the later in erg/s/cm2/Hz\n '''\n self.funit = u.erg/(u.cm**2 * u.s * u.micron)\n self.flabel = 'F_lam'\n self.flux.to(self.funit,equivalencies=u.spectral_density(self.wave))\n self.noise.to(self.funit,equivalencies=u.spectral_density(self.wave))\n self.variance = self.noise**2\n return\n\n def normalize(self,**kwargs):\n '''\n :Purpose: Normalizes spectrum to its maximum flux.\n :param maskTelluric: masks telluric regions\n :type maskTelluric: optional, default = True\n '''\n if kwargs.get('waveRange',False) != False:\n rng = kwargs.get('waveRange')\n if not isinstance(rng,list):\n rng = [rng]\n if len(rng) < 2:\n rng = [rng[0]-0.02,rng[0]+0.02]\n self.scale(1./numpy.nanmax(self.flux.value[numpy.where(numpy.logical_and(self.wave > rng[0]*u.micron,self.wave < rng[1]*u.micron))]))\n else:\n self.scale(1./self.fluxMax(**kwargs).value)\n self.fscale = 'Normalized'\n return\n\n def plot(self,**kwargs):\n '''\n :Purpose: Plots spectrum. See SPLAT Plotting Routines page for more details.\n '''\n plotSpectrum(self,showNoise=True,showZero=True,**kwargs)\n\n def reset(self):\n '''\n :Purpose: Resets to original spectrum\n '''\n self.wave = copy.deepcopy(self.wave_original)\n self.flux = copy.deepcopy(self.flux_original)\n self.noise = copy.deepcopy(self.noise_original)\n self.variance = copy.deepcopy(self.variance_original)\n self.resolution = copy.deepcopy(self.resolution_original)\n self.slitpixelwidth = copy.deepcopy(self.slitpixelwidth_original)\n self.slitwidth = self.slitpixelwidth*spex_pixel_scale\n self.fscale = ''\n return\n\n def export(self,*args,**kwargs):\n '''\n :Purpose: export spectrum object to a file, either fits or ascii depending on file extension\n '''\n filename = self.simplefilename\n if len(args) > 0:\n filename = args[0]\n filename = kwargs.get('filename',filename)\n filename = kwargs.get('file',filename)\n\n# determine which type of file\n ftype = filename.split('.')[-1]\n\n# fits file\n if (ftype == 'fit' or ftype == 'fits'):\n try:\n data = numpy.vstack((self.wave.value,self.flux.value,self.noise.value)).T\n hdu = fits.PrimaryHDU(data)\n for k in self.header.keys():\n hdu.header[k] = self.header[k]\n hdu.writeto(filename,clobber=True)\n except:\n raise NameError('Problem saving spectrum object to file {}'.format(filename))\n\n# ascii file - by default space delimited (could make this more flexible)\n else:\n try:\n t = Table([self.wave.value,self.flux.value,self.noise.value],names=['wavelength','flux','uncertainty'])\n if kwargs.get('header',True):\n hd = ['{} = {}'.format(k,self.header[k]) for k in self.header.keys()]\n hd = list(set(hd))\n hd.sort()\n t.meta['comments']=hd\n ascii.write(t,output=filename,format=kwargs.get('format','commented_header'))\n except:\n raise NameError('Problem saving spectrum object to file {}'.format(filename))\n return\n\n def scale(self,factor):\n '''\n :Purpose: Smooths spectrum to a constant slit width (smooths by pixels)\n :param method: the type of window to create. See http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details.\n :type method: optional, default = 'hanning'\n :param slitpixelwidth: Width of the slit measured in subpixel values.\n :type slitpixelwidth: optional, default = 3.33\n :param slitwidth: Actual width of the slit, measured in arc seconds. Default value is the ``slitpixelwidth`` multiplied by the spectrograph pixel scale of 0.15 arcseconds.\n :param resolution:\n :type resolution: optional, default = 150\n :type slitwidth: optional, default = slitpixelwidth * 0.15\n '''\n self.flux = self.flux*factor\n self.noise = self.noise*factor\n self.variance = self.noise**2\n self.fscale = 'Scaled'\n return\n\n def smooth(self,**kwargs):\n '''Smooth spectrum to a constant slit width (smooth by pixels)'''\n method = kwargs.get('method','hanning')\n kwargs['method'] = method\n swargs = copy.deepcopy(kwargs)\n if (kwargs.get('slitPixelWidth','') != ''):\n del swargs['slitPixelWidth']\n self.smoothToSlitPixelWidth(kwargs['slitPixelWidth'],**swargs)\n elif (kwargs.get('resolution','') != ''):\n del swargs['resolution']\n self.smoothToResolution(kwargs['resolution'],**swargs)\n elif (kwargs.get('slitWidth','') != ''):\n del swargs['slitWidth']\n self.smoothToSlitWidth(kwargs['slitWidth'],**swargs)\n return\n\n def smoothToResolution(self,resolution,**kwargs):\n '''\n :Purpose: Smooths spectrum to a constant resolution\n :param resolution: resolution for smoothing the spectrum\n :param overscale: used for computing number of samples in the window\n :type overscale: optional, default = 10.\n :param method: the type of window to create. See http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details.\n :type method: optional, default = 'hanning'\n '''\n overscale = kwargs.get('overscale',10.)\n method = kwargs.get('method','hamming')\n kwargs['method'] = method\n\n# do nothing if requested resolution is higher than current resolution\n if (resolution < self.resolution):\n# sample onto a constant resolution grid at 5x current resolution\n r = resolution*overscale\n waveRng = self.waveRange()\n npix = numpy.floor(numpy.log(waveRng[1]/waveRng[0])/numpy.log(1.+1./r))\n wave_sample = [waveRng[0]*(1.+1./r)**i for i in numpy.arange(npix)]\n f = interp1d(self.wave,self.flux,bounds_error=False,fill_value=0.)\n v = interp1d(self.wave,self.variance,bounds_error=False,fill_value=numpy.nan)\n flx_sample = f(wave_sample)*self.funit\n var_sample = v(wave_sample)*self.funit**2\n# now convolve a function to smooth resampled spectrum\n window = signal.get_window(method,numpy.round(overscale))\n neff = numpy.sum(window)/numpy.nanmax(window) # effective number of pixels\n flx_smooth = signal.convolve(flx_sample, window/numpy.sum(window), mode='same')\n var_smooth = signal.convolve(var_sample, window/numpy.sum(window), mode='same')/neff\n# resample back to original wavelength grid\n f = interp1d(wave_sample,flx_smooth,bounds_error=False,fill_value=0.)\n v = interp1d(wave_sample,var_smooth,bounds_error=False,fill_value=0.)\n self.flux = f(self.wave)*self.funit\n self.variance = v(self.wave)*self.funit**2\n self.noise = numpy.array([n**0.5 for n in self.variance])\n self.slitpixelwidth = self.slitpixelwidth*self.resolution/resolution\n self.resolution = resolution\n self.slitwidth = self.slitpixelwidth*spex_pixel_scale\n self.history = ['Smoothed to constant resolution {}'.format(self.resolution)]\n return\n\n def smoothToSlitPixelWidth(self,width,**kwargs):\n '''\n :Purpose: Smooths spectrum to a constant slit width\n :param width: width for smoothing the spectrum\n :param method: the type of window to create. See http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details.\n :type method: optional, default = 'hanning'\n '''\n method = kwargs.get('method','hanning')\n kwargs['method'] = method\n# do nothing if requested resolution is higher than current resolution\n if (width > self.slitpixelwidth):\n# convolve a function to smooth spectrum\n window = signal.get_window(method,numpy.round(width))\n neff = numpy.sum(window)/numpy.nanmax(window) # effective number of pixels\n self.flux = signal.convolve(self.flux, window/numpy.sum(window), mode='same')\n self.variance = signal.convolve(self.variance, window/numpy.sum(window), mode='same')/neff\n self.noise = numpy.array([n**0.5 for n in self.variance])\n self.resolution = self.resolution*self.slitpixelwidth/width\n self.slitpixelwidth = width\n self.slitwidth = self.slitpixelwidth*spex_pixel_scale\n self.history = ['Smoothed to slit width of {}'.format(self.slitwidth)]\n return\n\n def smoothToSlitWidth(self,width,**kwargs):\n '''\n :Purpose: Smooths spectrum to a constant slit width (smooths by pixels)\n :param width: width for smoothing the spectrum\n :param method: the type of window to create. See http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details.\n :type method: optional, default = 'hanning'\n '''\n method = kwargs.get('method','hanning')\n kwargs['method'] = method\n pwidth = width/spex_pixel_scale\n self.smoothToSlitPixelWidth(pwidth,**kwargs)\n return\n\n def snr(self):\n '''\n :Purpose: Compute a representative S/N value\n .. note:: Unfinished\n '''\n pass\n return\n\n def surface(self,radius):\n '''\n :Purpose: Convert to surface fluxes given a radius, assuming at absolute fluxes\n .. note:: Unfinished\n '''\n pass\n return\n\n def waveRange(self):\n ii = numpy.where(self.flux.value > 0)\n return [numpy.nanmin(self.wave[ii]), numpy.nanmax(self.wave[ii])]\n\n\n\n\n# FUNCTIONS FOR SPLAT\ndef caldateToDate(d):\n '''\n :Purpose: Convert from numeric date to calendar date, and vice-versa.\n :param d: A numeric date of the format '20050412', or a date in the\n calendar format '2005 Jun 12'\n :Example:\n >>> import splat\n >>> caldate = splat.dateToCaldate('20050612')\n >>> print caldate\n 2005 Jun 12\n >>> date = splat.caldateToDate('2005 June 12')\n >>> print date\n 20050612\n '''\n return d[:4]+str((months.index(d[5:8])+1)/100.)[2:4]+d[-2:]\n\n\ndef checkFile(filename,**kwargs):\n '''\n :Purpose: Checks if a spectrum file exists in the SPLAT's library.\n :param filename: A string containing the spectrum's filename.\n :Example:\n >>> import splat\n >>> spectrum1 = 'spex_prism_1315+2334_110404.fits'\n >>> print splat.checkFile(spectrum1)\n True\n >>> spectrum2 = 'fake_name.fits'\n >>> print splat.checkFile(spectrum2)\n False\n '''\n url = kwargs.get('url',SPLAT_URL)+DATA_FOLDER\n return requests.get(url+filename).status_code == requests.codes.ok\n# flag = checkOnline()\n# if (flag):\n# try:\n# r = requests.get(url+filename)\n# open(os.path.basename(filename), 'wb').write(r.content)\n# open(os.path.basename(filename), 'wb').write(urllib2.urlopen(url+filename).read())\n# except:\n# flag = False\n# return flag\n\n\ndef checkAccess(**kwargs):\n '''\n :Purpose: Checks if user has access to unpublished spectra in SPLAT library.\n :Example:\n >>> import splat\n >>> print splat.checkAccess()\n True\n :Note: Must have the file .splat_access in your home directory with the correct passcode to use.\n '''\n access_file = '.splat_access'\n result = False\n\n try:\n home = os.environ.get('HOME')\n if home == None:\n home = './'\n bcode = requests.get(SPLAT_URL+access_file).content\n lcode = base64.b64encode(open(home+'/'+access_file,'r').read())\n if (bcode in lcode): # changed to partial because of EOL variations\n result = True\n except:\n result = False\n\n if (kwargs.get('report','') != ''):\n if result == True:\n print('You have full access to all SPLAT data')\n else:\n print('You have access only to published data')\n return result\n\n\ndef checkLocal(inputfile):\n '''\n :Purpose: Checks if a file is present locally or within the SPLAT\n code directory\n :Example:\n >>> import splat\n >>> splat.checkLocal('splat.py')\n True # found the code\n >>> splat.checkLocal('parameters.txt')\n False # can't find this file\n >>> splat.checkLocal('SpectralModels/BTSettl08/parameters.txt')\n True # found it\n '''\n if not os.path.exists(inputfile):\n if not os.path.exists(SPLAT_PATH+inputfile):\n return ''\n else:\n return SPLAT_PATH+inputfile\n else:\n return inputfile\n\n\ndef checkOnline(*args):\n '''\n :Purpose: Checks if SPLAT's URL is accessible from your machine--\n that is, checks if you and the host are online. Alternately\n checks if a given filename is present locally or online\n :Example:\n >>> import splat\n >>> splat.checkOnline()\n True # SPLAT's URL was detected.\n >>> splat.checkOnline()\n False # SPLAT's URL was not detected.\n >>> splat.checkOnline('SpectralModels/BTSettl08/parameters.txt')\n '' # Could not find this online file.\n '''\n if (len(args) != 0):\n if 'http://' in args[0]:\n if requests.get(args[0]).status_code == requests.codes.ok:\n \treturn args[0]\n return ''\n else:\n if requests.get(SPLAT_URL+args[0]).status_code == requests.codes.ok:\n return SPLAT_URL+args[0]\n return ''\n else:\n \treturn requests.get(SPLAT_URL).status_code == requests.codes.ok\n\n\n\n\ndef classifyByIndex(sp, *args, **kwargs):\n '''\n :Purpose: Determine the spectral type and uncertainty for a spectrum\n based on indices. Makes use of published index-SpT relations\n from `Reid et al. (2001) `_;\n `Testi et al. (2001) `_;\n `Allers et al. (2007) `_;\n and `Burgasser (2007) `_. Returns 2-element tuple\n containing spectral type (numeric or string) and\n uncertainty.\n\n :param sp: Spectrum class object, which should contain wave, flux and\n noise array elements.\n\n :param set: named set of indices to measure and compute spectral type\n\n - *'allers'*: H2O from `Allers et al. (2007) `_\n - *'burgasser'*: H2O-J, CH4-J, H2O-H, CH4-H, CH4-K from `Burgasser (2007) `_\n - *'reid'*:H2O-A and H2O-B from `Reid et al. (2001) `_\n - *'testi'*: sHJ, sKJ, sH2O_J, sH2O_H1, sH2O_H2, sH2O_K from `Testi et al. (2001) | | |