code
stringlengths 13
6.09M
| order_type
stringclasses 2
values | original_example
dict | step_ids
listlengths 1
5
|
|---|---|---|---|
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def plot_feature_VS_Observed(feature, df, linecolor):
"""
This function plots the 1880-2004 time series plots for the selected feature and observed earth
:param
Input: df -- > The dataframe of each of the features,processed before
feature --> The feature to compare with observed earth temperature
linecolor --> The line color for this feature
Output : the plot of feaure compared with observed earth temperature
"""
assert isinstance(df, pd.DataFrame)
assert isinstance(feature, str)
assert isinstance(linecolor, str)
fig = go.Figure()
fig.add_trace(go.Scatter(x=df['Year'], y=df[feature], name=feature,
line_color=linecolor, opacity=1))
fig.add_trace(go.Scatter(x=df['Year'], y=df['Observed'], name=
'Observed', line_color='dimgray', opacity=0.5))
fig.update_layout(plot_bgcolor='rgba(0, 0, 0,0)', xaxis_title=
'1880- 2005', yaxis_title='Average Temp (K)', title_text=feature +
' vs Observed', showlegend=True)
fig.show()
<|reserved_special_token_1|>
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from matplotlib import pyplot as plt
def plot_feature_VS_Observed(feature, df, linecolor):
"""
This function plots the 1880-2004 time series plots for the selected feature and observed earth
:param
Input: df -- > The dataframe of each of the features,processed before
feature --> The feature to compare with observed earth temperature
linecolor --> The line color for this feature
Output : the plot of feaure compared with observed earth temperature
"""
assert isinstance(df, pd.DataFrame)
assert isinstance(feature, str)
assert isinstance(linecolor, str)
fig = go.Figure()
fig.add_trace(go.Scatter(x=df['Year'], y=df[feature], name=feature,
line_color=linecolor, opacity=1))
fig.add_trace(go.Scatter(x=df['Year'], y=df['Observed'], name=
'Observed', line_color='dimgray', opacity=0.5))
fig.update_layout(plot_bgcolor='rgba(0, 0, 0,0)', xaxis_title=
'1880- 2005', yaxis_title='Average Temp (K)', title_text=feature +
' vs Observed', showlegend=True)
fig.show()
<|reserved_special_token_1|>
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from matplotlib import pyplot as plt
def plot_feature_VS_Observed(feature, df, linecolor):
"""
This function plots the 1880-2004 time series plots for the selected feature and observed earth
:param
Input: df -- > The dataframe of each of the features,processed before
feature --> The feature to compare with observed earth temperature
linecolor --> The line color for this feature
Output : the plot of feaure compared with observed earth temperature
"""
assert isinstance(df,pd.DataFrame)
assert isinstance(feature,str)
assert isinstance(linecolor,str)
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df['Year'],
y=df[feature],
name=feature,
line_color=linecolor,
opacity=1))
fig.add_trace(go.Scatter(
x=df['Year'],
y=df['Observed'],
name="Observed",
line_color='dimgray',
opacity=0.5) )
# Use date string to set xaxis range
fig.update_layout(plot_bgcolor='rgba(0, 0, 0,0)',
xaxis_title="1880- 2005",
yaxis_title="Average Temp (K)",
title_text= feature + " vs Observed",
showlegend=True)
fig.show()
|
flexible
|
{
"blob_id": "8348d353e6fdea77c9c994d541db1420ef57a797",
"index": 4399,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef plot_feature_VS_Observed(feature, df, linecolor):\n \"\"\"\n This function plots the 1880-2004 time series plots for the selected feature and observed earth\n :param\n Input: df -- > The dataframe of each of the features,processed before\n feature --> The feature to compare with observed earth temperature\n linecolor --> The line color for this feature\n Output : the plot of feaure compared with observed earth temperature\n \"\"\"\n assert isinstance(df, pd.DataFrame)\n assert isinstance(feature, str)\n assert isinstance(linecolor, str)\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=df['Year'], y=df[feature], name=feature,\n line_color=linecolor, opacity=1))\n fig.add_trace(go.Scatter(x=df['Year'], y=df['Observed'], name=\n 'Observed', line_color='dimgray', opacity=0.5))\n fig.update_layout(plot_bgcolor='rgba(0, 0, 0,0)', xaxis_title=\n '1880- 2005', yaxis_title='Average Temp (K)', title_text=feature +\n ' vs Observed', showlegend=True)\n fig.show()\n",
"step-3": "import numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom matplotlib import pyplot as plt\n\n\ndef plot_feature_VS_Observed(feature, df, linecolor):\n \"\"\"\n This function plots the 1880-2004 time series plots for the selected feature and observed earth\n :param\n Input: df -- > The dataframe of each of the features,processed before\n feature --> The feature to compare with observed earth temperature\n linecolor --> The line color for this feature\n Output : the plot of feaure compared with observed earth temperature\n \"\"\"\n assert isinstance(df, pd.DataFrame)\n assert isinstance(feature, str)\n assert isinstance(linecolor, str)\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=df['Year'], y=df[feature], name=feature,\n line_color=linecolor, opacity=1))\n fig.add_trace(go.Scatter(x=df['Year'], y=df['Observed'], name=\n 'Observed', line_color='dimgray', opacity=0.5))\n fig.update_layout(plot_bgcolor='rgba(0, 0, 0,0)', xaxis_title=\n '1880- 2005', yaxis_title='Average Temp (K)', title_text=feature +\n ' vs Observed', showlegend=True)\n fig.show()\n",
"step-4": "import numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom matplotlib import pyplot as plt\n\ndef plot_feature_VS_Observed(feature, df, linecolor):\n \"\"\"\n This function plots the 1880-2004 time series plots for the selected feature and observed earth\n :param\n Input: df -- > The dataframe of each of the features,processed before\n feature --> The feature to compare with observed earth temperature\n linecolor --> The line color for this feature\n Output : the plot of feaure compared with observed earth temperature\n \"\"\"\n assert isinstance(df,pd.DataFrame)\n assert isinstance(feature,str)\n assert isinstance(linecolor,str)\n \n \n fig = go.Figure()\n \n fig.add_trace(go.Scatter(\n x=df['Year'],\n y=df[feature],\n name=feature,\n line_color=linecolor,\n opacity=1))\n \n fig.add_trace(go.Scatter(\n x=df['Year'],\n y=df['Observed'],\n name=\"Observed\",\n line_color='dimgray',\n opacity=0.5) )\n \n # Use date string to set xaxis range\n fig.update_layout(plot_bgcolor='rgba(0, 0, 0,0)',\n xaxis_title=\"1880- 2005\",\n yaxis_title=\"Average Temp (K)\",\n title_text= feature + \" vs Observed\",\n showlegend=True)\n \n fig.show()\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
# -*- coding:utf-8 -*-
__author__ = 'yyp'
__date__ = '2018-5-26 3:42'
'''
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
'''
class Solution:
"""
Time: O(n)
Space:O(1)
"""
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
l, res, freq = 0, 0, [False for _ in range(256)]
for idx, char in enumerate(s):
if freq[ord(char)]:
while s[l] != char:
freq[ord(s[l])] = False
l += 1
l += 1
else:
freq[ord(char)] = True
res = max(idx - l + 1, res)
return res
|
normal
|
{
"blob_id": "b7c43f4242e38318c9e5423ea73e9d9d86759a53",
"index": 4663,
"step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l, res, freq = 0, 0, [(False) for _ in range(256)]\n for idx, char in enumerate(s):\n if freq[ord(char)]:\n while s[l] != char:\n freq[ord(s[l])] = False\n l += 1\n l += 1\n else:\n freq[ord(char)] = True\n res = max(idx - l + 1, res)\n return res\n",
"step-3": "<mask token>\n\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Space:O(1)\n \"\"\"\n\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l, res, freq = 0, 0, [(False) for _ in range(256)]\n for idx, char in enumerate(s):\n if freq[ord(char)]:\n while s[l] != char:\n freq[ord(s[l])] = False\n l += 1\n l += 1\n else:\n freq[ord(char)] = True\n res = max(idx - l + 1, res)\n return res\n",
"step-4": "__author__ = 'yyp'\n__date__ = '2018-5-26 3:42'\n<mask token>\n\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Space:O(1)\n \"\"\"\n\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l, res, freq = 0, 0, [(False) for _ in range(256)]\n for idx, char in enumerate(s):\n if freq[ord(char)]:\n while s[l] != char:\n freq[ord(s[l])] = False\n l += 1\n l += 1\n else:\n freq[ord(char)] = True\n res = max(idx - l + 1, res)\n return res\n",
"step-5": "# -*- coding:utf-8 -*-\n__author__ = 'yyp'\n__date__ = '2018-5-26 3:42'\n\n'''\nGiven a string, find the length of the longest substring without repeating characters.\nExamples:\nGiven \"abcabcbb\", the answer is \"abc\", which the length is 3.\nGiven \"bbbbb\", the answer is \"b\", with the length of 1.\nGiven \"pwwkew\", the answer is \"wke\", with the length of 3. Note that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n'''\n\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Space:O(1)\n \"\"\"\n\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l, res, freq = 0, 0, [False for _ in range(256)]\n for idx, char in enumerate(s):\n if freq[ord(char)]:\n while s[l] != char:\n freq[ord(s[l])] = False\n l += 1\n l += 1\n else:\n freq[ord(char)] = True\n res = max(idx - l + 1, res)\n return res\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for numbers in n_list:
n_dict = {}
for n in numbers:
if n in n_dict:
n_dict[n] += 1
else:
n_dict[n] = 1
mode = []
if len(n_dict) == 1 or len(n_dict) == len(numbers):
print(numbers, '= 없다')
else:
mode_count = max(n_dict.values())
for e in n_dict.keys():
if n_dict[e] == mode_count:
mode.append(e)
print(numbers, '=', mode)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
n_list = [[12, 17, 19, 17, 23], [26, 37, 26, 37, 91], [28, 30, 32, 34, 144],
[10, 10, 10, 10, 10]]
for numbers in n_list:
n_dict = {}
for n in numbers:
if n in n_dict:
n_dict[n] += 1
else:
n_dict[n] = 1
mode = []
if len(n_dict) == 1 or len(n_dict) == len(numbers):
print(numbers, '= 없다')
else:
mode_count = max(n_dict.values())
for e in n_dict.keys():
if n_dict[e] == mode_count:
mode.append(e)
print(numbers, '=', mode)
<|reserved_special_token_1|>
"""
리스트에 있는 숫자들의 최빈값을 구하는 프로그램을 만들어라.
[12, 17, 19, 17, 23] = 17
[26, 37, 26, 37, 91] = 26, 37
[28, 30, 32, 34, 144] = 없다
최빈값 : 자료의 값 중에서 가장 많이 나타난 값
① 자료의 값이 모두 같거나 모두 다르면 최빈값은 없다.
② 자료의 값이 모두 다를 때, 도수가 가장 큰 값이 1개 이상 있으면 그 값은 모두 최빈값이다.
"""
n_list = [[12, 17, 19, 17, 23],
[26, 37, 26, 37, 91],
[28, 30, 32, 34, 144],
[10, 10, 10, 10, 10]]
for numbers in n_list:
n_dict = {}
for n in numbers:
if n in n_dict:
n_dict[n] += 1
else:
n_dict[n] = 1
mode = []
if len(n_dict) == 1 or len(n_dict) == len(numbers):
print(numbers, '= 없다')
else:
mode_count = max(n_dict.values())
for e in n_dict.keys():
if n_dict[e] == mode_count:
mode.append(e)
print(numbers, '=', mode)
|
flexible
|
{
"blob_id": "39f9341313e29a22ec5e05ce9371bf65e89c91bd",
"index": 25,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor numbers in n_list:\n n_dict = {}\n for n in numbers:\n if n in n_dict:\n n_dict[n] += 1\n else:\n n_dict[n] = 1\n mode = []\n if len(n_dict) == 1 or len(n_dict) == len(numbers):\n print(numbers, '= 없다')\n else:\n mode_count = max(n_dict.values())\n for e in n_dict.keys():\n if n_dict[e] == mode_count:\n mode.append(e)\n print(numbers, '=', mode)\n",
"step-3": "<mask token>\nn_list = [[12, 17, 19, 17, 23], [26, 37, 26, 37, 91], [28, 30, 32, 34, 144],\n [10, 10, 10, 10, 10]]\nfor numbers in n_list:\n n_dict = {}\n for n in numbers:\n if n in n_dict:\n n_dict[n] += 1\n else:\n n_dict[n] = 1\n mode = []\n if len(n_dict) == 1 or len(n_dict) == len(numbers):\n print(numbers, '= 없다')\n else:\n mode_count = max(n_dict.values())\n for e in n_dict.keys():\n if n_dict[e] == mode_count:\n mode.append(e)\n print(numbers, '=', mode)\n",
"step-4": "\"\"\"\n리스트에 있는 숫자들의 최빈값을 구하는 프로그램을 만들어라.\n\n[12, 17, 19, 17, 23] = 17\n[26, 37, 26, 37, 91] = 26, 37\n[28, 30, 32, 34, 144] = 없다\n\n최빈값 : 자료의 값 중에서 가장 많이 나타난 값 \n① 자료의 값이 모두 같거나 모두 다르면 최빈값은 없다.\n② 자료의 값이 모두 다를 때, 도수가 가장 큰 값이 1개 이상 있으면 그 값은 모두 최빈값이다.\n\"\"\"\n\nn_list = [[12, 17, 19, 17, 23],\n [26, 37, 26, 37, 91],\n [28, 30, 32, 34, 144],\n [10, 10, 10, 10, 10]]\n \nfor numbers in n_list:\n n_dict = {}\n for n in numbers:\n if n in n_dict:\n n_dict[n] += 1\n else:\n n_dict[n] = 1\n mode = []\n if len(n_dict) == 1 or len(n_dict) == len(numbers):\n print(numbers, '= 없다')\n else:\n mode_count = max(n_dict.values())\n for e in n_dict.keys():\n if n_dict[e] == mode_count:\n mode.append(e)\n print(numbers, '=', mode)\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from django.apps import AppConfig
class AppValidationsConfig(AppConfig):
name = 'app_validations'
|
normal
|
{
"blob_id": "7a6a8b5e344a7b60e369f100885d1e26afa28f46",
"index": 7600,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass AppValidationsConfig(AppConfig):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass AppValidationsConfig(AppConfig):\n name = 'app_validations'\n",
"step-4": "from django.apps import AppConfig\n\n\nclass AppValidationsConfig(AppConfig):\n name = 'app_validations'\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import ast
import datetime
from pathlib import Path
from typing import Any, Dict
import yaml
from .lemmatizer import LemmatizerPymorphy2, Preprocessor
def get_config(path_to_config: str) -> Dict[str, Any]:
"""Get config.
Args:
path_to_config (str): Path to config.
Returns:
Dict[str, Any]: Config.
"""
with open(path_to_config, mode="r") as fp:
config = yaml.safe_load(fp)
# backward compatibility
if "experiment_name" not in config:
config["experiment_name"] = "model"
config["path_to_save_folder"] = (
Path(config["path_to_save_folder"])
/ f"{config['experiment_name']}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}"
)
config["path_to_config"] = path_to_config
config["path_to_save_model"] = config["path_to_save_folder"] / "model.joblib"
config["path_to_save_logfile"] = config["path_to_save_folder"] / "logging.txt"
config["path_to_save_target_names_mapping"] = (
config["path_to_save_folder"] / "target_names.json"
)
# tf-idf
if ("tf-idf" not in config) or (config["tf-idf"] is None):
config["tf-idf"] = {}
if "ngram_range" in config["tf-idf"]:
config["tf-idf"]["ngram_range"] = ast.literal_eval(
config["tf-idf"]["ngram_range"]
)
if "preprocessing" in config: # backward compatibility
lemmatization = config["preprocessing"]["lemmatization"]
if lemmatization:
if lemmatization == "pymorphy2":
lemmatizer = LemmatizerPymorphy2()
preprocessor = Preprocessor(lemmatizer)
config["tf-idf"]["preprocessor"] = preprocessor
else:
raise KeyError(
f"Unknown lemmatizer {lemmatization}. Available lemmatizers: none, pymorphy2."
)
# logreg
if ("logreg" not in config) or (config["logreg"] is None):
config["logreg"] = {}
return config
|
normal
|
{
"blob_id": "c85d7e799a652e82bfaf58e1e8bfa9c4606a8ecb",
"index": 917,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_config(path_to_config: str) ->Dict[str, Any]:\n \"\"\"Get config.\n\n Args:\n path_to_config (str): Path to config.\n\n Returns:\n Dict[str, Any]: Config.\n \"\"\"\n with open(path_to_config, mode='r') as fp:\n config = yaml.safe_load(fp)\n if 'experiment_name' not in config:\n config['experiment_name'] = 'model'\n config['path_to_save_folder'] = (Path(config['path_to_save_folder']) /\n f\"{config['experiment_name']}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}\"\n )\n config['path_to_config'] = path_to_config\n config['path_to_save_model'] = config['path_to_save_folder'\n ] / 'model.joblib'\n config['path_to_save_logfile'] = config['path_to_save_folder'\n ] / 'logging.txt'\n config['path_to_save_target_names_mapping'] = config['path_to_save_folder'\n ] / 'target_names.json'\n if 'tf-idf' not in config or config['tf-idf'] is None:\n config['tf-idf'] = {}\n if 'ngram_range' in config['tf-idf']:\n config['tf-idf']['ngram_range'] = ast.literal_eval(config['tf-idf']\n ['ngram_range'])\n if 'preprocessing' in config:\n lemmatization = config['preprocessing']['lemmatization']\n if lemmatization:\n if lemmatization == 'pymorphy2':\n lemmatizer = LemmatizerPymorphy2()\n preprocessor = Preprocessor(lemmatizer)\n config['tf-idf']['preprocessor'] = preprocessor\n else:\n raise KeyError(\n f'Unknown lemmatizer {lemmatization}. Available lemmatizers: none, pymorphy2.'\n )\n if 'logreg' not in config or config['logreg'] is None:\n config['logreg'] = {}\n return config\n",
"step-3": "import ast\nimport datetime\nfrom pathlib import Path\nfrom typing import Any, Dict\nimport yaml\nfrom .lemmatizer import LemmatizerPymorphy2, Preprocessor\n\n\ndef get_config(path_to_config: str) ->Dict[str, Any]:\n \"\"\"Get config.\n\n Args:\n path_to_config (str): Path to config.\n\n Returns:\n Dict[str, Any]: Config.\n \"\"\"\n with open(path_to_config, mode='r') as fp:\n config = yaml.safe_load(fp)\n if 'experiment_name' not in config:\n config['experiment_name'] = 'model'\n config['path_to_save_folder'] = (Path(config['path_to_save_folder']) /\n f\"{config['experiment_name']}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}\"\n )\n config['path_to_config'] = path_to_config\n config['path_to_save_model'] = config['path_to_save_folder'\n ] / 'model.joblib'\n config['path_to_save_logfile'] = config['path_to_save_folder'\n ] / 'logging.txt'\n config['path_to_save_target_names_mapping'] = config['path_to_save_folder'\n ] / 'target_names.json'\n if 'tf-idf' not in config or config['tf-idf'] is None:\n config['tf-idf'] = {}\n if 'ngram_range' in config['tf-idf']:\n config['tf-idf']['ngram_range'] = ast.literal_eval(config['tf-idf']\n ['ngram_range'])\n if 'preprocessing' in config:\n lemmatization = config['preprocessing']['lemmatization']\n if lemmatization:\n if lemmatization == 'pymorphy2':\n lemmatizer = LemmatizerPymorphy2()\n preprocessor = Preprocessor(lemmatizer)\n config['tf-idf']['preprocessor'] = preprocessor\n else:\n raise KeyError(\n f'Unknown lemmatizer {lemmatization}. Available lemmatizers: none, pymorphy2.'\n )\n if 'logreg' not in config or config['logreg'] is None:\n config['logreg'] = {}\n return config\n",
"step-4": "import ast\nimport datetime\nfrom pathlib import Path\nfrom typing import Any, Dict\n\nimport yaml\n\nfrom .lemmatizer import LemmatizerPymorphy2, Preprocessor\n\n\ndef get_config(path_to_config: str) -> Dict[str, Any]:\n \"\"\"Get config.\n\n Args:\n path_to_config (str): Path to config.\n\n Returns:\n Dict[str, Any]: Config.\n \"\"\"\n\n with open(path_to_config, mode=\"r\") as fp:\n config = yaml.safe_load(fp)\n\n # backward compatibility\n if \"experiment_name\" not in config:\n config[\"experiment_name\"] = \"model\"\n\n config[\"path_to_save_folder\"] = (\n Path(config[\"path_to_save_folder\"])\n / f\"{config['experiment_name']}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}\"\n )\n\n config[\"path_to_config\"] = path_to_config\n config[\"path_to_save_model\"] = config[\"path_to_save_folder\"] / \"model.joblib\"\n config[\"path_to_save_logfile\"] = config[\"path_to_save_folder\"] / \"logging.txt\"\n config[\"path_to_save_target_names_mapping\"] = (\n config[\"path_to_save_folder\"] / \"target_names.json\"\n )\n\n # tf-idf\n if (\"tf-idf\" not in config) or (config[\"tf-idf\"] is None):\n config[\"tf-idf\"] = {}\n if \"ngram_range\" in config[\"tf-idf\"]:\n config[\"tf-idf\"][\"ngram_range\"] = ast.literal_eval(\n config[\"tf-idf\"][\"ngram_range\"]\n )\n\n if \"preprocessing\" in config: # backward compatibility\n lemmatization = config[\"preprocessing\"][\"lemmatization\"]\n\n if lemmatization:\n if lemmatization == \"pymorphy2\":\n lemmatizer = LemmatizerPymorphy2()\n preprocessor = Preprocessor(lemmatizer)\n\n config[\"tf-idf\"][\"preprocessor\"] = preprocessor\n\n else:\n raise KeyError(\n f\"Unknown lemmatizer {lemmatization}. Available lemmatizers: none, pymorphy2.\"\n )\n\n # logreg\n if (\"logreg\" not in config) or (config[\"logreg\"] is None):\n config[\"logreg\"] = {}\n\n return config\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#!/usr/bin/env python
# coding=utf-8
import sys,os
dir = '/home/ellen/yjoqm/fdfs_client/pic'
def scp_file(filename):
cmd = 'scp ellen@61.147.182.142:/home/ellen/yjoqm/fdfs_client/pic/%s .' %filename
os.system(cmd)
def main(args):
args = sys.argv[1]
scp_file(args)
print 'done~~~~'
if __name__ == '__main__':
args = sys.argv
if len(args) < 1:
print 'usage: python scp_file xxxx'
sys.exit(2)
main(args)
|
normal
|
{
"blob_id": "e2489f9d3041c45129fdd71da6652a6093c96d2d",
"index": 8487,
"step-1": "#!/usr/bin/env python\n# coding=utf-8\nimport sys,os\n\ndir = '/home/ellen/yjoqm/fdfs_client/pic'\n\ndef scp_file(filename):\n cmd = 'scp ellen@61.147.182.142:/home/ellen/yjoqm/fdfs_client/pic/%s .' %filename\n os.system(cmd)\n\ndef main(args):\n args = sys.argv[1]\n \n scp_file(args)\n print 'done~~~~'\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) < 1:\n print 'usage: python scp_file xxxx'\n sys.exit(2)\n main(args)\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
from rllab.algos.trpo import TRPO
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab.envs.gym_env import GymEnv
from rllab.envs.normalized_env import normalize
from rllab.misc.instrument import run_experiment_lite
from rllab.policies.gaussian_mlp_policy import GaussianMLPPolicy
from rllab.policies.gaussian_rbf_policy import GaussianRBFPolicy
from rllab.policies.gaussian_hmlp_policy import GaussianHMLPPolicy
from rllab.policies.gaussian_hlc_policy import GaussianHLCPolicy
import numpy as np
import joblib
def run_task(*_):
env = normalize(GymEnv("DartWalker2d-v1", record_video=False))
policy_sep = GaussianHLCPolicy(
env_spec=env.spec,
# The neural network policy should have two hidden layers, each with 32 hidden units.
hidden_sizes=(64,32),
sub_out_dim=3,
option_dim=2,
#init_std=0.1,
)
policy_sep = joblib.load('data/local/experiment/Walker2d_hlc_2/policy_0.pkl')
'''# copy parameter from integrated controller to separate controller
hrl_pol_param = policy_int._mean_network.get_params()
hlc_param = policy_sep._mean_network.get_params()
llc_param = policy_sep._lowlevelnetwork.get_params()
for param in hlc_param:
for hrl_param in hrl_pol_param:
if param.name == hrl_param.name:
param.set_value(hrl_param.get_value(borrow=True))
for param in llc_param:
for hrl_param in hrl_pol_param:
if param.name == hrl_param.name:
param.set_value(hrl_param.get_value(borrow=True))'''
baseline = LinearFeatureBaseline(env_spec=env.spec)
'''o = np.random.random(17)*0
o[0]=1.25
a, ainfo = policy_int.get_action(o)
a2, a2info = policy_sep.get_action(o)
action1 = ainfo['mean']
action2 = policy_sep.lowlevel_action(o, a2)
print(action1)
print(action2)
abc'''
algo2 = TRPO(
env=env,
policy=policy_sep,
baseline=baseline,
batch_size=15000,
max_path_length=env.horizon,
n_itr=200,
discount=0.99,
step_size=0.01,
epopt_epsilon = 1.0,
epopt_after_iter = 0,
# Uncomment both lines (this and the plot parameter below) to enable plotting
# plot=True,
)
algo2.train()
run_experiment_lite(
run_task,
# Number of parallel workers for sampling
n_parallel=2,
# Only keep the snapshot parameters for the last iteration
snapshot_mode="last",
# Specifies the seed for the experiment. If this is not provided, a random seed
# will be used
seed=1,
exp_name='Walker2d_hlc_cont',
# plot=True
)
|
normal
|
{
"blob_id": "9f479ad2acf4f6deb0ca4db606c3d804979c10bd",
"index": 3804,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef run_task(*_):\n env = normalize(GymEnv('DartWalker2d-v1', record_video=False))\n policy_sep = GaussianHLCPolicy(env_spec=env.spec, hidden_sizes=(64, 32),\n sub_out_dim=3, option_dim=2)\n policy_sep = joblib.load(\n 'data/local/experiment/Walker2d_hlc_2/policy_0.pkl')\n \"\"\"# copy parameter from integrated controller to separate controller\n hrl_pol_param = policy_int._mean_network.get_params()\n hlc_param = policy_sep._mean_network.get_params()\n llc_param = policy_sep._lowlevelnetwork.get_params()\n\n for param in hlc_param:\n for hrl_param in hrl_pol_param:\n if param.name == hrl_param.name:\n param.set_value(hrl_param.get_value(borrow=True))\n\n for param in llc_param:\n for hrl_param in hrl_pol_param:\n if param.name == hrl_param.name:\n param.set_value(hrl_param.get_value(borrow=True))\"\"\"\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n \"\"\"o = np.random.random(17)*0\n o[0]=1.25\n a, ainfo = policy_int.get_action(o)\n a2, a2info = policy_sep.get_action(o)\n action1 = ainfo['mean']\n action2 = policy_sep.lowlevel_action(o, a2)\n print(action1)\n print(action2)\n abc\"\"\"\n algo2 = TRPO(env=env, policy=policy_sep, baseline=baseline, batch_size=\n 15000, max_path_length=env.horizon, n_itr=200, discount=0.99,\n step_size=0.01, epopt_epsilon=1.0, epopt_after_iter=0)\n algo2.train()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef run_task(*_):\n env = normalize(GymEnv('DartWalker2d-v1', record_video=False))\n policy_sep = GaussianHLCPolicy(env_spec=env.spec, hidden_sizes=(64, 32),\n sub_out_dim=3, option_dim=2)\n policy_sep = joblib.load(\n 'data/local/experiment/Walker2d_hlc_2/policy_0.pkl')\n \"\"\"# copy parameter from integrated controller to separate controller\n hrl_pol_param = policy_int._mean_network.get_params()\n hlc_param = policy_sep._mean_network.get_params()\n llc_param = policy_sep._lowlevelnetwork.get_params()\n\n for param in hlc_param:\n for hrl_param in hrl_pol_param:\n if param.name == hrl_param.name:\n param.set_value(hrl_param.get_value(borrow=True))\n\n for param in llc_param:\n for hrl_param in hrl_pol_param:\n if param.name == hrl_param.name:\n param.set_value(hrl_param.get_value(borrow=True))\"\"\"\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n \"\"\"o = np.random.random(17)*0\n o[0]=1.25\n a, ainfo = policy_int.get_action(o)\n a2, a2info = policy_sep.get_action(o)\n action1 = ainfo['mean']\n action2 = policy_sep.lowlevel_action(o, a2)\n print(action1)\n print(action2)\n abc\"\"\"\n algo2 = TRPO(env=env, policy=policy_sep, baseline=baseline, batch_size=\n 15000, max_path_length=env.horizon, n_itr=200, discount=0.99,\n step_size=0.01, epopt_epsilon=1.0, epopt_after_iter=0)\n algo2.train()\n\n\nrun_experiment_lite(run_task, n_parallel=2, snapshot_mode='last', seed=1,\n exp_name='Walker2d_hlc_cont')\n",
"step-4": "from rllab.algos.trpo import TRPO\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.envs.gym_env import GymEnv\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc.instrument import run_experiment_lite\nfrom rllab.policies.gaussian_mlp_policy import GaussianMLPPolicy\nfrom rllab.policies.gaussian_rbf_policy import GaussianRBFPolicy\nfrom rllab.policies.gaussian_hmlp_policy import GaussianHMLPPolicy\nfrom rllab.policies.gaussian_hlc_policy import GaussianHLCPolicy\nimport numpy as np\nimport joblib\n\n\ndef run_task(*_):\n env = normalize(GymEnv('DartWalker2d-v1', record_video=False))\n policy_sep = GaussianHLCPolicy(env_spec=env.spec, hidden_sizes=(64, 32),\n sub_out_dim=3, option_dim=2)\n policy_sep = joblib.load(\n 'data/local/experiment/Walker2d_hlc_2/policy_0.pkl')\n \"\"\"# copy parameter from integrated controller to separate controller\n hrl_pol_param = policy_int._mean_network.get_params()\n hlc_param = policy_sep._mean_network.get_params()\n llc_param = policy_sep._lowlevelnetwork.get_params()\n\n for param in hlc_param:\n for hrl_param in hrl_pol_param:\n if param.name == hrl_param.name:\n param.set_value(hrl_param.get_value(borrow=True))\n\n for param in llc_param:\n for hrl_param in hrl_pol_param:\n if param.name == hrl_param.name:\n param.set_value(hrl_param.get_value(borrow=True))\"\"\"\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n \"\"\"o = np.random.random(17)*0\n o[0]=1.25\n a, ainfo = policy_int.get_action(o)\n a2, a2info = policy_sep.get_action(o)\n action1 = ainfo['mean']\n action2 = policy_sep.lowlevel_action(o, a2)\n print(action1)\n print(action2)\n abc\"\"\"\n algo2 = TRPO(env=env, policy=policy_sep, baseline=baseline, batch_size=\n 15000, max_path_length=env.horizon, n_itr=200, discount=0.99,\n step_size=0.01, epopt_epsilon=1.0, epopt_after_iter=0)\n algo2.train()\n\n\nrun_experiment_lite(run_task, n_parallel=2, snapshot_mode='last', seed=1,\n exp_name='Walker2d_hlc_cont')\n",
"step-5": "from rllab.algos.trpo import TRPO\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.envs.gym_env import GymEnv\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc.instrument import run_experiment_lite\nfrom rllab.policies.gaussian_mlp_policy import GaussianMLPPolicy\nfrom rllab.policies.gaussian_rbf_policy import GaussianRBFPolicy\nfrom rllab.policies.gaussian_hmlp_policy import GaussianHMLPPolicy\nfrom rllab.policies.gaussian_hlc_policy import GaussianHLCPolicy\n\nimport numpy as np\nimport joblib\n\ndef run_task(*_):\n env = normalize(GymEnv(\"DartWalker2d-v1\", record_video=False))\n\n policy_sep = GaussianHLCPolicy(\n env_spec=env.spec,\n # The neural network policy should have two hidden layers, each with 32 hidden units.\n hidden_sizes=(64,32),\n sub_out_dim=3,\n option_dim=2,\n #init_std=0.1,\n )\n\n policy_sep = joblib.load('data/local/experiment/Walker2d_hlc_2/policy_0.pkl')\n\n '''# copy parameter from integrated controller to separate controller\n hrl_pol_param = policy_int._mean_network.get_params()\n hlc_param = policy_sep._mean_network.get_params()\n llc_param = policy_sep._lowlevelnetwork.get_params()\n\n for param in hlc_param:\n for hrl_param in hrl_pol_param:\n if param.name == hrl_param.name:\n param.set_value(hrl_param.get_value(borrow=True))\n\n for param in llc_param:\n for hrl_param in hrl_pol_param:\n if param.name == hrl_param.name:\n param.set_value(hrl_param.get_value(borrow=True))'''\n\n\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n\n '''o = np.random.random(17)*0\n o[0]=1.25\n a, ainfo = policy_int.get_action(o)\n a2, a2info = policy_sep.get_action(o)\n action1 = ainfo['mean']\n action2 = policy_sep.lowlevel_action(o, a2)\n print(action1)\n print(action2)\n abc'''\n\n algo2 = TRPO(\n env=env,\n policy=policy_sep,\n baseline=baseline,\n batch_size=15000,\n max_path_length=env.horizon,\n n_itr=200,\n discount=0.99,\n step_size=0.01,\n epopt_epsilon = 1.0,\n epopt_after_iter = 0,\n # Uncomment both lines (this and the plot parameter below) to enable plotting\n # plot=True,\n )\n algo2.train()\n\n\nrun_experiment_lite(\n run_task,\n # Number of parallel workers for sampling\n n_parallel=2,\n # Only keep the snapshot parameters for the last iteration\n snapshot_mode=\"last\",\n # Specifies the seed for the experiment. If this is not provided, a random seed\n # will be used\n seed=1,\n exp_name='Walker2d_hlc_cont',\n # plot=True\n)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def bfs(start):
visited = [False] * (n + 1)
visited[start] = True
q = deque()
q.append(start)
cnt = 1
while q:
now = q.popleft()
for i in graph[now]:
if not visited[i]:
visited[i] = True
q.append(i)
cnt += 1
return cnt
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for _ in range(m):
a, b = map(int, input().split())
graph[b].append(a)
def bfs(start):
visited = [False] * (n + 1)
visited[start] = True
q = deque()
q.append(start)
cnt = 1
while q:
now = q.popleft()
for i in graph[now]:
if not visited[i]:
visited[i] = True
q.append(i)
cnt += 1
return cnt
<|reserved_special_token_0|>
for i in range(1, n + 1):
result = bfs(i)
if result > max_cnt:
answer = [i]
max_cnt = result
elif result == max_cnt:
answer.append(i)
print(*answer)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
input = sys.stdin.readline
n, m = map(int, input().split())
graph = [[] for _ in range(n + 1)]
for _ in range(m):
a, b = map(int, input().split())
graph[b].append(a)
def bfs(start):
visited = [False] * (n + 1)
visited[start] = True
q = deque()
q.append(start)
cnt = 1
while q:
now = q.popleft()
for i in graph[now]:
if not visited[i]:
visited[i] = True
q.append(i)
cnt += 1
return cnt
answer = []
max_cnt = 0
for i in range(1, n + 1):
result = bfs(i)
if result > max_cnt:
answer = [i]
max_cnt = result
elif result == max_cnt:
answer.append(i)
print(*answer)
<|reserved_special_token_1|>
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
graph = [[] for _ in range(n + 1)]
for _ in range(m):
a, b = map(int, input().split())
graph[b].append(a)
def bfs(start):
visited = [False] * (n + 1)
visited[start] = True
q = deque()
q.append(start)
cnt = 1
while q:
now = q.popleft()
for i in graph[now]:
if not visited[i]:
visited[i] = True
q.append(i)
cnt += 1
return cnt
answer = []
max_cnt = 0
for i in range(1, n + 1):
result = bfs(i)
if result > max_cnt:
answer = [i]
max_cnt = result
elif result == max_cnt:
answer.append(i)
print(*answer)
<|reserved_special_token_1|>
# 효율적인 해킹
# https://www.acmicpc.net/problem/1325
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
graph = [[] for _ in range(n + 1)]
for _ in range(m):
a, b = map(int, input().split())
graph[b].append(a) # B를 해킹하면 A도 해킹할 수 있다
def bfs(start):
visited = [False] * (n + 1)
visited[start] = True
q = deque()
q.append(start)
cnt = 1 # start를 해킹했을 때 해킹할 수 있는 컴퓨터의 개수
while q:
now = q.popleft()
for i in graph[now]:
if not visited[i]:
visited[i] = True
q.append(i)
cnt += 1
return cnt
answer = []
max_cnt = 0
for i in range(1, n + 1):
result = bfs(i)
if result > max_cnt:
answer = [i]
max_cnt = result
elif result == max_cnt:
answer.append(i)
print(*answer)
|
flexible
|
{
"blob_id": "8a631adc8d919fb1dded27177818c4cb30148e94",
"index": 610,
"step-1": "<mask token>\n\n\ndef bfs(start):\n visited = [False] * (n + 1)\n visited[start] = True\n q = deque()\n q.append(start)\n cnt = 1\n while q:\n now = q.popleft()\n for i in graph[now]:\n if not visited[i]:\n visited[i] = True\n q.append(i)\n cnt += 1\n return cnt\n\n\n<mask token>\n",
"step-2": "<mask token>\nfor _ in range(m):\n a, b = map(int, input().split())\n graph[b].append(a)\n\n\ndef bfs(start):\n visited = [False] * (n + 1)\n visited[start] = True\n q = deque()\n q.append(start)\n cnt = 1\n while q:\n now = q.popleft()\n for i in graph[now]:\n if not visited[i]:\n visited[i] = True\n q.append(i)\n cnt += 1\n return cnt\n\n\n<mask token>\nfor i in range(1, n + 1):\n result = bfs(i)\n if result > max_cnt:\n answer = [i]\n max_cnt = result\n elif result == max_cnt:\n answer.append(i)\nprint(*answer)\n",
"step-3": "<mask token>\ninput = sys.stdin.readline\nn, m = map(int, input().split())\ngraph = [[] for _ in range(n + 1)]\nfor _ in range(m):\n a, b = map(int, input().split())\n graph[b].append(a)\n\n\ndef bfs(start):\n visited = [False] * (n + 1)\n visited[start] = True\n q = deque()\n q.append(start)\n cnt = 1\n while q:\n now = q.popleft()\n for i in graph[now]:\n if not visited[i]:\n visited[i] = True\n q.append(i)\n cnt += 1\n return cnt\n\n\nanswer = []\nmax_cnt = 0\nfor i in range(1, n + 1):\n result = bfs(i)\n if result > max_cnt:\n answer = [i]\n max_cnt = result\n elif result == max_cnt:\n answer.append(i)\nprint(*answer)\n",
"step-4": "from collections import deque\nimport sys\ninput = sys.stdin.readline\nn, m = map(int, input().split())\ngraph = [[] for _ in range(n + 1)]\nfor _ in range(m):\n a, b = map(int, input().split())\n graph[b].append(a)\n\n\ndef bfs(start):\n visited = [False] * (n + 1)\n visited[start] = True\n q = deque()\n q.append(start)\n cnt = 1\n while q:\n now = q.popleft()\n for i in graph[now]:\n if not visited[i]:\n visited[i] = True\n q.append(i)\n cnt += 1\n return cnt\n\n\nanswer = []\nmax_cnt = 0\nfor i in range(1, n + 1):\n result = bfs(i)\n if result > max_cnt:\n answer = [i]\n max_cnt = result\n elif result == max_cnt:\n answer.append(i)\nprint(*answer)\n",
"step-5": "# 효율적인 해킹\n# https://www.acmicpc.net/problem/1325\n\nfrom collections import deque\nimport sys\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\n\ngraph = [[] for _ in range(n + 1)]\nfor _ in range(m):\n a, b = map(int, input().split())\n graph[b].append(a) # B를 해킹하면 A도 해킹할 수 있다\n\ndef bfs(start):\n visited = [False] * (n + 1)\n visited[start] = True\n q = deque()\n q.append(start)\n\n cnt = 1 # start를 해킹했을 때 해킹할 수 있는 컴퓨터의 개수\n while q:\n now = q.popleft()\n for i in graph[now]:\n if not visited[i]:\n visited[i] = True\n q.append(i)\n cnt += 1\n\n return cnt\n\nanswer = []\nmax_cnt = 0\nfor i in range(1, n + 1):\n result = bfs(i)\n if result > max_cnt:\n answer = [i]\n max_cnt = result\n elif result == max_cnt:\n answer.append(i)\n\nprint(*answer)",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#!/usr/bin/python
import os
from subprocess import Popen, PIPE, STDOUT
import time
import re
import telnetlib
from get_sys_info import get_node_list, get_spec_node_list, get_active_tcu, get_ru_list, is_active_ru
g_rg_list = [
'/SGWNetMgr',
'/SS7SGU',
'/MGW_CMRG',
'/MGW_OMURG',
'/Directory',
]
status_dict={
"administrative": "UNLOCKED",
"operational": "ENABLED",
"usage": "ACTIVE",
"procedural": '',
"availability": '',
"unknown": "FALSE",
"alarm": '',
"role": "ACTIVE"
}
def get_mo_status(mo_name):
cmd = 'fshascli -s ' + mo_name
output = os.popen(cmd).readlines()
mo_status = {}
for line in output:
if len(line) > 1:
p = re.compile(r'(\S*)\((\S*)\)')
m = p.search(line)
if m:
mo_status[m.group(1)] = m.group(2)
return mo_status
def cmp_mo_status(mo_status):
ret = True
error_info = ''
for k, v in mo_status.items():
if k != 'role' and status_dict[k] != v :
error_info = " " + k + " should be \"" + status_dict[k] + "\" But is \"" + v +"\""
ret = False
return ret, error_info
return ret, error_info
def is_ru_active(mo_status):
return 'role' in mo_status and mo_status['role'] == 'ACTIVE'
def check_mo_status(mo_name, mo_status):
status, error_info = cmp_mo_status(mo_status)
if status:
print("%-40s OK"%(mo_name))
else:
print("%-40s NOK:"%(mo_name))
print(error_info)
return status
def check_mo_list(ru_list):
status = True
for ru in ru_list:
mo_status = get_mo_status(ru)
if is_ru_active(mo_status):
status = check_mo_status(ru, mo_status) and status
return status
def check_rg_status(rg_name):
# print("start to check RG " + rg_name + " ...")
mo_status = get_mo_status(rg_name)
status = check_mo_status(rg_name, mo_status)
if status:
ru_list = get_ru_list(rg_name)
if ru_list:
status = check_mo_list(ru_list) and status
return status
def check_clock():
cmd = 'fsclish -c "show mgw synchronization inputreference"'
ret = os.popen(cmd).read()
print(ret)
r_list = ret.split()
if 'yes' in r_list and 'ok' in r_list:
print("Clock is ok")
return True
else:
print "================================================================="
print "CLOCK IS NOT OK !!!"
print "================================================================="
return False
def is_needed_node_available(node_list):
num_tcu = 0
num_tdm = 0
num_cla = 1
for node in node_list:
if node.startswith("TCU"):
num_tcu += 1
if node.startswith("TDM"):
num_tdm += 1
# if node.startswith("CLA"):
# num_cla += 1
if num_tcu == 0:
print "No Working DSP available"
if num_tdm == 0:
print "No Working TDM available"
if num_cla == 0:
print "No Working CLA available"
return num_tcu and num_cla and num_tdm
def check_needed_rg(rg_list):
result = True
for rg in rg_list:
result = check_rg_status(rg) and result
return result
def check_node():
result = True
node_list = get_node_list()
if not is_needed_node_available(node_list):
print "Please first make the node working!"
return
for node in node_list:
if not check_rg_status("/"+node):
result = False
return result
def check_node_list(node_list):
result = True
for node in node_list:
result = check_rg_status("/"+node) and result
return result
def check_all(node_list_all):
ret = True
ret = check_needed_rg(g_rg_list) and ret
ret = check_node_list(node_list_all) and ret
ret = check_clock() and ret
return ret
def check_for_link(node_list_all):
tcu_list = get_spec_node_list(node_list_all, "TCU")
tdm_list = get_spec_node_list(node_list_all, "TDM")
active_tcu_list = get_active_tcu(tcu_list)
ret = True
ret = check_node_list(tdm_list) and ret
ret = check_node_list(active_tcu_list) and ret
ret = check_needed_rg(g_rg_list) and ret
check_clock()
return ret
from optparse import OptionParser
if __name__ == '__main__':
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-a", "--all",
action="store_true", dest="check_all_flag",
default=False)
opts, args = parser.parse_args()
node_list = get_node_list()
ret = False
if(opts.check_all_flag):
ret = check_all(node_list)
else:
ret = check_for_link(node_list)
# os.system('tail -f /srv/Log/log/syslog | grep srm')
if ret:
print ("Check ok")
else:
print("Not all check passed, please first check the RU and clock status")
|
normal
|
{
"blob_id": "603d904404ace88205a524d8bfbe3e621b65f425",
"index": 8750,
"step-1": "#!/usr/bin/python\nimport os\nfrom subprocess import Popen, PIPE, STDOUT\nimport time\nimport re\nimport telnetlib\nfrom get_sys_info import get_node_list, get_spec_node_list, get_active_tcu, get_ru_list, is_active_ru\ng_rg_list = [\n\t\t\t'/SGWNetMgr',\n\t\t\t'/SS7SGU',\n\t\t\t'/MGW_CMRG',\n\t\t\t'/MGW_OMURG',\n\t\t\t'/Directory',\n]\n\nstatus_dict={\n\t\"administrative\":\t\"UNLOCKED\",\n\t\"operational\":\t\t\"ENABLED\",\n\t\"usage\":\t\t\t\"ACTIVE\",\n\t\"procedural\":\t\t'',\n\t\"availability\":\t\t'',\n\t\"unknown\":\t\t\t\"FALSE\",\n\t\"alarm\":\t\t\t'',\n\t\"role\":\t\t\t\t\"ACTIVE\"\n}\n\ndef get_mo_status(mo_name):\n\tcmd = 'fshascli -s ' + mo_name\n\toutput = os.popen(cmd).readlines()\n\tmo_status = {}\n\tfor line in output:\n\t\tif len(line) > 1:\n\t\t\tp = re.compile(r'(\\S*)\\((\\S*)\\)')\n\t\t\tm = p.search(line)\n\t\t\tif m:\n\t\t\t\tmo_status[m.group(1)] = m.group(2)\n\treturn mo_status\n\n\ndef cmp_mo_status(mo_status):\n\tret = True\n\terror_info = ''\n\tfor k, v in mo_status.items():\n\t\tif k != 'role' and status_dict[k] != v :\n\t\t\terror_info = \" \" + k + \" should be \\\"\" + status_dict[k] + \"\\\" But is \\\"\" + v +\"\\\"\"\n\t\t\tret = False\n\t\t\treturn ret, error_info\n\treturn ret, error_info\n\ndef is_ru_active(mo_status):\n\treturn 'role' in mo_status and mo_status['role'] == 'ACTIVE'\n\n\t\ndef check_mo_status(mo_name, mo_status):\n\tstatus, error_info = cmp_mo_status(mo_status)\n\tif status:\n\t\tprint(\"%-40s OK\"%(mo_name))\n\telse:\n\t\tprint(\"%-40s NOK:\"%(mo_name))\n\t\tprint(error_info)\n\treturn status\n\t\t\n\ndef check_mo_list(ru_list):\n\tstatus = True\n\tfor ru in ru_list:\n\t\tmo_status = get_mo_status(ru)\n\t\tif is_ru_active(mo_status):\n\t\t\tstatus = check_mo_status(ru, mo_status) and status\n\treturn status\n\t\t\n\t\ndef check_rg_status(rg_name):\n#\tprint(\"start to check RG \" + rg_name + \" ...\")\n\tmo_status = get_mo_status(rg_name)\n\tstatus = check_mo_status(rg_name, mo_status)\n\n\tif status:\n\t\tru_list = get_ru_list(rg_name)\n\t\tif ru_list:\n\t\t\tstatus = check_mo_list(ru_list) and status\n\treturn status\n\n\ndef check_clock():\n\tcmd = 'fsclish -c \"show mgw synchronization inputreference\"'\n\tret = os.popen(cmd).read()\n\tprint(ret)\n\tr_list = ret.split()\n\tif 'yes' in r_list and 'ok' in r_list:\n\t\tprint(\"Clock is ok\")\n\t\treturn True\n\telse:\n\t\tprint \"=================================================================\"\n\t\tprint \"CLOCK IS NOT OK !!!\"\n\t\tprint \"=================================================================\"\n\t\treturn False\n\ndef is_needed_node_available(node_list):\n\tnum_tcu = 0\n\tnum_tdm = 0\n\tnum_cla = 1\n\tfor node in node_list:\n\t\tif node.startswith(\"TCU\"):\n\t\t\tnum_tcu += 1\n\t\tif node.startswith(\"TDM\"):\n\t\t\tnum_tdm += 1\n#\t\tif node.startswith(\"CLA\"):\n#\t\t\tnum_cla += 1\n\tif num_tcu == 0:\n\t\tprint \"No Working DSP available\"\n\tif num_tdm == 0:\n\t\tprint \"No Working TDM available\"\n\tif num_cla == 0:\n\t\tprint \"No Working CLA available\"\n\treturn num_tcu and num_cla and num_tdm\n\ndef check_needed_rg(rg_list):\n\tresult = True\n\tfor rg in rg_list:\n\t\tresult = check_rg_status(rg) and result\n\treturn result\n\t\ndef check_node():\n\tresult = True\n\tnode_list = get_node_list()\t\n\tif not is_needed_node_available(node_list):\n\t\tprint \"Please first make the node working!\"\n\t\treturn\n\tfor node in node_list:\n\t\tif not check_rg_status(\"/\"+node):\n\t\t\tresult = False\t\n\treturn result\n\ndef check_node_list(node_list):\n\tresult = True\n\tfor node in node_list:\n\t\tresult = check_rg_status(\"/\"+node) and result\n\treturn result\n\n\t\ndef check_all(node_list_all):\n\tret = True\n\tret = check_needed_rg(g_rg_list) and ret \n\tret = check_node_list(node_list_all) and ret\n\tret = check_clock() and ret \n\treturn ret\n\t\ndef check_for_link(node_list_all):\n\ttcu_list = get_spec_node_list(node_list_all, \"TCU\")\n\ttdm_list = get_spec_node_list(node_list_all, \"TDM\")\n\tactive_tcu_list = get_active_tcu(tcu_list)\n\tret = True\n\tret = check_node_list(tdm_list) and ret\n\tret = check_node_list(active_tcu_list) and ret\n\tret = check_needed_rg(g_rg_list) and ret\n\tcheck_clock()\n\treturn ret\n\n\nfrom optparse import OptionParser\n\nif __name__ == '__main__':\n usage = \"usage: %prog [options] arg\"\n parser = OptionParser(usage)\n parser.add_option(\"-a\", \"--all\",\n action=\"store_true\", dest=\"check_all_flag\",\n default=False)\n opts, args = parser.parse_args()\n node_list = get_node_list()\n ret = False\n if(opts.check_all_flag):\n\t ret = check_all(node_list)\n else:\n ret = check_for_link(node_list)\n#\t\tos.system('tail -f /srv/Log/log/syslog | grep srm')\n if ret:\n print (\"Check ok\")\n else:\n\t\tprint(\"Not all check passed, please first check the RU and clock status\")\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
class CourseSchedule:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CourseSchedule:
<|reserved_special_token_0|>
def can_finish(self, numCourses: int, prerequisites: List[List[int]]
) ->bool:
pre_map = {i: [] for i in range(numCourses)}
for crs, pre in prerequisites:
pre_map[crs].append(pre)
visited_set = set()
def dfs(crs):
if crs in visited_set:
return False
if pre_map[crs] == []:
return True
visited_set.add(crs)
for pre in pre_map[crs]:
if not dfs(pre):
return False
visited_set.remove(crs)
pre_map[crs] = []
return True
for crs in range(numCourses):
if not dfs(crs):
return False
return True
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CourseSchedule:
"""
Problem: Course Schedule (#207)
Key Insights:
1. Create adjaceny list of courses to prerequisites.
2. Use DFS and visited set to detect a cycle. If there is a cycle, cannot finish all the courses.
3. Remember to remove a course (node) from visited set if that course is "cleared" (able to take the course).
4. Note that this is not a cycle (so if don't remove node in step 3, would incorrectly identify this as a cycle):
1 -> 2 -> 3
2 -> 4 -> 3
More info:
1. Concept of Topological order: for an edge uv, u must always come before v (so no cycles where v also comes before u)
Time Complexity:
O(V + E):
1. Create pre_map: O(P), P: prerequisites
a. We're iterating through the list of prereqs
2. Call dfs: O(C), C: courses
a. We're iterating through all the courses once
3. dfs: O(V + E)
a. We visit each course and each edge at most once
Space Complexity: O(V + E)
1. Create pre_map: O(V + E), V: courses, E: prereqs
2. dfs call stack: O(V + E)
"""
def can_finish(self, numCourses: int, prerequisites: List[List[int]]
) ->bool:
pre_map = {i: [] for i in range(numCourses)}
for crs, pre in prerequisites:
pre_map[crs].append(pre)
visited_set = set()
def dfs(crs):
if crs in visited_set:
return False
if pre_map[crs] == []:
return True
visited_set.add(crs)
for pre in pre_map[crs]:
if not dfs(pre):
return False
visited_set.remove(crs)
pre_map[crs] = []
return True
for crs in range(numCourses):
if not dfs(crs):
return False
return True
<|reserved_special_token_1|>
from typing import List
class CourseSchedule:
"""
Problem: Course Schedule (#207)
Key Insights:
1. Create adjaceny list of courses to prerequisites.
2. Use DFS and visited set to detect a cycle. If there is a cycle, cannot finish all the courses.
3. Remember to remove a course (node) from visited set if that course is "cleared" (able to take the course).
4. Note that this is not a cycle (so if don't remove node in step 3, would incorrectly identify this as a cycle):
1 -> 2 -> 3
2 -> 4 -> 3
More info:
1. Concept of Topological order: for an edge uv, u must always come before v (so no cycles where v also comes before u)
Time Complexity:
O(V + E):
1. Create pre_map: O(P), P: prerequisites
a. We're iterating through the list of prereqs
2. Call dfs: O(C), C: courses
a. We're iterating through all the courses once
3. dfs: O(V + E)
a. We visit each course and each edge at most once
Space Complexity: O(V + E)
1. Create pre_map: O(V + E), V: courses, E: prereqs
2. dfs call stack: O(V + E)
"""
def can_finish(self, numCourses: int, prerequisites: List[List[int]]
) ->bool:
pre_map = {i: [] for i in range(numCourses)}
for crs, pre in prerequisites:
pre_map[crs].append(pre)
visited_set = set()
def dfs(crs):
if crs in visited_set:
return False
if pre_map[crs] == []:
return True
visited_set.add(crs)
for pre in pre_map[crs]:
if not dfs(pre):
return False
visited_set.remove(crs)
pre_map[crs] = []
return True
for crs in range(numCourses):
if not dfs(crs):
return False
return True
|
flexible
|
{
"blob_id": "7c53c7bec6b6b2d4d6be89b750eeef83ca9115cc",
"index": 2960,
"step-1": "<mask token>\n\n\nclass CourseSchedule:\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass CourseSchedule:\n <mask token>\n\n def can_finish(self, numCourses: int, prerequisites: List[List[int]]\n ) ->bool:\n pre_map = {i: [] for i in range(numCourses)}\n for crs, pre in prerequisites:\n pre_map[crs].append(pre)\n visited_set = set()\n\n def dfs(crs):\n if crs in visited_set:\n return False\n if pre_map[crs] == []:\n return True\n visited_set.add(crs)\n for pre in pre_map[crs]:\n if not dfs(pre):\n return False\n visited_set.remove(crs)\n pre_map[crs] = []\n return True\n for crs in range(numCourses):\n if not dfs(crs):\n return False\n return True\n",
"step-3": "<mask token>\n\n\nclass CourseSchedule:\n \"\"\"\n Problem: Course Schedule (#207)\n Key Insights:\n 1. Create adjaceny list of courses to prerequisites.\n 2. Use DFS and visited set to detect a cycle. If there is a cycle, cannot finish all the courses.\n 3. Remember to remove a course (node) from visited set if that course is \"cleared\" (able to take the course). \n 4. Note that this is not a cycle (so if don't remove node in step 3, would incorrectly identify this as a cycle):\n 1 -> 2 -> 3 \n 2 -> 4 -> 3 \n More info: \n 1. Concept of Topological order: for an edge uv, u must always come before v (so no cycles where v also comes before u)\n\n Time Complexity:\n O(V + E):\n 1. Create pre_map: O(P), P: prerequisites\n a. We're iterating through the list of prereqs \n 2. Call dfs: O(C), C: courses\n a. We're iterating through all the courses once \n 3. dfs: O(V + E)\n a. We visit each course and each edge at most once\n\n Space Complexity: O(V + E)\n 1. Create pre_map: O(V + E), V: courses, E: prereqs\n 2. dfs call stack: O(V + E) \n \"\"\"\n\n def can_finish(self, numCourses: int, prerequisites: List[List[int]]\n ) ->bool:\n pre_map = {i: [] for i in range(numCourses)}\n for crs, pre in prerequisites:\n pre_map[crs].append(pre)\n visited_set = set()\n\n def dfs(crs):\n if crs in visited_set:\n return False\n if pre_map[crs] == []:\n return True\n visited_set.add(crs)\n for pre in pre_map[crs]:\n if not dfs(pre):\n return False\n visited_set.remove(crs)\n pre_map[crs] = []\n return True\n for crs in range(numCourses):\n if not dfs(crs):\n return False\n return True\n",
"step-4": "from typing import List\n\n\nclass CourseSchedule:\n \"\"\"\n Problem: Course Schedule (#207)\n Key Insights:\n 1. Create adjaceny list of courses to prerequisites.\n 2. Use DFS and visited set to detect a cycle. If there is a cycle, cannot finish all the courses.\n 3. Remember to remove a course (node) from visited set if that course is \"cleared\" (able to take the course). \n 4. Note that this is not a cycle (so if don't remove node in step 3, would incorrectly identify this as a cycle):\n 1 -> 2 -> 3 \n 2 -> 4 -> 3 \n More info: \n 1. Concept of Topological order: for an edge uv, u must always come before v (so no cycles where v also comes before u)\n\n Time Complexity:\n O(V + E):\n 1. Create pre_map: O(P), P: prerequisites\n a. We're iterating through the list of prereqs \n 2. Call dfs: O(C), C: courses\n a. We're iterating through all the courses once \n 3. dfs: O(V + E)\n a. We visit each course and each edge at most once\n\n Space Complexity: O(V + E)\n 1. Create pre_map: O(V + E), V: courses, E: prereqs\n 2. dfs call stack: O(V + E) \n \"\"\"\n\n def can_finish(self, numCourses: int, prerequisites: List[List[int]]\n ) ->bool:\n pre_map = {i: [] for i in range(numCourses)}\n for crs, pre in prerequisites:\n pre_map[crs].append(pre)\n visited_set = set()\n\n def dfs(crs):\n if crs in visited_set:\n return False\n if pre_map[crs] == []:\n return True\n visited_set.add(crs)\n for pre in pre_map[crs]:\n if not dfs(pre):\n return False\n visited_set.remove(crs)\n pre_map[crs] = []\n return True\n for crs in range(numCourses):\n if not dfs(crs):\n return False\n return True\n",
"step-5": null,
"step-ids": [
1,
2,
3,
4
]
}
|
[
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def read_modified_alert_ids():
""" Read modified alert IDs from file, then remove them from the file."""
if not os.path.exists(MODIFIED_ALERTS_FILE):
return []
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
fp = open(MODIFIED_ALERTS_FILE, 'r+')
ids = fp.read().split('\n')
ids = filter(len, ids)
ids = list(map(int, ids))
ids = list(set(ids))
fp.close()
lock.release()
return ids
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def read_modified_alert_ids():
""" Read modified alert IDs from file, then remove them from the file."""
if not os.path.exists(MODIFIED_ALERTS_FILE):
return []
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
fp = open(MODIFIED_ALERTS_FILE, 'r+')
ids = fp.read().split('\n')
ids = filter(len, ids)
ids = list(map(int, ids))
ids = list(set(ids))
fp.close()
lock.release()
return ids
def write_modified_alert_ids(ids):
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
fp = open(MODIFIED_ALERTS_FILE, 'a')
for alert_id in ids:
fp.write(str(alert_id) + '\n')
fp.close()
lock.release()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
MODIFIED_ALERTS_FILE = '/tmp/alert_triage_modified_alerts'
def read_modified_alert_ids():
""" Read modified alert IDs from file, then remove them from the file."""
if not os.path.exists(MODIFIED_ALERTS_FILE):
return []
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
fp = open(MODIFIED_ALERTS_FILE, 'r+')
ids = fp.read().split('\n')
ids = filter(len, ids)
ids = list(map(int, ids))
ids = list(set(ids))
fp.close()
lock.release()
return ids
def write_modified_alert_ids(ids):
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
fp = open(MODIFIED_ALERTS_FILE, 'a')
for alert_id in ids:
fp.write(str(alert_id) + '\n')
fp.close()
lock.release()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import os
from alert_triage.util import filelock
MODIFIED_ALERTS_FILE = '/tmp/alert_triage_modified_alerts'
def read_modified_alert_ids():
""" Read modified alert IDs from file, then remove them from the file."""
if not os.path.exists(MODIFIED_ALERTS_FILE):
return []
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
fp = open(MODIFIED_ALERTS_FILE, 'r+')
ids = fp.read().split('\n')
ids = filter(len, ids)
ids = list(map(int, ids))
ids = list(set(ids))
fp.close()
lock.release()
return ids
def write_modified_alert_ids(ids):
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
fp = open(MODIFIED_ALERTS_FILE, 'a')
for alert_id in ids:
fp.write(str(alert_id) + '\n')
fp.close()
lock.release()
<|reserved_special_token_1|>
"""
"""
import os
from alert_triage.util import filelock
MODIFIED_ALERTS_FILE = "/tmp/alert_triage_modified_alerts"
def read_modified_alert_ids():
""" Read modified alert IDs from file, then remove them from the file."""
# Return an empty list if the file doesn't exist.
if not os.path.exists(MODIFIED_ALERTS_FILE):
return []
# Get a lock on the file
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
# Open the file and read in the data.
fp = open(MODIFIED_ALERTS_FILE, "r+")
ids = fp.read().split("\n")
# remove zero length strings
ids = filter(len, ids)
# convert IDs to int
ids = list(map(int, ids))
# remove duplicates
ids = list(set(ids))
# close and remove the file
fp.close()
#TODO: uncomment when live
#os.unlink(MODIFIED_ALERTS_FILE)
# Release the lock.
lock.release()
return ids
def write_modified_alert_ids(ids):
# Get a lock on the file
lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)
lock.acquire()
# Open the file and write the alert IDs.
fp = open(MODIFIED_ALERTS_FILE, "a")
for alert_id in ids:
fp.write(str(alert_id) + "\n")
fp.close()
# Release the lock.
lock.release()
|
flexible
|
{
"blob_id": "90ae14d8af163343520365a5565a7c44de57059d",
"index": 5662,
"step-1": "<mask token>\n\n\ndef read_modified_alert_ids():\n \"\"\" Read modified alert IDs from file, then remove them from the file.\"\"\"\n if not os.path.exists(MODIFIED_ALERTS_FILE):\n return []\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n fp = open(MODIFIED_ALERTS_FILE, 'r+')\n ids = fp.read().split('\\n')\n ids = filter(len, ids)\n ids = list(map(int, ids))\n ids = list(set(ids))\n fp.close()\n lock.release()\n return ids\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef read_modified_alert_ids():\n \"\"\" Read modified alert IDs from file, then remove them from the file.\"\"\"\n if not os.path.exists(MODIFIED_ALERTS_FILE):\n return []\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n fp = open(MODIFIED_ALERTS_FILE, 'r+')\n ids = fp.read().split('\\n')\n ids = filter(len, ids)\n ids = list(map(int, ids))\n ids = list(set(ids))\n fp.close()\n lock.release()\n return ids\n\n\ndef write_modified_alert_ids(ids):\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n fp = open(MODIFIED_ALERTS_FILE, 'a')\n for alert_id in ids:\n fp.write(str(alert_id) + '\\n')\n fp.close()\n lock.release()\n",
"step-3": "<mask token>\nMODIFIED_ALERTS_FILE = '/tmp/alert_triage_modified_alerts'\n\n\ndef read_modified_alert_ids():\n \"\"\" Read modified alert IDs from file, then remove them from the file.\"\"\"\n if not os.path.exists(MODIFIED_ALERTS_FILE):\n return []\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n fp = open(MODIFIED_ALERTS_FILE, 'r+')\n ids = fp.read().split('\\n')\n ids = filter(len, ids)\n ids = list(map(int, ids))\n ids = list(set(ids))\n fp.close()\n lock.release()\n return ids\n\n\ndef write_modified_alert_ids(ids):\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n fp = open(MODIFIED_ALERTS_FILE, 'a')\n for alert_id in ids:\n fp.write(str(alert_id) + '\\n')\n fp.close()\n lock.release()\n",
"step-4": "<mask token>\nimport os\nfrom alert_triage.util import filelock\nMODIFIED_ALERTS_FILE = '/tmp/alert_triage_modified_alerts'\n\n\ndef read_modified_alert_ids():\n \"\"\" Read modified alert IDs from file, then remove them from the file.\"\"\"\n if not os.path.exists(MODIFIED_ALERTS_FILE):\n return []\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n fp = open(MODIFIED_ALERTS_FILE, 'r+')\n ids = fp.read().split('\\n')\n ids = filter(len, ids)\n ids = list(map(int, ids))\n ids = list(set(ids))\n fp.close()\n lock.release()\n return ids\n\n\ndef write_modified_alert_ids(ids):\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n fp = open(MODIFIED_ALERTS_FILE, 'a')\n for alert_id in ids:\n fp.write(str(alert_id) + '\\n')\n fp.close()\n lock.release()\n",
"step-5": "\"\"\"\n\"\"\"\n\nimport os\n\nfrom alert_triage.util import filelock\n\nMODIFIED_ALERTS_FILE = \"/tmp/alert_triage_modified_alerts\"\n\ndef read_modified_alert_ids():\n \"\"\" Read modified alert IDs from file, then remove them from the file.\"\"\"\n # Return an empty list if the file doesn't exist.\n if not os.path.exists(MODIFIED_ALERTS_FILE):\n return []\n # Get a lock on the file\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n # Open the file and read in the data.\n fp = open(MODIFIED_ALERTS_FILE, \"r+\")\n ids = fp.read().split(\"\\n\")\n # remove zero length strings\n ids = filter(len, ids)\n # convert IDs to int\n ids = list(map(int, ids))\n # remove duplicates\n ids = list(set(ids))\n # close and remove the file\n fp.close()\n #TODO: uncomment when live\n #os.unlink(MODIFIED_ALERTS_FILE)\n # Release the lock.\n lock.release()\n return ids\n\ndef write_modified_alert_ids(ids):\n # Get a lock on the file\n lock = filelock.FileLock(MODIFIED_ALERTS_FILE, 5)\n lock.acquire()\n # Open the file and write the alert IDs.\n fp = open(MODIFIED_ALERTS_FILE, \"a\")\n for alert_id in ids:\n fp.write(str(alert_id) + \"\\n\")\n fp.close()\n # Release the lock.\n lock.release()\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class GerenciaLedsConfig(AppConfig):
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class GerenciaLedsConfig(AppConfig):
name = 'gerencia_leds'
<|reserved_special_token_1|>
from django.apps import AppConfig
class GerenciaLedsConfig(AppConfig):
name = 'gerencia_leds'
|
flexible
|
{
"blob_id": "0754103c2d8cef0fd23b03a8f64ade8f049bce48",
"index": 4890,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass GerenciaLedsConfig(AppConfig):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass GerenciaLedsConfig(AppConfig):\n name = 'gerencia_leds'\n",
"step-4": "from django.apps import AppConfig\n\n\nclass GerenciaLedsConfig(AppConfig):\n name = 'gerencia_leds'\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
# using python3
class Rational:
def __init__(self, numer, denom):
self.numer = numer
self.denom = denom
def __add__(self, other):
return Rational(
self.numer * other.denom + other.numer * self.denom,
self.denom * other.denom
)
def __sub__(self, other):
return Rational(
self.numer * other.denom - other.numer * self.denom,
self.denom * other.denom
)
def __mul__(self, other):
return Rational(
self.numer * other.numer,
self.denom * other.denom
)
def __truediv__(self, other):
return Rational(
self.numer * other.denom,
self.denom * other.numer
)
def __str__(self):
return "{numer}/{denom}".format(
numer=self.numer, denom=self.denom
)
def __repr__(self):
return "Rational({numer}/{denom})".format(
numer=self.numer, denom=self.denom
)
|
normal
|
{
"blob_id": "8098b9c27689dd4168ef05c03d4ec00f67f8090e",
"index": 4771,
"step-1": "class Rational:\n\n def __init__(self, numer, denom):\n self.numer = numer\n self.denom = denom\n <mask token>\n <mask token>\n\n def __mul__(self, other):\n return Rational(self.numer * other.numer, self.denom * other.denom)\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class Rational:\n\n def __init__(self, numer, denom):\n self.numer = numer\n self.denom = denom\n <mask token>\n\n def __sub__(self, other):\n return Rational(self.numer * other.denom - other.numer * self.denom,\n self.denom * other.denom)\n\n def __mul__(self, other):\n return Rational(self.numer * other.numer, self.denom * other.denom)\n\n def __truediv__(self, other):\n return Rational(self.numer * other.denom, self.denom * other.numer)\n <mask token>\n\n def __repr__(self):\n return 'Rational({numer}/{denom})'.format(numer=self.numer, denom=\n self.denom)\n",
"step-3": "class Rational:\n\n def __init__(self, numer, denom):\n self.numer = numer\n self.denom = denom\n <mask token>\n\n def __sub__(self, other):\n return Rational(self.numer * other.denom - other.numer * self.denom,\n self.denom * other.denom)\n\n def __mul__(self, other):\n return Rational(self.numer * other.numer, self.denom * other.denom)\n\n def __truediv__(self, other):\n return Rational(self.numer * other.denom, self.denom * other.numer)\n\n def __str__(self):\n return '{numer}/{denom}'.format(numer=self.numer, denom=self.denom)\n\n def __repr__(self):\n return 'Rational({numer}/{denom})'.format(numer=self.numer, denom=\n self.denom)\n",
"step-4": "class Rational:\n\n def __init__(self, numer, denom):\n self.numer = numer\n self.denom = denom\n\n def __add__(self, other):\n return Rational(self.numer * other.denom + other.numer * self.denom,\n self.denom * other.denom)\n\n def __sub__(self, other):\n return Rational(self.numer * other.denom - other.numer * self.denom,\n self.denom * other.denom)\n\n def __mul__(self, other):\n return Rational(self.numer * other.numer, self.denom * other.denom)\n\n def __truediv__(self, other):\n return Rational(self.numer * other.denom, self.denom * other.numer)\n\n def __str__(self):\n return '{numer}/{denom}'.format(numer=self.numer, denom=self.denom)\n\n def __repr__(self):\n return 'Rational({numer}/{denom})'.format(numer=self.numer, denom=\n self.denom)\n",
"step-5": "# using python3\n\n\nclass Rational:\n def __init__(self, numer, denom):\n self.numer = numer\n self.denom = denom\n\n def __add__(self, other):\n return Rational(\n self.numer * other.denom + other.numer * self.denom,\n self.denom * other.denom\n )\n\n def __sub__(self, other):\n return Rational(\n self.numer * other.denom - other.numer * self.denom,\n self.denom * other.denom\n )\n\n def __mul__(self, other):\n return Rational(\n self.numer * other.numer,\n self.denom * other.denom\n )\n\n def __truediv__(self, other):\n return Rational(\n self.numer * other.denom,\n self.denom * other.numer\n )\n\n def __str__(self):\n return \"{numer}/{denom}\".format(\n numer=self.numer, denom=self.denom\n )\n\n def __repr__(self):\n return \"Rational({numer}/{denom})\".format(\n numer=self.numer, denom=self.denom\n )\n\n",
"step-ids": [
3,
6,
7,
8,
9
]
}
|
[
3,
6,
7,
8,
9
] |
<|reserved_special_token_0|>
def best_hits(distf, maxscore, verbose=False):
"""
Find the best hits
"""
bh = {}
allph = set()
with open(distf, 'r') as din:
for li in din:
p = li.strip().split('\t')
if float(p[3]) <= maxscore:
if p[0] not in bh:
bh[p[0]] = set()
bh[p[0]].add(p[1])
allph.add(p[0])
if verbose:
for p in allph:
if p not in bh:
sys.stderr.write(
f"""WARNING: With a score of {maxscore} did not find any hits to {p}
"""
)
return bh
def find_vc(mdf, genomecol, vccol, verbose=False):
"""
Read the metadata file and return a hash of genome->viral cluster
"""
vc = {}
with open(mdf, 'r') as fin:
for li in fin:
p = li.strip().split('\t')
vc[p[genomecol]] = p[vccol]
if verbose:
sys.stderr.write(f'Found {len(vc)} virus clusters in {mdf}\n')
return vc
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def best_hits(distf, maxscore, verbose=False):
"""
Find the best hits
"""
bh = {}
allph = set()
with open(distf, 'r') as din:
for li in din:
p = li.strip().split('\t')
if float(p[3]) <= maxscore:
if p[0] not in bh:
bh[p[0]] = set()
bh[p[0]].add(p[1])
allph.add(p[0])
if verbose:
for p in allph:
if p not in bh:
sys.stderr.write(
f"""WARNING: With a score of {maxscore} did not find any hits to {p}
"""
)
return bh
def find_vc(mdf, genomecol, vccol, verbose=False):
"""
Read the metadata file and return a hash of genome->viral cluster
"""
vc = {}
with open(mdf, 'r') as fin:
for li in fin:
p = li.strip().split('\t')
vc[p[genomecol]] = p[vccol]
if verbose:
sys.stderr.write(f'Found {len(vc)} virus clusters in {mdf}\n')
return vc
def count_hits(bh, vc, verbose=False):
"""
Count the vc hits per genome
"""
hc = {}
for g in bh:
hc[g] = {}
for b in bh[g]:
hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1
besthit = None
bhc = 0
for h in hc[g]:
if hc[g][h] > bhc:
bhc = hc[g][h]
besthit = h
print(f'{g}\t{besthit}')
return hc
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def best_hits(distf, maxscore, verbose=False):
"""
Find the best hits
"""
bh = {}
allph = set()
with open(distf, 'r') as din:
for li in din:
p = li.strip().split('\t')
if float(p[3]) <= maxscore:
if p[0] not in bh:
bh[p[0]] = set()
bh[p[0]].add(p[1])
allph.add(p[0])
if verbose:
for p in allph:
if p not in bh:
sys.stderr.write(
f"""WARNING: With a score of {maxscore} did not find any hits to {p}
"""
)
return bh
def find_vc(mdf, genomecol, vccol, verbose=False):
"""
Read the metadata file and return a hash of genome->viral cluster
"""
vc = {}
with open(mdf, 'r') as fin:
for li in fin:
p = li.strip().split('\t')
vc[p[genomecol]] = p[vccol]
if verbose:
sys.stderr.write(f'Found {len(vc)} virus clusters in {mdf}\n')
return vc
def count_hits(bh, vc, verbose=False):
"""
Count the vc hits per genome
"""
hc = {}
for g in bh:
hc[g] = {}
for b in bh[g]:
hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1
besthit = None
bhc = 0
for h in hc[g]:
if hc[g][h] > bhc:
bhc = hc[g][h]
besthit = h
print(f'{g}\t{besthit}')
return hc
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=' ')
parser.add_argument('-d', help='mash distance file', required=True)
parser.add_argument('-c', help='distance cutoff score, default = 0',
default=0, type=float)
parser.add_argument('-m', help='metadata file', required=True)
parser.add_argument('-g', help='genome column, default = 0', default=0,
type=int)
parser.add_argument('-l', help='virus cluster col in the metadata file',
type=int, required=True)
parser.add_argument('-v', help='verbose output', action='store_true')
args = parser.parse_args()
bh = best_hits(args.d, args.c, args.v)
vc = find_vc(args.m, args.g, args.l, args.v)
count_hits(bh, vc, args.v)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import os
import sys
import argparse
def best_hits(distf, maxscore, verbose=False):
"""
Find the best hits
"""
bh = {}
allph = set()
with open(distf, 'r') as din:
for li in din:
p = li.strip().split('\t')
if float(p[3]) <= maxscore:
if p[0] not in bh:
bh[p[0]] = set()
bh[p[0]].add(p[1])
allph.add(p[0])
if verbose:
for p in allph:
if p not in bh:
sys.stderr.write(
f"""WARNING: With a score of {maxscore} did not find any hits to {p}
"""
)
return bh
def find_vc(mdf, genomecol, vccol, verbose=False):
"""
Read the metadata file and return a hash of genome->viral cluster
"""
vc = {}
with open(mdf, 'r') as fin:
for li in fin:
p = li.strip().split('\t')
vc[p[genomecol]] = p[vccol]
if verbose:
sys.stderr.write(f'Found {len(vc)} virus clusters in {mdf}\n')
return vc
def count_hits(bh, vc, verbose=False):
"""
Count the vc hits per genome
"""
hc = {}
for g in bh:
hc[g] = {}
for b in bh[g]:
hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1
besthit = None
bhc = 0
for h in hc[g]:
if hc[g][h] > bhc:
bhc = hc[g][h]
besthit = h
print(f'{g}\t{besthit}')
return hc
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=' ')
parser.add_argument('-d', help='mash distance file', required=True)
parser.add_argument('-c', help='distance cutoff score, default = 0',
default=0, type=float)
parser.add_argument('-m', help='metadata file', required=True)
parser.add_argument('-g', help='genome column, default = 0', default=0,
type=int)
parser.add_argument('-l', help='virus cluster col in the metadata file',
type=int, required=True)
parser.add_argument('-v', help='verbose output', action='store_true')
args = parser.parse_args()
bh = best_hits(args.d, args.c, args.v)
vc = find_vc(args.m, args.g, args.l, args.v)
count_hits(bh, vc, args.v)
<|reserved_special_token_1|>
"""
We have created mash sketches of the GPDB database, the MGV database, and the SDSU phage, and
this will figure out the top hits and summarize their familes.
"""
import os
import sys
import argparse
def best_hits(distf, maxscore, verbose=False):
"""
Find the best hits
"""
bh = {}
allph = set()
with open(distf, 'r') as din:
for li in din:
p = li.strip().split("\t")
if float(p[3]) <= maxscore:
if p[0] not in bh:
bh[p[0]] = set()
bh[p[0]].add(p[1])
allph.add(p[0])
if verbose:
for p in allph:
if p not in bh:
sys.stderr.write(f"WARNING: With a score of {maxscore} did not find any hits to {p}\n")
return bh
def find_vc(mdf, genomecol, vccol, verbose=False):
"""
Read the metadata file and return a hash of genome->viral cluster
"""
vc = {}
with open(mdf, 'r') as fin:
for li in fin:
p = li.strip().split("\t")
vc[p[genomecol]] = p[vccol]
if verbose:
sys.stderr.write(f"Found {len(vc)} virus clusters in {mdf}\n")
return vc
def count_hits(bh, vc, verbose=False):
"""
Count the vc hits per genome
"""
hc = {}
for g in bh:
hc[g] = {}
for b in bh[g]:
hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1
besthit = None
bhc = 0
for h in hc[g]:
if hc[g][h] > bhc:
bhc = hc[g][h]
besthit = h
#print(f"{g}\t{besthit}\t{bhc}\t{len(bh[g])}")
print(f"{g}\t{besthit}")
return hc
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=' ')
parser.add_argument('-d', help='mash distance file', required=True)
parser.add_argument('-c', help='distance cutoff score, default = 0', default=0, type=float)
parser.add_argument('-m', help='metadata file', required=True)
parser.add_argument('-g', help='genome column, default = 0', default=0, type=int)
parser.add_argument('-l', help='virus cluster col in the metadata file', type=int, required=True)
parser.add_argument('-v', help='verbose output', action='store_true')
args = parser.parse_args()
bh = best_hits(args.d, args.c, args.v)
vc = find_vc(args.m, args.g, args.l, args.v)
count_hits(bh, vc,args.v)
|
flexible
|
{
"blob_id": "22523304c9e2ce1339a7527cdbd67a81c780d806",
"index": 1090,
"step-1": "<mask token>\n\n\ndef best_hits(distf, maxscore, verbose=False):\n \"\"\"\n Find the best hits\n \"\"\"\n bh = {}\n allph = set()\n with open(distf, 'r') as din:\n for li in din:\n p = li.strip().split('\\t')\n if float(p[3]) <= maxscore:\n if p[0] not in bh:\n bh[p[0]] = set()\n bh[p[0]].add(p[1])\n allph.add(p[0])\n if verbose:\n for p in allph:\n if p not in bh:\n sys.stderr.write(\n f\"\"\"WARNING: With a score of {maxscore} did not find any hits to {p}\n\"\"\"\n )\n return bh\n\n\ndef find_vc(mdf, genomecol, vccol, verbose=False):\n \"\"\"\n Read the metadata file and return a hash of genome->viral cluster\n \"\"\"\n vc = {}\n with open(mdf, 'r') as fin:\n for li in fin:\n p = li.strip().split('\\t')\n vc[p[genomecol]] = p[vccol]\n if verbose:\n sys.stderr.write(f'Found {len(vc)} virus clusters in {mdf}\\n')\n return vc\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef best_hits(distf, maxscore, verbose=False):\n \"\"\"\n Find the best hits\n \"\"\"\n bh = {}\n allph = set()\n with open(distf, 'r') as din:\n for li in din:\n p = li.strip().split('\\t')\n if float(p[3]) <= maxscore:\n if p[0] not in bh:\n bh[p[0]] = set()\n bh[p[0]].add(p[1])\n allph.add(p[0])\n if verbose:\n for p in allph:\n if p not in bh:\n sys.stderr.write(\n f\"\"\"WARNING: With a score of {maxscore} did not find any hits to {p}\n\"\"\"\n )\n return bh\n\n\ndef find_vc(mdf, genomecol, vccol, verbose=False):\n \"\"\"\n Read the metadata file and return a hash of genome->viral cluster\n \"\"\"\n vc = {}\n with open(mdf, 'r') as fin:\n for li in fin:\n p = li.strip().split('\\t')\n vc[p[genomecol]] = p[vccol]\n if verbose:\n sys.stderr.write(f'Found {len(vc)} virus clusters in {mdf}\\n')\n return vc\n\n\ndef count_hits(bh, vc, verbose=False):\n \"\"\"\n Count the vc hits per genome\n \"\"\"\n hc = {}\n for g in bh:\n hc[g] = {}\n for b in bh[g]:\n hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1\n besthit = None\n bhc = 0\n for h in hc[g]:\n if hc[g][h] > bhc:\n bhc = hc[g][h]\n besthit = h\n print(f'{g}\\t{besthit}')\n return hc\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef best_hits(distf, maxscore, verbose=False):\n \"\"\"\n Find the best hits\n \"\"\"\n bh = {}\n allph = set()\n with open(distf, 'r') as din:\n for li in din:\n p = li.strip().split('\\t')\n if float(p[3]) <= maxscore:\n if p[0] not in bh:\n bh[p[0]] = set()\n bh[p[0]].add(p[1])\n allph.add(p[0])\n if verbose:\n for p in allph:\n if p not in bh:\n sys.stderr.write(\n f\"\"\"WARNING: With a score of {maxscore} did not find any hits to {p}\n\"\"\"\n )\n return bh\n\n\ndef find_vc(mdf, genomecol, vccol, verbose=False):\n \"\"\"\n Read the metadata file and return a hash of genome->viral cluster\n \"\"\"\n vc = {}\n with open(mdf, 'r') as fin:\n for li in fin:\n p = li.strip().split('\\t')\n vc[p[genomecol]] = p[vccol]\n if verbose:\n sys.stderr.write(f'Found {len(vc)} virus clusters in {mdf}\\n')\n return vc\n\n\ndef count_hits(bh, vc, verbose=False):\n \"\"\"\n Count the vc hits per genome\n \"\"\"\n hc = {}\n for g in bh:\n hc[g] = {}\n for b in bh[g]:\n hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1\n besthit = None\n bhc = 0\n for h in hc[g]:\n if hc[g][h] > bhc:\n bhc = hc[g][h]\n besthit = h\n print(f'{g}\\t{besthit}')\n return hc\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=' ')\n parser.add_argument('-d', help='mash distance file', required=True)\n parser.add_argument('-c', help='distance cutoff score, default = 0',\n default=0, type=float)\n parser.add_argument('-m', help='metadata file', required=True)\n parser.add_argument('-g', help='genome column, default = 0', default=0,\n type=int)\n parser.add_argument('-l', help='virus cluster col in the metadata file',\n type=int, required=True)\n parser.add_argument('-v', help='verbose output', action='store_true')\n args = parser.parse_args()\n bh = best_hits(args.d, args.c, args.v)\n vc = find_vc(args.m, args.g, args.l, args.v)\n count_hits(bh, vc, args.v)\n",
"step-4": "<mask token>\nimport os\nimport sys\nimport argparse\n\n\ndef best_hits(distf, maxscore, verbose=False):\n \"\"\"\n Find the best hits\n \"\"\"\n bh = {}\n allph = set()\n with open(distf, 'r') as din:\n for li in din:\n p = li.strip().split('\\t')\n if float(p[3]) <= maxscore:\n if p[0] not in bh:\n bh[p[0]] = set()\n bh[p[0]].add(p[1])\n allph.add(p[0])\n if verbose:\n for p in allph:\n if p not in bh:\n sys.stderr.write(\n f\"\"\"WARNING: With a score of {maxscore} did not find any hits to {p}\n\"\"\"\n )\n return bh\n\n\ndef find_vc(mdf, genomecol, vccol, verbose=False):\n \"\"\"\n Read the metadata file and return a hash of genome->viral cluster\n \"\"\"\n vc = {}\n with open(mdf, 'r') as fin:\n for li in fin:\n p = li.strip().split('\\t')\n vc[p[genomecol]] = p[vccol]\n if verbose:\n sys.stderr.write(f'Found {len(vc)} virus clusters in {mdf}\\n')\n return vc\n\n\ndef count_hits(bh, vc, verbose=False):\n \"\"\"\n Count the vc hits per genome\n \"\"\"\n hc = {}\n for g in bh:\n hc[g] = {}\n for b in bh[g]:\n hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1\n besthit = None\n bhc = 0\n for h in hc[g]:\n if hc[g][h] > bhc:\n bhc = hc[g][h]\n besthit = h\n print(f'{g}\\t{besthit}')\n return hc\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=' ')\n parser.add_argument('-d', help='mash distance file', required=True)\n parser.add_argument('-c', help='distance cutoff score, default = 0',\n default=0, type=float)\n parser.add_argument('-m', help='metadata file', required=True)\n parser.add_argument('-g', help='genome column, default = 0', default=0,\n type=int)\n parser.add_argument('-l', help='virus cluster col in the metadata file',\n type=int, required=True)\n parser.add_argument('-v', help='verbose output', action='store_true')\n args = parser.parse_args()\n bh = best_hits(args.d, args.c, args.v)\n vc = find_vc(args.m, args.g, args.l, args.v)\n count_hits(bh, vc, args.v)\n",
"step-5": "\"\"\"\nWe have created mash sketches of the GPDB database, the MGV database, and the SDSU phage, and\nthis will figure out the top hits and summarize their familes.\n\"\"\"\n\nimport os\nimport sys\nimport argparse\n\n\ndef best_hits(distf, maxscore, verbose=False):\n \"\"\"\n Find the best hits\n \"\"\"\n bh = {}\n allph = set()\n with open(distf, 'r') as din:\n for li in din:\n p = li.strip().split(\"\\t\")\n if float(p[3]) <= maxscore:\n if p[0] not in bh:\n bh[p[0]] = set()\n bh[p[0]].add(p[1])\n allph.add(p[0])\n\n if verbose:\n for p in allph:\n if p not in bh:\n sys.stderr.write(f\"WARNING: With a score of {maxscore} did not find any hits to {p}\\n\")\n return bh\n\ndef find_vc(mdf, genomecol, vccol, verbose=False):\n \"\"\"\n Read the metadata file and return a hash of genome->viral cluster\n \"\"\"\n vc = {}\n with open(mdf, 'r') as fin:\n for li in fin:\n p = li.strip().split(\"\\t\")\n vc[p[genomecol]] = p[vccol]\n if verbose:\n sys.stderr.write(f\"Found {len(vc)} virus clusters in {mdf}\\n\")\n return vc\n\n\ndef count_hits(bh, vc, verbose=False):\n \"\"\"\n Count the vc hits per genome\n \"\"\"\n\n hc = {}\n for g in bh:\n hc[g] = {}\n for b in bh[g]:\n hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1\n besthit = None\n bhc = 0\n for h in hc[g]:\n if hc[g][h] > bhc:\n bhc = hc[g][h]\n besthit = h\n #print(f\"{g}\\t{besthit}\\t{bhc}\\t{len(bh[g])}\")\n print(f\"{g}\\t{besthit}\")\n\n return hc\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=' ')\n parser.add_argument('-d', help='mash distance file', required=True)\n parser.add_argument('-c', help='distance cutoff score, default = 0', default=0, type=float)\n parser.add_argument('-m', help='metadata file', required=True)\n parser.add_argument('-g', help='genome column, default = 0', default=0, type=int)\n parser.add_argument('-l', help='virus cluster col in the metadata file', type=int, required=True)\n parser.add_argument('-v', help='verbose output', action='store_true')\n args = parser.parse_args()\n\n bh = best_hits(args.d, args.c, args.v)\n vc = find_vc(args.m, args.g, args.l, args.v)\n count_hits(bh, vc,args.v)\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]
self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=
LabelVocabulary.PADDING)
self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,
0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3,
0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)
self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)
self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8,
0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4,
0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)
self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6
], dtype=torch.float)
self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4
], dtype=torch.float)
self.crf = ConditionalRandomField(5)
self.crf.transitions = torch.nn.Parameter(self.transitions)
self.crf.start_transitions = torch.nn.Parameter(self.
transitions_from_start)
self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)
constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3,
3), (3, 4), (4, 4), (4, 0)}
for i in range(5):
constraints.add((5, i))
constraints.add((i, 6))
constraint_crf = ConditionalRandomField(num_tags=5, constraints=
constraints)
constraint_crf.transitions = torch.nn.Parameter(self.transitions)
constraint_crf.start_transitions = torch.nn.Parameter(self.
transitions_from_start)
constraint_crf.end_transitions = torch.nn.Parameter(self.
transitions_to_end)
self.constraint_crf = constraint_crf
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]
self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=
LabelVocabulary.PADDING)
self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,
0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3,
0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)
self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)
self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8,
0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4,
0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)
self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6
], dtype=torch.float)
self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4
], dtype=torch.float)
self.crf = ConditionalRandomField(5)
self.crf.transitions = torch.nn.Parameter(self.transitions)
self.crf.start_transitions = torch.nn.Parameter(self.
transitions_from_start)
self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)
constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3,
3), (3, 4), (4, 4), (4, 0)}
for i in range(5):
constraints.add((5, i))
constraints.add((i, 6))
constraint_crf = ConditionalRandomField(num_tags=5, constraints=
constraints)
constraint_crf.transitions = torch.nn.Parameter(self.transitions)
constraint_crf.start_transitions = torch.nn.Parameter(self.
transitions_from_start)
constraint_crf.end_transitions = torch.nn.Parameter(self.
transitions_to_end)
self.constraint_crf = constraint_crf
@pytest.fixture(scope='class')
def crf_data():
"""
产生测试用的 crf data
:return:
"""
return CRFData()
def test_crf_label_index_decoder(crf_data):
"""
测试 crf label index decoder
:param crf_data: crf data
:return:
"""
mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)
crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,
label_vocabulary=crf_data.label_vocabulary)
label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)
padding_index = crf_data.label_vocabulary.padding_index
expect = [[2, 4, 3], [4, 2, padding_index]]
ASSERT.assertListEqual(expect, label_indices.tolist())
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]
self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=
LabelVocabulary.PADDING)
self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,
0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3,
0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)
self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)
self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8,
0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4,
0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)
self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6
], dtype=torch.float)
self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4
], dtype=torch.float)
self.crf = ConditionalRandomField(5)
self.crf.transitions = torch.nn.Parameter(self.transitions)
self.crf.start_transitions = torch.nn.Parameter(self.
transitions_from_start)
self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)
constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3,
3), (3, 4), (4, 4), (4, 0)}
for i in range(5):
constraints.add((5, i))
constraints.add((i, 6))
constraint_crf = ConditionalRandomField(num_tags=5, constraints=
constraints)
constraint_crf.transitions = torch.nn.Parameter(self.transitions)
constraint_crf.start_transitions = torch.nn.Parameter(self.
transitions_from_start)
constraint_crf.end_transitions = torch.nn.Parameter(self.
transitions_to_end)
self.constraint_crf = constraint_crf
@pytest.fixture(scope='class')
def crf_data():
"""
产生测试用的 crf data
:return:
"""
return CRFData()
def test_crf_label_index_decoder(crf_data):
"""
测试 crf label index decoder
:param crf_data: crf data
:return:
"""
mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)
crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,
label_vocabulary=crf_data.label_vocabulary)
label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)
padding_index = crf_data.label_vocabulary.padding_index
expect = [[2, 4, 3], [4, 2, padding_index]]
ASSERT.assertListEqual(expect, label_indices.tolist())
def test_crf_label_index_decoder_with_constraint(crf_data):
mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.uint8)
crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.
constraint_crf, label_vocabulary=crf_data.label_vocabulary)
label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)
padding_index = crf_data.label_vocabulary.padding_index
expect = [[2, 3, 3], [2, 3, padding_index]]
ASSERT.assertListEqual(expect, label_indices.tolist())
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import pytest
import torch
from easytext.tests import ASSERT
from easytext.data import LabelVocabulary
from easytext.modules import ConditionalRandomField
from easytext.label_decoder import CRFLabelIndexDecoder
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]
self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=
LabelVocabulary.PADDING)
self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,
0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3,
0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)
self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)
self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8,
0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4,
0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)
self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6
], dtype=torch.float)
self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4
], dtype=torch.float)
self.crf = ConditionalRandomField(5)
self.crf.transitions = torch.nn.Parameter(self.transitions)
self.crf.start_transitions = torch.nn.Parameter(self.
transitions_from_start)
self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)
constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3,
3), (3, 4), (4, 4), (4, 0)}
for i in range(5):
constraints.add((5, i))
constraints.add((i, 6))
constraint_crf = ConditionalRandomField(num_tags=5, constraints=
constraints)
constraint_crf.transitions = torch.nn.Parameter(self.transitions)
constraint_crf.start_transitions = torch.nn.Parameter(self.
transitions_from_start)
constraint_crf.end_transitions = torch.nn.Parameter(self.
transitions_to_end)
self.constraint_crf = constraint_crf
@pytest.fixture(scope='class')
def crf_data():
"""
产生测试用的 crf data
:return:
"""
return CRFData()
def test_crf_label_index_decoder(crf_data):
"""
测试 crf label index decoder
:param crf_data: crf data
:return:
"""
mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)
crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,
label_vocabulary=crf_data.label_vocabulary)
label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)
padding_index = crf_data.label_vocabulary.padding_index
expect = [[2, 4, 3], [4, 2, padding_index]]
ASSERT.assertListEqual(expect, label_indices.tolist())
def test_crf_label_index_decoder_with_constraint(crf_data):
mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.uint8)
crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.
constraint_crf, label_vocabulary=crf_data.label_vocabulary)
label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)
padding_index = crf_data.label_vocabulary.padding_index
expect = [[2, 3, 3], [2, 3, padding_index]]
ASSERT.assertListEqual(expect, label_indices.tolist())
<|reserved_special_token_1|>
#!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 PanXu, Inc. All Rights Reserved
#
"""
测试 label index decoder
Authors: PanXu
Date: 2020/07/05 15:10:00
"""
import pytest
import torch
from easytext.tests import ASSERT
from easytext.data import LabelVocabulary
from easytext.modules import ConditionalRandomField
from easytext.label_decoder import CRFLabelIndexDecoder
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [["O", "I-X", "B-X", "I-Y", "B-Y"]]
self.label_vocabulary = LabelVocabulary(labels=bio_labels,
padding=LabelVocabulary.PADDING)
self.logits = torch.tensor([
[[0, 0, .5, .5, .2], [0, 0, .3, .3, .1], [0, 0, .9, 10, 1]],
[[0, 0, .2, .5, .2], [0, 0, 3, .3, .1], [0, 0, .9, 1, 1]],
], dtype=torch.float)
self.tags = torch.tensor([
[2, 3, 4],
[3, 2, 2]
], dtype=torch.long)
self.transitions = torch.tensor([
[0.1, 0.2, 0.3, 0.4, 0.5],
[0.8, 0.3, 0.1, 0.7, 0.9],
[-0.3, 2.1, -5.6, 3.4, 4.0],
[0.2, 0.4, 0.6, -0.3, -0.4],
[1.0, 1.0, 1.0, 1.0, 1.0]
], dtype=torch.float)
self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6], dtype=torch.float)
self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4], dtype=torch.float)
# Use the CRF Module with fixed transitions to compute the log_likelihood
self.crf = ConditionalRandomField(5)
self.crf.transitions = torch.nn.Parameter(self.transitions)
self.crf.start_transitions = torch.nn.Parameter(self.transitions_from_start)
self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)
# constraint crf
constraints = {(0, 0), (0, 1),
(1, 1), (1, 2),
(2, 2), (2, 3),
(3, 3), (3, 4),
(4, 4), (4, 0)}
# Add the transitions to the end tag
# and from the start tag.
for i in range(5):
constraints.add((5, i))
constraints.add((i, 6))
constraint_crf = ConditionalRandomField(num_tags=5, constraints=constraints)
constraint_crf.transitions = torch.nn.Parameter(self.transitions)
constraint_crf.start_transitions = torch.nn.Parameter(self.transitions_from_start)
constraint_crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)
self.constraint_crf = constraint_crf
@pytest.fixture(scope="class")
def crf_data():
"""
产生测试用的 crf data
:return:
"""
return CRFData()
def test_crf_label_index_decoder(crf_data):
"""
测试 crf label index decoder
:param crf_data: crf data
:return:
"""
mask = torch.tensor([
[1, 1, 1],
[1, 1, 0]
], dtype=torch.long)
crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,
label_vocabulary=crf_data.label_vocabulary)
label_indices = crf_label_index_decoder(logits=crf_data.logits,
mask=mask)
padding_index = crf_data.label_vocabulary.padding_index
expect = [[2, 4, 3], [4, 2, padding_index]]
ASSERT.assertListEqual(expect, label_indices.tolist())
def test_crf_label_index_decoder_with_constraint(crf_data):
mask = torch.tensor([
[1, 1, 1],
[1, 1, 0]
], dtype=torch.uint8)
crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.constraint_crf,
label_vocabulary=crf_data.label_vocabulary)
label_indices = crf_label_index_decoder(logits=crf_data.logits,
mask=mask)
padding_index = crf_data.label_vocabulary.padding_index
expect = [[2, 3, 3], [2, 3, padding_index]]
ASSERT.assertListEqual(expect, label_indices.tolist())
|
flexible
|
{
"blob_id": "f64138ee5a64f09deb72b47b86bd7795acddad4d",
"index": 9980,
"step-1": "<mask token>\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\n@pytest.fixture(scope='class')\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\ndef test_crf_label_index_decoder(crf_data):\n \"\"\"\n 测试 crf label index decoder\n :param crf_data: crf data\n :return:\n \"\"\"\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,\n label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 4, 3], [4, 2, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\n@pytest.fixture(scope='class')\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\ndef test_crf_label_index_decoder(crf_data):\n \"\"\"\n 测试 crf label index decoder\n :param crf_data: crf data\n :return:\n \"\"\"\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,\n label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 4, 3], [4, 2, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n\n\ndef test_crf_label_index_decoder_with_constraint(crf_data):\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.uint8)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.\n constraint_crf, label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 3, 3], [2, 3, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n",
"step-4": "<mask token>\nimport pytest\nimport torch\nfrom easytext.tests import ASSERT\nfrom easytext.data import LabelVocabulary\nfrom easytext.modules import ConditionalRandomField\nfrom easytext.label_decoder import CRFLabelIndexDecoder\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=\n LabelVocabulary.PADDING)\n self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3,\n 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, \n 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float)\n self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long)\n self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, \n 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, \n 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float)\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6\n ], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4\n ], dtype=torch.float)\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, \n 3), (3, 4), (4, 4), (4, 0)}\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=\n constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.\n transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.\n transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\n@pytest.fixture(scope='class')\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\ndef test_crf_label_index_decoder(crf_data):\n \"\"\"\n 测试 crf label index decoder\n :param crf_data: crf data\n :return:\n \"\"\"\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,\n label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 4, 3], [4, 2, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n\n\ndef test_crf_label_index_decoder_with_constraint(crf_data):\n mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.uint8)\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.\n constraint_crf, label_vocabulary=crf_data.label_vocabulary)\n label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 3, 3], [2, 3, padding_index]]\n ASSERT.assertListEqual(expect, label_indices.tolist())\n",
"step-5": "#!/usr/bin/env python 3\n# -*- coding: utf-8 -*-\n\n#\n# Copyright (c) 2020 PanXu, Inc. All Rights Reserved\n#\n\"\"\"\n测试 label index decoder\n\nAuthors: PanXu\nDate: 2020/07/05 15:10:00\n\"\"\"\nimport pytest\nimport torch\n\nfrom easytext.tests import ASSERT\n\nfrom easytext.data import LabelVocabulary\nfrom easytext.modules import ConditionalRandomField\nfrom easytext.label_decoder import CRFLabelIndexDecoder\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [[\"O\", \"I-X\", \"B-X\", \"I-Y\", \"B-Y\"]]\n\n self.label_vocabulary = LabelVocabulary(labels=bio_labels,\n padding=LabelVocabulary.PADDING)\n\n self.logits = torch.tensor([\n [[0, 0, .5, .5, .2], [0, 0, .3, .3, .1], [0, 0, .9, 10, 1]],\n [[0, 0, .2, .5, .2], [0, 0, 3, .3, .1], [0, 0, .9, 1, 1]],\n ], dtype=torch.float)\n\n self.tags = torch.tensor([\n [2, 3, 4],\n [3, 2, 2]\n ], dtype=torch.long)\n\n self.transitions = torch.tensor([\n [0.1, 0.2, 0.3, 0.4, 0.5],\n [0.8, 0.3, 0.1, 0.7, 0.9],\n [-0.3, 2.1, -5.6, 3.4, 4.0],\n [0.2, 0.4, 0.6, -0.3, -0.4],\n [1.0, 1.0, 1.0, 1.0, 1.0]\n ], dtype=torch.float)\n\n self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6], dtype=torch.float)\n self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4], dtype=torch.float)\n\n # Use the CRF Module with fixed transitions to compute the log_likelihood\n self.crf = ConditionalRandomField(5)\n self.crf.transitions = torch.nn.Parameter(self.transitions)\n self.crf.start_transitions = torch.nn.Parameter(self.transitions_from_start)\n self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n\n # constraint crf\n constraints = {(0, 0), (0, 1),\n (1, 1), (1, 2),\n (2, 2), (2, 3),\n (3, 3), (3, 4),\n (4, 4), (4, 0)}\n\n # Add the transitions to the end tag\n # and from the start tag.\n for i in range(5):\n constraints.add((5, i))\n constraints.add((i, 6))\n\n constraint_crf = ConditionalRandomField(num_tags=5, constraints=constraints)\n constraint_crf.transitions = torch.nn.Parameter(self.transitions)\n constraint_crf.start_transitions = torch.nn.Parameter(self.transitions_from_start)\n constraint_crf.end_transitions = torch.nn.Parameter(self.transitions_to_end)\n self.constraint_crf = constraint_crf\n\n\n@pytest.fixture(scope=\"class\")\ndef crf_data():\n \"\"\"\n 产生测试用的 crf data\n :return:\n \"\"\"\n return CRFData()\n\n\ndef test_crf_label_index_decoder(crf_data):\n \"\"\"\n 测试 crf label index decoder\n :param crf_data: crf data\n :return:\n \"\"\"\n mask = torch.tensor([\n [1, 1, 1],\n [1, 1, 0]\n ], dtype=torch.long)\n\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf,\n label_vocabulary=crf_data.label_vocabulary)\n\n label_indices = crf_label_index_decoder(logits=crf_data.logits,\n mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 4, 3], [4, 2, padding_index]]\n\n ASSERT.assertListEqual(expect, label_indices.tolist())\n\n\ndef test_crf_label_index_decoder_with_constraint(crf_data):\n mask = torch.tensor([\n [1, 1, 1],\n [1, 1, 0]\n ], dtype=torch.uint8)\n\n crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.constraint_crf,\n label_vocabulary=crf_data.label_vocabulary)\n\n label_indices = crf_label_index_decoder(logits=crf_data.logits,\n mask=mask)\n padding_index = crf_data.label_vocabulary.padding_index\n expect = [[2, 3, 3], [2, 3, padding_index]]\n\n ASSERT.assertListEqual(expect, label_indices.tolist())\n",
"step-ids": [
3,
5,
6,
7,
8
]
}
|
[
3,
5,
6,
7,
8
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def check_image(file_type):
match = re.match('image/*', file_type)
return match
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def check_image(file_type):
match = re.match('image/*', file_type)
return match
def compress_image(data):
with open(PATH.format(data['name']), 'wb+') as file:
file.write(data['binary'])
image = Image.open(PATH.format(data['name']))
new_img = image.resize((128, 128))
new_img.save(PATH.format(data['name']))
with open(PATH.format(data['name']), 'rb') as image_file:
image = image_file.read()
os.remove(PATH.format(data['name']))
return image
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import re
import os
from PIL import Image
from common.constant import PATH
def check_image(file_type):
match = re.match('image/*', file_type)
return match
def compress_image(data):
with open(PATH.format(data['name']), 'wb+') as file:
file.write(data['binary'])
image = Image.open(PATH.format(data['name']))
new_img = image.resize((128, 128))
new_img.save(PATH.format(data['name']))
with open(PATH.format(data['name']), 'rb') as image_file:
image = image_file.read()
os.remove(PATH.format(data['name']))
return image
<|reserved_special_token_1|>
""" Image Check / Compress Image"""
import re
import os
from PIL import Image
from common.constant import PATH
def check_image(file_type):
match = re.match("image/*", file_type)
return match
def compress_image(data):
with open(PATH.format(data['name']), 'wb+') as file:
file.write(data['binary'])
image = Image.open(PATH.format(data['name']))
new_img = image.resize((128, 128))
new_img.save(PATH.format(data['name']))
with open(PATH.format(data['name']), 'rb') as image_file:
image = image_file.read()
os.remove(PATH.format(data['name']))
return image
|
flexible
|
{
"blob_id": "13fa650557a4a8827c9fb2e514bed178df19a32c",
"index": 1295,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef check_image(file_type):\n match = re.match('image/*', file_type)\n return match\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef check_image(file_type):\n match = re.match('image/*', file_type)\n return match\n\n\ndef compress_image(data):\n with open(PATH.format(data['name']), 'wb+') as file:\n file.write(data['binary'])\n image = Image.open(PATH.format(data['name']))\n new_img = image.resize((128, 128))\n new_img.save(PATH.format(data['name']))\n with open(PATH.format(data['name']), 'rb') as image_file:\n image = image_file.read()\n os.remove(PATH.format(data['name']))\n return image\n",
"step-4": "<mask token>\nimport re\nimport os\nfrom PIL import Image\nfrom common.constant import PATH\n\n\ndef check_image(file_type):\n match = re.match('image/*', file_type)\n return match\n\n\ndef compress_image(data):\n with open(PATH.format(data['name']), 'wb+') as file:\n file.write(data['binary'])\n image = Image.open(PATH.format(data['name']))\n new_img = image.resize((128, 128))\n new_img.save(PATH.format(data['name']))\n with open(PATH.format(data['name']), 'rb') as image_file:\n image = image_file.read()\n os.remove(PATH.format(data['name']))\n return image\n",
"step-5": "\"\"\" Image Check / Compress Image\"\"\"\n\nimport re\nimport os\nfrom PIL import Image\n\nfrom common.constant import PATH\n\n\ndef check_image(file_type):\n match = re.match(\"image/*\", file_type)\n return match\n\n\ndef compress_image(data):\n with open(PATH.format(data['name']), 'wb+') as file:\n file.write(data['binary'])\n image = Image.open(PATH.format(data['name']))\n new_img = image.resize((128, 128))\n new_img.save(PATH.format(data['name']))\n\n with open(PATH.format(data['name']), 'rb') as image_file:\n image = image_file.read()\n os.remove(PATH.format(data['name']))\n return image\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def version_100_iq(limit):
nums = []
for x in range(2, limit):
facs = 0
n = x
for p in primes:
if n % p == 0:
facs += 1
while n % p == 0:
n //= p
if n == 1 or facs >= 4:
break
if facs >= 4:
nums.append(x)
return set(nums)
def version_1(limit):
def search(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return 0
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
not_used = prod % primes[i] != 0
count = num_distinct >= 4 and not not_used
count += search(prod * primes[i], i, num_distinct + not_used)
count += search(prod, i + 1, num_distinct)
return count
return search(1, 0, 0)
def version_2(limit):
def search(prod, i, num_distinct):
if prod >= limit:
return
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
if i >= len(primes):
return
search(prod * primes[i], i + 1, num_distinct + 1)
search(prod, i + 1, num_distinct)
return search(1, 0, 0)
def find_prods_by_num_distinct_primes(limit, primes):
prods_by_num_distinct = [set() for _ in range(5)]
prods_by_num_distinct[0] |= {1}
def add_prods(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return
prods_by_num_distinct[min(num_distinct, 4)].add(prod)
add_prods(prod * primes[i], i + 1, num_distinct + 1)
add_prods(prod, i + 1, num_distinct)
add_prods(1, 0, 0)
return [sorted(s) for s in prods_by_num_distinct]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
start_time()
<|reserved_special_token_0|>
print('limit=', limit)
<|reserved_special_token_0|>
def version_100_iq(limit):
nums = []
for x in range(2, limit):
facs = 0
n = x
for p in primes:
if n % p == 0:
facs += 1
while n % p == 0:
n //= p
if n == 1 or facs >= 4:
break
if facs >= 4:
nums.append(x)
return set(nums)
def version_1(limit):
def search(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return 0
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
not_used = prod % primes[i] != 0
count = num_distinct >= 4 and not not_used
count += search(prod * primes[i], i, num_distinct + not_used)
count += search(prod, i + 1, num_distinct)
return count
return search(1, 0, 0)
def version_2(limit):
def search(prod, i, num_distinct):
if prod >= limit:
return
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
if i >= len(primes):
return
search(prod * primes[i], i + 1, num_distinct + 1)
search(prod, i + 1, num_distinct)
return search(1, 0, 0)
def find_prods_by_num_distinct_primes(limit, primes):
prods_by_num_distinct = [set() for _ in range(5)]
prods_by_num_distinct[0] |= {1}
def add_prods(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return
prods_by_num_distinct[min(num_distinct, 4)].add(prod)
add_prods(prod * primes[i], i + 1, num_distinct + 1)
add_prods(prod, i + 1, num_distinct)
add_prods(1, 0, 0)
return [sorted(s) for s in prods_by_num_distinct]
version_2(limit)
<|reserved_special_token_0|>
for n in sorted(v1):
for mult in range(1, 401):
if mult * n >= limit:
break
if mult in pset:
continue
if n * mult in res:
print(n, mult, n * mult)
res.add(n * mult)
count += 1
else:
print('not enough huh...', n)
count += (limit - 100 * n) // n
print(len(res))
print('Solution:', count)
<|reserved_special_token_0|>
print('100 IQ version:', len(iq_100))
end_time()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
start_time()
primes = read_primes(100)
<|reserved_special_token_0|>
limit = 43268
print('limit=', limit)
v1 = set()
v2 = set()
def version_100_iq(limit):
nums = []
for x in range(2, limit):
facs = 0
n = x
for p in primes:
if n % p == 0:
facs += 1
while n % p == 0:
n //= p
if n == 1 or facs >= 4:
break
if facs >= 4:
nums.append(x)
return set(nums)
def version_1(limit):
def search(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return 0
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
not_used = prod % primes[i] != 0
count = num_distinct >= 4 and not not_used
count += search(prod * primes[i], i, num_distinct + not_used)
count += search(prod, i + 1, num_distinct)
return count
return search(1, 0, 0)
def version_2(limit):
def search(prod, i, num_distinct):
if prod >= limit:
return
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
if i >= len(primes):
return
search(prod * primes[i], i + 1, num_distinct + 1)
search(prod, i + 1, num_distinct)
return search(1, 0, 0)
def find_prods_by_num_distinct_primes(limit, primes):
prods_by_num_distinct = [set() for _ in range(5)]
prods_by_num_distinct[0] |= {1}
def add_prods(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return
prods_by_num_distinct[min(num_distinct, 4)].add(prod)
add_prods(prod * primes[i], i + 1, num_distinct + 1)
add_prods(prod, i + 1, num_distinct)
add_prods(1, 0, 0)
return [sorted(s) for s in prods_by_num_distinct]
version_2(limit)
pset = set(primes)
res = set()
count = 0
for n in sorted(v1):
for mult in range(1, 401):
if mult * n >= limit:
break
if mult in pset:
continue
if n * mult in res:
print(n, mult, n * mult)
res.add(n * mult)
count += 1
else:
print('not enough huh...', n)
count += (limit - 100 * n) // n
print(len(res))
print('Solution:', count)
iq_100 = version_100_iq(limit)
print('100 IQ version:', len(iq_100))
end_time()
<|reserved_special_token_1|>
from lib.utility import start_time, end_time
from lib.prime import read_primes
from bisect import bisect_left
start_time()
primes = read_primes(100)
import random
limit = 43268
print('limit=', limit)
v1 = set()
v2 = set()
def version_100_iq(limit):
nums = []
for x in range(2, limit):
facs = 0
n = x
for p in primes:
if n % p == 0:
facs += 1
while n % p == 0:
n //= p
if n == 1 or facs >= 4:
break
if facs >= 4:
nums.append(x)
return set(nums)
def version_1(limit):
def search(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return 0
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
not_used = prod % primes[i] != 0
count = num_distinct >= 4 and not not_used
count += search(prod * primes[i], i, num_distinct + not_used)
count += search(prod, i + 1, num_distinct)
return count
return search(1, 0, 0)
def version_2(limit):
def search(prod, i, num_distinct):
if prod >= limit:
return
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
if i >= len(primes):
return
search(prod * primes[i], i + 1, num_distinct + 1)
search(prod, i + 1, num_distinct)
return search(1, 0, 0)
def find_prods_by_num_distinct_primes(limit, primes):
prods_by_num_distinct = [set() for _ in range(5)]
prods_by_num_distinct[0] |= {1}
def add_prods(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return
prods_by_num_distinct[min(num_distinct, 4)].add(prod)
add_prods(prod * primes[i], i + 1, num_distinct + 1)
add_prods(prod, i + 1, num_distinct)
add_prods(1, 0, 0)
return [sorted(s) for s in prods_by_num_distinct]
version_2(limit)
pset = set(primes)
res = set()
count = 0
for n in sorted(v1):
for mult in range(1, 401):
if mult * n >= limit:
break
if mult in pset:
continue
if n * mult in res:
print(n, mult, n * mult)
res.add(n * mult)
count += 1
else:
print('not enough huh...', n)
count += (limit - 100 * n) // n
print(len(res))
print('Solution:', count)
iq_100 = version_100_iq(limit)
print('100 IQ version:', len(iq_100))
end_time()
<|reserved_special_token_1|>
from lib.utility import start_time, end_time
from lib.prime import read_primes
from bisect import bisect_left
start_time()
primes = read_primes(100)
# limit = 10 ** 16
import random
# limit = random.randint(1000, 10 ** 5)
limit = 43268
# limit = 10 ** 16
print('limit=', limit)
v1 = set()
v2 = set()
def version_100_iq(limit):
nums = []
for x in range(2, limit):
facs = 0
n = x
for p in primes:
if n % p == 0:
facs += 1
while n % p == 0:
n //= p
if n == 1 or facs >= 4:
break
if facs >= 4:
nums.append(x)
return set(nums)
def version_1(limit):
def search(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return 0
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
not_used = (prod % primes[i] != 0)
count = (num_distinct >= 4) and not not_used
count += search(prod * primes[i], i, num_distinct + not_used)
count += search(prod, i + 1, num_distinct)
return count
return search(1, 0, 0)
def version_2(limit):
def search(prod, i, num_distinct):
if prod >= limit:
return
if prod not in v1 and num_distinct >= 4:
v1.add(prod)
if i >= len(primes):
return
search(prod * primes[i], i + 1, num_distinct + 1)
search(prod, i + 1, num_distinct)
return search(1, 0, 0)
def find_prods_by_num_distinct_primes(limit, primes):
prods_by_num_distinct = [set() for _ in range(5)]
prods_by_num_distinct[0] |= {1}
def add_prods(prod, i, num_distinct):
if prod >= limit or i >= len(primes):
return
# not_used = (prod % primes[i] != 0)
# if not not_used:
prods_by_num_distinct[min(num_distinct, 4)].add(prod)
add_prods(prod * primes[i], i + 1, num_distinct + 1)
add_prods(prod, i + 1, num_distinct)
add_prods(1, 0, 0)
return [sorted(s) for s in prods_by_num_distinct]
version_2(limit)
pset = set(primes)
res = set()
count = 0
for n in sorted(v1):
for mult in range(1, 401):
if mult * n >= limit:
break
# if n % mult != 0 and mult in pset:
if mult in pset:
# assert(n * mult in v1), (n, mult)
continue
# print(n, mult)
if n * mult in res:
print(n, mult, n * mult)
res.add(n * mult)
count += 1
else:
print('not enough huh...', n)
count += (limit - 100*n) // n
print(len(res))
# n = 7 # a splitting point that seems to be the fastest
# lo = find_prods_by_num_distinct_primes(limit, primes[:n])
# hi = find_prods_by_num_distinct_primes(limit, primes[n:])
# max_sol = 0
# count = 0
# for lo_num_distinct_primes in range(0, 5):
# for prod in lo[lo_num_distinct_primes]:
# for hi_num_distinct_primes in range(4 - lo_num_distinct_primes, 5):
# # count += bisect_left(hi[hi_num_distinct_primes], limit / prod)
# for v in hi[hi_num_distinct_primes]:
# if v * prod < limit:
# count += 1
# # count += (limit - 1) // (v * prod)
print('Solution:', count)
iq_100 = version_100_iq(limit)
print('100 IQ version:', len(iq_100))
# if count != len(iq_100):
# print(iq_100 - v1)
# assert count == len(iq_100)
end_time()
|
flexible
|
{
"blob_id": "ea8676a4c55bbe0ae2ff8abf924accfc0bd8f661",
"index": 1272,
"step-1": "<mask token>\n\n\ndef version_100_iq(limit):\n nums = []\n for x in range(2, limit):\n facs = 0\n n = x\n for p in primes:\n if n % p == 0:\n facs += 1\n while n % p == 0:\n n //= p\n if n == 1 or facs >= 4:\n break\n if facs >= 4:\n nums.append(x)\n return set(nums)\n\n\ndef version_1(limit):\n\n def search(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return 0\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n not_used = prod % primes[i] != 0\n count = num_distinct >= 4 and not not_used\n count += search(prod * primes[i], i, num_distinct + not_used)\n count += search(prod, i + 1, num_distinct)\n return count\n return search(1, 0, 0)\n\n\ndef version_2(limit):\n\n def search(prod, i, num_distinct):\n if prod >= limit:\n return\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n if i >= len(primes):\n return\n search(prod * primes[i], i + 1, num_distinct + 1)\n search(prod, i + 1, num_distinct)\n return search(1, 0, 0)\n\n\ndef find_prods_by_num_distinct_primes(limit, primes):\n prods_by_num_distinct = [set() for _ in range(5)]\n prods_by_num_distinct[0] |= {1}\n\n def add_prods(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return\n prods_by_num_distinct[min(num_distinct, 4)].add(prod)\n add_prods(prod * primes[i], i + 1, num_distinct + 1)\n add_prods(prod, i + 1, num_distinct)\n add_prods(1, 0, 0)\n return [sorted(s) for s in prods_by_num_distinct]\n\n\n<mask token>\n",
"step-2": "<mask token>\nstart_time()\n<mask token>\nprint('limit=', limit)\n<mask token>\n\n\ndef version_100_iq(limit):\n nums = []\n for x in range(2, limit):\n facs = 0\n n = x\n for p in primes:\n if n % p == 0:\n facs += 1\n while n % p == 0:\n n //= p\n if n == 1 or facs >= 4:\n break\n if facs >= 4:\n nums.append(x)\n return set(nums)\n\n\ndef version_1(limit):\n\n def search(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return 0\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n not_used = prod % primes[i] != 0\n count = num_distinct >= 4 and not not_used\n count += search(prod * primes[i], i, num_distinct + not_used)\n count += search(prod, i + 1, num_distinct)\n return count\n return search(1, 0, 0)\n\n\ndef version_2(limit):\n\n def search(prod, i, num_distinct):\n if prod >= limit:\n return\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n if i >= len(primes):\n return\n search(prod * primes[i], i + 1, num_distinct + 1)\n search(prod, i + 1, num_distinct)\n return search(1, 0, 0)\n\n\ndef find_prods_by_num_distinct_primes(limit, primes):\n prods_by_num_distinct = [set() for _ in range(5)]\n prods_by_num_distinct[0] |= {1}\n\n def add_prods(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return\n prods_by_num_distinct[min(num_distinct, 4)].add(prod)\n add_prods(prod * primes[i], i + 1, num_distinct + 1)\n add_prods(prod, i + 1, num_distinct)\n add_prods(1, 0, 0)\n return [sorted(s) for s in prods_by_num_distinct]\n\n\nversion_2(limit)\n<mask token>\nfor n in sorted(v1):\n for mult in range(1, 401):\n if mult * n >= limit:\n break\n if mult in pset:\n continue\n if n * mult in res:\n print(n, mult, n * mult)\n res.add(n * mult)\n count += 1\n else:\n print('not enough huh...', n)\n count += (limit - 100 * n) // n\nprint(len(res))\nprint('Solution:', count)\n<mask token>\nprint('100 IQ version:', len(iq_100))\nend_time()\n",
"step-3": "<mask token>\nstart_time()\nprimes = read_primes(100)\n<mask token>\nlimit = 43268\nprint('limit=', limit)\nv1 = set()\nv2 = set()\n\n\ndef version_100_iq(limit):\n nums = []\n for x in range(2, limit):\n facs = 0\n n = x\n for p in primes:\n if n % p == 0:\n facs += 1\n while n % p == 0:\n n //= p\n if n == 1 or facs >= 4:\n break\n if facs >= 4:\n nums.append(x)\n return set(nums)\n\n\ndef version_1(limit):\n\n def search(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return 0\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n not_used = prod % primes[i] != 0\n count = num_distinct >= 4 and not not_used\n count += search(prod * primes[i], i, num_distinct + not_used)\n count += search(prod, i + 1, num_distinct)\n return count\n return search(1, 0, 0)\n\n\ndef version_2(limit):\n\n def search(prod, i, num_distinct):\n if prod >= limit:\n return\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n if i >= len(primes):\n return\n search(prod * primes[i], i + 1, num_distinct + 1)\n search(prod, i + 1, num_distinct)\n return search(1, 0, 0)\n\n\ndef find_prods_by_num_distinct_primes(limit, primes):\n prods_by_num_distinct = [set() for _ in range(5)]\n prods_by_num_distinct[0] |= {1}\n\n def add_prods(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return\n prods_by_num_distinct[min(num_distinct, 4)].add(prod)\n add_prods(prod * primes[i], i + 1, num_distinct + 1)\n add_prods(prod, i + 1, num_distinct)\n add_prods(1, 0, 0)\n return [sorted(s) for s in prods_by_num_distinct]\n\n\nversion_2(limit)\npset = set(primes)\nres = set()\ncount = 0\nfor n in sorted(v1):\n for mult in range(1, 401):\n if mult * n >= limit:\n break\n if mult in pset:\n continue\n if n * mult in res:\n print(n, mult, n * mult)\n res.add(n * mult)\n count += 1\n else:\n print('not enough huh...', n)\n count += (limit - 100 * n) // n\nprint(len(res))\nprint('Solution:', count)\niq_100 = version_100_iq(limit)\nprint('100 IQ version:', len(iq_100))\nend_time()\n",
"step-4": "from lib.utility import start_time, end_time\nfrom lib.prime import read_primes\nfrom bisect import bisect_left\nstart_time()\nprimes = read_primes(100)\nimport random\nlimit = 43268\nprint('limit=', limit)\nv1 = set()\nv2 = set()\n\n\ndef version_100_iq(limit):\n nums = []\n for x in range(2, limit):\n facs = 0\n n = x\n for p in primes:\n if n % p == 0:\n facs += 1\n while n % p == 0:\n n //= p\n if n == 1 or facs >= 4:\n break\n if facs >= 4:\n nums.append(x)\n return set(nums)\n\n\ndef version_1(limit):\n\n def search(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return 0\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n not_used = prod % primes[i] != 0\n count = num_distinct >= 4 and not not_used\n count += search(prod * primes[i], i, num_distinct + not_used)\n count += search(prod, i + 1, num_distinct)\n return count\n return search(1, 0, 0)\n\n\ndef version_2(limit):\n\n def search(prod, i, num_distinct):\n if prod >= limit:\n return\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n if i >= len(primes):\n return\n search(prod * primes[i], i + 1, num_distinct + 1)\n search(prod, i + 1, num_distinct)\n return search(1, 0, 0)\n\n\ndef find_prods_by_num_distinct_primes(limit, primes):\n prods_by_num_distinct = [set() for _ in range(5)]\n prods_by_num_distinct[0] |= {1}\n\n def add_prods(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return\n prods_by_num_distinct[min(num_distinct, 4)].add(prod)\n add_prods(prod * primes[i], i + 1, num_distinct + 1)\n add_prods(prod, i + 1, num_distinct)\n add_prods(1, 0, 0)\n return [sorted(s) for s in prods_by_num_distinct]\n\n\nversion_2(limit)\npset = set(primes)\nres = set()\ncount = 0\nfor n in sorted(v1):\n for mult in range(1, 401):\n if mult * n >= limit:\n break\n if mult in pset:\n continue\n if n * mult in res:\n print(n, mult, n * mult)\n res.add(n * mult)\n count += 1\n else:\n print('not enough huh...', n)\n count += (limit - 100 * n) // n\nprint(len(res))\nprint('Solution:', count)\niq_100 = version_100_iq(limit)\nprint('100 IQ version:', len(iq_100))\nend_time()\n",
"step-5": "from lib.utility import start_time, end_time\nfrom lib.prime import read_primes\nfrom bisect import bisect_left\nstart_time()\n\nprimes = read_primes(100)\n# limit = 10 ** 16\nimport random\n# limit = random.randint(1000, 10 ** 5)\nlimit = 43268\n# limit = 10 ** 16\nprint('limit=', limit)\nv1 = set()\nv2 = set()\n\n\ndef version_100_iq(limit):\n nums = []\n for x in range(2, limit):\n facs = 0\n n = x\n for p in primes:\n if n % p == 0:\n facs += 1\n\n while n % p == 0:\n n //= p\n\n if n == 1 or facs >= 4:\n break\n\n if facs >= 4:\n nums.append(x)\n\n return set(nums)\n\n\ndef version_1(limit):\n def search(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return 0\n\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n\n not_used = (prod % primes[i] != 0)\n count = (num_distinct >= 4) and not not_used\n count += search(prod * primes[i], i, num_distinct + not_used)\n count += search(prod, i + 1, num_distinct)\n return count\n\n return search(1, 0, 0)\n\n\ndef version_2(limit):\n def search(prod, i, num_distinct):\n if prod >= limit:\n return\n\n if prod not in v1 and num_distinct >= 4:\n v1.add(prod)\n\n if i >= len(primes):\n return\n\n search(prod * primes[i], i + 1, num_distinct + 1)\n search(prod, i + 1, num_distinct)\n\n return search(1, 0, 0)\n\n\ndef find_prods_by_num_distinct_primes(limit, primes):\n prods_by_num_distinct = [set() for _ in range(5)]\n prods_by_num_distinct[0] |= {1}\n\n def add_prods(prod, i, num_distinct):\n if prod >= limit or i >= len(primes):\n return\n\n # not_used = (prod % primes[i] != 0)\n # if not not_used:\n prods_by_num_distinct[min(num_distinct, 4)].add(prod)\n\n add_prods(prod * primes[i], i + 1, num_distinct + 1)\n add_prods(prod, i + 1, num_distinct)\n\n add_prods(1, 0, 0)\n return [sorted(s) for s in prods_by_num_distinct]\n\n\nversion_2(limit)\n\npset = set(primes)\n\nres = set()\ncount = 0\nfor n in sorted(v1):\n for mult in range(1, 401):\n if mult * n >= limit:\n break\n # if n % mult != 0 and mult in pset:\n if mult in pset:\n # assert(n * mult in v1), (n, mult)\n continue\n\n\n # print(n, mult)\n if n * mult in res:\n print(n, mult, n * mult)\n res.add(n * mult)\n count += 1\n else:\n print('not enough huh...', n)\n count += (limit - 100*n) // n\n\n\nprint(len(res))\n# n = 7 # a splitting point that seems to be the fastest\n# lo = find_prods_by_num_distinct_primes(limit, primes[:n])\n# hi = find_prods_by_num_distinct_primes(limit, primes[n:])\n\n\n# max_sol = 0\n# count = 0\n# for lo_num_distinct_primes in range(0, 5):\n# for prod in lo[lo_num_distinct_primes]:\n# for hi_num_distinct_primes in range(4 - lo_num_distinct_primes, 5):\n# # count += bisect_left(hi[hi_num_distinct_primes], limit / prod)\n# for v in hi[hi_num_distinct_primes]:\n# if v * prod < limit:\n# count += 1\n# # count += (limit - 1) // (v * prod)\n\n\nprint('Solution:', count)\n\niq_100 = version_100_iq(limit)\nprint('100 IQ version:', len(iq_100))\n\n# if count != len(iq_100):\n # print(iq_100 - v1)\n# assert count == len(iq_100)\n\n\n\nend_time()\n",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
<|reserved_special_token_0|>
class WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __repr__(self):
return (
f'{self.__class__.__name__}(warmup_steps={self.warmup_steps}, steps_per_epoch={self.steps_per_epoch}, step_size={self.step_size}, gamma={self.gamma})'
)
def get_lr(self):
self.step_num += 1
if self.step_num % self.steps_per_epoch == 0:
self.epoch_num += 1
if self.step_num <= self.warmup_steps:
return [(lr * self.lr_scale * self.step_num) for lr in self.
base_lrs]
else:
return [(lr * self.gamma ** ((self.epoch_num - self.
warmup_epoch) // self.step_size)) for lr in self.base_lrs]
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):
<|reserved_special_token_0|>
def __init__(self, optimizer: torch.optim.Optimizer, warmup_steps:
Union[int, float]=25000, steps_per_epoch: int=10000, step_size: int
=1, gamma: float=0.1, last_epoch: int=-1):
assert check_argument_types()
self.warmup_steps = warmup_steps
self.step_num = 0
self.epoch_num = 0
self.steps_per_epoch = steps_per_epoch
self.warmup_epoch = warmup_steps // steps_per_epoch
self.lr_scale = warmup_steps ** -1
self.step_size = step_size
self.gamma = gamma
super().__init__(optimizer, last_epoch)
def __repr__(self):
return (
f'{self.__class__.__name__}(warmup_steps={self.warmup_steps}, steps_per_epoch={self.steps_per_epoch}, step_size={self.step_size}, gamma={self.gamma})'
)
def get_lr(self):
self.step_num += 1
if self.step_num % self.steps_per_epoch == 0:
self.epoch_num += 1
if self.step_num <= self.warmup_steps:
return [(lr * self.lr_scale * self.step_num) for lr in self.
base_lrs]
else:
return [(lr * self.gamma ** ((self.epoch_num - self.
warmup_epoch) // self.step_size)) for lr in self.base_lrs]
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):
"""The WarmupStepLR scheduler.
This scheduler is the combination of WarmupLR and StepLR:
WarmupLR:
lr = optimizer.lr * warmup_step ** 0.5
* min(step ** -0.5, step * warmup_step ** -1.5)
WarmupStepLR:
if step <= warmup_step:
lr = optimizer.lr * warmup_step ** 0.5
* min(step ** -0.5, step * warmup_step ** -1.5)
else:
lr = optimizer.lr * (gamma ** (epoch//step_size))
Note that the maximum lr equals to optimizer.lr in this scheduler.
"""
def __init__(self, optimizer: torch.optim.Optimizer, warmup_steps:
Union[int, float]=25000, steps_per_epoch: int=10000, step_size: int
=1, gamma: float=0.1, last_epoch: int=-1):
assert check_argument_types()
self.warmup_steps = warmup_steps
self.step_num = 0
self.epoch_num = 0
self.steps_per_epoch = steps_per_epoch
self.warmup_epoch = warmup_steps // steps_per_epoch
self.lr_scale = warmup_steps ** -1
self.step_size = step_size
self.gamma = gamma
super().__init__(optimizer, last_epoch)
def __repr__(self):
return (
f'{self.__class__.__name__}(warmup_steps={self.warmup_steps}, steps_per_epoch={self.steps_per_epoch}, step_size={self.step_size}, gamma={self.gamma})'
)
def get_lr(self):
self.step_num += 1
if self.step_num % self.steps_per_epoch == 0:
self.epoch_num += 1
if self.step_num <= self.warmup_steps:
return [(lr * self.lr_scale * self.step_num) for lr in self.
base_lrs]
else:
return [(lr * self.gamma ** ((self.epoch_num - self.
warmup_epoch) // self.step_size)) for lr in self.base_lrs]
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from typing import Union
import torch
from torch.optim.lr_scheduler import _LRScheduler
from typeguard import check_argument_types
from espnet2.schedulers.abs_scheduler import AbsBatchStepScheduler
class WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):
"""The WarmupStepLR scheduler.
This scheduler is the combination of WarmupLR and StepLR:
WarmupLR:
lr = optimizer.lr * warmup_step ** 0.5
* min(step ** -0.5, step * warmup_step ** -1.5)
WarmupStepLR:
if step <= warmup_step:
lr = optimizer.lr * warmup_step ** 0.5
* min(step ** -0.5, step * warmup_step ** -1.5)
else:
lr = optimizer.lr * (gamma ** (epoch//step_size))
Note that the maximum lr equals to optimizer.lr in this scheduler.
"""
def __init__(self, optimizer: torch.optim.Optimizer, warmup_steps:
Union[int, float]=25000, steps_per_epoch: int=10000, step_size: int
=1, gamma: float=0.1, last_epoch: int=-1):
assert check_argument_types()
self.warmup_steps = warmup_steps
self.step_num = 0
self.epoch_num = 0
self.steps_per_epoch = steps_per_epoch
self.warmup_epoch = warmup_steps // steps_per_epoch
self.lr_scale = warmup_steps ** -1
self.step_size = step_size
self.gamma = gamma
super().__init__(optimizer, last_epoch)
def __repr__(self):
return (
f'{self.__class__.__name__}(warmup_steps={self.warmup_steps}, steps_per_epoch={self.steps_per_epoch}, step_size={self.step_size}, gamma={self.gamma})'
)
def get_lr(self):
self.step_num += 1
if self.step_num % self.steps_per_epoch == 0:
self.epoch_num += 1
if self.step_num <= self.warmup_steps:
return [(lr * self.lr_scale * self.step_num) for lr in self.
base_lrs]
else:
return [(lr * self.gamma ** ((self.epoch_num - self.
warmup_epoch) // self.step_size)) for lr in self.base_lrs]
<|reserved_special_token_1|>
"""Step (with Warm up) learning rate scheduler module."""
from typing import Union
import torch
from torch.optim.lr_scheduler import _LRScheduler
from typeguard import check_argument_types
from espnet2.schedulers.abs_scheduler import AbsBatchStepScheduler
class WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):
"""The WarmupStepLR scheduler.
This scheduler is the combination of WarmupLR and StepLR:
WarmupLR:
lr = optimizer.lr * warmup_step ** 0.5
* min(step ** -0.5, step * warmup_step ** -1.5)
WarmupStepLR:
if step <= warmup_step:
lr = optimizer.lr * warmup_step ** 0.5
* min(step ** -0.5, step * warmup_step ** -1.5)
else:
lr = optimizer.lr * (gamma ** (epoch//step_size))
Note that the maximum lr equals to optimizer.lr in this scheduler.
"""
def __init__(
self,
optimizer: torch.optim.Optimizer,
# for WarmupLR
warmup_steps: Union[int, float] = 25000,
# for StepLR
steps_per_epoch: int = 10000,
step_size: int = 1,
gamma: float = 0.1,
last_epoch: int = -1,
):
assert check_argument_types()
self.warmup_steps = warmup_steps
self.step_num = 0
self.epoch_num = 0
# NOTE: This number should be adjusted accordingly
# once batch_size/ngpu/num_nodes is changed.
# To get the exact number of iterations per epoch, refer to
# https://github.com/espnet/espnet/discussions/4404
self.steps_per_epoch = steps_per_epoch
self.warmup_epoch = warmup_steps // steps_per_epoch
self.lr_scale = warmup_steps**-1
# after warmup_steps, decrease lr by `gamma` every `step_size` epochs
self.step_size = step_size
self.gamma = gamma
# __init__() must be invoked before setting field
# because step() is also invoked in __init__()
super().__init__(optimizer, last_epoch)
def __repr__(self):
return (
f"{self.__class__.__name__}(warmup_steps={self.warmup_steps}, "
f"steps_per_epoch={self.steps_per_epoch},"
f" step_size={self.step_size}, gamma={self.gamma})"
)
def get_lr(self):
self.step_num += 1
if self.step_num % self.steps_per_epoch == 0:
self.epoch_num += 1
if self.step_num <= self.warmup_steps:
return [lr * self.lr_scale * self.step_num for lr in self.base_lrs]
else:
return [
lr
* self.gamma ** ((self.epoch_num - self.warmup_epoch) // self.step_size)
for lr in self.base_lrs
]
|
flexible
|
{
"blob_id": "bce16762c0739087a8309872da4ac04298c50893",
"index": 7695,
"step-1": "<mask token>\n\n\nclass WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):\n <mask token>\n <mask token>\n\n def __repr__(self):\n return (\n f'{self.__class__.__name__}(warmup_steps={self.warmup_steps}, steps_per_epoch={self.steps_per_epoch}, step_size={self.step_size}, gamma={self.gamma})'\n )\n\n def get_lr(self):\n self.step_num += 1\n if self.step_num % self.steps_per_epoch == 0:\n self.epoch_num += 1\n if self.step_num <= self.warmup_steps:\n return [(lr * self.lr_scale * self.step_num) for lr in self.\n base_lrs]\n else:\n return [(lr * self.gamma ** ((self.epoch_num - self.\n warmup_epoch) // self.step_size)) for lr in self.base_lrs]\n",
"step-2": "<mask token>\n\n\nclass WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):\n <mask token>\n\n def __init__(self, optimizer: torch.optim.Optimizer, warmup_steps:\n Union[int, float]=25000, steps_per_epoch: int=10000, step_size: int\n =1, gamma: float=0.1, last_epoch: int=-1):\n assert check_argument_types()\n self.warmup_steps = warmup_steps\n self.step_num = 0\n self.epoch_num = 0\n self.steps_per_epoch = steps_per_epoch\n self.warmup_epoch = warmup_steps // steps_per_epoch\n self.lr_scale = warmup_steps ** -1\n self.step_size = step_size\n self.gamma = gamma\n super().__init__(optimizer, last_epoch)\n\n def __repr__(self):\n return (\n f'{self.__class__.__name__}(warmup_steps={self.warmup_steps}, steps_per_epoch={self.steps_per_epoch}, step_size={self.step_size}, gamma={self.gamma})'\n )\n\n def get_lr(self):\n self.step_num += 1\n if self.step_num % self.steps_per_epoch == 0:\n self.epoch_num += 1\n if self.step_num <= self.warmup_steps:\n return [(lr * self.lr_scale * self.step_num) for lr in self.\n base_lrs]\n else:\n return [(lr * self.gamma ** ((self.epoch_num - self.\n warmup_epoch) // self.step_size)) for lr in self.base_lrs]\n",
"step-3": "<mask token>\n\n\nclass WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):\n \"\"\"The WarmupStepLR scheduler.\n\n This scheduler is the combination of WarmupLR and StepLR:\n\n WarmupLR:\n lr = optimizer.lr * warmup_step ** 0.5\n * min(step ** -0.5, step * warmup_step ** -1.5)\n WarmupStepLR:\n if step <= warmup_step:\n lr = optimizer.lr * warmup_step ** 0.5\n * min(step ** -0.5, step * warmup_step ** -1.5)\n else:\n lr = optimizer.lr * (gamma ** (epoch//step_size))\n\n Note that the maximum lr equals to optimizer.lr in this scheduler.\n\n \"\"\"\n\n def __init__(self, optimizer: torch.optim.Optimizer, warmup_steps:\n Union[int, float]=25000, steps_per_epoch: int=10000, step_size: int\n =1, gamma: float=0.1, last_epoch: int=-1):\n assert check_argument_types()\n self.warmup_steps = warmup_steps\n self.step_num = 0\n self.epoch_num = 0\n self.steps_per_epoch = steps_per_epoch\n self.warmup_epoch = warmup_steps // steps_per_epoch\n self.lr_scale = warmup_steps ** -1\n self.step_size = step_size\n self.gamma = gamma\n super().__init__(optimizer, last_epoch)\n\n def __repr__(self):\n return (\n f'{self.__class__.__name__}(warmup_steps={self.warmup_steps}, steps_per_epoch={self.steps_per_epoch}, step_size={self.step_size}, gamma={self.gamma})'\n )\n\n def get_lr(self):\n self.step_num += 1\n if self.step_num % self.steps_per_epoch == 0:\n self.epoch_num += 1\n if self.step_num <= self.warmup_steps:\n return [(lr * self.lr_scale * self.step_num) for lr in self.\n base_lrs]\n else:\n return [(lr * self.gamma ** ((self.epoch_num - self.\n warmup_epoch) // self.step_size)) for lr in self.base_lrs]\n",
"step-4": "<mask token>\nfrom typing import Union\nimport torch\nfrom torch.optim.lr_scheduler import _LRScheduler\nfrom typeguard import check_argument_types\nfrom espnet2.schedulers.abs_scheduler import AbsBatchStepScheduler\n\n\nclass WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):\n \"\"\"The WarmupStepLR scheduler.\n\n This scheduler is the combination of WarmupLR and StepLR:\n\n WarmupLR:\n lr = optimizer.lr * warmup_step ** 0.5\n * min(step ** -0.5, step * warmup_step ** -1.5)\n WarmupStepLR:\n if step <= warmup_step:\n lr = optimizer.lr * warmup_step ** 0.5\n * min(step ** -0.5, step * warmup_step ** -1.5)\n else:\n lr = optimizer.lr * (gamma ** (epoch//step_size))\n\n Note that the maximum lr equals to optimizer.lr in this scheduler.\n\n \"\"\"\n\n def __init__(self, optimizer: torch.optim.Optimizer, warmup_steps:\n Union[int, float]=25000, steps_per_epoch: int=10000, step_size: int\n =1, gamma: float=0.1, last_epoch: int=-1):\n assert check_argument_types()\n self.warmup_steps = warmup_steps\n self.step_num = 0\n self.epoch_num = 0\n self.steps_per_epoch = steps_per_epoch\n self.warmup_epoch = warmup_steps // steps_per_epoch\n self.lr_scale = warmup_steps ** -1\n self.step_size = step_size\n self.gamma = gamma\n super().__init__(optimizer, last_epoch)\n\n def __repr__(self):\n return (\n f'{self.__class__.__name__}(warmup_steps={self.warmup_steps}, steps_per_epoch={self.steps_per_epoch}, step_size={self.step_size}, gamma={self.gamma})'\n )\n\n def get_lr(self):\n self.step_num += 1\n if self.step_num % self.steps_per_epoch == 0:\n self.epoch_num += 1\n if self.step_num <= self.warmup_steps:\n return [(lr * self.lr_scale * self.step_num) for lr in self.\n base_lrs]\n else:\n return [(lr * self.gamma ** ((self.epoch_num - self.\n warmup_epoch) // self.step_size)) for lr in self.base_lrs]\n",
"step-5": "\"\"\"Step (with Warm up) learning rate scheduler module.\"\"\"\nfrom typing import Union\n\nimport torch\nfrom torch.optim.lr_scheduler import _LRScheduler\nfrom typeguard import check_argument_types\n\nfrom espnet2.schedulers.abs_scheduler import AbsBatchStepScheduler\n\n\nclass WarmupStepLR(_LRScheduler, AbsBatchStepScheduler):\n \"\"\"The WarmupStepLR scheduler.\n\n This scheduler is the combination of WarmupLR and StepLR:\n\n WarmupLR:\n lr = optimizer.lr * warmup_step ** 0.5\n * min(step ** -0.5, step * warmup_step ** -1.5)\n WarmupStepLR:\n if step <= warmup_step:\n lr = optimizer.lr * warmup_step ** 0.5\n * min(step ** -0.5, step * warmup_step ** -1.5)\n else:\n lr = optimizer.lr * (gamma ** (epoch//step_size))\n\n Note that the maximum lr equals to optimizer.lr in this scheduler.\n\n \"\"\"\n\n def __init__(\n self,\n optimizer: torch.optim.Optimizer,\n # for WarmupLR\n warmup_steps: Union[int, float] = 25000,\n # for StepLR\n steps_per_epoch: int = 10000,\n step_size: int = 1,\n gamma: float = 0.1,\n last_epoch: int = -1,\n ):\n assert check_argument_types()\n self.warmup_steps = warmup_steps\n\n self.step_num = 0\n self.epoch_num = 0\n # NOTE: This number should be adjusted accordingly\n # once batch_size/ngpu/num_nodes is changed.\n # To get the exact number of iterations per epoch, refer to\n # https://github.com/espnet/espnet/discussions/4404\n self.steps_per_epoch = steps_per_epoch\n self.warmup_epoch = warmup_steps // steps_per_epoch\n\n self.lr_scale = warmup_steps**-1\n\n # after warmup_steps, decrease lr by `gamma` every `step_size` epochs\n self.step_size = step_size\n self.gamma = gamma\n\n # __init__() must be invoked before setting field\n # because step() is also invoked in __init__()\n super().__init__(optimizer, last_epoch)\n\n def __repr__(self):\n return (\n f\"{self.__class__.__name__}(warmup_steps={self.warmup_steps}, \"\n f\"steps_per_epoch={self.steps_per_epoch},\"\n f\" step_size={self.step_size}, gamma={self.gamma})\"\n )\n\n def get_lr(self):\n self.step_num += 1\n if self.step_num % self.steps_per_epoch == 0:\n self.epoch_num += 1\n\n if self.step_num <= self.warmup_steps:\n return [lr * self.lr_scale * self.step_num for lr in self.base_lrs]\n else:\n return [\n lr\n * self.gamma ** ((self.epoch_num - self.warmup_epoch) // self.step_size)\n for lr in self.base_lrs\n ]\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
<|reserved_special_token_0|>
class TestRoomService(BaseTestCase):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class TestDeviceService(BaseTestCase):
"""Test the device service"""
def test_get_device(self):
device = create_simple_device()
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(2, data['data']['id'])
self.assertEqual('LED1', data['data']['device_name'])
self.assertEqual('simpledevices', data['data']['type'])
self.assertIn('success', data['status'])
def test_get_invalid_device(self):
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
self.assertIn('fail', data['status'])
def test_patch_device(self):
device = create_rgb_device()
patch_data = {'red': 225}
with self.client:
response = self.client.patch('/api/devices/1', data=json.dumps(
patch_data), content_type='application/json')
response_data = json.loads(response.data.decode())
self.assertEqual(response_data['data']['device_name'], 'LED Strip1'
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response_data['data']['red'], 225)
self.assertEqual('rgbleds', response_data['data']['type'])
self.assertIn('success', response_data['status'])
def test_patch_device_invalid_attribute(self):
device = create_rgb_device()
patch_data = {'purple': 225}
with self.client:
response = self.client.patch('/api/devices/1', data=json.dumps(
patch_data), content_type='application/json')
response_data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400)
self.assertIn('fail', response_data['status'])
self.assertIn('Attribute does not exist', response_data['message'])
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TestRoomService(BaseTestCase):
<|reserved_special_token_0|>
def test_get_room(self):
room = create_room()
with self.client:
response = self.client.get('/api/rooms/1')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(1, data['data']['id'])
self.assertEqual('Living Room', data['data']['room_name'])
self.assertIn('success', data['status'])
<|reserved_special_token_0|>
def test_get_all_rooms(self):
room1 = create_room()
room2 = create_room(room_name='Kitchen')
with self.client:
response = self.client.get('api/rooms')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(len(data['data']['rooms']), 2)
self.assertEqual(data['data']['rooms'][0]['room_name'],
'Living Room')
self.assertEqual(data['data']['rooms'][1]['room_name'], 'Kitchen')
self.assertIn('success', data['status'])
class TestDeviceService(BaseTestCase):
"""Test the device service"""
def test_get_device(self):
device = create_simple_device()
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(2, data['data']['id'])
self.assertEqual('LED1', data['data']['device_name'])
self.assertEqual('simpledevices', data['data']['type'])
self.assertIn('success', data['status'])
def test_get_invalid_device(self):
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
self.assertIn('fail', data['status'])
def test_patch_device(self):
device = create_rgb_device()
patch_data = {'red': 225}
with self.client:
response = self.client.patch('/api/devices/1', data=json.dumps(
patch_data), content_type='application/json')
response_data = json.loads(response.data.decode())
self.assertEqual(response_data['data']['device_name'], 'LED Strip1'
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response_data['data']['red'], 225)
self.assertEqual('rgbleds', response_data['data']['type'])
self.assertIn('success', response_data['status'])
def test_patch_device_invalid_attribute(self):
device = create_rgb_device()
patch_data = {'purple': 225}
with self.client:
response = self.client.patch('/api/devices/1', data=json.dumps(
patch_data), content_type='application/json')
response_data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400)
self.assertIn('fail', response_data['status'])
self.assertIn('Attribute does not exist', response_data['message'])
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TestRoomService(BaseTestCase):
"""Test the room service"""
def test_get_room(self):
room = create_room()
with self.client:
response = self.client.get('/api/rooms/1')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(1, data['data']['id'])
self.assertEqual('Living Room', data['data']['room_name'])
self.assertIn('success', data['status'])
def test_invalid_room(self):
with self.client:
response = self.client.get('api/rooms/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
self.assertIn('fail', data['status'])
def test_get_all_rooms(self):
room1 = create_room()
room2 = create_room(room_name='Kitchen')
with self.client:
response = self.client.get('api/rooms')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(len(data['data']['rooms']), 2)
self.assertEqual(data['data']['rooms'][0]['room_name'],
'Living Room')
self.assertEqual(data['data']['rooms'][1]['room_name'], 'Kitchen')
self.assertIn('success', data['status'])
class TestDeviceService(BaseTestCase):
"""Test the device service"""
def test_get_device(self):
device = create_simple_device()
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(2, data['data']['id'])
self.assertEqual('LED1', data['data']['device_name'])
self.assertEqual('simpledevices', data['data']['type'])
self.assertIn('success', data['status'])
def test_get_invalid_device(self):
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
self.assertIn('fail', data['status'])
def test_patch_device(self):
device = create_rgb_device()
patch_data = {'red': 225}
with self.client:
response = self.client.patch('/api/devices/1', data=json.dumps(
patch_data), content_type='application/json')
response_data = json.loads(response.data.decode())
self.assertEqual(response_data['data']['device_name'], 'LED Strip1'
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response_data['data']['red'], 225)
self.assertEqual('rgbleds', response_data['data']['type'])
self.assertIn('success', response_data['status'])
def test_patch_device_invalid_attribute(self):
device = create_rgb_device()
patch_data = {'purple': 225}
with self.client:
response = self.client.patch('/api/devices/1', data=json.dumps(
patch_data), content_type='application/json')
response_data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400)
self.assertIn('fail', response_data['status'])
self.assertIn('Attribute does not exist', response_data['message'])
<|reserved_special_token_1|>
import unittest
import json
from app.tests.base import BaseTestCase
from app import db
from app.tests.utils import create_room, create_simple_device, create_rgb_device
class TestRoomService(BaseTestCase):
"""Test the room service"""
def test_get_room(self):
room = create_room()
with self.client:
response = self.client.get('/api/rooms/1')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(1, data['data']['id'])
self.assertEqual('Living Room', data['data']['room_name'])
self.assertIn('success', data['status'])
def test_invalid_room(self):
with self.client:
response = self.client.get('api/rooms/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
self.assertIn('fail', data['status'])
def test_get_all_rooms(self):
room1 = create_room()
room2 = create_room(room_name='Kitchen')
with self.client:
response = self.client.get('api/rooms')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(len(data['data']['rooms']), 2)
self.assertEqual(data['data']['rooms'][0]['room_name'],
'Living Room')
self.assertEqual(data['data']['rooms'][1]['room_name'], 'Kitchen')
self.assertIn('success', data['status'])
class TestDeviceService(BaseTestCase):
"""Test the device service"""
def test_get_device(self):
device = create_simple_device()
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(2, data['data']['id'])
self.assertEqual('LED1', data['data']['device_name'])
self.assertEqual('simpledevices', data['data']['type'])
self.assertIn('success', data['status'])
def test_get_invalid_device(self):
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
self.assertIn('fail', data['status'])
def test_patch_device(self):
device = create_rgb_device()
patch_data = {'red': 225}
with self.client:
response = self.client.patch('/api/devices/1', data=json.dumps(
patch_data), content_type='application/json')
response_data = json.loads(response.data.decode())
self.assertEqual(response_data['data']['device_name'], 'LED Strip1'
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response_data['data']['red'], 225)
self.assertEqual('rgbleds', response_data['data']['type'])
self.assertIn('success', response_data['status'])
def test_patch_device_invalid_attribute(self):
device = create_rgb_device()
patch_data = {'purple': 225}
with self.client:
response = self.client.patch('/api/devices/1', data=json.dumps(
patch_data), content_type='application/json')
response_data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400)
self.assertIn('fail', response_data['status'])
self.assertIn('Attribute does not exist', response_data['message'])
<|reserved_special_token_1|>
import unittest
import json
from app.tests.base import BaseTestCase
from app import db
from app.tests.utils import create_room, create_simple_device, create_rgb_device
class TestRoomService(BaseTestCase):
"""Test the room service"""
def test_get_room(self):
room = create_room()
with self.client:
response = self.client.get('/api/rooms/1')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(1, data['data']['id'])
self.assertEqual('Living Room', data['data']['room_name'])
self.assertIn('success', data['status'])
def test_invalid_room(self):
with self.client:
response = self.client.get('api/rooms/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
self.assertIn('fail', data['status'])
def test_get_all_rooms(self):
room1 = create_room()
room2 = create_room(room_name="Kitchen")
with self.client:
response = self.client.get('api/rooms')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(len(data['data']['rooms']), 2)
self.assertEqual(data['data']['rooms'][0]['room_name'], 'Living Room')
self.assertEqual(data['data']['rooms'][1]['room_name'], 'Kitchen')
self.assertIn('success', data['status'])
class TestDeviceService(BaseTestCase):
"""Test the device service"""
def test_get_device(self):
device = create_simple_device()
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
self.assertEqual(2, data['data']['id'])
self.assertEqual('LED1', data['data']['device_name'])
self.assertEqual('simpledevices', data['data']['type'])
self.assertIn('success', data['status'])
def test_get_invalid_device(self):
with self.client:
response = self.client.get('api/devices/2')
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
self.assertIn('fail', data['status'])
def test_patch_device(self):
device = create_rgb_device()
patch_data = {'red': 225}
with self.client:
response = self.client.patch(
'/api/devices/1',
data=json.dumps(patch_data),
content_type='application/json'
)
response_data = json.loads(response.data.decode())
self.assertEqual(response_data['data']['device_name'], 'LED Strip1')
self.assertEqual(response.status_code, 200)
self.assertEqual(response_data['data']['red'], 225)
self.assertEqual('rgbleds', response_data['data']['type'])
self.assertIn('success', response_data['status'])
def test_patch_device_invalid_attribute(self):
device = create_rgb_device()
patch_data = {'purple': 225}
with self.client:
response = self.client.patch(
'/api/devices/1',
data=json.dumps(patch_data),
content_type='application/json'
)
response_data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 400)
self.assertIn('fail', response_data['status'])
self.assertIn('Attribute does not exist', response_data['message'])
|
flexible
|
{
"blob_id": "332e2945e34c861b2132f6b42ef59416a38455a5",
"index": 2542,
"step-1": "<mask token>\n\n\nclass TestRoomService(BaseTestCase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TestDeviceService(BaseTestCase):\n \"\"\"Test the device service\"\"\"\n\n def test_get_device(self):\n device = create_simple_device()\n with self.client:\n response = self.client.get('api/devices/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(2, data['data']['id'])\n self.assertEqual('LED1', data['data']['device_name'])\n self.assertEqual('simpledevices', data['data']['type'])\n self.assertIn('success', data['status'])\n\n def test_get_invalid_device(self):\n with self.client:\n response = self.client.get('api/devices/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 404)\n self.assertIn('fail', data['status'])\n\n def test_patch_device(self):\n device = create_rgb_device()\n patch_data = {'red': 225}\n with self.client:\n response = self.client.patch('/api/devices/1', data=json.dumps(\n patch_data), content_type='application/json')\n response_data = json.loads(response.data.decode())\n self.assertEqual(response_data['data']['device_name'], 'LED Strip1'\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response_data['data']['red'], 225)\n self.assertEqual('rgbleds', response_data['data']['type'])\n self.assertIn('success', response_data['status'])\n\n def test_patch_device_invalid_attribute(self):\n device = create_rgb_device()\n patch_data = {'purple': 225}\n with self.client:\n response = self.client.patch('/api/devices/1', data=json.dumps(\n patch_data), content_type='application/json')\n response_data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 400)\n self.assertIn('fail', response_data['status'])\n self.assertIn('Attribute does not exist', response_data['message'])\n",
"step-2": "<mask token>\n\n\nclass TestRoomService(BaseTestCase):\n <mask token>\n\n def test_get_room(self):\n room = create_room()\n with self.client:\n response = self.client.get('/api/rooms/1')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(1, data['data']['id'])\n self.assertEqual('Living Room', data['data']['room_name'])\n self.assertIn('success', data['status'])\n <mask token>\n\n def test_get_all_rooms(self):\n room1 = create_room()\n room2 = create_room(room_name='Kitchen')\n with self.client:\n response = self.client.get('api/rooms')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(data['data']['rooms']), 2)\n self.assertEqual(data['data']['rooms'][0]['room_name'],\n 'Living Room')\n self.assertEqual(data['data']['rooms'][1]['room_name'], 'Kitchen')\n self.assertIn('success', data['status'])\n\n\nclass TestDeviceService(BaseTestCase):\n \"\"\"Test the device service\"\"\"\n\n def test_get_device(self):\n device = create_simple_device()\n with self.client:\n response = self.client.get('api/devices/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(2, data['data']['id'])\n self.assertEqual('LED1', data['data']['device_name'])\n self.assertEqual('simpledevices', data['data']['type'])\n self.assertIn('success', data['status'])\n\n def test_get_invalid_device(self):\n with self.client:\n response = self.client.get('api/devices/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 404)\n self.assertIn('fail', data['status'])\n\n def test_patch_device(self):\n device = create_rgb_device()\n patch_data = {'red': 225}\n with self.client:\n response = self.client.patch('/api/devices/1', data=json.dumps(\n patch_data), content_type='application/json')\n response_data = json.loads(response.data.decode())\n self.assertEqual(response_data['data']['device_name'], 'LED Strip1'\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response_data['data']['red'], 225)\n self.assertEqual('rgbleds', response_data['data']['type'])\n self.assertIn('success', response_data['status'])\n\n def test_patch_device_invalid_attribute(self):\n device = create_rgb_device()\n patch_data = {'purple': 225}\n with self.client:\n response = self.client.patch('/api/devices/1', data=json.dumps(\n patch_data), content_type='application/json')\n response_data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 400)\n self.assertIn('fail', response_data['status'])\n self.assertIn('Attribute does not exist', response_data['message'])\n",
"step-3": "<mask token>\n\n\nclass TestRoomService(BaseTestCase):\n \"\"\"Test the room service\"\"\"\n\n def test_get_room(self):\n room = create_room()\n with self.client:\n response = self.client.get('/api/rooms/1')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(1, data['data']['id'])\n self.assertEqual('Living Room', data['data']['room_name'])\n self.assertIn('success', data['status'])\n\n def test_invalid_room(self):\n with self.client:\n response = self.client.get('api/rooms/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 404)\n self.assertIn('fail', data['status'])\n\n def test_get_all_rooms(self):\n room1 = create_room()\n room2 = create_room(room_name='Kitchen')\n with self.client:\n response = self.client.get('api/rooms')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(data['data']['rooms']), 2)\n self.assertEqual(data['data']['rooms'][0]['room_name'],\n 'Living Room')\n self.assertEqual(data['data']['rooms'][1]['room_name'], 'Kitchen')\n self.assertIn('success', data['status'])\n\n\nclass TestDeviceService(BaseTestCase):\n \"\"\"Test the device service\"\"\"\n\n def test_get_device(self):\n device = create_simple_device()\n with self.client:\n response = self.client.get('api/devices/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(2, data['data']['id'])\n self.assertEqual('LED1', data['data']['device_name'])\n self.assertEqual('simpledevices', data['data']['type'])\n self.assertIn('success', data['status'])\n\n def test_get_invalid_device(self):\n with self.client:\n response = self.client.get('api/devices/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 404)\n self.assertIn('fail', data['status'])\n\n def test_patch_device(self):\n device = create_rgb_device()\n patch_data = {'red': 225}\n with self.client:\n response = self.client.patch('/api/devices/1', data=json.dumps(\n patch_data), content_type='application/json')\n response_data = json.loads(response.data.decode())\n self.assertEqual(response_data['data']['device_name'], 'LED Strip1'\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response_data['data']['red'], 225)\n self.assertEqual('rgbleds', response_data['data']['type'])\n self.assertIn('success', response_data['status'])\n\n def test_patch_device_invalid_attribute(self):\n device = create_rgb_device()\n patch_data = {'purple': 225}\n with self.client:\n response = self.client.patch('/api/devices/1', data=json.dumps(\n patch_data), content_type='application/json')\n response_data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 400)\n self.assertIn('fail', response_data['status'])\n self.assertIn('Attribute does not exist', response_data['message'])\n",
"step-4": "import unittest\nimport json\nfrom app.tests.base import BaseTestCase\nfrom app import db\nfrom app.tests.utils import create_room, create_simple_device, create_rgb_device\n\n\nclass TestRoomService(BaseTestCase):\n \"\"\"Test the room service\"\"\"\n\n def test_get_room(self):\n room = create_room()\n with self.client:\n response = self.client.get('/api/rooms/1')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(1, data['data']['id'])\n self.assertEqual('Living Room', data['data']['room_name'])\n self.assertIn('success', data['status'])\n\n def test_invalid_room(self):\n with self.client:\n response = self.client.get('api/rooms/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 404)\n self.assertIn('fail', data['status'])\n\n def test_get_all_rooms(self):\n room1 = create_room()\n room2 = create_room(room_name='Kitchen')\n with self.client:\n response = self.client.get('api/rooms')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(data['data']['rooms']), 2)\n self.assertEqual(data['data']['rooms'][0]['room_name'],\n 'Living Room')\n self.assertEqual(data['data']['rooms'][1]['room_name'], 'Kitchen')\n self.assertIn('success', data['status'])\n\n\nclass TestDeviceService(BaseTestCase):\n \"\"\"Test the device service\"\"\"\n\n def test_get_device(self):\n device = create_simple_device()\n with self.client:\n response = self.client.get('api/devices/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(2, data['data']['id'])\n self.assertEqual('LED1', data['data']['device_name'])\n self.assertEqual('simpledevices', data['data']['type'])\n self.assertIn('success', data['status'])\n\n def test_get_invalid_device(self):\n with self.client:\n response = self.client.get('api/devices/2')\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 404)\n self.assertIn('fail', data['status'])\n\n def test_patch_device(self):\n device = create_rgb_device()\n patch_data = {'red': 225}\n with self.client:\n response = self.client.patch('/api/devices/1', data=json.dumps(\n patch_data), content_type='application/json')\n response_data = json.loads(response.data.decode())\n self.assertEqual(response_data['data']['device_name'], 'LED Strip1'\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response_data['data']['red'], 225)\n self.assertEqual('rgbleds', response_data['data']['type'])\n self.assertIn('success', response_data['status'])\n\n def test_patch_device_invalid_attribute(self):\n device = create_rgb_device()\n patch_data = {'purple': 225}\n with self.client:\n response = self.client.patch('/api/devices/1', data=json.dumps(\n patch_data), content_type='application/json')\n response_data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 400)\n self.assertIn('fail', response_data['status'])\n self.assertIn('Attribute does not exist', response_data['message'])\n",
"step-5": "import unittest\nimport json\n\nfrom app.tests.base import BaseTestCase\nfrom app import db\nfrom app.tests.utils import create_room, create_simple_device, create_rgb_device\n\nclass TestRoomService(BaseTestCase):\n\t\"\"\"Test the room service\"\"\"\n\n\tdef test_get_room(self):\n\t\troom = create_room()\n\n\t\twith self.client:\n\t\t\tresponse = self.client.get('/api/rooms/1')\n\t\t\tdata = json.loads(response.data.decode())\n\t\t\tself.assertEqual(response.status_code, 200)\n\t\t\tself.assertEqual(1, data['data']['id'])\n\t\t\tself.assertEqual('Living Room', data['data']['room_name'])\n\t\t\tself.assertIn('success', data['status'])\n\n\tdef test_invalid_room(self):\n\t\twith self.client:\n\t\t\tresponse = self.client.get('api/rooms/2')\n\t\t\tdata = json.loads(response.data.decode())\n\t\t\tself.assertEqual(response.status_code, 404)\n\t\t\tself.assertIn('fail', data['status'])\n\n\tdef test_get_all_rooms(self):\n\t\troom1 = create_room()\n\t\troom2 = create_room(room_name=\"Kitchen\")\n\n\t\twith self.client:\n\t\t\tresponse = self.client.get('api/rooms')\n\t\t\tdata = json.loads(response.data.decode())\n\n\t\t\tself.assertEqual(response.status_code, 200)\n\t\t\tself.assertEqual(len(data['data']['rooms']), 2)\n\t\t\tself.assertEqual(data['data']['rooms'][0]['room_name'], 'Living Room')\n\t\t\tself.assertEqual(data['data']['rooms'][1]['room_name'], 'Kitchen')\n\t\t\tself.assertIn('success', data['status'])\n\nclass TestDeviceService(BaseTestCase):\n\t\"\"\"Test the device service\"\"\"\n\n\tdef test_get_device(self):\n\t\tdevice = create_simple_device()\n\n\t\twith self.client:\n\t\t\tresponse = self.client.get('api/devices/2')\n\t\t\tdata = json.loads(response.data.decode())\n\n\t\t\tself.assertEqual(response.status_code, 200)\n\t\t\tself.assertEqual(2, data['data']['id'])\n\t\t\tself.assertEqual('LED1', data['data']['device_name'])\n\t\t\tself.assertEqual('simpledevices', data['data']['type'])\n\t\t\tself.assertIn('success', data['status'])\n\n\tdef test_get_invalid_device(self):\n\t\twith self.client:\n\t\t\tresponse = self.client.get('api/devices/2')\n\t\t\tdata = json.loads(response.data.decode())\n\t\t\tself.assertEqual(response.status_code, 404)\n\t\t\tself.assertIn('fail', data['status'])\n\n\n\tdef test_patch_device(self):\n\t\tdevice = create_rgb_device()\n\t\tpatch_data = {'red': 225}\n\n\t\twith self.client:\n\t\t\tresponse = self.client.patch(\n\t\t\t\t'/api/devices/1',\n\t\t\t\tdata=json.dumps(patch_data),\n\t\t\t\tcontent_type='application/json'\n\t\t\t)\n\t\t\tresponse_data = json.loads(response.data.decode())\n\n\t\t\tself.assertEqual(response_data['data']['device_name'], 'LED Strip1')\n\t\t\tself.assertEqual(response.status_code, 200)\n\t\t\tself.assertEqual(response_data['data']['red'], 225)\n\t\t\tself.assertEqual('rgbleds', response_data['data']['type'])\n\t\t\tself.assertIn('success', response_data['status'])\n\n\tdef test_patch_device_invalid_attribute(self):\n\t\tdevice = create_rgb_device()\n\t\tpatch_data = {'purple': 225}\n\n\t\twith self.client:\n\t\t\tresponse = self.client.patch(\n\t\t\t\t'/api/devices/1',\n\t\t\t\tdata=json.dumps(patch_data),\n\t\t\t\tcontent_type='application/json'\n\t\t\t)\n\t\t\tresponse_data = json.loads(response.data.decode())\n\n\t\t\tself.assertEqual(response.status_code, 400)\n\t\t\tself.assertIn('fail', response_data['status'])\n\t\t\tself.assertIn('Attribute does not exist', response_data['message'])\n\n\n",
"step-ids": [
7,
9,
11,
12,
13
]
}
|
[
7,
9,
11,
12,
13
] |
<|reserved_special_token_0|>
class ResizeImageBuilder:
def __init__(self):
pass
def setOriginImagePath(self, filePath):
try:
img = Image.open(filePath)
print('origin image mode:', img.mode)
img = img.convert('RGB')
print('target image mode:', img.mode)
self.baseImage = img
return None
except (BaseException, e):
return str(filePath + ' open error: ' + traceback.format_exc(e))
def createImageWithOriginImage(self, img, imageSize):
return img.resize((imageSize, imageSize), Image.ANTIALIAS)
<|reserved_special_token_0|>
def createImage(self, savePath, imageSize):
if self.baseImage == None:
print(
'error: self.baseImage == None, please call setOriginImagePath() before createImage()'
)
return
try:
newimg = self.createImageWithOriginImage(self.baseImage, imageSize)
self.saveImageWithPath(newimg, savePath)
except (BaseException, e):
return 'createImage error: ' + traceback.format_exc(e)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class ResizeImageBuilder:
def __init__(self):
pass
def setOriginImagePath(self, filePath):
try:
img = Image.open(filePath)
print('origin image mode:', img.mode)
img = img.convert('RGB')
print('target image mode:', img.mode)
self.baseImage = img
return None
except (BaseException, e):
return str(filePath + ' open error: ' + traceback.format_exc(e))
def createImageWithOriginImage(self, img, imageSize):
return img.resize((imageSize, imageSize), Image.ANTIALIAS)
def saveImageWithPath(self, img, savePath):
img.save(savePath)
def createImage(self, savePath, imageSize):
if self.baseImage == None:
print(
'error: self.baseImage == None, please call setOriginImagePath() before createImage()'
)
return
try:
newimg = self.createImageWithOriginImage(self.baseImage, imageSize)
self.saveImageWithPath(newimg, savePath)
except (BaseException, e):
return 'createImage error: ' + traceback.format_exc(e)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class ResizeImageBuilder:
def __init__(self):
pass
def setOriginImagePath(self, filePath):
try:
img = Image.open(filePath)
print('origin image mode:', img.mode)
img = img.convert('RGB')
print('target image mode:', img.mode)
self.baseImage = img
return None
except (BaseException, e):
return str(filePath + ' open error: ' + traceback.format_exc(e))
def createImageWithOriginImage(self, img, imageSize):
return img.resize((imageSize, imageSize), Image.ANTIALIAS)
def saveImageWithPath(self, img, savePath):
img.save(savePath)
def createImage(self, savePath, imageSize):
if self.baseImage == None:
print(
'error: self.baseImage == None, please call setOriginImagePath() before createImage()'
)
return
try:
newimg = self.createImageWithOriginImage(self.baseImage, imageSize)
self.saveImageWithPath(newimg, savePath)
except (BaseException, e):
return 'createImage error: ' + traceback.format_exc(e)
def main():
pass
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
import sys, os, traceback
from PIL import Image
class ResizeImageBuilder:
def __init__(self):
pass
def setOriginImagePath(self, filePath):
try:
img = Image.open(filePath)
print('origin image mode:', img.mode)
img = img.convert('RGB')
print('target image mode:', img.mode)
self.baseImage = img
return None
except (BaseException, e):
return str(filePath + ' open error: ' + traceback.format_exc(e))
def createImageWithOriginImage(self, img, imageSize):
return img.resize((imageSize, imageSize), Image.ANTIALIAS)
def saveImageWithPath(self, img, savePath):
img.save(savePath)
def createImage(self, savePath, imageSize):
if self.baseImage == None:
print(
'error: self.baseImage == None, please call setOriginImagePath() before createImage()'
)
return
try:
newimg = self.createImageWithOriginImage(self.baseImage, imageSize)
self.saveImageWithPath(newimg, savePath)
except (BaseException, e):
return 'createImage error: ' + traceback.format_exc(e)
def main():
pass
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys,os,traceback
from PIL import Image
class ResizeImageBuilder:
def __init__(self):
# print(self.__class__)
pass
def setOriginImagePath(self, filePath):
try:
img = Image.open(filePath)
# img = img.convert('RGB')
# size = 32, 32
# img.thumbnail(size)
print('origin image mode:', img.mode)
img = img.convert('RGB')
print('target image mode:', img.mode)
# img.show()
self.baseImage = img
return None
except (BaseException,e):
return str(filePath + " open error: " + traceback.format_exc(e))
def createImageWithOriginImage(self, img, imageSize):
return img.resize((imageSize, imageSize),Image.ANTIALIAS)
def saveImageWithPath(self, img, savePath):
img.save(savePath)
def createImage(self, savePath, imageSize):
if self.baseImage == None:
print('error: self.baseImage == None, please call setOriginImagePath() before createImage()')
return
try:
newimg = self.createImageWithOriginImage(self.baseImage, imageSize)
self.saveImageWithPath(newimg, savePath)
# print('done')
except (BaseException,e):
return 'createImage error: ' + traceback.format_exc(e)
def main():
# builder = ResizeImageBuilder()
# builder.setOriginImagePath(originImagePath)
# builder.createImage(path1, size1)
# builder.createImage(path2, size2)
pass
if __name__ == '__main__':
main()
|
flexible
|
{
"blob_id": "47119f46cdbbb7306aef8237d4f56f0f10690ae4",
"index": 9245,
"step-1": "<mask token>\n\n\nclass ResizeImageBuilder:\n\n def __init__(self):\n pass\n\n def setOriginImagePath(self, filePath):\n try:\n img = Image.open(filePath)\n print('origin image mode:', img.mode)\n img = img.convert('RGB')\n print('target image mode:', img.mode)\n self.baseImage = img\n return None\n except (BaseException, e):\n return str(filePath + ' open error: ' + traceback.format_exc(e))\n\n def createImageWithOriginImage(self, img, imageSize):\n return img.resize((imageSize, imageSize), Image.ANTIALIAS)\n <mask token>\n\n def createImage(self, savePath, imageSize):\n if self.baseImage == None:\n print(\n 'error: self.baseImage == None, please call setOriginImagePath() before createImage()'\n )\n return\n try:\n newimg = self.createImageWithOriginImage(self.baseImage, imageSize)\n self.saveImageWithPath(newimg, savePath)\n except (BaseException, e):\n return 'createImage error: ' + traceback.format_exc(e)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass ResizeImageBuilder:\n\n def __init__(self):\n pass\n\n def setOriginImagePath(self, filePath):\n try:\n img = Image.open(filePath)\n print('origin image mode:', img.mode)\n img = img.convert('RGB')\n print('target image mode:', img.mode)\n self.baseImage = img\n return None\n except (BaseException, e):\n return str(filePath + ' open error: ' + traceback.format_exc(e))\n\n def createImageWithOriginImage(self, img, imageSize):\n return img.resize((imageSize, imageSize), Image.ANTIALIAS)\n\n def saveImageWithPath(self, img, savePath):\n img.save(savePath)\n\n def createImage(self, savePath, imageSize):\n if self.baseImage == None:\n print(\n 'error: self.baseImage == None, please call setOriginImagePath() before createImage()'\n )\n return\n try:\n newimg = self.createImageWithOriginImage(self.baseImage, imageSize)\n self.saveImageWithPath(newimg, savePath)\n except (BaseException, e):\n return 'createImage error: ' + traceback.format_exc(e)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass ResizeImageBuilder:\n\n def __init__(self):\n pass\n\n def setOriginImagePath(self, filePath):\n try:\n img = Image.open(filePath)\n print('origin image mode:', img.mode)\n img = img.convert('RGB')\n print('target image mode:', img.mode)\n self.baseImage = img\n return None\n except (BaseException, e):\n return str(filePath + ' open error: ' + traceback.format_exc(e))\n\n def createImageWithOriginImage(self, img, imageSize):\n return img.resize((imageSize, imageSize), Image.ANTIALIAS)\n\n def saveImageWithPath(self, img, savePath):\n img.save(savePath)\n\n def createImage(self, savePath, imageSize):\n if self.baseImage == None:\n print(\n 'error: self.baseImage == None, please call setOriginImagePath() before createImage()'\n )\n return\n try:\n newimg = self.createImageWithOriginImage(self.baseImage, imageSize)\n self.saveImageWithPath(newimg, savePath)\n except (BaseException, e):\n return 'createImage error: ' + traceback.format_exc(e)\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "import sys, os, traceback\nfrom PIL import Image\n\n\nclass ResizeImageBuilder:\n\n def __init__(self):\n pass\n\n def setOriginImagePath(self, filePath):\n try:\n img = Image.open(filePath)\n print('origin image mode:', img.mode)\n img = img.convert('RGB')\n print('target image mode:', img.mode)\n self.baseImage = img\n return None\n except (BaseException, e):\n return str(filePath + ' open error: ' + traceback.format_exc(e))\n\n def createImageWithOriginImage(self, img, imageSize):\n return img.resize((imageSize, imageSize), Image.ANTIALIAS)\n\n def saveImageWithPath(self, img, savePath):\n img.save(savePath)\n\n def createImage(self, savePath, imageSize):\n if self.baseImage == None:\n print(\n 'error: self.baseImage == None, please call setOriginImagePath() before createImage()'\n )\n return\n try:\n newimg = self.createImageWithOriginImage(self.baseImage, imageSize)\n self.saveImageWithPath(newimg, savePath)\n except (BaseException, e):\n return 'createImage error: ' + traceback.format_exc(e)\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys,os,traceback\nfrom PIL import Image\n\nclass ResizeImageBuilder:\n def __init__(self):\n # print(self.__class__)\n pass\n\n def setOriginImagePath(self, filePath):\n try:\n img = Image.open(filePath)\n # img = img.convert('RGB')\n # size = 32, 32\n # img.thumbnail(size)\n print('origin image mode:', img.mode)\n img = img.convert('RGB')\n print('target image mode:', img.mode)\n # img.show()\n self.baseImage = img\n return None\n except (BaseException,e):\n return str(filePath + \" open error: \" + traceback.format_exc(e))\n\n def createImageWithOriginImage(self, img, imageSize):\n return img.resize((imageSize, imageSize),Image.ANTIALIAS)\n\n def saveImageWithPath(self, img, savePath):\n img.save(savePath)\n\n def createImage(self, savePath, imageSize):\n if self.baseImage == None:\n print('error: self.baseImage == None, please call setOriginImagePath() before createImage()')\n return\n\n try:\n newimg = self.createImageWithOriginImage(self.baseImage, imageSize)\n self.saveImageWithPath(newimg, savePath)\n # print('done')\n except (BaseException,e):\n return 'createImage error: ' + traceback.format_exc(e)\n\ndef main():\n # builder = ResizeImageBuilder()\n # builder.setOriginImagePath(originImagePath)\n # builder.createImage(path1, size1)\n # builder.createImage(path2, size2)\n pass\n\nif __name__ == '__main__':\n main()",
"step-ids": [
5,
6,
8,
9,
10
]
}
|
[
5,
6,
8,
9,
10
] |
from project import db
from project.models import User, Recipe, Association, Ingre, Recipe_ingre
user=User.query.filter_by(username="xiaofan").first()
recipe=Recipe.query.filter_by(recipename="Jerry").first()
recipes = Recipe.query.filter(Recipe.users.any(username="xiaofan")).all()
if recipe not in recipes:
user.add_recipes([recipe])
# commit the changes
db.session.commit()
|
normal
|
{
"blob_id": "07f8fd305e2311c0e37a785da0a826b8ea4e78ba",
"index": 4154,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif recipe not in recipes:\n user.add_recipes([recipe])\n db.session.commit()\n",
"step-3": "<mask token>\nuser = User.query.filter_by(username='xiaofan').first()\nrecipe = Recipe.query.filter_by(recipename='Jerry').first()\nrecipes = Recipe.query.filter(Recipe.users.any(username='xiaofan')).all()\nif recipe not in recipes:\n user.add_recipes([recipe])\n db.session.commit()\n",
"step-4": "from project import db\nfrom project.models import User, Recipe, Association, Ingre, Recipe_ingre\nuser = User.query.filter_by(username='xiaofan').first()\nrecipe = Recipe.query.filter_by(recipename='Jerry').first()\nrecipes = Recipe.query.filter(Recipe.users.any(username='xiaofan')).all()\nif recipe not in recipes:\n user.add_recipes([recipe])\n db.session.commit()\n",
"step-5": "from project import db\nfrom project.models import User, Recipe, Association, Ingre, Recipe_ingre\n\n\n\n\nuser=User.query.filter_by(username=\"xiaofan\").first()\nrecipe=Recipe.query.filter_by(recipename=\"Jerry\").first()\nrecipes = Recipe.query.filter(Recipe.users.any(username=\"xiaofan\")).all()\n\nif recipe not in recipes:\n user.add_recipes([recipe])\n\n # commit the changes\n db.session.commit()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class UserRegistrationForm(UserCreationForm):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Meta:
model = User
fields = 'first_name', 'last_name', 'email', 'password1', 'password2'
<|reserved_special_token_0|>
class UserLoginForm(forms.Form):
username = forms.CharField(label='', widget=forms.TextInput(attrs={
'placeholder': 'Username'}))
password = forms.CharField(label='', widget=forms.PasswordInput(attrs={
'placeholder': 'Password'}))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class UserRegistrationForm(UserCreationForm):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Meta:
model = User
fields = 'first_name', 'last_name', 'email', 'password1', 'password2'
def save(self, commit=True):
user = super(UserRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.user_type = 2
if commit:
user.save()
return user
class UserLoginForm(forms.Form):
username = forms.CharField(label='', widget=forms.TextInput(attrs={
'placeholder': 'Username'}))
password = forms.CharField(label='', widget=forms.PasswordInput(attrs={
'placeholder': 'Password'}))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
password1 = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = 'first_name', 'last_name', 'email', 'password1', 'password2'
def save(self, commit=True):
user = super(UserRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.user_type = 2
if commit:
user.save()
return user
class UserLoginForm(forms.Form):
username = forms.CharField(label='', widget=forms.TextInput(attrs={
'placeholder': 'Username'}))
password = forms.CharField(label='', widget=forms.PasswordInput(attrs={
'placeholder': 'Password'}))
<|reserved_special_token_1|>
from accounts.models import User
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
password1 = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = 'first_name', 'last_name', 'email', 'password1', 'password2'
def save(self, commit=True):
user = super(UserRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.user_type = 2
if commit:
user.save()
return user
class UserLoginForm(forms.Form):
username = forms.CharField(label='', widget=forms.TextInput(attrs={
'placeholder': 'Username'}))
password = forms.CharField(label='', widget=forms.PasswordInput(attrs={
'placeholder': 'Password'}))
<|reserved_special_token_1|>
from accounts.models import User
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
password1 = forms.CharField(
widget=forms.PasswordInput,
# help_text=password_validation.password_validators_help_text_html(),
)
class Meta:
model = User
fields = ("first_name","last_name","email", "password1", "password2")
def save(self, commit=True):
user = super(UserRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.user_type = 2
if commit:
user.save()
return user
class UserLoginForm(forms.Form):
username=forms.CharField(label='',widget=forms.TextInput(attrs={'placeholder':'Username'}))
password=forms.CharField(label='',widget=forms.PasswordInput(attrs={'placeholder':'Password'}))
|
flexible
|
{
"blob_id": "e50517910e191594034f60a021647f4415b6f1c4",
"index": 2822,
"step-1": "<mask token>\n\n\nclass UserRegistrationForm(UserCreationForm):\n <mask token>\n <mask token>\n\n\n class Meta:\n model = User\n fields = 'first_name', 'last_name', 'email', 'password1', 'password2'\n <mask token>\n\n\nclass UserLoginForm(forms.Form):\n username = forms.CharField(label='', widget=forms.TextInput(attrs={\n 'placeholder': 'Username'}))\n password = forms.CharField(label='', widget=forms.PasswordInput(attrs={\n 'placeholder': 'Password'}))\n",
"step-2": "<mask token>\n\n\nclass UserRegistrationForm(UserCreationForm):\n <mask token>\n <mask token>\n\n\n class Meta:\n model = User\n fields = 'first_name', 'last_name', 'email', 'password1', 'password2'\n\n def save(self, commit=True):\n user = super(UserRegistrationForm, self).save(commit=False)\n user.email = self.cleaned_data['email']\n user.user_type = 2\n if commit:\n user.save()\n return user\n\n\nclass UserLoginForm(forms.Form):\n username = forms.CharField(label='', widget=forms.TextInput(attrs={\n 'placeholder': 'Username'}))\n password = forms.CharField(label='', widget=forms.PasswordInput(attrs={\n 'placeholder': 'Password'}))\n",
"step-3": "<mask token>\n\n\nclass UserRegistrationForm(UserCreationForm):\n email = forms.EmailField(required=True)\n password1 = forms.CharField(widget=forms.PasswordInput)\n\n\n class Meta:\n model = User\n fields = 'first_name', 'last_name', 'email', 'password1', 'password2'\n\n def save(self, commit=True):\n user = super(UserRegistrationForm, self).save(commit=False)\n user.email = self.cleaned_data['email']\n user.user_type = 2\n if commit:\n user.save()\n return user\n\n\nclass UserLoginForm(forms.Form):\n username = forms.CharField(label='', widget=forms.TextInput(attrs={\n 'placeholder': 'Username'}))\n password = forms.CharField(label='', widget=forms.PasswordInput(attrs={\n 'placeholder': 'Password'}))\n",
"step-4": "from accounts.models import User\nfrom django.forms import ModelForm\nfrom django import forms\nfrom django.contrib.auth.forms import UserCreationForm\n\n\nclass UserRegistrationForm(UserCreationForm):\n email = forms.EmailField(required=True)\n password1 = forms.CharField(widget=forms.PasswordInput)\n\n\n class Meta:\n model = User\n fields = 'first_name', 'last_name', 'email', 'password1', 'password2'\n\n def save(self, commit=True):\n user = super(UserRegistrationForm, self).save(commit=False)\n user.email = self.cleaned_data['email']\n user.user_type = 2\n if commit:\n user.save()\n return user\n\n\nclass UserLoginForm(forms.Form):\n username = forms.CharField(label='', widget=forms.TextInput(attrs={\n 'placeholder': 'Username'}))\n password = forms.CharField(label='', widget=forms.PasswordInput(attrs={\n 'placeholder': 'Password'}))\n",
"step-5": "from accounts.models import User\nfrom django.forms import ModelForm\nfrom django import forms\nfrom django.contrib.auth.forms import UserCreationForm\n\nclass UserRegistrationForm(UserCreationForm):\n\temail = forms.EmailField(required=True)\n\tpassword1 = forms.CharField(\n\n\t\twidget=forms.PasswordInput,\n\t\t# help_text=password_validation.password_validators_help_text_html(),\n\t)\n\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = (\"first_name\",\"last_name\",\"email\", \"password1\", \"password2\")\n\n\n\tdef save(self, commit=True):\n\t\tuser = super(UserRegistrationForm, self).save(commit=False)\n\t\tuser.email = self.cleaned_data['email']\n\t\tuser.user_type = 2\n\t\tif commit:\n\t\t\tuser.save()\n\t\treturn user\n\n\nclass UserLoginForm(forms.Form):\n username=forms.CharField(label='',widget=forms.TextInput(attrs={'placeholder':'Username'}))\n password=forms.CharField(label='',widget=forms.PasswordInput(attrs={'placeholder':'Password'}))\n\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
<|reserved_special_token_0|>
class LinearRegressor:
<|reserved_special_token_0|>
def _cost_function(self, y_pred, y, m):
"""
Gets the cost for the predicted values when contrasted with the correct ones.
y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor
y: An (1 x m) vector that corresponds to the y (right) values in the dataset
m: the number of samples (it could be also inferred from the shape of y or y_pred)
TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration
"""
sumatory = 0
for x in range(m):
sumatory += (y_pred[0][x] - y[0][x]) ** 2
cost = 1 / (2 * m) * sumatory
return cost
<|reserved_special_token_0|>
def _cost_function_derivative(self, y_pred, y, X, m):
"""
Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.
y_pred: an (1 x m) array with the predicted values for X dataset
y: an (1 x m) array with the right values for X dataset
X: the input dataset
m: the number of samples in the dataset
TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.
"""
derivatives = np.zeros((X.shape[0], 1))
for j in range(X.shape[0]):
auxsum = 0
for i in range(m):
auxsum += (y_pred[0][i] - y[0][i]) * X[j][i]
derivatives[j][0] = self.theta[j][0] - self.alpha * 1 / m * auxsum
return derivatives
def fit(self, X, y):
"""
Fits the linear regressor to the values in the dataset
X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples
y: is an (1 x m) vector, where m is the number of samples/examples
TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions
"""
n, m = X.shape[0], X.shape[1]
self.theta = np.random.uniform(-10, 10, (n, 1))
for i in range(self.epochs):
y_pred = self.predict(X)
cost = self._cost_function(y_pred, y, m)
gradient = self._cost_function_derivative(y_pred, y, X, m)
self.theta = gradient
self.costs.append(cost)
pass
print('Final theta is {} (cost: {})'.format(self.theta.T, cost))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class LinearRegressor:
<|reserved_special_token_0|>
def _cost_function(self, y_pred, y, m):
"""
Gets the cost for the predicted values when contrasted with the correct ones.
y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor
y: An (1 x m) vector that corresponds to the y (right) values in the dataset
m: the number of samples (it could be also inferred from the shape of y or y_pred)
TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration
"""
sumatory = 0
for x in range(m):
sumatory += (y_pred[0][x] - y[0][x]) ** 2
cost = 1 / (2 * m) * sumatory
return cost
def _hypothesis(self, X):
"""
Calculates the hypothesis for the given examples using the current self.theta values.
X: an m x n array of m samples/examples with n features each.
Creo que X es en realidad nxm
transpose de theta es 1xn y * nxm = 1xm
TODO: you must return a (1 x m) array, which corresponds to the estimated value for each of the m samples
"""
result = np.transpose(self.theta) @ X
return result
def _cost_function_derivative(self, y_pred, y, X, m):
"""
Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.
y_pred: an (1 x m) array with the predicted values for X dataset
y: an (1 x m) array with the right values for X dataset
X: the input dataset
m: the number of samples in the dataset
TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.
"""
derivatives = np.zeros((X.shape[0], 1))
for j in range(X.shape[0]):
auxsum = 0
for i in range(m):
auxsum += (y_pred[0][i] - y[0][i]) * X[j][i]
derivatives[j][0] = self.theta[j][0] - self.alpha * 1 / m * auxsum
return derivatives
def fit(self, X, y):
"""
Fits the linear regressor to the values in the dataset
X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples
y: is an (1 x m) vector, where m is the number of samples/examples
TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions
"""
n, m = X.shape[0], X.shape[1]
self.theta = np.random.uniform(-10, 10, (n, 1))
for i in range(self.epochs):
y_pred = self.predict(X)
cost = self._cost_function(y_pred, y, m)
gradient = self._cost_function_derivative(y_pred, y, X, m)
self.theta = gradient
self.costs.append(cost)
pass
print('Final theta is {} (cost: {})'.format(self.theta.T, cost))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class LinearRegressor:
def __init__(self, alpha=0.1, epochs=1):
self.alpha = alpha
self.epochs = epochs
self.costs = []
self.theta = None
def _cost_function(self, y_pred, y, m):
"""
Gets the cost for the predicted values when contrasted with the correct ones.
y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor
y: An (1 x m) vector that corresponds to the y (right) values in the dataset
m: the number of samples (it could be also inferred from the shape of y or y_pred)
TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration
"""
sumatory = 0
for x in range(m):
sumatory += (y_pred[0][x] - y[0][x]) ** 2
cost = 1 / (2 * m) * sumatory
return cost
def _hypothesis(self, X):
"""
Calculates the hypothesis for the given examples using the current self.theta values.
X: an m x n array of m samples/examples with n features each.
Creo que X es en realidad nxm
transpose de theta es 1xn y * nxm = 1xm
TODO: you must return a (1 x m) array, which corresponds to the estimated value for each of the m samples
"""
result = np.transpose(self.theta) @ X
return result
def _cost_function_derivative(self, y_pred, y, X, m):
"""
Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.
y_pred: an (1 x m) array with the predicted values for X dataset
y: an (1 x m) array with the right values for X dataset
X: the input dataset
m: the number of samples in the dataset
TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.
"""
derivatives = np.zeros((X.shape[0], 1))
for j in range(X.shape[0]):
auxsum = 0
for i in range(m):
auxsum += (y_pred[0][i] - y[0][i]) * X[j][i]
derivatives[j][0] = self.theta[j][0] - self.alpha * 1 / m * auxsum
return derivatives
def fit(self, X, y):
"""
Fits the linear regressor to the values in the dataset
X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples
y: is an (1 x m) vector, where m is the number of samples/examples
TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions
"""
n, m = X.shape[0], X.shape[1]
self.theta = np.random.uniform(-10, 10, (n, 1))
for i in range(self.epochs):
y_pred = self.predict(X)
cost = self._cost_function(y_pred, y, m)
gradient = self._cost_function_derivative(y_pred, y, X, m)
self.theta = gradient
self.costs.append(cost)
pass
print('Final theta is {} (cost: {})'.format(self.theta.T, cost))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
import numpy as np
class LinearRegressor:
def __init__(self, alpha=0.1, epochs=1):
self.alpha = alpha
self.epochs = epochs
self.costs = []
self.theta = None
def _cost_function(self, y_pred, y, m):
"""
Gets the cost for the predicted values when contrasted with the correct ones.
y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor
y: An (1 x m) vector that corresponds to the y (right) values in the dataset
m: the number of samples (it could be also inferred from the shape of y or y_pred)
TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration
"""
sumatory = 0
for x in range(m):
sumatory += (y_pred[0][x] - y[0][x]) ** 2
cost = 1 / (2 * m) * sumatory
return cost
def _hypothesis(self, X):
"""
Calculates the hypothesis for the given examples using the current self.theta values.
X: an m x n array of m samples/examples with n features each.
Creo que X es en realidad nxm
transpose de theta es 1xn y * nxm = 1xm
TODO: you must return a (1 x m) array, which corresponds to the estimated value for each of the m samples
"""
result = np.transpose(self.theta) @ X
return result
def _cost_function_derivative(self, y_pred, y, X, m):
"""
Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.
y_pred: an (1 x m) array with the predicted values for X dataset
y: an (1 x m) array with the right values for X dataset
X: the input dataset
m: the number of samples in the dataset
TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.
"""
derivatives = np.zeros((X.shape[0], 1))
for j in range(X.shape[0]):
auxsum = 0
for i in range(m):
auxsum += (y_pred[0][i] - y[0][i]) * X[j][i]
derivatives[j][0] = self.theta[j][0] - self.alpha * 1 / m * auxsum
return derivatives
def fit(self, X, y):
"""
Fits the linear regressor to the values in the dataset
X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples
y: is an (1 x m) vector, where m is the number of samples/examples
TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions
"""
n, m = X.shape[0], X.shape[1]
self.theta = np.random.uniform(-10, 10, (n, 1))
for i in range(self.epochs):
y_pred = self.predict(X)
cost = self._cost_function(y_pred, y, m)
gradient = self._cost_function_derivative(y_pred, y, X, m)
self.theta = gradient
self.costs.append(cost)
pass
print('Final theta is {} (cost: {})'.format(self.theta.T, cost))
def predict(self, X):
"""
Predicts the values for the given X samples using the current configuration of the Linear Regressor.
X: an (n x m') array with m' samples of n dimensions whose value must be predicted.
TODO: You must return a (1 x m') array that includes the predictions for the given m' samples.
"""
predictions = self._hypothesis(X)
return predictions
<|reserved_special_token_1|>
import numpy as np
class LinearRegressor():
def __init__(self, alpha=0.1, epochs=1):
self.alpha = alpha
self.epochs = epochs
self.costs = []
self.theta = None
def _cost_function(self, y_pred, y, m):
"""
Gets the cost for the predicted values when contrasted with the correct ones.
y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor
y: An (1 x m) vector that corresponds to the y (right) values in the dataset
m: the number of samples (it could be also inferred from the shape of y or y_pred)
TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration
"""
sumatory = 0
for x in range(m):
sumatory += (y_pred[0][x] -y[0][x])**2
cost = 1/(2*m) * sumatory
return cost
def _hypothesis(self, X):
"""
Calculates the hypothesis for the given examples using the current self.theta values.
X: an m x n array of m samples/examples with n features each.
Creo que X es en realidad nxm
transpose de theta es 1xn y * nxm = 1xm
TODO: you must return a (1 x m) array, which corresponds to the estimated value for each of the m samples
"""
# * is element wise multiplication
# numpy.dot(), or @ operator will work
result = np.transpose(self.theta)@ X
#emptyResult = np.zeros((1,X.shape[1]))
return result
def _cost_function_derivative(self, y_pred, y, X, m):
"""
Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.
y_pred: an (1 x m) array with the predicted values for X dataset
y: an (1 x m) array with the right values for X dataset
X: the input dataset
m: the number of samples in the dataset
TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.
"""
derivatives= np.zeros((X.shape[0],1))
for j in range(X.shape[0]):
auxsum = 0
for i in range(m):
auxsum+=(y_pred[0][i] -y[0][i])*X[j][i]
derivatives[j][0] = self.theta[j][0] - self.alpha * 1/m * auxsum
#empty_derivatives = np.zeros((X.shape[0],1))
return derivatives
def fit(self, X, y):
"""
Fits the linear regressor to the values in the dataset
X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples
y: is an (1 x m) vector, where m is the number of samples/examples
TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions
"""
n, m = X.shape[0], X.shape[1]
# theta is (nx1) (one theta per dimension)
self.theta = np.random.uniform(-10, 10, (n, 1))
for i in range(self.epochs):
# Get predictions
y_pred = self.predict(X)
# calculate cost
# cost = ...
cost = self._cost_function(y_pred, y, m)
# gradient is an (n) x 1 array, it refers to the derivate per theta
gradient = self._cost_function_derivative(y_pred, y, X, m)
# delta/update rule
self.theta = gradient
self.costs.append(cost)
pass
print("Final theta is {} (cost: {})".format(self.theta.T, cost))
def predict(self, X):
"""
Predicts the values for the given X samples using the current configuration of the Linear Regressor.
X: an (n x m') array with m' samples of n dimensions whose value must be predicted.
TODO: You must return a (1 x m') array that includes the predictions for the given m' samples.
"""
# ! You could simply call the hypothesis here
predictions= self._hypothesis(X)
#empty_predictions = np.zeros((1,X.shape[1]))
return predictions
|
flexible
|
{
"blob_id": "d805a1290c107a8d768417a432e338b182b7cd6b",
"index": 5524,
"step-1": "<mask token>\n\n\nclass LinearRegressor:\n <mask token>\n\n def _cost_function(self, y_pred, y, m):\n \"\"\"\n Gets the cost for the predicted values when contrasted with the correct ones.\n y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor\n y: An (1 x m) vector that corresponds to the y (right) values in the dataset\n m: the number of samples (it could be also inferred from the shape of y or y_pred)\n\n TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration\n \"\"\"\n sumatory = 0\n for x in range(m):\n sumatory += (y_pred[0][x] - y[0][x]) ** 2\n cost = 1 / (2 * m) * sumatory\n return cost\n <mask token>\n\n def _cost_function_derivative(self, y_pred, y, X, m):\n \"\"\"\n Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.\n y_pred: an (1 x m) array with the predicted values for X dataset\n y: an (1 x m) array with the right values for X dataset\n X: the input dataset\n m: the number of samples in the dataset\n\n TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.\n \"\"\"\n derivatives = np.zeros((X.shape[0], 1))\n for j in range(X.shape[0]):\n auxsum = 0\n for i in range(m):\n auxsum += (y_pred[0][i] - y[0][i]) * X[j][i]\n derivatives[j][0] = self.theta[j][0] - self.alpha * 1 / m * auxsum\n return derivatives\n\n def fit(self, X, y):\n \"\"\"\n Fits the linear regressor to the values in the dataset\n X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples\n y: is an (1 x m) vector, where m is the number of samples/examples\n\n TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions\n \"\"\"\n n, m = X.shape[0], X.shape[1]\n self.theta = np.random.uniform(-10, 10, (n, 1))\n for i in range(self.epochs):\n y_pred = self.predict(X)\n cost = self._cost_function(y_pred, y, m)\n gradient = self._cost_function_derivative(y_pred, y, X, m)\n self.theta = gradient\n self.costs.append(cost)\n pass\n print('Final theta is {} (cost: {})'.format(self.theta.T, cost))\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass LinearRegressor:\n <mask token>\n\n def _cost_function(self, y_pred, y, m):\n \"\"\"\n Gets the cost for the predicted values when contrasted with the correct ones.\n y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor\n y: An (1 x m) vector that corresponds to the y (right) values in the dataset\n m: the number of samples (it could be also inferred from the shape of y or y_pred)\n\n TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration\n \"\"\"\n sumatory = 0\n for x in range(m):\n sumatory += (y_pred[0][x] - y[0][x]) ** 2\n cost = 1 / (2 * m) * sumatory\n return cost\n\n def _hypothesis(self, X):\n \"\"\"\n Calculates the hypothesis for the given examples using the current self.theta values.\n X: an m x n array of m samples/examples with n features each.\n Creo que X es en realidad nxm\n transpose de theta es 1xn y * nxm = 1xm\n\n TODO: you must return a (1 x m) array, which corresponds to the estimated value for each of the m samples\n \"\"\"\n result = np.transpose(self.theta) @ X\n return result\n\n def _cost_function_derivative(self, y_pred, y, X, m):\n \"\"\"\n Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.\n y_pred: an (1 x m) array with the predicted values for X dataset\n y: an (1 x m) array with the right values for X dataset\n X: the input dataset\n m: the number of samples in the dataset\n\n TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.\n \"\"\"\n derivatives = np.zeros((X.shape[0], 1))\n for j in range(X.shape[0]):\n auxsum = 0\n for i in range(m):\n auxsum += (y_pred[0][i] - y[0][i]) * X[j][i]\n derivatives[j][0] = self.theta[j][0] - self.alpha * 1 / m * auxsum\n return derivatives\n\n def fit(self, X, y):\n \"\"\"\n Fits the linear regressor to the values in the dataset\n X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples\n y: is an (1 x m) vector, where m is the number of samples/examples\n\n TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions\n \"\"\"\n n, m = X.shape[0], X.shape[1]\n self.theta = np.random.uniform(-10, 10, (n, 1))\n for i in range(self.epochs):\n y_pred = self.predict(X)\n cost = self._cost_function(y_pred, y, m)\n gradient = self._cost_function_derivative(y_pred, y, X, m)\n self.theta = gradient\n self.costs.append(cost)\n pass\n print('Final theta is {} (cost: {})'.format(self.theta.T, cost))\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass LinearRegressor:\n\n def __init__(self, alpha=0.1, epochs=1):\n self.alpha = alpha\n self.epochs = epochs\n self.costs = []\n self.theta = None\n\n def _cost_function(self, y_pred, y, m):\n \"\"\"\n Gets the cost for the predicted values when contrasted with the correct ones.\n y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor\n y: An (1 x m) vector that corresponds to the y (right) values in the dataset\n m: the number of samples (it could be also inferred from the shape of y or y_pred)\n\n TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration\n \"\"\"\n sumatory = 0\n for x in range(m):\n sumatory += (y_pred[0][x] - y[0][x]) ** 2\n cost = 1 / (2 * m) * sumatory\n return cost\n\n def _hypothesis(self, X):\n \"\"\"\n Calculates the hypothesis for the given examples using the current self.theta values.\n X: an m x n array of m samples/examples with n features each.\n Creo que X es en realidad nxm\n transpose de theta es 1xn y * nxm = 1xm\n\n TODO: you must return a (1 x m) array, which corresponds to the estimated value for each of the m samples\n \"\"\"\n result = np.transpose(self.theta) @ X\n return result\n\n def _cost_function_derivative(self, y_pred, y, X, m):\n \"\"\"\n Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.\n y_pred: an (1 x m) array with the predicted values for X dataset\n y: an (1 x m) array with the right values for X dataset\n X: the input dataset\n m: the number of samples in the dataset\n\n TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.\n \"\"\"\n derivatives = np.zeros((X.shape[0], 1))\n for j in range(X.shape[0]):\n auxsum = 0\n for i in range(m):\n auxsum += (y_pred[0][i] - y[0][i]) * X[j][i]\n derivatives[j][0] = self.theta[j][0] - self.alpha * 1 / m * auxsum\n return derivatives\n\n def fit(self, X, y):\n \"\"\"\n Fits the linear regressor to the values in the dataset\n X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples\n y: is an (1 x m) vector, where m is the number of samples/examples\n\n TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions\n \"\"\"\n n, m = X.shape[0], X.shape[1]\n self.theta = np.random.uniform(-10, 10, (n, 1))\n for i in range(self.epochs):\n y_pred = self.predict(X)\n cost = self._cost_function(y_pred, y, m)\n gradient = self._cost_function_derivative(y_pred, y, X, m)\n self.theta = gradient\n self.costs.append(cost)\n pass\n print('Final theta is {} (cost: {})'.format(self.theta.T, cost))\n <mask token>\n",
"step-4": "import numpy as np\n\n\nclass LinearRegressor:\n\n def __init__(self, alpha=0.1, epochs=1):\n self.alpha = alpha\n self.epochs = epochs\n self.costs = []\n self.theta = None\n\n def _cost_function(self, y_pred, y, m):\n \"\"\"\n Gets the cost for the predicted values when contrasted with the correct ones.\n y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor\n y: An (1 x m) vector that corresponds to the y (right) values in the dataset\n m: the number of samples (it could be also inferred from the shape of y or y_pred)\n\n TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration\n \"\"\"\n sumatory = 0\n for x in range(m):\n sumatory += (y_pred[0][x] - y[0][x]) ** 2\n cost = 1 / (2 * m) * sumatory\n return cost\n\n def _hypothesis(self, X):\n \"\"\"\n Calculates the hypothesis for the given examples using the current self.theta values.\n X: an m x n array of m samples/examples with n features each.\n Creo que X es en realidad nxm\n transpose de theta es 1xn y * nxm = 1xm\n\n TODO: you must return a (1 x m) array, which corresponds to the estimated value for each of the m samples\n \"\"\"\n result = np.transpose(self.theta) @ X\n return result\n\n def _cost_function_derivative(self, y_pred, y, X, m):\n \"\"\"\n Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.\n y_pred: an (1 x m) array with the predicted values for X dataset\n y: an (1 x m) array with the right values for X dataset\n X: the input dataset\n m: the number of samples in the dataset\n\n TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.\n \"\"\"\n derivatives = np.zeros((X.shape[0], 1))\n for j in range(X.shape[0]):\n auxsum = 0\n for i in range(m):\n auxsum += (y_pred[0][i] - y[0][i]) * X[j][i]\n derivatives[j][0] = self.theta[j][0] - self.alpha * 1 / m * auxsum\n return derivatives\n\n def fit(self, X, y):\n \"\"\"\n Fits the linear regressor to the values in the dataset\n X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples\n y: is an (1 x m) vector, where m is the number of samples/examples\n\n TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions\n \"\"\"\n n, m = X.shape[0], X.shape[1]\n self.theta = np.random.uniform(-10, 10, (n, 1))\n for i in range(self.epochs):\n y_pred = self.predict(X)\n cost = self._cost_function(y_pred, y, m)\n gradient = self._cost_function_derivative(y_pred, y, X, m)\n self.theta = gradient\n self.costs.append(cost)\n pass\n print('Final theta is {} (cost: {})'.format(self.theta.T, cost))\n\n def predict(self, X):\n \"\"\"\n Predicts the values for the given X samples using the current configuration of the Linear Regressor.\n\n X: an (n x m') array with m' samples of n dimensions whose value must be predicted.\n\n TODO: You must return a (1 x m') array that includes the predictions for the given m' samples.\n \"\"\"\n predictions = self._hypothesis(X)\n return predictions\n",
"step-5": "import numpy as np\n\n\nclass LinearRegressor():\n def __init__(self, alpha=0.1, epochs=1):\n self.alpha = alpha\n self.epochs = epochs\n self.costs = []\n self.theta = None\n\n def _cost_function(self, y_pred, y, m):\n \"\"\"\n Gets the cost for the predicted values when contrasted with the correct ones.\n y_pred: An (1 x m) vector that corresponds to the values predicted by the Linear Regressor\n y: An (1 x m) vector that corresponds to the y (right) values in the dataset\n m: the number of samples (it could be also inferred from the shape of y or y_pred)\n\n TODO: You must implement the cost function and return an scalar that corresponds to the error produced by the Linear Regressor with its current configuration\n \"\"\"\n sumatory = 0\n for x in range(m):\n sumatory += (y_pred[0][x] -y[0][x])**2\n\n cost = 1/(2*m) * sumatory\n return cost\n\n\n def _hypothesis(self, X):\n \"\"\"\n Calculates the hypothesis for the given examples using the current self.theta values.\n X: an m x n array of m samples/examples with n features each.\n Creo que X es en realidad nxm\n transpose de theta es 1xn y * nxm = 1xm\n\n TODO: you must return a (1 x m) array, which corresponds to the estimated value for each of the m samples\n \"\"\"\n # * is element wise multiplication\n # numpy.dot(), or @ operator will work\n result = np.transpose(self.theta)@ X \n #emptyResult = np.zeros((1,X.shape[1]))\n return result \n\n def _cost_function_derivative(self, y_pred, y, X, m):\n \"\"\"\n Calculates the derivatives (gradient) of the cost function through the obtained/predicted values.\n y_pred: an (1 x m) array with the predicted values for X dataset\n y: an (1 x m) array with the right values for X dataset\n X: the input dataset\n m: the number of samples in the dataset\n\n TODO: You must implement the calculation of derivatives. An (n x 1) array that corresponds to the gradient of current theta values (the derivative per theta parameter) must be returned.\n \"\"\"\n\n derivatives= np.zeros((X.shape[0],1))\n for j in range(X.shape[0]):\n auxsum = 0\n for i in range(m):\n auxsum+=(y_pred[0][i] -y[0][i])*X[j][i]\n derivatives[j][0] = self.theta[j][0] - self.alpha * 1/m * auxsum\n\n #empty_derivatives = np.zeros((X.shape[0],1))\n return derivatives\n\n def fit(self, X, y):\n \"\"\"\n Fits the linear regressor to the values in the dataset\n X: is an (n x m) vector, where n is the number of features and m is the number of samples/examples\n y: is an (1 x m) vector, where m is the number of samples/examples\n\n TODO: You need to provide an implementation that in each epoch is updating the values for the theta parameters by using the hypothesis and cost function functions\n \"\"\"\n\n n, m = X.shape[0], X.shape[1]\n\n # theta is (nx1) (one theta per dimension)\n self.theta = np.random.uniform(-10, 10, (n, 1))\n\n for i in range(self.epochs):\n # Get predictions\n y_pred = self.predict(X)\n\n # calculate cost\n # cost = ...\n cost = self._cost_function(y_pred, y, m)\n \n\n # gradient is an (n) x 1 array, it refers to the derivate per theta\n gradient = self._cost_function_derivative(y_pred, y, X, m)\n\n # delta/update rule\n self.theta = gradient\n\n self.costs.append(cost)\n pass\n\n print(\"Final theta is {} (cost: {})\".format(self.theta.T, cost))\n\n def predict(self, X):\n \"\"\"\n Predicts the values for the given X samples using the current configuration of the Linear Regressor.\n\n X: an (n x m') array with m' samples of n dimensions whose value must be predicted.\n\n TODO: You must return a (1 x m') array that includes the predictions for the given m' samples.\n \"\"\"\n # ! You could simply call the hypothesis here\n predictions= self._hypothesis(X)\n #empty_predictions = np.zeros((1,X.shape[1]))\n return predictions",
"step-ids": [
4,
5,
6,
8,
9
]
}
|
[
4,
5,
6,
8,
9
] |
<|reserved_special_token_0|>
def ftp_download():
file_remote = 'ftp_upload.jpg'
file_local = (
'/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg')
bufsize = 1024
fp = open(file_local, 'wb')
f.retrbinary('RETR ' + file_remote, fp.write, bufsize)
fp.close()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def ftp_download():
file_remote = 'ftp_upload.jpg'
file_local = (
'/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg')
bufsize = 1024
fp = open(file_local, 'wb')
f.retrbinary('RETR ' + file_remote, fp.write, bufsize)
fp.close()
def ftp_upload():
file_remote = 'test_upload.jpg'
file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_upload.jpg'
bufsize = 1024
fp = open(file_local, 'rb')
f.storbinary('STOR ' + file_remote, fp, bufsize)
fp.close()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def ftp_download():
file_remote = 'ftp_upload.jpg'
file_local = (
'/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg')
bufsize = 1024
fp = open(file_local, 'wb')
f.retrbinary('RETR ' + file_remote, fp.write, bufsize)
fp.close()
def ftp_upload():
file_remote = 'test_upload.jpg'
file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_upload.jpg'
bufsize = 1024
fp = open(file_local, 'rb')
f.storbinary('STOR ' + file_remote, fp, bufsize)
fp.close()
if __name__ == '__main__':
host = 'www.aiforu.com'
username = 'admin_camera'
password = 'QcZ8M9aDga'
f = ftplib.FTP(host)
f.login(username, password)
pwd_path = f.pwd()
print('FTP当前路径:', pwd_path)
ftp_download()
ftp_upload()
f.quit()
<|reserved_special_token_1|>
import ftplib
def ftp_download():
file_remote = 'ftp_upload.jpg'
file_local = (
'/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg')
bufsize = 1024
fp = open(file_local, 'wb')
f.retrbinary('RETR ' + file_remote, fp.write, bufsize)
fp.close()
def ftp_upload():
file_remote = 'test_upload.jpg'
file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_upload.jpg'
bufsize = 1024
fp = open(file_local, 'rb')
f.storbinary('STOR ' + file_remote, fp, bufsize)
fp.close()
if __name__ == '__main__':
host = 'www.aiforu.com'
username = 'admin_camera'
password = 'QcZ8M9aDga'
f = ftplib.FTP(host)
f.login(username, password)
pwd_path = f.pwd()
print('FTP当前路径:', pwd_path)
ftp_download()
ftp_upload()
f.quit()
<|reserved_special_token_1|>
import ftplib
def ftp_download():
file_remote = 'ftp_upload.jpg'
file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg'
bufsize = 1024
fp = open(file_local, 'wb')
f.retrbinary('RETR ' + file_remote, fp.write, bufsize)
fp.close()
def ftp_upload():
file_remote = 'test_upload.jpg'
file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_upload.jpg'
bufsize = 1024
fp = open(file_local, 'rb')
f.storbinary('STOR ' + file_remote, fp, bufsize)
fp.close()
if __name__ == '__main__':
host = 'www.aiforu.com'
username = 'admin_camera'
password = 'QcZ8M9aDga'
f = ftplib.FTP(host)
f.login(username, password)
pwd_path = f.pwd()
print("FTP当前路径:", pwd_path)
ftp_download()
ftp_upload()
f.quit()
|
flexible
|
{
"blob_id": "a1b85d140c45f082ceac54ad8aa9aa5c3659d5cf",
"index": 9661,
"step-1": "<mask token>\n\n\ndef ftp_download():\n file_remote = 'ftp_upload.jpg'\n file_local = (\n '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg')\n bufsize = 1024\n fp = open(file_local, 'wb')\n f.retrbinary('RETR ' + file_remote, fp.write, bufsize)\n fp.close()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef ftp_download():\n file_remote = 'ftp_upload.jpg'\n file_local = (\n '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg')\n bufsize = 1024\n fp = open(file_local, 'wb')\n f.retrbinary('RETR ' + file_remote, fp.write, bufsize)\n fp.close()\n\n\ndef ftp_upload():\n file_remote = 'test_upload.jpg'\n file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_upload.jpg'\n bufsize = 1024\n fp = open(file_local, 'rb')\n f.storbinary('STOR ' + file_remote, fp, bufsize)\n fp.close()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef ftp_download():\n file_remote = 'ftp_upload.jpg'\n file_local = (\n '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg')\n bufsize = 1024\n fp = open(file_local, 'wb')\n f.retrbinary('RETR ' + file_remote, fp.write, bufsize)\n fp.close()\n\n\ndef ftp_upload():\n file_remote = 'test_upload.jpg'\n file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_upload.jpg'\n bufsize = 1024\n fp = open(file_local, 'rb')\n f.storbinary('STOR ' + file_remote, fp, bufsize)\n fp.close()\n\n\nif __name__ == '__main__':\n host = 'www.aiforu.com'\n username = 'admin_camera'\n password = 'QcZ8M9aDga'\n f = ftplib.FTP(host)\n f.login(username, password)\n pwd_path = f.pwd()\n print('FTP当前路径:', pwd_path)\nftp_download()\nftp_upload()\nf.quit()\n",
"step-4": "import ftplib\n\n\ndef ftp_download():\n file_remote = 'ftp_upload.jpg'\n file_local = (\n '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg')\n bufsize = 1024\n fp = open(file_local, 'wb')\n f.retrbinary('RETR ' + file_remote, fp.write, bufsize)\n fp.close()\n\n\ndef ftp_upload():\n file_remote = 'test_upload.jpg'\n file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_upload.jpg'\n bufsize = 1024\n fp = open(file_local, 'rb')\n f.storbinary('STOR ' + file_remote, fp, bufsize)\n fp.close()\n\n\nif __name__ == '__main__':\n host = 'www.aiforu.com'\n username = 'admin_camera'\n password = 'QcZ8M9aDga'\n f = ftplib.FTP(host)\n f.login(username, password)\n pwd_path = f.pwd()\n print('FTP当前路径:', pwd_path)\nftp_download()\nftp_upload()\nf.quit()\n",
"step-5": "\nimport ftplib\n\ndef ftp_download():\n file_remote = 'ftp_upload.jpg'\n file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_download.jpg'\n bufsize = 1024\n fp = open(file_local, 'wb')\n f.retrbinary('RETR ' + file_remote, fp.write, bufsize)\n fp.close()\n \ndef ftp_upload():\n file_remote = 'test_upload.jpg'\n file_local = '/home/pi/Desktop/Camera-Rasp-Arduino-sensors/test_upload.jpg'\n bufsize = 1024\n fp = open(file_local, 'rb')\n f.storbinary('STOR ' + file_remote, fp, bufsize)\n fp.close()\n\n \nif __name__ == '__main__':\n host = 'www.aiforu.com'\n username = 'admin_camera'\n password = 'QcZ8M9aDga'\n \n \n f = ftplib.FTP(host)\n f.login(username, password)\n \n \n pwd_path = f.pwd()\n print(\"FTP当前路径:\", pwd_path)\n \n \n \nftp_download()\nftp_upload()\nf.quit()\n ",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
from random import random, randint, choice
from copy import deepcopy
from math import log
"""
Обертка для функций, которые будут находиться в узлах,
представляющих функции. Его члены – имя функции, сама функция
и количество принимаемых параметров.
"""
class fwrapper:
def __init__(self, function, childcount, name):
self.function = function
self.childcount = childcount
self.name = name
"""
Класс функциональных узлов (имеющих потомков). Инициализируется экземпляром класса fwrapper.
Метод evaluate вычисляет значения дочерних узлов и передает их представленной данным узлом
функции в качестве параметров.
"""
class node:
def __init__(self, fw, children):
self.function = fw.function
self.name = fw.name
self.children = children
def evaluate(self, inp):
results = [n.evaluate(inp) for n in self.children]
return self.function(results)
# Метод display выводит представление дерева в виде строки
def display(self, indent=0):
print((' ' * indent) + self.name)
for c in self.children:
c.display(indent + 1)
"""
Класс узлов, которые просто возвращают один из переданных программе параметров.
Его метод evaluate возвращает параметр, соответствующий значению idx.
"""
class paramnode:
def __init__(self, idx):
self.idx = idx
def evaluate(self, inp):
return inp[self.idx]
# Это метод просто печатает индекс возвращаемого параметра
def display(self, indent=0):
print('%sp%d' % (' ' * indent, self.idx))
"""
Узлы, возвращающие константы. Метод evaluate просто возвращает
то значение, которым экземпляр был инициализирован.
"""
class constnode:
def __init__(self, v):
self.v = v
def evaluate(self, inp):
return self.v
def display(self, indent=0):
print('%s%d' % (' ' * indent, self.v))
"""
Простые функции типа add и subtract можно встроить с помощью лямбда-выражений.
Для остальных функцию придется написать в отдельном блоке.
В любом случае функция обертывается в экземпляр класса fwrapper
вместе со своим именем и числом параметров.
"""
addw = fwrapper(lambda l: l[0] + l[1], 2, 'add')
subw = fwrapper(lambda l: l[0] - l[1], 2, 'subtract')
mulw = fwrapper(lambda l: l[0] * l[1], 2, 'multiply')
def iffunc(l):
if l[0] > 0:
return l[1]
else:
return l[2]
ifw = fwrapper(iffunc, 3, 'if')
def isgreater(l):
if l[0] > l[1]:
return 1
else:
return 0
gtw = fwrapper(isgreater, 2, 'isgreater')
# В этой строке создается список всех функций, чтобы впоследствии из него
# можно было выбирать элементы случайным образом.
flist = [addw, mulw, ifw, gtw, subw]
# C помощью класса node можно построить дерево программы (в качестве примера)
def exampletree():
return node(ifw, [
node(gtw, [paramnode(0), constnode(3)]),
node(addw, [paramnode(1), constnode(5)]),
node(subw, [paramnode(1), constnode(2)]),
]
)
"""
Эта функция создает узел, содержащий случайно выбранную функцию, и проверяет,
сколько у этой функции должно быть параметров. Для каждого дочернего узла функция
вызывает себя рекурсивно, чтобы создать новый узел. Так конструируется все дерево,
причем процесс построения ветвей завершается в тот момент, когда у очередного узла
нет дочерних (то есть он представляет либо константу, либо переменную-параметр).
Параметр pc равен числу параметров, принимаемых деревом на входе. Параметр fpr
задает вероятность того, что вновь создаваемый узел будет соответствовать функции,
а ppr – вероятность того, что узел, не являющийся функцией, будет иметь тип paramnode.
"""
def makerandomtree(pc, maxdepth=4, fpr=0.5, ppr=0.6):
if random() < fpr and maxdepth > 0:
f = choice(flist)
children = [makerandomtree(pc, maxdepth - 1, fpr, ppr)
for i in range(f.childcount)]
return node(f, children)
elif random() < ppr:
return paramnode(randint(0, pc - 1))
else:
return constnode(randint(0, 10))
def hiddenfunction(x, y):
return x ** 2 + 2 * y + 3 * x + 5
def buildhiddenset():
rows = []
for i in range(200):
x = randint(0, 40)
y = randint(0, 40)
rows.append([x, y, hiddenfunction(x, y)])
return rows
"""
Эта функция перебирает все строки набора данных, вычисляет функцию от указанных
в ней аргументов и сравнивает с результатом. Абсолютные значения разностей суммируются.
Чем меньше сумма, тем лучше программа, а значение 0 говорит о том, что все результаты
в точности совпали.
"""
def scorefunction(tree, s):
dif = 0
for data in s:
v = tree.evaluate([data[0], data[1]])
dif += abs(v - data[2])
return dif
"""
Эта функция начинает с корня дерева и решает, следует ли изменить
узел. Если нет, она рекурсивно вызывает mutate для дочерних узлов.
Может случиться, что мутации подвергнутся все узлы, а иногда дерево
вообще не изменится.
"""
# Мутация путем замены поддерева
def mutate(t, pc, probchange=0.1):
if random() < probchange:
return makerandomtree(pc)
else:
result = deepcopy(t)
if hasattr(t, "children"):
result.children = [mutate(c, pc, probchange) for c in t.children]
return result
"""
Функции, выполняющей скрещивание, передаются два дерева, и она
обходит оба. Если случайно выбранное число не превышает пороговой
вероятности, то функция возвращает копию первого дерева, в которой
одна из ветвей заменена какой-то ветвью, взятой из второго дерева.
Поскольку обход выполняется параллельно, то скрещивание произойдет примерно на одном уровне каждого дерева.
"""
# Функция скрещивания. Две успешные программы комбинируются с целью получения новой программы.
def crossover(t1, t2, probswap=0.7, top=1):
if random() < probswap and not top:
return deepcopy(t2)
else:
result = deepcopy(t1)
if hasattr(t1, 'children') and hasattr(t2, 'children'):
result.children = [crossover(c, choice(t2.children), probswap, 0)
for c in t1.children]
return result
# Функция возвращает функцию ранжирования для имеющегося набора данных
def getrankfunction(dataset):
def rankfunction(population):
scores = [(scorefunction(t, dataset), t) for t in population]
scores.sort()
return scores
return rankfunction
"""
Создание конкурентной среды, в которой программы будут эволюционировать.
Смысл в том, чтобы создать набор случайных программ, отобрать из них
наилучшие для копирования и модификации и повторять процесс, пока не будет
выполнено некое условие останова.
"""
def evolve(pc, popsize, rankfunction, maxgen=500, mutationrate=0.1, breedingrate=0.4, pexp=0.7, pnew=0.05):
"""Эта функция создает случайную исходную популяцию, а затем выполняет не более maxgen итераций цикла,
вызывая каждый раз функцию rankfunction для ранжирования программ от наилучшей до наихудшей.
Наилучшая программа автоматически попадает в следующее поколение без изменения.
Args:
rankfunction: Функция, применяемая для ранжирования списка программ от наилучшей к наихудшей.
mutationrate: Вероятность мутации, передаваемая функции mutate.
breedingrate: Вероятность скрещивания, передаваемая функции crossover.
popsize: Размер исходной популяции.
probexp: Скорость убывания вероятности выбора программ с низким рангом. Чем выше значение, тем более суров процесс естественного отбора/
probnew: Вероятность включения в новую популяцию совершенно новой случайно сгенерированной программы.
Returns:
tuple: Найденное наилучшее совпадние
"""
# Возвращает случайное число, отдавая предпочтение более маленьким числам.
# Чем меньше значение pexp, тем больше будет доля маленьких чисел.
def selectindex():
return int(log(random()) / log(pexp))
# Создаем случайную исходную популяцию
population = [makerandomtree(pc) for i in range(popsize)]
for i in range(maxgen):
scores = rankfunction(population)
print(scores[0][0])
if scores[0][0] == 0: break
# Две наилучшие особи отбираются всегда
newpop = [scores[0][1], scores[1][1]]
# Строим следующее поколение
while len(newpop) < popsize:
if random() > pnew:
newpop.append(mutate(
crossover(scores[selectindex()][1],
scores[selectindex()][1],
probswap=breedingrate),
pc, probchange=mutationrate))
else:
# Добавляем случайный узел для внесения неопределенности
newpop.append(makerandomtree(pc))
population = newpop
scores[0][1].display()
return scores[0][1]
#[
# (10, "program1"),
# (17, "program2"),
#]
def gridgame(p):
# Размер доски
max = (3, 3)
# Запоминаем последний ход каждого игрока
lastmove = [-1, -1]
# Запоминаем положения игроков
location = [[randint(0, max[0]), randint(0, max[1])]]
# Располагаем второго игрока на достаточном удалении от первого
location.append([(location[0][0] + 2) % 4, (location[0][1] + 2) % 4])
# Не более 50 ходов до объявления ничьей
for o in range(50):
# Для каждого игрока
for i in range(2):
locs = location[i][:] + location[1 - i][:]
locs.append(lastmove[i])
move = p[i].evaluate(locs) % 4
# Если игрок два раза подряд ходит в одном направлении, ему
# засчитывается проигрыш
if lastmove[i] == move: return 1 - i
lastmove[i] = move
if move == 0:
location[i][0] -= 1
# Доска ограничена
if location[i][0] < 0: location[i][0] = 0
if move == 1:
location[i][0] += 1
if location[i][0] > max[0]: location[i][0] = max[0]
if move == 2:
location[i][1] -= 1
if location[i][1] < 0: location[i][1] = 0
if move == 3:
location[i][1] += 1
if location[i][1] > max[1]: location[i][1] = max[1]
# Если противник захвачен в плен, вы выиграли
if location[i] == location[1 - i]: return i
return -1
def tournament(pl):
# Массив для подсчета проигрышей
losses = [0 for p in pl]
# Каждый игрок встречается со всеми другими
for i in range(len(pl)):
for j in range(len(pl)):
if i == j: continue
# Кто выиграл?
winner = gridgame([pl[i], pl[j]])
# Два очка за поражение, одно за ничью
if winner == 0:
losses[j] += 2
elif winner == 1:
losses[i] += 2
elif winner == -1:
losses[i] += 1
losses[i] += 1
pass
# Отсортировать и вернуть результаты
z = list(zip(losses, pl))
z.sort(key=lambda t: t[0])
# input()
print(z[0][1].display(indent=4))
return z
class humanplayer:
def evaluate(self, board):
# Получить мою позицию и позиции других игроков
me = tuple(board[0:2])
others = [tuple(board[x:x + 2]) for x in range(2, len(board) - 1, 2)]
# Нарисовать доску
for i in range(4):
for j in range(4):
if (i, j) == me:
print('O',end=' ')
elif (i, j) in others:
print('X',end=' ')
else:
print('.',end=' ')
print()
# Показать ходы, для справки
print('Your last move was %d' % board[len(board) - 1])
print(' 0')
print('2 3')
print(' 1')
print('Enter move: ')
# Вернуть введенное пользователем число
move = int(input())
return move
class fwrapper:
def __init__(self, function, params, name):
self.function = function
self.childcount = params
self.name = name
# flist={'str':[substringw,concatw],'int':[indexw]}
flist = [addw, mulw, ifw, gtw, subw]
|
normal
|
{
"blob_id": "89881f3cc6703b3f43f5d2dae87fa943d8a21513",
"index": 5485,
"step-1": "<mask token>\n\n\nclass fwrapper:\n\n def __init__(self, function, childcount, name):\n self.function = function\n self.childcount = childcount\n self.name = name\n\n\n<mask token>\n\n\nclass node:\n\n def __init__(self, fw, children):\n self.function = fw.function\n self.name = fw.name\n self.children = children\n\n def evaluate(self, inp):\n results = [n.evaluate(inp) for n in self.children]\n return self.function(results)\n\n def display(self, indent=0):\n print(' ' * indent + self.name)\n for c in self.children:\n c.display(indent + 1)\n\n\n<mask token>\n\n\nclass paramnode:\n\n def __init__(self, idx):\n self.idx = idx\n\n def evaluate(self, inp):\n return inp[self.idx]\n\n def display(self, indent=0):\n print('%sp%d' % (' ' * indent, self.idx))\n\n\n<mask token>\n\n\nclass constnode:\n\n def __init__(self, v):\n self.v = v\n\n def evaluate(self, inp):\n return self.v\n\n def display(self, indent=0):\n print('%s%d' % (' ' * indent, self.v))\n\n\n<mask token>\n\n\ndef iffunc(l):\n if l[0] > 0:\n return l[1]\n else:\n return l[2]\n\n\n<mask token>\n\n\ndef buildhiddenset():\n rows = []\n for i in range(200):\n x = randint(0, 40)\n y = randint(0, 40)\n rows.append([x, y, hiddenfunction(x, y)])\n return rows\n\n\n<mask token>\n\n\ndef scorefunction(tree, s):\n dif = 0\n for data in s:\n v = tree.evaluate([data[0], data[1]])\n dif += abs(v - data[2])\n return dif\n\n\n<mask token>\n\n\ndef getrankfunction(dataset):\n\n def rankfunction(population):\n scores = [(scorefunction(t, dataset), t) for t in population]\n scores.sort()\n return scores\n return rankfunction\n\n\n<mask token>\n\n\ndef evolve(pc, popsize, rankfunction, maxgen=500, mutationrate=0.1,\n breedingrate=0.4, pexp=0.7, pnew=0.05):\n \"\"\"Эта функция создает случайную исходную популяцию, а затем выполняет не более maxgen итераций цикла,\n вызывая каждый раз функцию rankfunction для ранжирования программ от наилучшей до наихудшей.\n Наилучшая программа автоматически попадает в следующее поколение без изменения. \n Args:\n rankfunction: Функция, применяемая для ранжирования списка программ от наилучшей к наихудшей.\n mutationrate: Вероятность мутации, передаваемая функции mutate.\n breedingrate: Вероятность скрещивания, передаваемая функции crossover.\n popsize: Размер исходной популяции.\n probexp: Скорость убывания вероятности выбора программ с низким рангом. Чем выше значение, тем более суров процесс естественного отбора/\n probnew: Вероятность включения в новую популяцию совершенно новой случайно сгенерированной программы.\n\n Returns:\n tuple: Найденное наилучшее совпадние\n\n \"\"\"\n\n def selectindex():\n return int(log(random()) / log(pexp))\n population = [makerandomtree(pc) for i in range(popsize)]\n for i in range(maxgen):\n scores = rankfunction(population)\n print(scores[0][0])\n if scores[0][0] == 0:\n break\n newpop = [scores[0][1], scores[1][1]]\n while len(newpop) < popsize:\n if random() > pnew:\n newpop.append(mutate(crossover(scores[selectindex()][1],\n scores[selectindex()][1], probswap=breedingrate), pc,\n probchange=mutationrate))\n else:\n newpop.append(makerandomtree(pc))\n population = newpop\n scores[0][1].display()\n return scores[0][1]\n\n\n<mask token>\n\n\nclass humanplayer:\n\n def evaluate(self, board):\n me = tuple(board[0:2])\n others = [tuple(board[x:x + 2]) for x in range(2, len(board) - 1, 2)]\n for i in range(4):\n for j in range(4):\n if (i, j) == me:\n print('O', end=' ')\n elif (i, j) in others:\n print('X', end=' ')\n else:\n print('.', end=' ')\n print()\n print('Your last move was %d' % board[len(board) - 1])\n print(' 0')\n print('2 3')\n print(' 1')\n print('Enter move: ')\n move = int(input())\n return move\n\n\nclass fwrapper:\n\n def __init__(self, function, params, name):\n self.function = function\n self.childcount = params\n self.name = name\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass fwrapper:\n\n def __init__(self, function, childcount, name):\n self.function = function\n self.childcount = childcount\n self.name = name\n\n\n<mask token>\n\n\nclass node:\n\n def __init__(self, fw, children):\n self.function = fw.function\n self.name = fw.name\n self.children = children\n\n def evaluate(self, inp):\n results = [n.evaluate(inp) for n in self.children]\n return self.function(results)\n\n def display(self, indent=0):\n print(' ' * indent + self.name)\n for c in self.children:\n c.display(indent + 1)\n\n\n<mask token>\n\n\nclass paramnode:\n\n def __init__(self, idx):\n self.idx = idx\n\n def evaluate(self, inp):\n return inp[self.idx]\n\n def display(self, indent=0):\n print('%sp%d' % (' ' * indent, self.idx))\n\n\n<mask token>\n\n\nclass constnode:\n\n def __init__(self, v):\n self.v = v\n\n def evaluate(self, inp):\n return self.v\n\n def display(self, indent=0):\n print('%s%d' % (' ' * indent, self.v))\n\n\n<mask token>\n\n\ndef iffunc(l):\n if l[0] > 0:\n return l[1]\n else:\n return l[2]\n\n\n<mask token>\n\n\ndef buildhiddenset():\n rows = []\n for i in range(200):\n x = randint(0, 40)\n y = randint(0, 40)\n rows.append([x, y, hiddenfunction(x, y)])\n return rows\n\n\n<mask token>\n\n\ndef scorefunction(tree, s):\n dif = 0\n for data in s:\n v = tree.evaluate([data[0], data[1]])\n dif += abs(v - data[2])\n return dif\n\n\n<mask token>\n\n\ndef mutate(t, pc, probchange=0.1):\n if random() < probchange:\n return makerandomtree(pc)\n else:\n result = deepcopy(t)\n if hasattr(t, 'children'):\n result.children = [mutate(c, pc, probchange) for c in t.children]\n return result\n\n\n<mask token>\n\n\ndef getrankfunction(dataset):\n\n def rankfunction(population):\n scores = [(scorefunction(t, dataset), t) for t in population]\n scores.sort()\n return scores\n return rankfunction\n\n\n<mask token>\n\n\ndef evolve(pc, popsize, rankfunction, maxgen=500, mutationrate=0.1,\n breedingrate=0.4, pexp=0.7, pnew=0.05):\n \"\"\"Эта функция создает случайную исходную популяцию, а затем выполняет не более maxgen итераций цикла,\n вызывая каждый раз функцию rankfunction для ранжирования программ от наилучшей до наихудшей.\n Наилучшая программа автоматически попадает в следующее поколение без изменения. \n Args:\n rankfunction: Функция, применяемая для ранжирования списка программ от наилучшей к наихудшей.\n mutationrate: Вероятность мутации, передаваемая функции mutate.\n breedingrate: Вероятность скрещивания, передаваемая функции crossover.\n popsize: Размер исходной популяции.\n probexp: Скорость убывания вероятности выбора программ с низким рангом. Чем выше значение, тем более суров процесс естественного отбора/\n probnew: Вероятность включения в новую популяцию совершенно новой случайно сгенерированной программы.\n\n Returns:\n tuple: Найденное наилучшее совпадние\n\n \"\"\"\n\n def selectindex():\n return int(log(random()) / log(pexp))\n population = [makerandomtree(pc) for i in range(popsize)]\n for i in range(maxgen):\n scores = rankfunction(population)\n print(scores[0][0])\n if scores[0][0] == 0:\n break\n newpop = [scores[0][1], scores[1][1]]\n while len(newpop) < popsize:\n if random() > pnew:\n newpop.append(mutate(crossover(scores[selectindex()][1],\n scores[selectindex()][1], probswap=breedingrate), pc,\n probchange=mutationrate))\n else:\n newpop.append(makerandomtree(pc))\n population = newpop\n scores[0][1].display()\n return scores[0][1]\n\n\n<mask token>\n\n\ndef tournament(pl):\n losses = [(0) for p in pl]\n for i in range(len(pl)):\n for j in range(len(pl)):\n if i == j:\n continue\n winner = gridgame([pl[i], pl[j]])\n if winner == 0:\n losses[j] += 2\n elif winner == 1:\n losses[i] += 2\n elif winner == -1:\n losses[i] += 1\n losses[i] += 1\n pass\n z = list(zip(losses, pl))\n z.sort(key=lambda t: t[0])\n print(z[0][1].display(indent=4))\n return z\n\n\nclass humanplayer:\n\n def evaluate(self, board):\n me = tuple(board[0:2])\n others = [tuple(board[x:x + 2]) for x in range(2, len(board) - 1, 2)]\n for i in range(4):\n for j in range(4):\n if (i, j) == me:\n print('O', end=' ')\n elif (i, j) in others:\n print('X', end=' ')\n else:\n print('.', end=' ')\n print()\n print('Your last move was %d' % board[len(board) - 1])\n print(' 0')\n print('2 3')\n print(' 1')\n print('Enter move: ')\n move = int(input())\n return move\n\n\nclass fwrapper:\n\n def __init__(self, function, params, name):\n self.function = function\n self.childcount = params\n self.name = name\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass fwrapper:\n\n def __init__(self, function, childcount, name):\n self.function = function\n self.childcount = childcount\n self.name = name\n\n\n<mask token>\n\n\nclass node:\n\n def __init__(self, fw, children):\n self.function = fw.function\n self.name = fw.name\n self.children = children\n\n def evaluate(self, inp):\n results = [n.evaluate(inp) for n in self.children]\n return self.function(results)\n\n def display(self, indent=0):\n print(' ' * indent + self.name)\n for c in self.children:\n c.display(indent + 1)\n\n\n<mask token>\n\n\nclass paramnode:\n\n def __init__(self, idx):\n self.idx = idx\n\n def evaluate(self, inp):\n return inp[self.idx]\n\n def display(self, indent=0):\n print('%sp%d' % (' ' * indent, self.idx))\n\n\n<mask token>\n\n\nclass constnode:\n\n def __init__(self, v):\n self.v = v\n\n def evaluate(self, inp):\n return self.v\n\n def display(self, indent=0):\n print('%s%d' % (' ' * indent, self.v))\n\n\n<mask token>\n\n\ndef iffunc(l):\n if l[0] > 0:\n return l[1]\n else:\n return l[2]\n\n\n<mask token>\n\n\ndef isgreater(l):\n if l[0] > l[1]:\n return 1\n else:\n return 0\n\n\n<mask token>\n\n\ndef exampletree():\n return node(ifw, [node(gtw, [paramnode(0), constnode(3)]), node(addw, [\n paramnode(1), constnode(5)]), node(subw, [paramnode(1), constnode(2)])]\n )\n\n\n<mask token>\n\n\ndef makerandomtree(pc, maxdepth=4, fpr=0.5, ppr=0.6):\n if random() < fpr and maxdepth > 0:\n f = choice(flist)\n children = [makerandomtree(pc, maxdepth - 1, fpr, ppr) for i in\n range(f.childcount)]\n return node(f, children)\n elif random() < ppr:\n return paramnode(randint(0, pc - 1))\n else:\n return constnode(randint(0, 10))\n\n\n<mask token>\n\n\ndef buildhiddenset():\n rows = []\n for i in range(200):\n x = randint(0, 40)\n y = randint(0, 40)\n rows.append([x, y, hiddenfunction(x, y)])\n return rows\n\n\n<mask token>\n\n\ndef scorefunction(tree, s):\n dif = 0\n for data in s:\n v = tree.evaluate([data[0], data[1]])\n dif += abs(v - data[2])\n return dif\n\n\n<mask token>\n\n\ndef mutate(t, pc, probchange=0.1):\n if random() < probchange:\n return makerandomtree(pc)\n else:\n result = deepcopy(t)\n if hasattr(t, 'children'):\n result.children = [mutate(c, pc, probchange) for c in t.children]\n return result\n\n\n<mask token>\n\n\ndef getrankfunction(dataset):\n\n def rankfunction(population):\n scores = [(scorefunction(t, dataset), t) for t in population]\n scores.sort()\n return scores\n return rankfunction\n\n\n<mask token>\n\n\ndef evolve(pc, popsize, rankfunction, maxgen=500, mutationrate=0.1,\n breedingrate=0.4, pexp=0.7, pnew=0.05):\n \"\"\"Эта функция создает случайную исходную популяцию, а затем выполняет не более maxgen итераций цикла,\n вызывая каждый раз функцию rankfunction для ранжирования программ от наилучшей до наихудшей.\n Наилучшая программа автоматически попадает в следующее поколение без изменения. \n Args:\n rankfunction: Функция, применяемая для ранжирования списка программ от наилучшей к наихудшей.\n mutationrate: Вероятность мутации, передаваемая функции mutate.\n breedingrate: Вероятность скрещивания, передаваемая функции crossover.\n popsize: Размер исходной популяции.\n probexp: Скорость убывания вероятности выбора программ с низким рангом. Чем выше значение, тем более суров процесс естественного отбора/\n probnew: Вероятность включения в новую популяцию совершенно новой случайно сгенерированной программы.\n\n Returns:\n tuple: Найденное наилучшее совпадние\n\n \"\"\"\n\n def selectindex():\n return int(log(random()) / log(pexp))\n population = [makerandomtree(pc) for i in range(popsize)]\n for i in range(maxgen):\n scores = rankfunction(population)\n print(scores[0][0])\n if scores[0][0] == 0:\n break\n newpop = [scores[0][1], scores[1][1]]\n while len(newpop) < popsize:\n if random() > pnew:\n newpop.append(mutate(crossover(scores[selectindex()][1],\n scores[selectindex()][1], probswap=breedingrate), pc,\n probchange=mutationrate))\n else:\n newpop.append(makerandomtree(pc))\n population = newpop\n scores[0][1].display()\n return scores[0][1]\n\n\n<mask token>\n\n\ndef tournament(pl):\n losses = [(0) for p in pl]\n for i in range(len(pl)):\n for j in range(len(pl)):\n if i == j:\n continue\n winner = gridgame([pl[i], pl[j]])\n if winner == 0:\n losses[j] += 2\n elif winner == 1:\n losses[i] += 2\n elif winner == -1:\n losses[i] += 1\n losses[i] += 1\n pass\n z = list(zip(losses, pl))\n z.sort(key=lambda t: t[0])\n print(z[0][1].display(indent=4))\n return z\n\n\nclass humanplayer:\n\n def evaluate(self, board):\n me = tuple(board[0:2])\n others = [tuple(board[x:x + 2]) for x in range(2, len(board) - 1, 2)]\n for i in range(4):\n for j in range(4):\n if (i, j) == me:\n print('O', end=' ')\n elif (i, j) in others:\n print('X', end=' ')\n else:\n print('.', end=' ')\n print()\n print('Your last move was %d' % board[len(board) - 1])\n print(' 0')\n print('2 3')\n print(' 1')\n print('Enter move: ')\n move = int(input())\n return move\n\n\nclass fwrapper:\n\n def __init__(self, function, params, name):\n self.function = function\n self.childcount = params\n self.name = name\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass fwrapper:\n\n def __init__(self, function, childcount, name):\n self.function = function\n self.childcount = childcount\n self.name = name\n\n\n<mask token>\n\n\nclass node:\n\n def __init__(self, fw, children):\n self.function = fw.function\n self.name = fw.name\n self.children = children\n\n def evaluate(self, inp):\n results = [n.evaluate(inp) for n in self.children]\n return self.function(results)\n\n def display(self, indent=0):\n print(' ' * indent + self.name)\n for c in self.children:\n c.display(indent + 1)\n\n\n<mask token>\n\n\nclass paramnode:\n\n def __init__(self, idx):\n self.idx = idx\n\n def evaluate(self, inp):\n return inp[self.idx]\n\n def display(self, indent=0):\n print('%sp%d' % (' ' * indent, self.idx))\n\n\n<mask token>\n\n\nclass constnode:\n\n def __init__(self, v):\n self.v = v\n\n def evaluate(self, inp):\n return self.v\n\n def display(self, indent=0):\n print('%s%d' % (' ' * indent, self.v))\n\n\n<mask token>\n\n\ndef iffunc(l):\n if l[0] > 0:\n return l[1]\n else:\n return l[2]\n\n\n<mask token>\n\n\ndef isgreater(l):\n if l[0] > l[1]:\n return 1\n else:\n return 0\n\n\n<mask token>\n\n\ndef exampletree():\n return node(ifw, [node(gtw, [paramnode(0), constnode(3)]), node(addw, [\n paramnode(1), constnode(5)]), node(subw, [paramnode(1), constnode(2)])]\n )\n\n\n<mask token>\n\n\ndef makerandomtree(pc, maxdepth=4, fpr=0.5, ppr=0.6):\n if random() < fpr and maxdepth > 0:\n f = choice(flist)\n children = [makerandomtree(pc, maxdepth - 1, fpr, ppr) for i in\n range(f.childcount)]\n return node(f, children)\n elif random() < ppr:\n return paramnode(randint(0, pc - 1))\n else:\n return constnode(randint(0, 10))\n\n\ndef hiddenfunction(x, y):\n return x ** 2 + 2 * y + 3 * x + 5\n\n\ndef buildhiddenset():\n rows = []\n for i in range(200):\n x = randint(0, 40)\n y = randint(0, 40)\n rows.append([x, y, hiddenfunction(x, y)])\n return rows\n\n\n<mask token>\n\n\ndef scorefunction(tree, s):\n dif = 0\n for data in s:\n v = tree.evaluate([data[0], data[1]])\n dif += abs(v - data[2])\n return dif\n\n\n<mask token>\n\n\ndef mutate(t, pc, probchange=0.1):\n if random() < probchange:\n return makerandomtree(pc)\n else:\n result = deepcopy(t)\n if hasattr(t, 'children'):\n result.children = [mutate(c, pc, probchange) for c in t.children]\n return result\n\n\n<mask token>\n\n\ndef crossover(t1, t2, probswap=0.7, top=1):\n if random() < probswap and not top:\n return deepcopy(t2)\n else:\n result = deepcopy(t1)\n if hasattr(t1, 'children') and hasattr(t2, 'children'):\n result.children = [crossover(c, choice(t2.children), probswap, \n 0) for c in t1.children]\n return result\n\n\ndef getrankfunction(dataset):\n\n def rankfunction(population):\n scores = [(scorefunction(t, dataset), t) for t in population]\n scores.sort()\n return scores\n return rankfunction\n\n\n<mask token>\n\n\ndef evolve(pc, popsize, rankfunction, maxgen=500, mutationrate=0.1,\n breedingrate=0.4, pexp=0.7, pnew=0.05):\n \"\"\"Эта функция создает случайную исходную популяцию, а затем выполняет не более maxgen итераций цикла,\n вызывая каждый раз функцию rankfunction для ранжирования программ от наилучшей до наихудшей.\n Наилучшая программа автоматически попадает в следующее поколение без изменения. \n Args:\n rankfunction: Функция, применяемая для ранжирования списка программ от наилучшей к наихудшей.\n mutationrate: Вероятность мутации, передаваемая функции mutate.\n breedingrate: Вероятность скрещивания, передаваемая функции crossover.\n popsize: Размер исходной популяции.\n probexp: Скорость убывания вероятности выбора программ с низким рангом. Чем выше значение, тем более суров процесс естественного отбора/\n probnew: Вероятность включения в новую популяцию совершенно новой случайно сгенерированной программы.\n\n Returns:\n tuple: Найденное наилучшее совпадние\n\n \"\"\"\n\n def selectindex():\n return int(log(random()) / log(pexp))\n population = [makerandomtree(pc) for i in range(popsize)]\n for i in range(maxgen):\n scores = rankfunction(population)\n print(scores[0][0])\n if scores[0][0] == 0:\n break\n newpop = [scores[0][1], scores[1][1]]\n while len(newpop) < popsize:\n if random() > pnew:\n newpop.append(mutate(crossover(scores[selectindex()][1],\n scores[selectindex()][1], probswap=breedingrate), pc,\n probchange=mutationrate))\n else:\n newpop.append(makerandomtree(pc))\n population = newpop\n scores[0][1].display()\n return scores[0][1]\n\n\ndef gridgame(p):\n max = 3, 3\n lastmove = [-1, -1]\n location = [[randint(0, max[0]), randint(0, max[1])]]\n location.append([(location[0][0] + 2) % 4, (location[0][1] + 2) % 4])\n for o in range(50):\n for i in range(2):\n locs = location[i][:] + location[1 - i][:]\n locs.append(lastmove[i])\n move = p[i].evaluate(locs) % 4\n if lastmove[i] == move:\n return 1 - i\n lastmove[i] = move\n if move == 0:\n location[i][0] -= 1\n if location[i][0] < 0:\n location[i][0] = 0\n if move == 1:\n location[i][0] += 1\n if location[i][0] > max[0]:\n location[i][0] = max[0]\n if move == 2:\n location[i][1] -= 1\n if location[i][1] < 0:\n location[i][1] = 0\n if move == 3:\n location[i][1] += 1\n if location[i][1] > max[1]:\n location[i][1] = max[1]\n if location[i] == location[1 - i]:\n return i\n return -1\n\n\ndef tournament(pl):\n losses = [(0) for p in pl]\n for i in range(len(pl)):\n for j in range(len(pl)):\n if i == j:\n continue\n winner = gridgame([pl[i], pl[j]])\n if winner == 0:\n losses[j] += 2\n elif winner == 1:\n losses[i] += 2\n elif winner == -1:\n losses[i] += 1\n losses[i] += 1\n pass\n z = list(zip(losses, pl))\n z.sort(key=lambda t: t[0])\n print(z[0][1].display(indent=4))\n return z\n\n\nclass humanplayer:\n\n def evaluate(self, board):\n me = tuple(board[0:2])\n others = [tuple(board[x:x + 2]) for x in range(2, len(board) - 1, 2)]\n for i in range(4):\n for j in range(4):\n if (i, j) == me:\n print('O', end=' ')\n elif (i, j) in others:\n print('X', end=' ')\n else:\n print('.', end=' ')\n print()\n print('Your last move was %d' % board[len(board) - 1])\n print(' 0')\n print('2 3')\n print(' 1')\n print('Enter move: ')\n move = int(input())\n return move\n\n\nclass fwrapper:\n\n def __init__(self, function, params, name):\n self.function = function\n self.childcount = params\n self.name = name\n\n\n<mask token>\n",
"step-5": "from random import random, randint, choice\r\nfrom copy import deepcopy\r\nfrom math import log\r\n\r\n\"\"\"\r\nОбертка для функций, которые будут находиться в узлах,\r\nпредставляющих функции. Его члены – имя функции, сама функция\r\nи количество принимаемых параметров.\r\n\"\"\"\r\nclass fwrapper:\r\n def __init__(self, function, childcount, name):\r\n self.function = function\r\n self.childcount = childcount\r\n self.name = name\r\n\r\n\"\"\"\r\nКласс функциональных узлов (имеющих потомков). Инициализируется экземпляром класса fwrapper.\r\nМетод evaluate вычисляет значения дочерних узлов и передает их представленной данным узлом\r\nфункции в качестве параметров.\r\n\"\"\"\r\nclass node:\r\n def __init__(self, fw, children):\r\n self.function = fw.function\r\n self.name = fw.name\r\n self.children = children\r\n\r\n def evaluate(self, inp):\r\n results = [n.evaluate(inp) for n in self.children]\r\n return self.function(results)\r\n \r\n # Метод display выводит представление дерева в виде строки\r\n def display(self, indent=0):\r\n print((' ' * indent) + self.name)\r\n for c in self.children:\r\n c.display(indent + 1)\r\n\r\n\"\"\"\r\nКласс узлов, которые просто возвращают один из переданных программе параметров.\r\nЕго метод evaluate возвращает параметр, соответствующий значению idx.\r\n\"\"\"\r\nclass paramnode:\r\n def __init__(self, idx):\r\n self.idx = idx\r\n\r\n def evaluate(self, inp):\r\n return inp[self.idx]\r\n \r\n # Это метод просто печатает индекс возвращаемого параметра\r\n def display(self, indent=0):\r\n print('%sp%d' % (' ' * indent, self.idx))\r\n\r\n\"\"\"\r\nУзлы, возвращающие константы. Метод evaluate просто возвращает\r\nто значение, которым экземпляр был инициализирован.\r\n\"\"\"\r\nclass constnode:\r\n def __init__(self, v):\r\n self.v = v\r\n\r\n def evaluate(self, inp):\r\n return self.v\r\n\r\n def display(self, indent=0):\r\n print('%s%d' % (' ' * indent, self.v))\r\n\r\n \r\n\"\"\"\r\nПростые функции типа add и subtract можно встроить с помощью лямбда-выражений.\r\nДля остальных функцию придется написать в отдельном блоке.\r\nВ любом случае функция обертывается в экземпляр класса fwrapper \r\nвместе со своим именем и числом параметров.\r\n\"\"\"\r\n\r\naddw = fwrapper(lambda l: l[0] + l[1], 2, 'add')\r\nsubw = fwrapper(lambda l: l[0] - l[1], 2, 'subtract')\r\nmulw = fwrapper(lambda l: l[0] * l[1], 2, 'multiply')\r\n\r\n\r\ndef iffunc(l):\r\n if l[0] > 0:\r\n return l[1]\r\n else:\r\n return l[2]\r\n\r\n\r\nifw = fwrapper(iffunc, 3, 'if')\r\n\r\n\r\ndef isgreater(l):\r\n if l[0] > l[1]:\r\n return 1\r\n else:\r\n return 0\r\n\r\n\r\ngtw = fwrapper(isgreater, 2, 'isgreater')\r\n\r\n# В этой строке создается список всех функций, чтобы впоследствии из него\r\n# можно было выбирать элементы случайным образом.\r\nflist = [addw, mulw, ifw, gtw, subw]\r\n\r\n# C помощью класса node можно построить дерево программы (в качестве примера)\r\ndef exampletree():\r\n return node(ifw, [\r\n node(gtw, [paramnode(0), constnode(3)]),\r\n node(addw, [paramnode(1), constnode(5)]),\r\n node(subw, [paramnode(1), constnode(2)]),\r\n ]\r\n )\r\n\r\n\r\n\"\"\"\r\nЭта функция создает узел, содержащий случайно выбранную функцию, и проверяет,\r\nсколько у этой функции должно быть параметров. Для каждого дочернего узла функция\r\nвызывает себя рекурсивно, чтобы создать новый узел. Так конструируется все дерево,\r\nпричем процесс построения ветвей завершается в тот момент, когда у очередного узла \r\nнет дочерних (то есть он представляет либо константу, либо переменную-параметр).\r\nПараметр pc равен числу параметров, принимаемых деревом на входе. Параметр fpr\r\nзадает вероятность того, что вновь создаваемый узел будет соответствовать функции,\r\nа ppr – вероятность того, что узел, не являющийся функцией, будет иметь тип paramnode.\r\n\"\"\"\r\ndef makerandomtree(pc, maxdepth=4, fpr=0.5, ppr=0.6):\r\n if random() < fpr and maxdepth > 0:\r\n f = choice(flist)\r\n children = [makerandomtree(pc, maxdepth - 1, fpr, ppr)\r\n for i in range(f.childcount)]\r\n return node(f, children)\r\n elif random() < ppr:\r\n return paramnode(randint(0, pc - 1))\r\n else:\r\n return constnode(randint(0, 10))\r\n\r\n\r\ndef hiddenfunction(x, y):\r\n return x ** 2 + 2 * y + 3 * x + 5\r\n\r\n\r\ndef buildhiddenset():\r\n rows = []\r\n for i in range(200):\r\n x = randint(0, 40)\r\n y = randint(0, 40)\r\n rows.append([x, y, hiddenfunction(x, y)])\r\n return rows\r\n\r\n\r\n\"\"\"\r\nЭта функция перебирает все строки набора данных, вычисляет функцию от указанных \r\nв ней аргументов и сравнивает с результатом. Абсолютные значения разностей суммируются.\r\nЧем меньше сумма, тем лучше программа, а значение 0 говорит о том, что все результаты \r\nв точности совпали. \r\n\"\"\"\r\ndef scorefunction(tree, s):\r\n dif = 0\r\n for data in s:\r\n v = tree.evaluate([data[0], data[1]])\r\n dif += abs(v - data[2])\r\n return dif\r\n\r\n\r\n\"\"\"\r\nЭта функция начинает с корня дерева и решает, следует ли изменить\r\nузел. Если нет, она рекурсивно вызывает mutate для дочерних узлов.\r\nМожет случиться, что мутации подвергнутся все узлы, а иногда дерево\r\nвообще не изменится.\r\n\"\"\"\r\n# Мутация путем замены поддерева\r\ndef mutate(t, pc, probchange=0.1):\r\n if random() < probchange:\r\n return makerandomtree(pc)\r\n else:\r\n result = deepcopy(t)\r\n if hasattr(t, \"children\"):\r\n result.children = [mutate(c, pc, probchange) for c in t.children]\r\n return result\r\n\r\n\"\"\"\r\nФункции, выполняющей скрещивание, передаются два дерева, и она\r\nобходит оба. Если случайно выбранное число не превышает пороговой\r\nвероятности, то функция возвращает копию первого дерева, в которой\r\nодна из ветвей заменена какой-то ветвью, взятой из второго дерева.\r\nПоскольку обход выполняется параллельно, то скрещивание произойдет примерно на одном уровне каждого дерева.\r\n\"\"\"\r\n# Функция скрещивания. Две успешные программы комбинируются с целью получения новой программы.\r\ndef crossover(t1, t2, probswap=0.7, top=1):\r\n if random() < probswap and not top:\r\n return deepcopy(t2)\r\n else:\r\n result = deepcopy(t1)\r\n if hasattr(t1, 'children') and hasattr(t2, 'children'):\r\n result.children = [crossover(c, choice(t2.children), probswap, 0)\r\n for c in t1.children]\r\n return result\r\n\r\n# Функция возвращает функцию ранжирования для имеющегося набора данных\r\ndef getrankfunction(dataset):\r\n def rankfunction(population):\r\n scores = [(scorefunction(t, dataset), t) for t in population]\r\n scores.sort()\r\n return scores\r\n\r\n return rankfunction\r\n\r\n\r\n\"\"\"\r\nСоздание конкурентной среды, в которой программы будут эволюционировать.\r\nСмысл в том, чтобы создать набор случайных программ, отобрать из них\r\nнаилучшие для копирования и модификации и повторять процесс, пока не будет\r\nвыполнено некое условие останова.\r\n\"\"\"\r\ndef evolve(pc, popsize, rankfunction, maxgen=500, mutationrate=0.1, breedingrate=0.4, pexp=0.7, pnew=0.05):\r\n \"\"\"Эта функция создает случайную исходную популяцию, а затем выполняет не более maxgen итераций цикла,\r\n вызывая каждый раз функцию rankfunction для ранжирования программ от наилучшей до наихудшей.\r\n Наилучшая программа автоматически попадает в следующее поколение без изменения. \r\n Args:\r\n rankfunction: Функция, применяемая для ранжирования списка программ от наилучшей к наихудшей.\r\n mutationrate: Вероятность мутации, передаваемая функции mutate.\r\n breedingrate: Вероятность скрещивания, передаваемая функции crossover.\r\n popsize: Размер исходной популяции.\r\n probexp: Скорость убывания вероятности выбора программ с низким рангом. Чем выше значение, тем более суров процесс естественного отбора/\r\n probnew: Вероятность включения в новую популяцию совершенно новой случайно сгенерированной программы.\r\n\r\n Returns:\r\n tuple: Найденное наилучшее совпадние\r\n\r\n \"\"\"\r\n # Возвращает случайное число, отдавая предпочтение более маленьким числам.\r\n # Чем меньше значение pexp, тем больше будет доля маленьких чисел.\r\n def selectindex():\r\n return int(log(random()) / log(pexp))\r\n\r\n # Создаем случайную исходную популяцию\r\n population = [makerandomtree(pc) for i in range(popsize)]\r\n for i in range(maxgen):\r\n scores = rankfunction(population)\r\n print(scores[0][0])\r\n if scores[0][0] == 0: break\r\n\r\n # Две наилучшие особи отбираются всегда\r\n newpop = [scores[0][1], scores[1][1]]\r\n\r\n # Строим следующее поколение\r\n while len(newpop) < popsize:\r\n if random() > pnew:\r\n newpop.append(mutate(\r\n crossover(scores[selectindex()][1],\r\n scores[selectindex()][1],\r\n probswap=breedingrate),\r\n pc, probchange=mutationrate))\r\n else:\r\n # Добавляем случайный узел для внесения неопределенности\r\n newpop.append(makerandomtree(pc))\r\n\r\n population = newpop\r\n scores[0][1].display()\r\n return scores[0][1]\r\n\r\n#[\r\n# (10, \"program1\"),\r\n# (17, \"program2\"),\r\n#]\r\n\r\ndef gridgame(p):\r\n # Размер доски\r\n max = (3, 3)\r\n\r\n # Запоминаем последний ход каждого игрока\r\n lastmove = [-1, -1]\r\n\r\n # Запоминаем положения игроков\r\n location = [[randint(0, max[0]), randint(0, max[1])]]\r\n\r\n # Располагаем второго игрока на достаточном удалении от первого\r\n location.append([(location[0][0] + 2) % 4, (location[0][1] + 2) % 4])\r\n # Не более 50 ходов до объявления ничьей\r\n for o in range(50):\r\n\r\n # Для каждого игрока\r\n for i in range(2):\r\n locs = location[i][:] + location[1 - i][:]\r\n locs.append(lastmove[i])\r\n move = p[i].evaluate(locs) % 4\r\n\r\n # Если игрок два раза подряд ходит в одном направлении, ему\r\n # засчитывается проигрыш\r\n if lastmove[i] == move: return 1 - i\r\n lastmove[i] = move\r\n if move == 0:\r\n location[i][0] -= 1\r\n # Доска ограничена\r\n if location[i][0] < 0: location[i][0] = 0\r\n if move == 1:\r\n location[i][0] += 1\r\n if location[i][0] > max[0]: location[i][0] = max[0]\r\n if move == 2:\r\n location[i][1] -= 1\r\n if location[i][1] < 0: location[i][1] = 0\r\n if move == 3:\r\n location[i][1] += 1\r\n if location[i][1] > max[1]: location[i][1] = max[1]\r\n\r\n # Если противник захвачен в плен, вы выиграли\r\n if location[i] == location[1 - i]: return i\r\n return -1\r\n\r\n\r\ndef tournament(pl):\r\n # Массив для подсчета проигрышей\r\n losses = [0 for p in pl]\r\n\r\n # Каждый игрок встречается со всеми другими\r\n for i in range(len(pl)):\r\n for j in range(len(pl)):\r\n if i == j: continue\r\n\r\n # Кто выиграл?\r\n winner = gridgame([pl[i], pl[j]])\r\n\r\n # Два очка за поражение, одно за ничью\r\n if winner == 0:\r\n losses[j] += 2\r\n elif winner == 1:\r\n losses[i] += 2\r\n elif winner == -1:\r\n losses[i] += 1\r\n losses[i] += 1\r\n pass\r\n\r\n # Отсортировать и вернуть результаты\r\n z = list(zip(losses, pl))\r\n z.sort(key=lambda t: t[0])\r\n # input()\r\n print(z[0][1].display(indent=4))\r\n return z\r\n\r\nclass humanplayer:\r\n def evaluate(self, board):\r\n\r\n # Получить мою позицию и позиции других игроков\r\n me = tuple(board[0:2])\r\n others = [tuple(board[x:x + 2]) for x in range(2, len(board) - 1, 2)]\r\n\r\n # Нарисовать доску\r\n for i in range(4):\r\n for j in range(4):\r\n if (i, j) == me:\r\n print('O',end=' ')\r\n elif (i, j) in others:\r\n print('X',end=' ')\r\n else:\r\n print('.',end=' ')\r\n print()\r\n\r\n # Показать ходы, для справки\r\n print('Your last move was %d' % board[len(board) - 1])\r\n print(' 0')\r\n print('2 3')\r\n print(' 1')\r\n print('Enter move: ')\r\n\r\n # Вернуть введенное пользователем число\r\n move = int(input())\r\n return move\r\n\r\n\r\nclass fwrapper:\r\n def __init__(self, function, params, name):\r\n self.function = function\r\n self.childcount = params\r\n self.name = name\r\n\r\n\r\n# flist={'str':[substringw,concatw],'int':[indexw]}\r\nflist = [addw, mulw, ifw, gtw, subw]\r\n",
"step-ids": [
23,
25,
28,
31,
34
]
}
|
[
23,
25,
28,
31,
34
] |
# @description Exporting outline (boundary faces) of zsoil results to vtu
# @input zsoil results
# @output vtu unstructured grid
# @author Matthias Preisig
# @date 2017/10/10
import numpy as np
from zsoil_tools import zsoil_results as zr
from zsoil_tools import vtktools
pathname = r'\\192.168.1.51\Mandats sur H RAID0\M1010_Tourbillon\stab_panneau'
prob = 'M1010_stabPann_m2_renfLat'
res = zr(pathname,prob)
res.read_rcf()
res.read_his()
tx = [67]
tsteps = []
for kt,step in enumerate(res.steps):
if step.conv_status in [-1]:
if step.time in tx:
tsteps.append(kt)
res.out_steps = tsteps
res.read_dat()
res.read_s00()
for lab in res.ele_group_labels:
if lab=='VOLUMICS':
res.read_s01() # volumics
## elif lab=='SHELLS':
## res.read_s02() # shells
## elif lab=='TRUSSES':
## res.read_s03() # trusses
## elif lab=='BEAMS':
## res.read_s04() # beams
## elif lab=='CONTACT':
## res.read_s07()
##vtktools.write_vtu(res,beams=True,verbose=False)
##vtktools.write_vtu(res,trusses=True,verbose=False)
vtktools.write_vtu(res,vol=True,verbose=False,outline=True)
##vtktools.write_vtu(res,shells=True,verbose=False)
|
normal
|
{
"blob_id": "fb6dd9ec7d8dc80eace90dadc2112c7c27125efd",
"index": 2055,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nres.read_rcf()\nres.read_his()\n<mask token>\nfor kt, step in enumerate(res.steps):\n if step.conv_status in [-1]:\n if step.time in tx:\n tsteps.append(kt)\n<mask token>\nres.read_dat()\nres.read_s00()\nfor lab in res.ele_group_labels:\n if lab == 'VOLUMICS':\n res.read_s01()\nvtktools.write_vtu(res, vol=True, verbose=False, outline=True)\n",
"step-3": "<mask token>\npathname = (\n '\\\\\\\\192.168.1.51\\\\Mandats sur H RAID0\\\\M1010_Tourbillon\\\\stab_panneau')\nprob = 'M1010_stabPann_m2_renfLat'\nres = zr(pathname, prob)\nres.read_rcf()\nres.read_his()\ntx = [67]\ntsteps = []\nfor kt, step in enumerate(res.steps):\n if step.conv_status in [-1]:\n if step.time in tx:\n tsteps.append(kt)\nres.out_steps = tsteps\nres.read_dat()\nres.read_s00()\nfor lab in res.ele_group_labels:\n if lab == 'VOLUMICS':\n res.read_s01()\nvtktools.write_vtu(res, vol=True, verbose=False, outline=True)\n",
"step-4": "import numpy as np\nfrom zsoil_tools import zsoil_results as zr\nfrom zsoil_tools import vtktools\npathname = (\n '\\\\\\\\192.168.1.51\\\\Mandats sur H RAID0\\\\M1010_Tourbillon\\\\stab_panneau')\nprob = 'M1010_stabPann_m2_renfLat'\nres = zr(pathname, prob)\nres.read_rcf()\nres.read_his()\ntx = [67]\ntsteps = []\nfor kt, step in enumerate(res.steps):\n if step.conv_status in [-1]:\n if step.time in tx:\n tsteps.append(kt)\nres.out_steps = tsteps\nres.read_dat()\nres.read_s00()\nfor lab in res.ele_group_labels:\n if lab == 'VOLUMICS':\n res.read_s01()\nvtktools.write_vtu(res, vol=True, verbose=False, outline=True)\n",
"step-5": "# @description Exporting outline (boundary faces) of zsoil results to vtu\n# @input zsoil results\n# @output vtu unstructured grid\n# @author Matthias Preisig\n# @date 2017/10/10\n\nimport numpy as np\n\nfrom zsoil_tools import zsoil_results as zr\nfrom zsoil_tools import vtktools\n\n\npathname = r'\\\\192.168.1.51\\Mandats sur H RAID0\\M1010_Tourbillon\\stab_panneau'\nprob = 'M1010_stabPann_m2_renfLat'\n\nres = zr(pathname,prob)\nres.read_rcf()\nres.read_his()\ntx = [67]\ntsteps = []\nfor kt,step in enumerate(res.steps):\n if step.conv_status in [-1]:\n if step.time in tx:\n tsteps.append(kt)\nres.out_steps = tsteps\nres.read_dat()\nres.read_s00()\nfor lab in res.ele_group_labels:\n if lab=='VOLUMICS':\n res.read_s01() # volumics\n## elif lab=='SHELLS':\n## res.read_s02() # shells\n## elif lab=='TRUSSES':\n## res.read_s03() # trusses\n## elif lab=='BEAMS':\n## res.read_s04() # beams\n## elif lab=='CONTACT':\n## res.read_s07()\n\n\n##vtktools.write_vtu(res,beams=True,verbose=False)\n##vtktools.write_vtu(res,trusses=True,verbose=False)\nvtktools.write_vtu(res,vol=True,verbose=False,outline=True)\n##vtktools.write_vtu(res,shells=True,verbose=False)\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
"""
Author:
C.M. Gosmeyer
Date:
Mar 2018
References:
"Introduction to Statistical Problem Solving in Geography",
J.C. McGrew, Jr., A.J. Lembo, Jr., C.B. Monroe
To Do:
Should tables interpolate?
y = y1 + ((x - x1) / (x2 - x1)) * (y2 - y1)
"""
import numpy as np
import pandas as pd
import os
# Get absolute path to table files.
p = os.path.abspath(__file__)
p = '/'.join(p.split('/')[:-1])
class LoadTable(object):
"""
"""
def __init__(self, filename):
self.filename = filename
def load_table(self):
table = pd.read_csv(self.filename)
return table
class LoadNormalTable(LoadTable):
""" A normal table object.
"""
def __init__(self):
LoadTable.__init__(self, os.path.join(p, 'normal_table.csv'))
temp_table = self.load_table()
self.normal_table = temp_table.set_index("z")
def find_z(self, prob, tails=1):
""" Given probability, return nearest Z-score from normal table.
Parameters
----------
prob : float
The probability, i.e., the area under section of probability
distriubtion curve.
tails : int
1 or 2. The prob will be divided by this number (all
calculations assume one tail). Do not change to 2 if your
`prob` value already is divided in half.
Returns
-------
z_score : float
The Z-score or standard score.
"""
prob /= float(tails)
normal_table = self.normal_table
# Find closest probability in table
nearest_probs = []
for col in list(normal_table):
nearest_probs.append(find_nearest(normal_table[col], prob))
nearest_probs = np.asarray(nearest_probs)
final_prob = find_nearest(nearest_probs, prob)
# Return the column and row
for col in list(normal_table):
if final_prob in list(normal_table[col]):
z1 = col
for i in normal_table.index:
if final_prob == normal_table[z1][i]:
z0 = i
# Build Z-score
z_score = float(z0) + float(z1)
return z_score
def find_prob(self, z, tails=1):
""" Given Z-score, return nearest probability from table.
Parameters
----------
z : float
The Z-score or standard score.
tails : int
1 or 2.
Returns
-------
prob : float
The probability, i.e., the area under section of probability
distriubtion curve.
"""
normal_table = self.normal_table
if z > 4:
prob = 0.5
else:
z0 = round(z, 1)
z1 = str(round(z, 2) - z0)
prob = round(normal_table[z1][z0], 6)
prob *= tails
return prob
class LoadStudentsTTable(LoadTable):
""" A normal table object.
"""
def __init__(self, tails):
"""
Parameters
----------
tails : int
1 or 2.
"""
if tails == 1:
LoadTable.__init__(self, os.path.join(p, 'students_t_table_one_tail.csv'))
else:
LoadTable.__init__(self, os.path.join(p, 'students_t_table_two_tail.csv'))
temp_table = self.load_table()
self.t_table = temp_table.set_index("df")
def find_t(self, df, confidence=0.95):
""" Finds the T-value of distribution. The table goes to df-1000,
after which all is effectively infinity and returns same value.
By default the confidence level is 95%.
Parameters
----------
df : int
Degrees of freedom (size of sample).
confidence : float
The confidence level (area under distriubtion curve within
interval).
Returns
-------
t_score : float
The test statistic.
"""
t_table = self.t_table
nearest_confidence = round(find_nearest(list(t_table), 1.0-confidence), 4)
nearest_df = round(find_nearest(t_table.index, df), 0)
t_score = round(t_table[str(nearest_confidence)][nearest_df], 4)
return t_score
def find_confidence(self, t, df):
""" Finds confidence level (area) of ONE tail of distribution.
Parameters
----------
t : float
The test statistic.
df : int
Degrees of freedom (size of sample).
"""
t_table = self.t_table
nearest_df = round(find_nearest(t_table.index, df), 0)
nearest_t = round(find_nearest(t_table.loc[nearest_df], t), 6)
for col in list(t_table):
if nearest_t == round(t_table[col][nearest_df], 6):
# Subtract from one to get confidence, divide by two to get
# single section on positive side of distribution.
confidence = (1.0 - float(col)) / 2.0
return confidence
class LoadChi2Table(LoadTable):
""" A normal table object.
"""
def __init__(self):
"""
"""
LoadTable.__init__(self, os.path.join(p, 'chi_square_table.csv'))
temp_table = self.load_table()
self.chi2_table = temp_table.set_index("df")
def find_chi2(self, df, confidence=0.95):
""" Finds the T-value of distribution. The table goes to df-1000,
after which all is effectively infinity and returns same value.
By default the confidence level is 95%.
Parameters
----------
df : int
Degrees of freedom (size of sample).
confidence : float
The confidence level (area under distriubtion curve within
interval).
Returns
-------
chi2 : float
The test statistic.
"""
chi2_table = self.chi2_table
nearest_confidence = round(find_nearest(list(chi2_table), 1.0-confidence), 4)
nearest_df = round(find_nearest(chi2_table.index, df), 0)
chi2 = round(chi2_table[str(nearest_confidence)][nearest_df], 4)
return chi2
def find_confidence(self, chi2, df):
""" Finds confidence level (area) of right-hand-side of distribution.
Parameters
----------
chi2 : float
The test statistic.
df : int
Degrees of freedom (size of sample).
"""
chi2_table = self.chi2_table
nearest_df = round(find_nearest(chi2_table.index, df), 0)
nearest_chi2 = round(find_nearest(chi2_table.loc[nearest_df], chi2), 6)
for col in list(chi2_table):
if nearest_chi2 == round(chi2_table[col][nearest_df], 6):
# Subtract from one to get confidence.
confidence = (1.0 - float(col))
return confidence
def find_nearest(array, value):
array = np.array(array, dtype=float)
value = float(value)
idx = pd.Series((np.abs(array-value))).idxmin()
return array[idx]
|
normal
|
{
"blob_id": "adb6e33dc665f88c82fcc399688a8dbd67b1e3e3",
"index": 9894,
"step-1": "<mask token>\n\n\nclass LoadStudentsTTable(LoadTable):\n <mask token>\n\n def __init__(self, tails):\n \"\"\"\n\n Parameters\n ----------\n tails : int\n 1 or 2.\n \"\"\"\n if tails == 1:\n LoadTable.__init__(self, os.path.join(p,\n 'students_t_table_one_tail.csv'))\n else:\n LoadTable.__init__(self, os.path.join(p,\n 'students_t_table_two_tail.csv'))\n temp_table = self.load_table()\n self.t_table = temp_table.set_index('df')\n <mask token>\n\n def find_confidence(self, t, df):\n \"\"\" Finds confidence level (area) of ONE tail of distribution.\n\n Parameters\n ----------\n t : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample). \n \"\"\"\n t_table = self.t_table\n nearest_df = round(find_nearest(t_table.index, df), 0)\n nearest_t = round(find_nearest(t_table.loc[nearest_df], t), 6)\n for col in list(t_table):\n if nearest_t == round(t_table[col][nearest_df], 6):\n confidence = (1.0 - float(col)) / 2.0\n return confidence\n\n\nclass LoadChi2Table(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n \"\"\"\n LoadTable.__init__(self, os.path.join(p, 'chi_square_table.csv'))\n temp_table = self.load_table()\n self.chi2_table = temp_table.set_index('df')\n\n def find_chi2(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n chi2 : float\n The test statistic.\n \"\"\"\n chi2_table = self.chi2_table\n nearest_confidence = round(find_nearest(list(chi2_table), 1.0 -\n confidence), 4)\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n chi2 = round(chi2_table[str(nearest_confidence)][nearest_df], 4)\n return chi2\n\n def find_confidence(self, chi2, df):\n \"\"\" Finds confidence level (area) of right-hand-side of distribution.\n\n Parameters\n ----------\n chi2 : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample).\n \"\"\"\n chi2_table = self.chi2_table\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n nearest_chi2 = round(find_nearest(chi2_table.loc[nearest_df], chi2), 6)\n for col in list(chi2_table):\n if nearest_chi2 == round(chi2_table[col][nearest_df], 6):\n confidence = 1.0 - float(col)\n return confidence\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass LoadTable(object):\n <mask token>\n\n def __init__(self, filename):\n self.filename = filename\n\n def load_table(self):\n table = pd.read_csv(self.filename)\n return table\n\n\nclass LoadNormalTable(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self):\n LoadTable.__init__(self, os.path.join(p, 'normal_table.csv'))\n temp_table = self.load_table()\n self.normal_table = temp_table.set_index('z')\n\n def find_z(self, prob, tails=1):\n \"\"\" Given probability, return nearest Z-score from normal table.\n\n Parameters\n ----------\n prob : float\n The probability, i.e., the area under section of probability\n distriubtion curve.\n tails : int\n 1 or 2. The prob will be divided by this number (all \n calculations assume one tail). Do not change to 2 if your\n `prob` value already is divided in half.\n\n Returns\n -------\n z_score : float\n The Z-score or standard score.\n \"\"\"\n prob /= float(tails)\n normal_table = self.normal_table\n nearest_probs = []\n for col in list(normal_table):\n nearest_probs.append(find_nearest(normal_table[col], prob))\n nearest_probs = np.asarray(nearest_probs)\n final_prob = find_nearest(nearest_probs, prob)\n for col in list(normal_table):\n if final_prob in list(normal_table[col]):\n z1 = col\n for i in normal_table.index:\n if final_prob == normal_table[z1][i]:\n z0 = i\n z_score = float(z0) + float(z1)\n return z_score\n\n def find_prob(self, z, tails=1):\n \"\"\" Given Z-score, return nearest probability from table.\n\n Parameters\n ----------\n z : float\n The Z-score or standard score.\n tails : int\n 1 or 2.\n\n Returns\n -------\n prob : float\n The probability, i.e., the area under section of probability\n distriubtion curve.\n \"\"\"\n normal_table = self.normal_table\n if z > 4:\n prob = 0.5\n else:\n z0 = round(z, 1)\n z1 = str(round(z, 2) - z0)\n prob = round(normal_table[z1][z0], 6)\n prob *= tails\n return prob\n\n\nclass LoadStudentsTTable(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self, tails):\n \"\"\"\n\n Parameters\n ----------\n tails : int\n 1 or 2.\n \"\"\"\n if tails == 1:\n LoadTable.__init__(self, os.path.join(p,\n 'students_t_table_one_tail.csv'))\n else:\n LoadTable.__init__(self, os.path.join(p,\n 'students_t_table_two_tail.csv'))\n temp_table = self.load_table()\n self.t_table = temp_table.set_index('df')\n\n def find_t(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n t_score : float\n The test statistic.\n \"\"\"\n t_table = self.t_table\n nearest_confidence = round(find_nearest(list(t_table), 1.0 -\n confidence), 4)\n nearest_df = round(find_nearest(t_table.index, df), 0)\n t_score = round(t_table[str(nearest_confidence)][nearest_df], 4)\n return t_score\n\n def find_confidence(self, t, df):\n \"\"\" Finds confidence level (area) of ONE tail of distribution.\n\n Parameters\n ----------\n t : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample). \n \"\"\"\n t_table = self.t_table\n nearest_df = round(find_nearest(t_table.index, df), 0)\n nearest_t = round(find_nearest(t_table.loc[nearest_df], t), 6)\n for col in list(t_table):\n if nearest_t == round(t_table[col][nearest_df], 6):\n confidence = (1.0 - float(col)) / 2.0\n return confidence\n\n\nclass LoadChi2Table(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n \"\"\"\n LoadTable.__init__(self, os.path.join(p, 'chi_square_table.csv'))\n temp_table = self.load_table()\n self.chi2_table = temp_table.set_index('df')\n\n def find_chi2(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n chi2 : float\n The test statistic.\n \"\"\"\n chi2_table = self.chi2_table\n nearest_confidence = round(find_nearest(list(chi2_table), 1.0 -\n confidence), 4)\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n chi2 = round(chi2_table[str(nearest_confidence)][nearest_df], 4)\n return chi2\n\n def find_confidence(self, chi2, df):\n \"\"\" Finds confidence level (area) of right-hand-side of distribution.\n\n Parameters\n ----------\n chi2 : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample).\n \"\"\"\n chi2_table = self.chi2_table\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n nearest_chi2 = round(find_nearest(chi2_table.loc[nearest_df], chi2), 6)\n for col in list(chi2_table):\n if nearest_chi2 == round(chi2_table[col][nearest_df], 6):\n confidence = 1.0 - float(col)\n return confidence\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass LoadTable(object):\n \"\"\"\n \"\"\"\n\n def __init__(self, filename):\n self.filename = filename\n\n def load_table(self):\n table = pd.read_csv(self.filename)\n return table\n\n\nclass LoadNormalTable(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self):\n LoadTable.__init__(self, os.path.join(p, 'normal_table.csv'))\n temp_table = self.load_table()\n self.normal_table = temp_table.set_index('z')\n\n def find_z(self, prob, tails=1):\n \"\"\" Given probability, return nearest Z-score from normal table.\n\n Parameters\n ----------\n prob : float\n The probability, i.e., the area under section of probability\n distriubtion curve.\n tails : int\n 1 or 2. The prob will be divided by this number (all \n calculations assume one tail). Do not change to 2 if your\n `prob` value already is divided in half.\n\n Returns\n -------\n z_score : float\n The Z-score or standard score.\n \"\"\"\n prob /= float(tails)\n normal_table = self.normal_table\n nearest_probs = []\n for col in list(normal_table):\n nearest_probs.append(find_nearest(normal_table[col], prob))\n nearest_probs = np.asarray(nearest_probs)\n final_prob = find_nearest(nearest_probs, prob)\n for col in list(normal_table):\n if final_prob in list(normal_table[col]):\n z1 = col\n for i in normal_table.index:\n if final_prob == normal_table[z1][i]:\n z0 = i\n z_score = float(z0) + float(z1)\n return z_score\n\n def find_prob(self, z, tails=1):\n \"\"\" Given Z-score, return nearest probability from table.\n\n Parameters\n ----------\n z : float\n The Z-score or standard score.\n tails : int\n 1 or 2.\n\n Returns\n -------\n prob : float\n The probability, i.e., the area under section of probability\n distriubtion curve.\n \"\"\"\n normal_table = self.normal_table\n if z > 4:\n prob = 0.5\n else:\n z0 = round(z, 1)\n z1 = str(round(z, 2) - z0)\n prob = round(normal_table[z1][z0], 6)\n prob *= tails\n return prob\n\n\nclass LoadStudentsTTable(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self, tails):\n \"\"\"\n\n Parameters\n ----------\n tails : int\n 1 or 2.\n \"\"\"\n if tails == 1:\n LoadTable.__init__(self, os.path.join(p,\n 'students_t_table_one_tail.csv'))\n else:\n LoadTable.__init__(self, os.path.join(p,\n 'students_t_table_two_tail.csv'))\n temp_table = self.load_table()\n self.t_table = temp_table.set_index('df')\n\n def find_t(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n t_score : float\n The test statistic.\n \"\"\"\n t_table = self.t_table\n nearest_confidence = round(find_nearest(list(t_table), 1.0 -\n confidence), 4)\n nearest_df = round(find_nearest(t_table.index, df), 0)\n t_score = round(t_table[str(nearest_confidence)][nearest_df], 4)\n return t_score\n\n def find_confidence(self, t, df):\n \"\"\" Finds confidence level (area) of ONE tail of distribution.\n\n Parameters\n ----------\n t : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample). \n \"\"\"\n t_table = self.t_table\n nearest_df = round(find_nearest(t_table.index, df), 0)\n nearest_t = round(find_nearest(t_table.loc[nearest_df], t), 6)\n for col in list(t_table):\n if nearest_t == round(t_table[col][nearest_df], 6):\n confidence = (1.0 - float(col)) / 2.0\n return confidence\n\n\nclass LoadChi2Table(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n \"\"\"\n LoadTable.__init__(self, os.path.join(p, 'chi_square_table.csv'))\n temp_table = self.load_table()\n self.chi2_table = temp_table.set_index('df')\n\n def find_chi2(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n chi2 : float\n The test statistic.\n \"\"\"\n chi2_table = self.chi2_table\n nearest_confidence = round(find_nearest(list(chi2_table), 1.0 -\n confidence), 4)\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n chi2 = round(chi2_table[str(nearest_confidence)][nearest_df], 4)\n return chi2\n\n def find_confidence(self, chi2, df):\n \"\"\" Finds confidence level (area) of right-hand-side of distribution.\n\n Parameters\n ----------\n chi2 : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample).\n \"\"\"\n chi2_table = self.chi2_table\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n nearest_chi2 = round(find_nearest(chi2_table.loc[nearest_df], chi2), 6)\n for col in list(chi2_table):\n if nearest_chi2 == round(chi2_table[col][nearest_df], 6):\n confidence = 1.0 - float(col)\n return confidence\n\n\n<mask token>\n",
"step-4": "<mask token>\np = os.path.abspath(__file__)\np = '/'.join(p.split('/')[:-1])\n\n\nclass LoadTable(object):\n \"\"\"\n \"\"\"\n\n def __init__(self, filename):\n self.filename = filename\n\n def load_table(self):\n table = pd.read_csv(self.filename)\n return table\n\n\nclass LoadNormalTable(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self):\n LoadTable.__init__(self, os.path.join(p, 'normal_table.csv'))\n temp_table = self.load_table()\n self.normal_table = temp_table.set_index('z')\n\n def find_z(self, prob, tails=1):\n \"\"\" Given probability, return nearest Z-score from normal table.\n\n Parameters\n ----------\n prob : float\n The probability, i.e., the area under section of probability\n distriubtion curve.\n tails : int\n 1 or 2. The prob will be divided by this number (all \n calculations assume one tail). Do not change to 2 if your\n `prob` value already is divided in half.\n\n Returns\n -------\n z_score : float\n The Z-score or standard score.\n \"\"\"\n prob /= float(tails)\n normal_table = self.normal_table\n nearest_probs = []\n for col in list(normal_table):\n nearest_probs.append(find_nearest(normal_table[col], prob))\n nearest_probs = np.asarray(nearest_probs)\n final_prob = find_nearest(nearest_probs, prob)\n for col in list(normal_table):\n if final_prob in list(normal_table[col]):\n z1 = col\n for i in normal_table.index:\n if final_prob == normal_table[z1][i]:\n z0 = i\n z_score = float(z0) + float(z1)\n return z_score\n\n def find_prob(self, z, tails=1):\n \"\"\" Given Z-score, return nearest probability from table.\n\n Parameters\n ----------\n z : float\n The Z-score or standard score.\n tails : int\n 1 or 2.\n\n Returns\n -------\n prob : float\n The probability, i.e., the area under section of probability\n distriubtion curve.\n \"\"\"\n normal_table = self.normal_table\n if z > 4:\n prob = 0.5\n else:\n z0 = round(z, 1)\n z1 = str(round(z, 2) - z0)\n prob = round(normal_table[z1][z0], 6)\n prob *= tails\n return prob\n\n\nclass LoadStudentsTTable(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self, tails):\n \"\"\"\n\n Parameters\n ----------\n tails : int\n 1 or 2.\n \"\"\"\n if tails == 1:\n LoadTable.__init__(self, os.path.join(p,\n 'students_t_table_one_tail.csv'))\n else:\n LoadTable.__init__(self, os.path.join(p,\n 'students_t_table_two_tail.csv'))\n temp_table = self.load_table()\n self.t_table = temp_table.set_index('df')\n\n def find_t(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n t_score : float\n The test statistic.\n \"\"\"\n t_table = self.t_table\n nearest_confidence = round(find_nearest(list(t_table), 1.0 -\n confidence), 4)\n nearest_df = round(find_nearest(t_table.index, df), 0)\n t_score = round(t_table[str(nearest_confidence)][nearest_df], 4)\n return t_score\n\n def find_confidence(self, t, df):\n \"\"\" Finds confidence level (area) of ONE tail of distribution.\n\n Parameters\n ----------\n t : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample). \n \"\"\"\n t_table = self.t_table\n nearest_df = round(find_nearest(t_table.index, df), 0)\n nearest_t = round(find_nearest(t_table.loc[nearest_df], t), 6)\n for col in list(t_table):\n if nearest_t == round(t_table[col][nearest_df], 6):\n confidence = (1.0 - float(col)) / 2.0\n return confidence\n\n\nclass LoadChi2Table(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n \"\"\"\n LoadTable.__init__(self, os.path.join(p, 'chi_square_table.csv'))\n temp_table = self.load_table()\n self.chi2_table = temp_table.set_index('df')\n\n def find_chi2(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n chi2 : float\n The test statistic.\n \"\"\"\n chi2_table = self.chi2_table\n nearest_confidence = round(find_nearest(list(chi2_table), 1.0 -\n confidence), 4)\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n chi2 = round(chi2_table[str(nearest_confidence)][nearest_df], 4)\n return chi2\n\n def find_confidence(self, chi2, df):\n \"\"\" Finds confidence level (area) of right-hand-side of distribution.\n\n Parameters\n ----------\n chi2 : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample).\n \"\"\"\n chi2_table = self.chi2_table\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n nearest_chi2 = round(find_nearest(chi2_table.loc[nearest_df], chi2), 6)\n for col in list(chi2_table):\n if nearest_chi2 == round(chi2_table[col][nearest_df], 6):\n confidence = 1.0 - float(col)\n return confidence\n\n\ndef find_nearest(array, value):\n array = np.array(array, dtype=float)\n value = float(value)\n idx = pd.Series(np.abs(array - value)).idxmin()\n return array[idx]\n",
"step-5": "\"\"\" \n\nAuthor:\n \n C.M. Gosmeyer\n\nDate:\n\n Mar 2018\n\nReferences:\n\n \"Introduction to Statistical Problem Solving in Geography\", \n J.C. McGrew, Jr., A.J. Lembo, Jr., C.B. Monroe\n\nTo Do:\n\n Should tables interpolate?\n\n y = y1 + ((x - x1) / (x2 - x1)) * (y2 - y1)\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\n\n# Get absolute path to table files.\np = os.path.abspath(__file__)\np = '/'.join(p.split('/')[:-1])\n\nclass LoadTable(object):\n \"\"\"\n \"\"\"\n def __init__(self, filename):\n self.filename = filename\n\n def load_table(self):\n table = pd.read_csv(self.filename)\n return table\n\nclass LoadNormalTable(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n def __init__(self):\n LoadTable.__init__(self, os.path.join(p, 'normal_table.csv'))\n temp_table = self.load_table()\n self.normal_table = temp_table.set_index(\"z\")\n\n def find_z(self, prob, tails=1):\n \"\"\" Given probability, return nearest Z-score from normal table.\n\n Parameters\n ----------\n prob : float\n The probability, i.e., the area under section of probability\n distriubtion curve.\n tails : int\n 1 or 2. The prob will be divided by this number (all \n calculations assume one tail). Do not change to 2 if your\n `prob` value already is divided in half.\n\n Returns\n -------\n z_score : float\n The Z-score or standard score.\n \"\"\"\n prob /= float(tails)\n normal_table = self.normal_table\n\n # Find closest probability in table\n nearest_probs = []\n for col in list(normal_table):\n nearest_probs.append(find_nearest(normal_table[col], prob))\n nearest_probs = np.asarray(nearest_probs)\n final_prob = find_nearest(nearest_probs, prob)\n\n # Return the column and row\n for col in list(normal_table):\n if final_prob in list(normal_table[col]):\n z1 = col\n\n for i in normal_table.index:\n if final_prob == normal_table[z1][i]:\n z0 = i\n \n # Build Z-score\n z_score = float(z0) + float(z1) \n\n return z_score\n\n def find_prob(self, z, tails=1):\n \"\"\" Given Z-score, return nearest probability from table.\n\n Parameters\n ----------\n z : float\n The Z-score or standard score.\n tails : int\n 1 or 2.\n\n Returns\n -------\n prob : float\n The probability, i.e., the area under section of probability\n distriubtion curve.\n \"\"\"\n normal_table = self.normal_table\n\n if z > 4:\n prob = 0.5\n\n else:\n z0 = round(z, 1)\n z1 = str(round(z, 2) - z0)\n\n prob = round(normal_table[z1][z0], 6)\n prob *= tails\n\n return prob\n\nclass LoadStudentsTTable(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n def __init__(self, tails):\n \"\"\"\n\n Parameters\n ----------\n tails : int\n 1 or 2.\n \"\"\"\n if tails == 1:\n LoadTable.__init__(self, os.path.join(p, 'students_t_table_one_tail.csv'))\n else:\n LoadTable.__init__(self, os.path.join(p, 'students_t_table_two_tail.csv'))\n temp_table = self.load_table()\n self.t_table = temp_table.set_index(\"df\")\n\n def find_t(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n t_score : float\n The test statistic.\n \"\"\"\n t_table = self.t_table\n nearest_confidence = round(find_nearest(list(t_table), 1.0-confidence), 4)\n nearest_df = round(find_nearest(t_table.index, df), 0)\n t_score = round(t_table[str(nearest_confidence)][nearest_df], 4)\n\n return t_score\n\n def find_confidence(self, t, df):\n \"\"\" Finds confidence level (area) of ONE tail of distribution.\n\n Parameters\n ----------\n t : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample). \n \"\"\"\n t_table = self.t_table\n nearest_df = round(find_nearest(t_table.index, df), 0)\n nearest_t = round(find_nearest(t_table.loc[nearest_df], t), 6)\n for col in list(t_table):\n if nearest_t == round(t_table[col][nearest_df], 6):\n # Subtract from one to get confidence, divide by two to get\n # single section on positive side of distribution.\n confidence = (1.0 - float(col)) / 2.0\n return confidence\n\nclass LoadChi2Table(LoadTable):\n \"\"\" A normal table object.\n \"\"\"\n def __init__(self):\n \"\"\"\n \"\"\"\n LoadTable.__init__(self, os.path.join(p, 'chi_square_table.csv'))\n temp_table = self.load_table()\n self.chi2_table = temp_table.set_index(\"df\") \n\n def find_chi2(self, df, confidence=0.95):\n \"\"\" Finds the T-value of distribution. The table goes to df-1000,\n after which all is effectively infinity and returns same value.\n\n By default the confidence level is 95%.\n\n Parameters\n ----------\n df : int\n Degrees of freedom (size of sample).\n confidence : float\n The confidence level (area under distriubtion curve within\n interval). \n\n Returns\n -------\n chi2 : float\n The test statistic.\n \"\"\"\n chi2_table = self.chi2_table\n nearest_confidence = round(find_nearest(list(chi2_table), 1.0-confidence), 4)\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n chi2 = round(chi2_table[str(nearest_confidence)][nearest_df], 4)\n return chi2\n\n def find_confidence(self, chi2, df):\n \"\"\" Finds confidence level (area) of right-hand-side of distribution.\n\n Parameters\n ----------\n chi2 : float\n The test statistic.\n df : int\n Degrees of freedom (size of sample).\n \"\"\"\n chi2_table = self.chi2_table\n nearest_df = round(find_nearest(chi2_table.index, df), 0)\n nearest_chi2 = round(find_nearest(chi2_table.loc[nearest_df], chi2), 6)\n for col in list(chi2_table):\n if nearest_chi2 == round(chi2_table[col][nearest_df], 6):\n # Subtract from one to get confidence.\n confidence = (1.0 - float(col))\n return confidence\n\ndef find_nearest(array, value):\n array = np.array(array, dtype=float)\n value = float(value)\n idx = pd.Series((np.abs(array-value))).idxmin()\n return array[idx]\n",
"step-ids": [
8,
18,
19,
21,
23
]
}
|
[
8,
18,
19,
21,
23
] |
class default_locations:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class default_locations:
mc_2016_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2016_postProcessing_directory = 'stops_2016_nano_v0p23/dilep/'
data_2016_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2016_postProcessing_directory = 'stops_2016_nano_v0p19/dilep/'
mc_2017_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2017_postProcessing_directory = 'stops_2017_nano_v0p23/dilep/'
data_2017_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2017_postProcessing_directory = 'stops_2017_nano_v0p19/dilep/'
mc_2018_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2018_postProcessing_directory = 'stops_2018_nano_v0p23/dilep/'
data_2018_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2018_postProcessing_directory = 'stops_2018_nano_v0p19/dilep/'
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class default_locations:
mc_2016_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2016_postProcessing_directory = 'stops_2016_nano_v0p23/dilep/'
data_2016_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2016_postProcessing_directory = 'stops_2016_nano_v0p19/dilep/'
mc_2017_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2017_postProcessing_directory = 'stops_2017_nano_v0p23/dilep/'
data_2017_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2017_postProcessing_directory = 'stops_2017_nano_v0p19/dilep/'
mc_2018_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2018_postProcessing_directory = 'stops_2018_nano_v0p23/dilep/'
data_2018_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2018_postProcessing_directory = 'stops_2018_nano_v0p19/dilep/'
<|reserved_special_token_0|>
if os.environ['HOSTNAME'].startswith('clip'):
default_locations.mc_2016_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.data_2016_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.mc_2017_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.data_2017_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.mc_2018_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.data_2018_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
<|reserved_special_token_1|>
class default_locations:
mc_2016_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2016_postProcessing_directory = 'stops_2016_nano_v0p23/dilep/'
data_2016_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2016_postProcessing_directory = 'stops_2016_nano_v0p19/dilep/'
mc_2017_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2017_postProcessing_directory = 'stops_2017_nano_v0p23/dilep/'
data_2017_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2017_postProcessing_directory = 'stops_2017_nano_v0p19/dilep/'
mc_2018_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'
mc_2018_postProcessing_directory = 'stops_2018_nano_v0p23/dilep/'
data_2018_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'
data_2018_postProcessing_directory = 'stops_2018_nano_v0p19/dilep/'
import os
if os.environ['HOSTNAME'].startswith('clip'):
default_locations.mc_2016_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.data_2016_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.mc_2017_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.data_2017_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.mc_2018_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
default_locations.data_2018_data_directory = (
'/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')
<|reserved_special_token_1|>
class default_locations:
mc_2016_data_directory = "/afs/hephy.at/data/cms06/nanoTuples/"
mc_2016_postProcessing_directory = "stops_2016_nano_v0p23/dilep/"
data_2016_data_directory = "/afs/hephy.at/data/cms07/nanoTuples/"
data_2016_postProcessing_directory = "stops_2016_nano_v0p19/dilep/"
mc_2017_data_directory = "/afs/hephy.at/data/cms06/nanoTuples/"
mc_2017_postProcessing_directory = "stops_2017_nano_v0p23/dilep/"
data_2017_data_directory = "/afs/hephy.at/data/cms07/nanoTuples/"
data_2017_postProcessing_directory = "stops_2017_nano_v0p19/dilep/"
mc_2018_data_directory = "/afs/hephy.at/data/cms06/nanoTuples/"
mc_2018_postProcessing_directory = "stops_2018_nano_v0p23/dilep/"
data_2018_data_directory = "/afs/hephy.at/data/cms07/nanoTuples/"
data_2018_postProcessing_directory = "stops_2018_nano_v0p19/dilep/"
import os
if os.environ['HOSTNAME'].startswith('clip'):
default_locations.mc_2016_data_directory = "/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/"
default_locations.data_2016_data_directory = "/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/"
default_locations.mc_2017_data_directory = "/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/"
default_locations.data_2017_data_directory = "/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/"
default_locations.mc_2018_data_directory = "/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/"
default_locations.data_2018_data_directory = "/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/"
|
flexible
|
{
"blob_id": "b6df9414f99294c7986d3eb5332d40288f059cd1",
"index": 1245,
"step-1": "class default_locations:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "class default_locations:\n mc_2016_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2016_postProcessing_directory = 'stops_2016_nano_v0p23/dilep/'\n data_2016_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2016_postProcessing_directory = 'stops_2016_nano_v0p19/dilep/'\n mc_2017_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2017_postProcessing_directory = 'stops_2017_nano_v0p23/dilep/'\n data_2017_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2017_postProcessing_directory = 'stops_2017_nano_v0p19/dilep/'\n mc_2018_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2018_postProcessing_directory = 'stops_2018_nano_v0p23/dilep/'\n data_2018_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2018_postProcessing_directory = 'stops_2018_nano_v0p19/dilep/'\n\n\n<mask token>\n",
"step-3": "class default_locations:\n mc_2016_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2016_postProcessing_directory = 'stops_2016_nano_v0p23/dilep/'\n data_2016_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2016_postProcessing_directory = 'stops_2016_nano_v0p19/dilep/'\n mc_2017_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2017_postProcessing_directory = 'stops_2017_nano_v0p23/dilep/'\n data_2017_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2017_postProcessing_directory = 'stops_2017_nano_v0p19/dilep/'\n mc_2018_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2018_postProcessing_directory = 'stops_2018_nano_v0p23/dilep/'\n data_2018_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2018_postProcessing_directory = 'stops_2018_nano_v0p19/dilep/'\n\n\n<mask token>\nif os.environ['HOSTNAME'].startswith('clip'):\n default_locations.mc_2016_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.data_2016_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.mc_2017_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.data_2017_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.mc_2018_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.data_2018_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n",
"step-4": "class default_locations:\n mc_2016_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2016_postProcessing_directory = 'stops_2016_nano_v0p23/dilep/'\n data_2016_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2016_postProcessing_directory = 'stops_2016_nano_v0p19/dilep/'\n mc_2017_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2017_postProcessing_directory = 'stops_2017_nano_v0p23/dilep/'\n data_2017_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2017_postProcessing_directory = 'stops_2017_nano_v0p19/dilep/'\n mc_2018_data_directory = '/afs/hephy.at/data/cms06/nanoTuples/'\n mc_2018_postProcessing_directory = 'stops_2018_nano_v0p23/dilep/'\n data_2018_data_directory = '/afs/hephy.at/data/cms07/nanoTuples/'\n data_2018_postProcessing_directory = 'stops_2018_nano_v0p19/dilep/'\n\n\nimport os\nif os.environ['HOSTNAME'].startswith('clip'):\n default_locations.mc_2016_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.data_2016_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.mc_2017_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.data_2017_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.mc_2018_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n default_locations.data_2018_data_directory = (\n '/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/')\n",
"step-5": "class default_locations:\n mc_2016_data_directory = \"/afs/hephy.at/data/cms06/nanoTuples/\" \n mc_2016_postProcessing_directory = \"stops_2016_nano_v0p23/dilep/\" \n data_2016_data_directory = \"/afs/hephy.at/data/cms07/nanoTuples/\" \n data_2016_postProcessing_directory = \"stops_2016_nano_v0p19/dilep/\" \n \n mc_2017_data_directory = \"/afs/hephy.at/data/cms06/nanoTuples/\" \n mc_2017_postProcessing_directory = \"stops_2017_nano_v0p23/dilep/\" \n data_2017_data_directory = \"/afs/hephy.at/data/cms07/nanoTuples/\" \n data_2017_postProcessing_directory = \"stops_2017_nano_v0p19/dilep/\" \n \n mc_2018_data_directory = \"/afs/hephy.at/data/cms06/nanoTuples/\" \n mc_2018_postProcessing_directory = \"stops_2018_nano_v0p23/dilep/\" \n data_2018_data_directory = \"/afs/hephy.at/data/cms07/nanoTuples/\" \n data_2018_postProcessing_directory = \"stops_2018_nano_v0p19/dilep/\"\n\nimport os\nif os.environ['HOSTNAME'].startswith('clip'):\n default_locations.mc_2016_data_directory = \"/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/\"\n default_locations.data_2016_data_directory = \"/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/\"\n default_locations.mc_2017_data_directory = \"/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/\"\n default_locations.data_2017_data_directory = \"/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/\"\n default_locations.mc_2018_data_directory = \"/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/\"\n default_locations.data_2018_data_directory = \"/mnt/hephy/cms/robert.schoefbeck/StopsDileptonLegacy/nanoTuples/\"\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
# Generated by Django 3.2 on 2021-05-03 17:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0005_alter_orderitem_price'),
]
operations = [
migrations.AddField(
model_name='order',
name='being_delivered',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='order',
name='payment_id',
field=models.CharField(blank=True, max_length=150),
),
migrations.AddField(
model_name='order',
name='ref_code',
field=models.CharField(blank=True, max_length=20, null=True),
),
]
|
normal
|
{
"blob_id": "f3b466dc5b6149be82b096791ca8445faf169380",
"index": 5216,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('orders', '0005_alter_orderitem_price')]\n operations = [migrations.AddField(model_name='order', name=\n 'being_delivered', field=models.BooleanField(default=False)),\n migrations.AddField(model_name='order', name='payment_id', field=\n models.CharField(blank=True, max_length=150)), migrations.AddField(\n model_name='order', name='ref_code', field=models.CharField(blank=\n True, max_length=20, null=True))]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('orders', '0005_alter_orderitem_price')]\n operations = [migrations.AddField(model_name='order', name=\n 'being_delivered', field=models.BooleanField(default=False)),\n migrations.AddField(model_name='order', name='payment_id', field=\n models.CharField(blank=True, max_length=150)), migrations.AddField(\n model_name='order', name='ref_code', field=models.CharField(blank=\n True, max_length=20, null=True))]\n",
"step-5": "# Generated by Django 3.2 on 2021-05-03 17:13\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0005_alter_orderitem_price'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='order',\n name='being_delivered',\n field=models.BooleanField(default=False),\n ),\n migrations.AddField(\n model_name='order',\n name='payment_id',\n field=models.CharField(blank=True, max_length=150),\n ),\n migrations.AddField(\n model_name='order',\n name='ref_code',\n field=models.CharField(blank=True, max_length=20, null=True),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def sortarray(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def sortarray(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
print(sortarray([1, 5, 2, 3]))
<|reserved_special_token_1|>
"""
Given a random set of numbers, Print them in sorted order.
Example 1:
Input:
N = 4
arr[] = {1, 5, 3, 2}
Output: {1, 2, 3, 5}
Explanation: After sorting array will
be like {1, 2, 3, 5}.
"""
#complexity--> n*log n
def sortarray(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while(j>=0 and arr[j]>key):
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
return arr
print(sortarray([1,5,2,3]))
|
flexible
|
{
"blob_id": "70cef88f3fe93d370e5d21a2b00b761ce530a099",
"index": 6366,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef sortarray(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and arr[j] > key:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key\n return arr\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef sortarray(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and arr[j] > key:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key\n return arr\n\n\nprint(sortarray([1, 5, 2, 3]))\n",
"step-4": "\"\"\"\nGiven a random set of numbers, Print them in sorted order.\n\nExample 1:\n\nInput:\nN = 4\narr[] = {1, 5, 3, 2}\nOutput: {1, 2, 3, 5}\nExplanation: After sorting array will \nbe like {1, 2, 3, 5}.\n\"\"\"\n#complexity--> n*log n\ndef sortarray(arr):\n for i in range(1,len(arr)):\n key=arr[i]\n j=i-1\n while(j>=0 and arr[j]>key):\n arr[j+1]=arr[j]\n j-=1\n arr[j+1]=key\n return arr\n\nprint(sortarray([1,5,2,3]))",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import pytest
from ansiblediscover.graph.node import Node
def test_build_identifier():
assert 'role:server_base' == Node.build_identifier('server_base', 'role')
def test_identifier():
node = Node('server_base', 'role', 'irrelevant')
assert 'role:server_base' == node.identifier()
def test_add_successor():
parent = Node('appserver', 'playbook', 'appserver.yml')
child = Node('server_base', 'role', 'roles/server_base')
parent.add_successor(child)
assert child in parent.successors
assert parent in child.predecessors
def test_add_predecessor():
parent = Node('appserver', 'playbook', 'appserver.yml')
child = Node('server_base', 'role', 'roles/server_base')
child.add_predecessor(parent)
assert child in parent.successors
assert parent in child.predecessors
def test_str():
name = 'myname'
typestring = 'mytype'
path = 'mypath'
node = Node(name, typestring, path)
assert str((typestring, name, path)) == str(node)
@pytest.mark.parametrize('this, other, equal', [
(('myname', 'mytype', 'mypath'), ('myname', 'mytype', 'mypath'), True),
(('myname', 'mytype', 'mypath'), ('othername', 'mytype', 'mypath'), False),
(('myname', 'mytype', 'mypath'), ('myname', 'othertype', 'mypath'), False),
(('myname', 'mytype', 'mypath'), ('myname', 'othertype', 'otherpath'), False),
])
def test_eq(this, other, equal):
this_node = Node(*this)
other_node = Node(*other)
assert (equal and (this_node == other_node)) or (not equal and (this_node != other_node))
@pytest.mark.parametrize('other', [
None,
[],
('myname', 'mytype', 'mypath'),
])
def test_eq_unequal_types(other):
this = Node('myname', 'mytype', 'mypath')
assert this != other
|
normal
|
{
"blob_id": "8e22db940124f92d3048055cf72dcaa79564cdc6",
"index": 1953,
"step-1": "<mask token>\n\n\ndef test_build_identifier():\n assert 'role:server_base' == Node.build_identifier('server_base', 'role')\n\n\ndef test_identifier():\n node = Node('server_base', 'role', 'irrelevant')\n assert 'role:server_base' == node.identifier()\n\n\ndef test_add_successor():\n parent = Node('appserver', 'playbook', 'appserver.yml')\n child = Node('server_base', 'role', 'roles/server_base')\n parent.add_successor(child)\n assert child in parent.successors\n assert parent in child.predecessors\n\n\n<mask token>\n\n\n@pytest.mark.parametrize('this, other, equal', [(('myname', 'mytype',\n 'mypath'), ('myname', 'mytype', 'mypath'), True), (('myname', 'mytype',\n 'mypath'), ('othername', 'mytype', 'mypath'), False), (('myname',\n 'mytype', 'mypath'), ('myname', 'othertype', 'mypath'), False), ((\n 'myname', 'mytype', 'mypath'), ('myname', 'othertype', 'otherpath'), \n False)])\ndef test_eq(this, other, equal):\n this_node = Node(*this)\n other_node = Node(*other)\n assert equal and this_node == other_node or not equal and this_node != other_node\n\n\n@pytest.mark.parametrize('other', [None, [], ('myname', 'mytype', 'mypath')])\ndef test_eq_unequal_types(other):\n this = Node('myname', 'mytype', 'mypath')\n assert this != other\n",
"step-2": "<mask token>\n\n\ndef test_build_identifier():\n assert 'role:server_base' == Node.build_identifier('server_base', 'role')\n\n\ndef test_identifier():\n node = Node('server_base', 'role', 'irrelevant')\n assert 'role:server_base' == node.identifier()\n\n\ndef test_add_successor():\n parent = Node('appserver', 'playbook', 'appserver.yml')\n child = Node('server_base', 'role', 'roles/server_base')\n parent.add_successor(child)\n assert child in parent.successors\n assert parent in child.predecessors\n\n\n<mask token>\n\n\ndef test_str():\n name = 'myname'\n typestring = 'mytype'\n path = 'mypath'\n node = Node(name, typestring, path)\n assert str((typestring, name, path)) == str(node)\n\n\n@pytest.mark.parametrize('this, other, equal', [(('myname', 'mytype',\n 'mypath'), ('myname', 'mytype', 'mypath'), True), (('myname', 'mytype',\n 'mypath'), ('othername', 'mytype', 'mypath'), False), (('myname',\n 'mytype', 'mypath'), ('myname', 'othertype', 'mypath'), False), ((\n 'myname', 'mytype', 'mypath'), ('myname', 'othertype', 'otherpath'), \n False)])\ndef test_eq(this, other, equal):\n this_node = Node(*this)\n other_node = Node(*other)\n assert equal and this_node == other_node or not equal and this_node != other_node\n\n\n@pytest.mark.parametrize('other', [None, [], ('myname', 'mytype', 'mypath')])\ndef test_eq_unequal_types(other):\n this = Node('myname', 'mytype', 'mypath')\n assert this != other\n",
"step-3": "<mask token>\n\n\ndef test_build_identifier():\n assert 'role:server_base' == Node.build_identifier('server_base', 'role')\n\n\ndef test_identifier():\n node = Node('server_base', 'role', 'irrelevant')\n assert 'role:server_base' == node.identifier()\n\n\ndef test_add_successor():\n parent = Node('appserver', 'playbook', 'appserver.yml')\n child = Node('server_base', 'role', 'roles/server_base')\n parent.add_successor(child)\n assert child in parent.successors\n assert parent in child.predecessors\n\n\ndef test_add_predecessor():\n parent = Node('appserver', 'playbook', 'appserver.yml')\n child = Node('server_base', 'role', 'roles/server_base')\n child.add_predecessor(parent)\n assert child in parent.successors\n assert parent in child.predecessors\n\n\ndef test_str():\n name = 'myname'\n typestring = 'mytype'\n path = 'mypath'\n node = Node(name, typestring, path)\n assert str((typestring, name, path)) == str(node)\n\n\n@pytest.mark.parametrize('this, other, equal', [(('myname', 'mytype',\n 'mypath'), ('myname', 'mytype', 'mypath'), True), (('myname', 'mytype',\n 'mypath'), ('othername', 'mytype', 'mypath'), False), (('myname',\n 'mytype', 'mypath'), ('myname', 'othertype', 'mypath'), False), ((\n 'myname', 'mytype', 'mypath'), ('myname', 'othertype', 'otherpath'), \n False)])\ndef test_eq(this, other, equal):\n this_node = Node(*this)\n other_node = Node(*other)\n assert equal and this_node == other_node or not equal and this_node != other_node\n\n\n@pytest.mark.parametrize('other', [None, [], ('myname', 'mytype', 'mypath')])\ndef test_eq_unequal_types(other):\n this = Node('myname', 'mytype', 'mypath')\n assert this != other\n",
"step-4": "import pytest\nfrom ansiblediscover.graph.node import Node\n\n\ndef test_build_identifier():\n assert 'role:server_base' == Node.build_identifier('server_base', 'role')\n\n\ndef test_identifier():\n node = Node('server_base', 'role', 'irrelevant')\n assert 'role:server_base' == node.identifier()\n\n\ndef test_add_successor():\n parent = Node('appserver', 'playbook', 'appserver.yml')\n child = Node('server_base', 'role', 'roles/server_base')\n parent.add_successor(child)\n assert child in parent.successors\n assert parent in child.predecessors\n\n\ndef test_add_predecessor():\n parent = Node('appserver', 'playbook', 'appserver.yml')\n child = Node('server_base', 'role', 'roles/server_base')\n child.add_predecessor(parent)\n assert child in parent.successors\n assert parent in child.predecessors\n\n\ndef test_str():\n name = 'myname'\n typestring = 'mytype'\n path = 'mypath'\n node = Node(name, typestring, path)\n assert str((typestring, name, path)) == str(node)\n\n\n@pytest.mark.parametrize('this, other, equal', [(('myname', 'mytype',\n 'mypath'), ('myname', 'mytype', 'mypath'), True), (('myname', 'mytype',\n 'mypath'), ('othername', 'mytype', 'mypath'), False), (('myname',\n 'mytype', 'mypath'), ('myname', 'othertype', 'mypath'), False), ((\n 'myname', 'mytype', 'mypath'), ('myname', 'othertype', 'otherpath'), \n False)])\ndef test_eq(this, other, equal):\n this_node = Node(*this)\n other_node = Node(*other)\n assert equal and this_node == other_node or not equal and this_node != other_node\n\n\n@pytest.mark.parametrize('other', [None, [], ('myname', 'mytype', 'mypath')])\ndef test_eq_unequal_types(other):\n this = Node('myname', 'mytype', 'mypath')\n assert this != other\n",
"step-5": "import pytest\n\nfrom ansiblediscover.graph.node import Node\n\n\ndef test_build_identifier():\n assert 'role:server_base' == Node.build_identifier('server_base', 'role')\n\n\ndef test_identifier():\n node = Node('server_base', 'role', 'irrelevant')\n assert 'role:server_base' == node.identifier()\n\n\ndef test_add_successor():\n parent = Node('appserver', 'playbook', 'appserver.yml')\n child = Node('server_base', 'role', 'roles/server_base')\n\n parent.add_successor(child)\n\n assert child in parent.successors\n assert parent in child.predecessors\n\n\ndef test_add_predecessor():\n parent = Node('appserver', 'playbook', 'appserver.yml')\n child = Node('server_base', 'role', 'roles/server_base')\n\n child.add_predecessor(parent)\n\n assert child in parent.successors\n assert parent in child.predecessors\n\n\ndef test_str():\n name = 'myname'\n typestring = 'mytype'\n path = 'mypath'\n node = Node(name, typestring, path)\n\n assert str((typestring, name, path)) == str(node)\n\n\n@pytest.mark.parametrize('this, other, equal', [\n (('myname', 'mytype', 'mypath'), ('myname', 'mytype', 'mypath'), True),\n (('myname', 'mytype', 'mypath'), ('othername', 'mytype', 'mypath'), False),\n (('myname', 'mytype', 'mypath'), ('myname', 'othertype', 'mypath'), False),\n (('myname', 'mytype', 'mypath'), ('myname', 'othertype', 'otherpath'), False),\n])\ndef test_eq(this, other, equal):\n this_node = Node(*this)\n other_node = Node(*other)\n\n assert (equal and (this_node == other_node)) or (not equal and (this_node != other_node))\n\n\n@pytest.mark.parametrize('other', [\n None,\n [],\n ('myname', 'mytype', 'mypath'),\n])\ndef test_eq_unequal_types(other):\n this = Node('myname', 'mytype', 'mypath')\n assert this != other\n",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, masonarmani38@gmail.com and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class LogisticsPlanningTool(Document):
def autoname(self):
if self.customer:
self.name = "{0}-{1}-{2}".format(self.customer, self.territory, self.schedule_delivery_date)
else:
self.name = "{0}-{1}".format(self.territory, self.schedule_delivery_date)
@frappe.whitelist(True)
def get_atls(ps, pe, territory=None, customer=None, include_pending=None):
conds = ""
if territory and str(territory) != str("Nigeria"):
conds += ' AND territory = "%s" ' % territory
if customer:
conds += ' AND customer = "%s" ' % customer
if not include_pending:
conds += " AND delivery_date BETWEEN DATE('%s') AND DATE('%s') " % (ps, pe)
return frappe.db.sql(
"SELECT name as authority_to_load, IFNULL(delivery_date, transaction_date) as delivery_date , customer, territory from `tabAuthority to Load` WHERE name NOT IN (SELECT l.name FROM `tabLogistics Planning Tool` l INNER JOIN `tabLogistics Planning Tool Detail` c ON(l.name=c.parent) WHERE c.status != 'Delivered') %s ORDER BY territory " % (
conds), as_dict=1)
|
normal
|
{
"blob_id": "4cbb78234ef6e63b856099060ecaeea1779d6ac5",
"index": 8412,
"step-1": "<mask token>\n\n\nclass LogisticsPlanningTool(Document):\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass LogisticsPlanningTool(Document):\n\n def autoname(self):\n if self.customer:\n self.name = '{0}-{1}-{2}'.format(self.customer, self.territory,\n self.schedule_delivery_date)\n else:\n self.name = '{0}-{1}'.format(self.territory, self.\n schedule_delivery_date)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass LogisticsPlanningTool(Document):\n\n def autoname(self):\n if self.customer:\n self.name = '{0}-{1}-{2}'.format(self.customer, self.territory,\n self.schedule_delivery_date)\n else:\n self.name = '{0}-{1}'.format(self.territory, self.\n schedule_delivery_date)\n\n\n@frappe.whitelist(True)\ndef get_atls(ps, pe, territory=None, customer=None, include_pending=None):\n conds = ''\n if territory and str(territory) != str('Nigeria'):\n conds += ' AND territory = \"%s\" ' % territory\n if customer:\n conds += ' AND customer = \"%s\" ' % customer\n if not include_pending:\n conds += \" AND delivery_date BETWEEN DATE('%s') AND DATE('%s') \" % (ps,\n pe)\n return frappe.db.sql(\n \"SELECT name as authority_to_load, IFNULL(delivery_date, transaction_date) as delivery_date , customer, territory from `tabAuthority to Load` WHERE name NOT IN (SELECT l.name FROM `tabLogistics Planning Tool` l INNER JOIN `tabLogistics Planning Tool Detail` c ON(l.name=c.parent) WHERE c.status != 'Delivered') %s ORDER BY territory \"\n % conds, as_dict=1)\n",
"step-4": "from __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\n\nclass LogisticsPlanningTool(Document):\n\n def autoname(self):\n if self.customer:\n self.name = '{0}-{1}-{2}'.format(self.customer, self.territory,\n self.schedule_delivery_date)\n else:\n self.name = '{0}-{1}'.format(self.territory, self.\n schedule_delivery_date)\n\n\n@frappe.whitelist(True)\ndef get_atls(ps, pe, territory=None, customer=None, include_pending=None):\n conds = ''\n if territory and str(territory) != str('Nigeria'):\n conds += ' AND territory = \"%s\" ' % territory\n if customer:\n conds += ' AND customer = \"%s\" ' % customer\n if not include_pending:\n conds += \" AND delivery_date BETWEEN DATE('%s') AND DATE('%s') \" % (ps,\n pe)\n return frappe.db.sql(\n \"SELECT name as authority_to_load, IFNULL(delivery_date, transaction_date) as delivery_date , customer, territory from `tabAuthority to Load` WHERE name NOT IN (SELECT l.name FROM `tabLogistics Planning Tool` l INNER JOIN `tabLogistics Planning Tool Detail` c ON(l.name=c.parent) WHERE c.status != 'Delivered') %s ORDER BY territory \"\n % conds, as_dict=1)\n",
"step-5": "# -*- coding: utf-8 -*-\n# Copyright (c) 2018, masonarmani38@gmail.com and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\n\nclass LogisticsPlanningTool(Document):\n def autoname(self):\n if self.customer:\n self.name = \"{0}-{1}-{2}\".format(self.customer, self.territory, self.schedule_delivery_date)\n else:\n self.name = \"{0}-{1}\".format(self.territory, self.schedule_delivery_date)\n\n\n@frappe.whitelist(True)\ndef get_atls(ps, pe, territory=None, customer=None, include_pending=None):\n conds = \"\"\n\n if territory and str(territory) != str(\"Nigeria\"):\n conds += ' AND territory = \"%s\" ' % territory\n if customer:\n conds += ' AND customer = \"%s\" ' % customer\n\n if not include_pending:\n conds += \" AND delivery_date BETWEEN DATE('%s') AND DATE('%s') \" % (ps, pe)\n\n return frappe.db.sql(\n \"SELECT name as authority_to_load, IFNULL(delivery_date, transaction_date) as delivery_date , customer, territory from `tabAuthority to Load` WHERE name NOT IN (SELECT l.name FROM `tabLogistics Planning Tool` l INNER JOIN `tabLogistics Planning Tool Detail` c ON(l.name=c.parent) WHERE c.status != 'Delivered') %s ORDER BY territory \" % (\n conds), as_dict=1)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
def init_process(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
os.makedirs(os.path.join(auto_dir, 'gaussian'), exist_ok=True)
os.makedirs(os.path.join(auto_dir, 'gaussview'), exist_ok=True)
def get_init_para_csv(auto_dir, monomer_name):
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df = pd.read_csv(
'/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'
.format(monomer_name))
df = df[(df['A2'] == 32) & (df['A1'] <= 0) & (df['A1'] >= -20) & (
df['theta'] > 45)]
inner_zip = df[['a', 'b', 'theta', 'A1', 'A2']].values
print(inner_zip)
init_para_list = []
for a, b, theta, A1, A2 in tqdm(inner_zip):
c = get_c_vec_vdw(monomer_name, A1, A2, a, b, theta)
init_para_list.append([np.round(a, 1), np.round(b, 1), theta,
A1, A2, np.round(c[0], 1), np.round(c[1], 1), np.round(c[2],
1), 'NotYet'])
df_init_params = pd.DataFrame(np.array(init_para_list), columns=[
'a', 'b', 'theta', 'A1', 'A2', 'cx', 'cy', 'cz', 'status'])
df_init_params.to_csv(init_params_csv, index=False)
get_init_para_csv(auto_dir, monomer_name)
auto_csv_path = os.path.join(auto_dir, 'step3-twist.csv')
if not os.path.exists(auto_csv_path):
df_E = pd.DataFrame(columns=['a', 'b', 'theta', 'A1', 'A2', 'cx',
'cy', 'cz', 'E', 'E_p', 'E_t', 'machine_type', 'status',
'file_name'])
else:
df_E = pd.read_csv(auto_csv_path)
df_E = df_E[df_E['status'] != 'InProgress']
df_E.to_csv(auto_csv_path, index=False)
df_init = pd.read_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv')
)
df_init['status'] = 'NotYet'
df_init.to_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv'),
index=False)
def main_process(args):
os.chdir(os.path.join(args.auto_dir, 'gaussian'))
isOver = False
while not isOver:
isOver = listen(args)
time.sleep(1)
<|reserved_special_token_0|>
def update_value_in_df(df, index, key, value):
df.loc[index, key] = value
return df
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def init_process(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
os.makedirs(os.path.join(auto_dir, 'gaussian'), exist_ok=True)
os.makedirs(os.path.join(auto_dir, 'gaussview'), exist_ok=True)
def get_init_para_csv(auto_dir, monomer_name):
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df = pd.read_csv(
'/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'
.format(monomer_name))
df = df[(df['A2'] == 32) & (df['A1'] <= 0) & (df['A1'] >= -20) & (
df['theta'] > 45)]
inner_zip = df[['a', 'b', 'theta', 'A1', 'A2']].values
print(inner_zip)
init_para_list = []
for a, b, theta, A1, A2 in tqdm(inner_zip):
c = get_c_vec_vdw(monomer_name, A1, A2, a, b, theta)
init_para_list.append([np.round(a, 1), np.round(b, 1), theta,
A1, A2, np.round(c[0], 1), np.round(c[1], 1), np.round(c[2],
1), 'NotYet'])
df_init_params = pd.DataFrame(np.array(init_para_list), columns=[
'a', 'b', 'theta', 'A1', 'A2', 'cx', 'cy', 'cz', 'status'])
df_init_params.to_csv(init_params_csv, index=False)
get_init_para_csv(auto_dir, monomer_name)
auto_csv_path = os.path.join(auto_dir, 'step3-twist.csv')
if not os.path.exists(auto_csv_path):
df_E = pd.DataFrame(columns=['a', 'b', 'theta', 'A1', 'A2', 'cx',
'cy', 'cz', 'E', 'E_p', 'E_t', 'machine_type', 'status',
'file_name'])
else:
df_E = pd.read_csv(auto_csv_path)
df_E = df_E[df_E['status'] != 'InProgress']
df_E.to_csv(auto_csv_path, index=False)
df_init = pd.read_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv')
)
df_init['status'] = 'NotYet'
df_init.to_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv'),
index=False)
def main_process(args):
os.chdir(os.path.join(args.auto_dir, 'gaussian'))
isOver = False
while not isOver:
isOver = listen(args)
time.sleep(1)
def listen(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
num_nodes = args.num_nodes
isTest = args.isTest
fixed_param_keys = ['A1', 'A2']
opt_param_keys = ['a', 'b', 'theta', 'cx', 'cy', 'cz']
auto_step2_csv = (
'/home/koyama/Working/interaction/{}/step2-twist/step2-twist.csv'.
format(monomer_name))
df_step2 = pd.read_csv(auto_step2_csv)
auto_csv = os.path.join(auto_dir, 'step3-twist.csv')
df_E = pd.read_csv(auto_csv)
df_queue = df_E.loc[df_E['status'] == 'InProgress', ['machine_type',
'file_name', 'A1', 'A2', 'a', 'b', 'theta', 'cx', 'cy', 'cz']]
machine_type_list = df_queue['machine_type'].values.tolist()
len_queue = len(df_queue)
maxnum_machine2 = 3
for idx, row in zip(df_queue.index, df_queue.values):
machine_type, file_name, A1, A2, a, b, theta, cx, cy, cz = row
log_filepath = os.path.join(*[auto_dir, 'gaussian', file_name])
if not os.path.exists(log_filepath):
continue
E_list = get_E(log_filepath)
if len(E_list) != 5:
continue
else:
len_queue -= 1
machine_type_list.remove(machine_type)
Ei0, Eip1, Eip2, Eit1, Eit2 = map(float, E_list)
Eit3 = Eit2
Eit4 = Eit1
try:
Ep, Et = df_step2[(df_step2['A1'] == A1) & (df_step2['A2'] ==
A2) & (df_step2['theta'] == theta) & (df_step2['a'] ==
a) & (df_step2['b'] == b)][['E_p', 'E_t']].values[0]
except IndexError:
inner_params_dict = {'A1': A1, 'A2': A2, 'a': a, 'b': b,
'theta': theta, 'cx': 0, 'cy': 0, 'cz': 0}
inner_file_name = exec_gjf(auto_dir, monomer_name,
inner_params_dict, machine_type, isInterlayer=False,
isTest=isTest)
time.sleep(200)
is_inner_over = False
while not is_inner_over:
time.sleep(30)
E_inner_list = get_E(inner_file_name)
is_inner_over = len(E_inner_list) == 2
Ep, Et = map(float, E_inner_list)
df_newline = pd.Series({**inner_params_dict, 'E': 2 * Ep +
4 * Et, 'E_p': Ep, 'E_t': Et, 'machine_type':
machine_type, 'status': 'Done', 'file_name':
inner_file_name})
df_step2 = df_step2.append(df_newline, ignore_index=True)
df_step2.to_csv(auto_step2_csv, index=False)
E = 4 * Et + 2 * Ep + 2 * (Ei0 + Eip1 + Eip2 + Eit1 + Eit2 +
Eit3 + Eit4)
df_E.loc[idx, ['E_p', 'E_t', 'E_i0', 'E_ip1', 'E_ip2', 'E_it1',
'E_it2', 'E_it3', 'E_it4', 'E', 'status']] = [Ep, Et, Ei0,
Eip1, Eip2, Eit1, Eit2, Eit3, Eit4, E, 'Done']
df_E.to_csv(auto_csv, index=False)
break
isAvailable = len_queue < num_nodes
machine2IsFull = machine_type_list.count(2) >= maxnum_machine2
machine_type = 1 if machine2IsFull else 2
if isAvailable:
params_dict = get_params_dict(auto_dir, num_nodes, fixed_param_keys,
opt_param_keys, monomer_name)
if len(params_dict) != 0:
alreadyCalculated = check_calc_status(auto_dir, params_dict)
if not alreadyCalculated:
file_name = exec_gjf(auto_dir, monomer_name, {**params_dict
}, machine_type, isInterlayer=True, isTest=isTest)
df_newline = pd.Series({**params_dict, 'E': 0.0, 'E_p': 0.0,
'E_t': 0.0, 'E_i0': 0.0, 'E_ip1': 0.0, 'E_ip2': 0.0,
'E_it1': 0.0, 'E_it2': 0.0, 'E_it3': 0.0, 'E_it4': 0.0,
'machine_type': machine_type, 'status': 'InProgress',
'file_name': file_name})
df_E = df_E.append(df_newline, ignore_index=True)
df_E.to_csv(auto_csv, index=False)
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_init_params_done = filter_df(df_init_params, {'status': 'Done'})
isOver = True if len(df_init_params_done) == len(df_init_params) else False
return isOver
def check_calc_status(auto_dir, params_dict):
df_E = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
if len(df_E) == 0:
return False
df_E_filtered = filter_df(df_E, params_dict)
df_E_filtered = df_E_filtered.reset_index(drop=True)
try:
status = get_values_from_df(df_E_filtered, 0, 'status')
return status == 'Done'
except KeyError:
return False
def get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys,
monomer_name):
"""
前提:
step3-twist_init_params.csvとstep3-twist.csvがauto_dirの下にある
"""
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
df_init_params_inprogress = df_init_params[df_init_params['status'] ==
'InProgress']
if len(df_init_params_inprogress) < num_nodes:
df_init_params_notyet = df_init_params[df_init_params['status'] ==
'NotYet']
for index in df_init_params_notyet.index:
df_init_params = update_value_in_df(df_init_params, index,
'status', 'InProgress')
df_init_params.to_csv(init_params_csv, index=False)
params_dict = df_init_params.loc[index, fixed_param_keys +
opt_param_keys].to_dict()
return params_dict
for index in df_init_params.index:
df_init_params = pd.read_csv(init_params_csv)
init_params_dict = df_init_params.loc[index, fixed_param_keys +
opt_param_keys].to_dict()
fixed_params_dict = df_init_params.loc[index, fixed_param_keys
].to_dict()
isDone, opt_params_dict = get_opt_params_dict(df_cur,
init_params_dict, fixed_params_dict, monomer_name)
if isDone:
df_init_params = update_value_in_df(df_init_params, index,
'status', 'Done')
if np.max(df_init_params.index) < index + 1:
status = 'Done'
else:
status = get_values_from_df(df_init_params, index + 1, 'status'
)
df_init_params.to_csv(init_params_csv, index=False)
if status == 'NotYet':
opt_params_dict = get_values_from_df(df_init_params, index +
1, opt_param_keys)
df_init_params = update_value_in_df(df_init_params, index +
1, 'status', 'InProgress')
df_init_params.to_csv(init_params_csv, index=False)
return {**fixed_params_dict, **opt_params_dict}
else:
continue
else:
df_inprogress = filter_df(df_cur, {**fixed_params_dict, **
opt_params_dict, 'status': 'InProgress'})
if len(df_inprogress) >= 1:
continue
return {**fixed_params_dict, **opt_params_dict}
return {}
<|reserved_special_token_0|>
def get_values_from_df(df, index, key):
return df.loc[index, key]
def update_value_in_df(df, index, key, value):
df.loc[index, key] = value
return df
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def init_process(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
os.makedirs(os.path.join(auto_dir, 'gaussian'), exist_ok=True)
os.makedirs(os.path.join(auto_dir, 'gaussview'), exist_ok=True)
def get_init_para_csv(auto_dir, monomer_name):
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df = pd.read_csv(
'/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'
.format(monomer_name))
df = df[(df['A2'] == 32) & (df['A1'] <= 0) & (df['A1'] >= -20) & (
df['theta'] > 45)]
inner_zip = df[['a', 'b', 'theta', 'A1', 'A2']].values
print(inner_zip)
init_para_list = []
for a, b, theta, A1, A2 in tqdm(inner_zip):
c = get_c_vec_vdw(monomer_name, A1, A2, a, b, theta)
init_para_list.append([np.round(a, 1), np.round(b, 1), theta,
A1, A2, np.round(c[0], 1), np.round(c[1], 1), np.round(c[2],
1), 'NotYet'])
df_init_params = pd.DataFrame(np.array(init_para_list), columns=[
'a', 'b', 'theta', 'A1', 'A2', 'cx', 'cy', 'cz', 'status'])
df_init_params.to_csv(init_params_csv, index=False)
get_init_para_csv(auto_dir, monomer_name)
auto_csv_path = os.path.join(auto_dir, 'step3-twist.csv')
if not os.path.exists(auto_csv_path):
df_E = pd.DataFrame(columns=['a', 'b', 'theta', 'A1', 'A2', 'cx',
'cy', 'cz', 'E', 'E_p', 'E_t', 'machine_type', 'status',
'file_name'])
else:
df_E = pd.read_csv(auto_csv_path)
df_E = df_E[df_E['status'] != 'InProgress']
df_E.to_csv(auto_csv_path, index=False)
df_init = pd.read_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv')
)
df_init['status'] = 'NotYet'
df_init.to_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv'),
index=False)
def main_process(args):
os.chdir(os.path.join(args.auto_dir, 'gaussian'))
isOver = False
while not isOver:
isOver = listen(args)
time.sleep(1)
def listen(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
num_nodes = args.num_nodes
isTest = args.isTest
fixed_param_keys = ['A1', 'A2']
opt_param_keys = ['a', 'b', 'theta', 'cx', 'cy', 'cz']
auto_step2_csv = (
'/home/koyama/Working/interaction/{}/step2-twist/step2-twist.csv'.
format(monomer_name))
df_step2 = pd.read_csv(auto_step2_csv)
auto_csv = os.path.join(auto_dir, 'step3-twist.csv')
df_E = pd.read_csv(auto_csv)
df_queue = df_E.loc[df_E['status'] == 'InProgress', ['machine_type',
'file_name', 'A1', 'A2', 'a', 'b', 'theta', 'cx', 'cy', 'cz']]
machine_type_list = df_queue['machine_type'].values.tolist()
len_queue = len(df_queue)
maxnum_machine2 = 3
for idx, row in zip(df_queue.index, df_queue.values):
machine_type, file_name, A1, A2, a, b, theta, cx, cy, cz = row
log_filepath = os.path.join(*[auto_dir, 'gaussian', file_name])
if not os.path.exists(log_filepath):
continue
E_list = get_E(log_filepath)
if len(E_list) != 5:
continue
else:
len_queue -= 1
machine_type_list.remove(machine_type)
Ei0, Eip1, Eip2, Eit1, Eit2 = map(float, E_list)
Eit3 = Eit2
Eit4 = Eit1
try:
Ep, Et = df_step2[(df_step2['A1'] == A1) & (df_step2['A2'] ==
A2) & (df_step2['theta'] == theta) & (df_step2['a'] ==
a) & (df_step2['b'] == b)][['E_p', 'E_t']].values[0]
except IndexError:
inner_params_dict = {'A1': A1, 'A2': A2, 'a': a, 'b': b,
'theta': theta, 'cx': 0, 'cy': 0, 'cz': 0}
inner_file_name = exec_gjf(auto_dir, monomer_name,
inner_params_dict, machine_type, isInterlayer=False,
isTest=isTest)
time.sleep(200)
is_inner_over = False
while not is_inner_over:
time.sleep(30)
E_inner_list = get_E(inner_file_name)
is_inner_over = len(E_inner_list) == 2
Ep, Et = map(float, E_inner_list)
df_newline = pd.Series({**inner_params_dict, 'E': 2 * Ep +
4 * Et, 'E_p': Ep, 'E_t': Et, 'machine_type':
machine_type, 'status': 'Done', 'file_name':
inner_file_name})
df_step2 = df_step2.append(df_newline, ignore_index=True)
df_step2.to_csv(auto_step2_csv, index=False)
E = 4 * Et + 2 * Ep + 2 * (Ei0 + Eip1 + Eip2 + Eit1 + Eit2 +
Eit3 + Eit4)
df_E.loc[idx, ['E_p', 'E_t', 'E_i0', 'E_ip1', 'E_ip2', 'E_it1',
'E_it2', 'E_it3', 'E_it4', 'E', 'status']] = [Ep, Et, Ei0,
Eip1, Eip2, Eit1, Eit2, Eit3, Eit4, E, 'Done']
df_E.to_csv(auto_csv, index=False)
break
isAvailable = len_queue < num_nodes
machine2IsFull = machine_type_list.count(2) >= maxnum_machine2
machine_type = 1 if machine2IsFull else 2
if isAvailable:
params_dict = get_params_dict(auto_dir, num_nodes, fixed_param_keys,
opt_param_keys, monomer_name)
if len(params_dict) != 0:
alreadyCalculated = check_calc_status(auto_dir, params_dict)
if not alreadyCalculated:
file_name = exec_gjf(auto_dir, monomer_name, {**params_dict
}, machine_type, isInterlayer=True, isTest=isTest)
df_newline = pd.Series({**params_dict, 'E': 0.0, 'E_p': 0.0,
'E_t': 0.0, 'E_i0': 0.0, 'E_ip1': 0.0, 'E_ip2': 0.0,
'E_it1': 0.0, 'E_it2': 0.0, 'E_it3': 0.0, 'E_it4': 0.0,
'machine_type': machine_type, 'status': 'InProgress',
'file_name': file_name})
df_E = df_E.append(df_newline, ignore_index=True)
df_E.to_csv(auto_csv, index=False)
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_init_params_done = filter_df(df_init_params, {'status': 'Done'})
isOver = True if len(df_init_params_done) == len(df_init_params) else False
return isOver
def check_calc_status(auto_dir, params_dict):
df_E = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
if len(df_E) == 0:
return False
df_E_filtered = filter_df(df_E, params_dict)
df_E_filtered = df_E_filtered.reset_index(drop=True)
try:
status = get_values_from_df(df_E_filtered, 0, 'status')
return status == 'Done'
except KeyError:
return False
def get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys,
monomer_name):
"""
前提:
step3-twist_init_params.csvとstep3-twist.csvがauto_dirの下にある
"""
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
df_init_params_inprogress = df_init_params[df_init_params['status'] ==
'InProgress']
if len(df_init_params_inprogress) < num_nodes:
df_init_params_notyet = df_init_params[df_init_params['status'] ==
'NotYet']
for index in df_init_params_notyet.index:
df_init_params = update_value_in_df(df_init_params, index,
'status', 'InProgress')
df_init_params.to_csv(init_params_csv, index=False)
params_dict = df_init_params.loc[index, fixed_param_keys +
opt_param_keys].to_dict()
return params_dict
for index in df_init_params.index:
df_init_params = pd.read_csv(init_params_csv)
init_params_dict = df_init_params.loc[index, fixed_param_keys +
opt_param_keys].to_dict()
fixed_params_dict = df_init_params.loc[index, fixed_param_keys
].to_dict()
isDone, opt_params_dict = get_opt_params_dict(df_cur,
init_params_dict, fixed_params_dict, monomer_name)
if isDone:
df_init_params = update_value_in_df(df_init_params, index,
'status', 'Done')
if np.max(df_init_params.index) < index + 1:
status = 'Done'
else:
status = get_values_from_df(df_init_params, index + 1, 'status'
)
df_init_params.to_csv(init_params_csv, index=False)
if status == 'NotYet':
opt_params_dict = get_values_from_df(df_init_params, index +
1, opt_param_keys)
df_init_params = update_value_in_df(df_init_params, index +
1, 'status', 'InProgress')
df_init_params.to_csv(init_params_csv, index=False)
return {**fixed_params_dict, **opt_params_dict}
else:
continue
else:
df_inprogress = filter_df(df_cur, {**fixed_params_dict, **
opt_params_dict, 'status': 'InProgress'})
if len(df_inprogress) >= 1:
continue
return {**fixed_params_dict, **opt_params_dict}
return {}
def get_opt_params_dict(df_cur, init_params_dict, fixed_params_dict,
monomer_name):
df_val = filter_df(df_cur, fixed_params_dict)
a_init_prev = init_params_dict['a']
b_init_prev = init_params_dict['b']
theta_init_prev = init_params_dict['theta']
A1 = init_params_dict['A1']
A2 = init_params_dict['A2']
while True:
E_list = []
heri_list = []
for a in [a_init_prev - 0.1, a_init_prev, a_init_prev + 0.1]:
for b in [b_init_prev - 0.1, b_init_prev, b_init_prev + 0.1]:
a = np.round(a, 1)
b = np.round(b, 1)
for theta in [theta_init_prev - 0.5, theta_init_prev,
theta_init_prev + 0.5]:
df_val_ab = df_val[(df_val['a'] == a) & (df_val['b'] ==
b) & (df_val['theta'] == theta) & (df_val['A1'] ==
A1) & (df_val['A2'] == A2) & (df_val['status'] ==
'Done')]
if len(df_val_ab) == 0:
cx, cy, cz = get_c_vec_vdw(monomer_name, A1, A2, a,
b, theta)
cx, cy, cz = np.round(cx, 1), np.round(cy, 1
), np.round(cz, 1)
return False, {'a': a, 'b': b, 'theta': theta, 'cx':
cx, 'cy': cy, 'cz': cz}
heri_list.append([a, b, theta])
E_list.append(df_val_ab['E'].values[0])
a_init, b_init, theta_init = heri_list[np.argmin(np.array(E_list))]
if (a_init == a_init_prev and b_init == b_init_prev and theta_init ==
theta_init_prev):
cx, cy, cz = get_c_vec_vdw(monomer_name, A1, A2, a_init, b_init,
theta_init)
cx, cy, cz = np.round(cx, 1), np.round(cy, 1), np.round(cz, 1)
return True, {'a': a_init, 'b': b_init, 'theta': theta_init,
'cx': cx, 'cy': cy, 'cz': cz}
else:
a_init_prev = a_init
b_init_prev = b_init
theta_init_prev = theta_init
def get_values_from_df(df, index, key):
return df.loc[index, key]
def update_value_in_df(df, index, key, value):
df.loc[index, key] = value
return df
def filter_df(df, dict_filter):
query = []
for k, v in dict_filter.items():
if type(v) == str:
query.append('{} == "{}"'.format(k, v))
else:
query.append('{} == {}'.format(k, v))
df_filtered = df.query(' and '.join(query))
return df_filtered
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
sys.path.append(os.path.join(os.environ['HOME'], 'Working/interaction/'))
<|reserved_special_token_0|>
def init_process(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
os.makedirs(os.path.join(auto_dir, 'gaussian'), exist_ok=True)
os.makedirs(os.path.join(auto_dir, 'gaussview'), exist_ok=True)
def get_init_para_csv(auto_dir, monomer_name):
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df = pd.read_csv(
'/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'
.format(monomer_name))
df = df[(df['A2'] == 32) & (df['A1'] <= 0) & (df['A1'] >= -20) & (
df['theta'] > 45)]
inner_zip = df[['a', 'b', 'theta', 'A1', 'A2']].values
print(inner_zip)
init_para_list = []
for a, b, theta, A1, A2 in tqdm(inner_zip):
c = get_c_vec_vdw(monomer_name, A1, A2, a, b, theta)
init_para_list.append([np.round(a, 1), np.round(b, 1), theta,
A1, A2, np.round(c[0], 1), np.round(c[1], 1), np.round(c[2],
1), 'NotYet'])
df_init_params = pd.DataFrame(np.array(init_para_list), columns=[
'a', 'b', 'theta', 'A1', 'A2', 'cx', 'cy', 'cz', 'status'])
df_init_params.to_csv(init_params_csv, index=False)
get_init_para_csv(auto_dir, monomer_name)
auto_csv_path = os.path.join(auto_dir, 'step3-twist.csv')
if not os.path.exists(auto_csv_path):
df_E = pd.DataFrame(columns=['a', 'b', 'theta', 'A1', 'A2', 'cx',
'cy', 'cz', 'E', 'E_p', 'E_t', 'machine_type', 'status',
'file_name'])
else:
df_E = pd.read_csv(auto_csv_path)
df_E = df_E[df_E['status'] != 'InProgress']
df_E.to_csv(auto_csv_path, index=False)
df_init = pd.read_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv')
)
df_init['status'] = 'NotYet'
df_init.to_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv'),
index=False)
def main_process(args):
os.chdir(os.path.join(args.auto_dir, 'gaussian'))
isOver = False
while not isOver:
isOver = listen(args)
time.sleep(1)
def listen(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
num_nodes = args.num_nodes
isTest = args.isTest
fixed_param_keys = ['A1', 'A2']
opt_param_keys = ['a', 'b', 'theta', 'cx', 'cy', 'cz']
auto_step2_csv = (
'/home/koyama/Working/interaction/{}/step2-twist/step2-twist.csv'.
format(monomer_name))
df_step2 = pd.read_csv(auto_step2_csv)
auto_csv = os.path.join(auto_dir, 'step3-twist.csv')
df_E = pd.read_csv(auto_csv)
df_queue = df_E.loc[df_E['status'] == 'InProgress', ['machine_type',
'file_name', 'A1', 'A2', 'a', 'b', 'theta', 'cx', 'cy', 'cz']]
machine_type_list = df_queue['machine_type'].values.tolist()
len_queue = len(df_queue)
maxnum_machine2 = 3
for idx, row in zip(df_queue.index, df_queue.values):
machine_type, file_name, A1, A2, a, b, theta, cx, cy, cz = row
log_filepath = os.path.join(*[auto_dir, 'gaussian', file_name])
if not os.path.exists(log_filepath):
continue
E_list = get_E(log_filepath)
if len(E_list) != 5:
continue
else:
len_queue -= 1
machine_type_list.remove(machine_type)
Ei0, Eip1, Eip2, Eit1, Eit2 = map(float, E_list)
Eit3 = Eit2
Eit4 = Eit1
try:
Ep, Et = df_step2[(df_step2['A1'] == A1) & (df_step2['A2'] ==
A2) & (df_step2['theta'] == theta) & (df_step2['a'] ==
a) & (df_step2['b'] == b)][['E_p', 'E_t']].values[0]
except IndexError:
inner_params_dict = {'A1': A1, 'A2': A2, 'a': a, 'b': b,
'theta': theta, 'cx': 0, 'cy': 0, 'cz': 0}
inner_file_name = exec_gjf(auto_dir, monomer_name,
inner_params_dict, machine_type, isInterlayer=False,
isTest=isTest)
time.sleep(200)
is_inner_over = False
while not is_inner_over:
time.sleep(30)
E_inner_list = get_E(inner_file_name)
is_inner_over = len(E_inner_list) == 2
Ep, Et = map(float, E_inner_list)
df_newline = pd.Series({**inner_params_dict, 'E': 2 * Ep +
4 * Et, 'E_p': Ep, 'E_t': Et, 'machine_type':
machine_type, 'status': 'Done', 'file_name':
inner_file_name})
df_step2 = df_step2.append(df_newline, ignore_index=True)
df_step2.to_csv(auto_step2_csv, index=False)
E = 4 * Et + 2 * Ep + 2 * (Ei0 + Eip1 + Eip2 + Eit1 + Eit2 +
Eit3 + Eit4)
df_E.loc[idx, ['E_p', 'E_t', 'E_i0', 'E_ip1', 'E_ip2', 'E_it1',
'E_it2', 'E_it3', 'E_it4', 'E', 'status']] = [Ep, Et, Ei0,
Eip1, Eip2, Eit1, Eit2, Eit3, Eit4, E, 'Done']
df_E.to_csv(auto_csv, index=False)
break
isAvailable = len_queue < num_nodes
machine2IsFull = machine_type_list.count(2) >= maxnum_machine2
machine_type = 1 if machine2IsFull else 2
if isAvailable:
params_dict = get_params_dict(auto_dir, num_nodes, fixed_param_keys,
opt_param_keys, monomer_name)
if len(params_dict) != 0:
alreadyCalculated = check_calc_status(auto_dir, params_dict)
if not alreadyCalculated:
file_name = exec_gjf(auto_dir, monomer_name, {**params_dict
}, machine_type, isInterlayer=True, isTest=isTest)
df_newline = pd.Series({**params_dict, 'E': 0.0, 'E_p': 0.0,
'E_t': 0.0, 'E_i0': 0.0, 'E_ip1': 0.0, 'E_ip2': 0.0,
'E_it1': 0.0, 'E_it2': 0.0, 'E_it3': 0.0, 'E_it4': 0.0,
'machine_type': machine_type, 'status': 'InProgress',
'file_name': file_name})
df_E = df_E.append(df_newline, ignore_index=True)
df_E.to_csv(auto_csv, index=False)
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_init_params_done = filter_df(df_init_params, {'status': 'Done'})
isOver = True if len(df_init_params_done) == len(df_init_params) else False
return isOver
def check_calc_status(auto_dir, params_dict):
df_E = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
if len(df_E) == 0:
return False
df_E_filtered = filter_df(df_E, params_dict)
df_E_filtered = df_E_filtered.reset_index(drop=True)
try:
status = get_values_from_df(df_E_filtered, 0, 'status')
return status == 'Done'
except KeyError:
return False
def get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys,
monomer_name):
"""
前提:
step3-twist_init_params.csvとstep3-twist.csvがauto_dirの下にある
"""
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
df_init_params_inprogress = df_init_params[df_init_params['status'] ==
'InProgress']
if len(df_init_params_inprogress) < num_nodes:
df_init_params_notyet = df_init_params[df_init_params['status'] ==
'NotYet']
for index in df_init_params_notyet.index:
df_init_params = update_value_in_df(df_init_params, index,
'status', 'InProgress')
df_init_params.to_csv(init_params_csv, index=False)
params_dict = df_init_params.loc[index, fixed_param_keys +
opt_param_keys].to_dict()
return params_dict
for index in df_init_params.index:
df_init_params = pd.read_csv(init_params_csv)
init_params_dict = df_init_params.loc[index, fixed_param_keys +
opt_param_keys].to_dict()
fixed_params_dict = df_init_params.loc[index, fixed_param_keys
].to_dict()
isDone, opt_params_dict = get_opt_params_dict(df_cur,
init_params_dict, fixed_params_dict, monomer_name)
if isDone:
df_init_params = update_value_in_df(df_init_params, index,
'status', 'Done')
if np.max(df_init_params.index) < index + 1:
status = 'Done'
else:
status = get_values_from_df(df_init_params, index + 1, 'status'
)
df_init_params.to_csv(init_params_csv, index=False)
if status == 'NotYet':
opt_params_dict = get_values_from_df(df_init_params, index +
1, opt_param_keys)
df_init_params = update_value_in_df(df_init_params, index +
1, 'status', 'InProgress')
df_init_params.to_csv(init_params_csv, index=False)
return {**fixed_params_dict, **opt_params_dict}
else:
continue
else:
df_inprogress = filter_df(df_cur, {**fixed_params_dict, **
opt_params_dict, 'status': 'InProgress'})
if len(df_inprogress) >= 1:
continue
return {**fixed_params_dict, **opt_params_dict}
return {}
def get_opt_params_dict(df_cur, init_params_dict, fixed_params_dict,
monomer_name):
df_val = filter_df(df_cur, fixed_params_dict)
a_init_prev = init_params_dict['a']
b_init_prev = init_params_dict['b']
theta_init_prev = init_params_dict['theta']
A1 = init_params_dict['A1']
A2 = init_params_dict['A2']
while True:
E_list = []
heri_list = []
for a in [a_init_prev - 0.1, a_init_prev, a_init_prev + 0.1]:
for b in [b_init_prev - 0.1, b_init_prev, b_init_prev + 0.1]:
a = np.round(a, 1)
b = np.round(b, 1)
for theta in [theta_init_prev - 0.5, theta_init_prev,
theta_init_prev + 0.5]:
df_val_ab = df_val[(df_val['a'] == a) & (df_val['b'] ==
b) & (df_val['theta'] == theta) & (df_val['A1'] ==
A1) & (df_val['A2'] == A2) & (df_val['status'] ==
'Done')]
if len(df_val_ab) == 0:
cx, cy, cz = get_c_vec_vdw(monomer_name, A1, A2, a,
b, theta)
cx, cy, cz = np.round(cx, 1), np.round(cy, 1
), np.round(cz, 1)
return False, {'a': a, 'b': b, 'theta': theta, 'cx':
cx, 'cy': cy, 'cz': cz}
heri_list.append([a, b, theta])
E_list.append(df_val_ab['E'].values[0])
a_init, b_init, theta_init = heri_list[np.argmin(np.array(E_list))]
if (a_init == a_init_prev and b_init == b_init_prev and theta_init ==
theta_init_prev):
cx, cy, cz = get_c_vec_vdw(monomer_name, A1, A2, a_init, b_init,
theta_init)
cx, cy, cz = np.round(cx, 1), np.round(cy, 1), np.round(cz, 1)
return True, {'a': a_init, 'b': b_init, 'theta': theta_init,
'cx': cx, 'cy': cy, 'cz': cz}
else:
a_init_prev = a_init
b_init_prev = b_init
theta_init_prev = theta_init
def get_values_from_df(df, index, key):
return df.loc[index, key]
def update_value_in_df(df, index, key, value):
df.loc[index, key] = value
return df
def filter_df(df, dict_filter):
query = []
for k, v in dict_filter.items():
if type(v) == str:
query.append('{} == "{}"'.format(k, v))
else:
query.append('{} == {}'.format(k, v))
df_filtered = df.query(' and '.join(query))
return df_filtered
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--init', action='store_true')
parser.add_argument('--isTest', action='store_true')
parser.add_argument('--auto-dir', type=str, help=
'path to dir which includes gaussian, gaussview and csv')
parser.add_argument('--monomer-name', type=str, help='monomer name')
parser.add_argument('--num-nodes', type=int, help='num nodes')
args = parser.parse_args()
if args.init:
print('----initial process----')
init_process(args)
print('----main process----')
main_process(args)
print('----finish process----')
<|reserved_special_token_1|>
import os
import pandas as pd
import time
import sys
from tqdm import tqdm
sys.path.append(os.path.join(os.environ['HOME'],'Working/interaction/'))
from src.make import exec_gjf
from src.vdw import vdw_R, get_c_vec_vdw
from src.utils import get_E
import argparse
import numpy as np
from scipy import signal
import scipy.spatial.distance as distance
import random
def init_process(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
os.makedirs(os.path.join(auto_dir,'gaussian'), exist_ok=True)
os.makedirs(os.path.join(auto_dir,'gaussview'), exist_ok=True)
def get_init_para_csv(auto_dir,monomer_name):
init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')
df = pd.read_csv('/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'.format(monomer_name))
# df = df[(df["A2"]==30)&(df["A1"]<=0)&(df["A1"]>=-10)&(df["theta"]>45)]
df = df[(df["A2"]==32)&(df["A1"]<=0)&(df["A1"]>=-20)&(df["theta"]>45)]
inner_zip = df[['a','b','theta','A1','A2']].values
print(inner_zip)
init_para_list = []
for a,b,theta,A1,A2 in tqdm(inner_zip):
c = get_c_vec_vdw(monomer_name,A1,A2,a,b,theta)
init_para_list.append([np.round(a,1),np.round(b,1),theta,A1,A2,np.round(c[0],1),np.round(c[1],1),np.round(c[2],1),'NotYet'])
df_init_params = pd.DataFrame(np.array(init_para_list),columns = ['a','b','theta','A1','A2','cx','cy','cz','status'])
df_init_params.to_csv(init_params_csv,index=False)
get_init_para_csv(auto_dir,monomer_name)
auto_csv_path = os.path.join(auto_dir,'step3-twist.csv')
if not os.path.exists(auto_csv_path):
df_E = pd.DataFrame(columns = ['a','b','theta','A1','A2','cx','cy','cz','E','E_p','E_t','machine_type','status','file_name'])
else:
df_E = pd.read_csv(auto_csv_path)
df_E = df_E[df_E['status']!='InProgress']
df_E.to_csv(auto_csv_path,index=False)
df_init=pd.read_csv(os.path.join(auto_dir,'step3-twist_init_params.csv'))
df_init['status']='NotYet'
df_init.to_csv(os.path.join(auto_dir,'step3-twist_init_params.csv'),index=False)
def main_process(args):
os.chdir(os.path.join(args.auto_dir,'gaussian'))
isOver = False
while not(isOver):
#check
isOver = listen(args)
time.sleep(1)
def listen(args):
auto_dir = args.auto_dir
monomer_name = args.monomer_name
num_nodes = args.num_nodes
isTest = args.isTest
fixed_param_keys = ['A1','A2']
opt_param_keys = ['a','b','theta','cx','cy','cz']
auto_step2_csv = '/home/koyama/Working/interaction/{}/step2-twist/step2-twist.csv'.format(monomer_name)
df_step2 = pd.read_csv(auto_step2_csv)
auto_csv = os.path.join(auto_dir,'step3-twist.csv')
df_E = pd.read_csv(auto_csv)
df_queue = df_E.loc[df_E['status']=='InProgress',['machine_type','file_name','A1','A2','a','b','theta','cx','cy','cz']]
machine_type_list = df_queue['machine_type'].values.tolist()
len_queue = len(df_queue)
maxnum_machine2 = 3#int(num_nodes/2)
for idx,row in zip(df_queue.index,df_queue.values):
machine_type,file_name,A1,A2,a,b,theta,cx,cy,cz = row
log_filepath = os.path.join(*[auto_dir,'gaussian',file_name])
if not(os.path.exists(log_filepath)):#logファイルが生成される直前だとまずいので
continue
E_list=get_E(log_filepath)
if len(E_list)!=5:
continue
else:
len_queue-=1;machine_type_list.remove(machine_type)
Ei0,Eip1,Eip2,Eit1,Eit2=map(float,E_list)
Eit3 = Eit2; Eit4 = Eit1
try:
Ep, Et = df_step2[(df_step2['A1']==A1)&(df_step2['A2']==A2)&(df_step2['theta']==theta)&(df_step2['a']==a)&(df_step2['b']==b)][['E_p','E_t']].values[0]
except IndexError:
inner_params_dict = {"A1":A1,"A2":A2,"a":a,"b":b,"theta":theta,'cx':0,'cy':0,'cz':0}
inner_file_name = exec_gjf(auto_dir, monomer_name, inner_params_dict, machine_type,isInterlayer=False,isTest=isTest)
time.sleep(200)#1:40で1計算終わる
is_inner_over = False
while not(is_inner_over):
time.sleep(30)#1:40で1計算終わる
E_inner_list=get_E(inner_file_name)
is_inner_over = len(E_inner_list)==2
Ep, Et=map(float,E_inner_list)
df_newline = pd.Series({**inner_params_dict,'E':2*Ep+4*Et,'E_p':Ep,'E_t':Et,'machine_type':machine_type,'status':'Done','file_name':inner_file_name})
df_step2=df_step2.append(df_newline,ignore_index=True)
df_step2.to_csv(auto_step2_csv,index=False)
E = 4*Et + 2*Ep + 2*(Ei0 + Eip1+ Eip2 + Eit1 + Eit2 + Eit3 + Eit4)
df_E.loc[idx, ['E_p','E_t','E_i0','E_ip1','E_ip2','E_it1','E_it2','E_it3','E_it4','E','status']] = [Ep,Et,Ei0,Eip1,Eip2,Eit1,Eit2,Eit3,Eit4,E,'Done']
df_E.to_csv(auto_csv,index=False)
break#2つ同時に計算終わったりしたらまずいので一個で切る
isAvailable = len_queue < num_nodes
machine2IsFull = machine_type_list.count(2) >= maxnum_machine2
machine_type = 1 if machine2IsFull else 2
if isAvailable:
params_dict = get_params_dict(auto_dir,num_nodes, fixed_param_keys, opt_param_keys, monomer_name)
if len(params_dict)!=0:#終わりがまだ見えないなら
alreadyCalculated = check_calc_status(auto_dir,params_dict)
if not(alreadyCalculated):
file_name = exec_gjf(auto_dir, monomer_name, {**params_dict}, machine_type,isInterlayer=True,isTest=isTest)
df_newline = pd.Series({**params_dict,'E':0.,'E_p':0.,'E_t':0.,'E_i0':0.,'E_ip1':0.,'E_ip2':0.,'E_it1':0.,'E_it2':0.,'E_it3':0.,'E_it4':0.,'machine_type':machine_type,'status':'InProgress','file_name':file_name})
df_E=df_E.append(df_newline,ignore_index=True)
df_E.to_csv(auto_csv,index=False)
init_params_csv=os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_init_params_done = filter_df(df_init_params,{'status':'Done'})
isOver = True if len(df_init_params_done)==len(df_init_params) else False
return isOver
def check_calc_status(auto_dir,params_dict):
df_E= pd.read_csv(os.path.join(auto_dir,'step3-twist.csv'))
if len(df_E)==0:
return False
df_E_filtered = filter_df(df_E, params_dict)
df_E_filtered = df_E_filtered.reset_index(drop=True)
try:
status = get_values_from_df(df_E_filtered,0,'status')
return status=='Done'
except KeyError:
return False
def get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys, monomer_name):
"""
前提:
step3-twist_init_params.csvとstep3-twist.csvがauto_dirの下にある
"""
init_params_csv=os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
df_init_params_inprogress = df_init_params[df_init_params['status']=='InProgress']
#最初の立ち上がり時
if len(df_init_params_inprogress) < num_nodes:
df_init_params_notyet = df_init_params[df_init_params['status']=='NotYet']
for index in df_init_params_notyet.index:
df_init_params = update_value_in_df(df_init_params,index,'status','InProgress')
df_init_params.to_csv(init_params_csv,index=False)
params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()
return params_dict
for index in df_init_params.index:
df_init_params = pd.read_csv(init_params_csv)
init_params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()
fixed_params_dict = df_init_params.loc[index,fixed_param_keys].to_dict()
isDone, opt_params_dict = get_opt_params_dict(df_cur, init_params_dict,fixed_params_dict, monomer_name)
if isDone:
# df_init_paramsのstatusをupdate
df_init_params = update_value_in_df(df_init_params,index,'status','Done')
if np.max(df_init_params.index) < index+1:
status = 'Done'
else:
status = get_values_from_df(df_init_params,index+1,'status')
df_init_params.to_csv(init_params_csv,index=False)
if status=='NotYet':
opt_params_dict = get_values_from_df(df_init_params,index+1,opt_param_keys)
df_init_params = update_value_in_df(df_init_params,index+1,'status','InProgress')
df_init_params.to_csv(init_params_csv,index=False)
return {**fixed_params_dict,**opt_params_dict}
else:
continue
else:
df_inprogress = filter_df(df_cur, {**fixed_params_dict,**opt_params_dict,'status':'InProgress'})
if len(df_inprogress)>=1:
continue
return {**fixed_params_dict,**opt_params_dict}
return {}
def get_opt_params_dict(df_cur, init_params_dict,fixed_params_dict, monomer_name):
df_val = filter_df(df_cur, fixed_params_dict)
a_init_prev = init_params_dict['a']; b_init_prev = init_params_dict['b']; theta_init_prev = init_params_dict['theta']
A1 = init_params_dict['A1']; A2 = init_params_dict['A2']
while True:
E_list=[];heri_list=[]
for a in [a_init_prev-0.1,a_init_prev,a_init_prev+0.1]:
for b in [b_init_prev-0.1,b_init_prev,b_init_prev+0.1]:
a = np.round(a,1);b = np.round(b,1)
for theta in [theta_init_prev-0.5,theta_init_prev,theta_init_prev+0.5]:
df_val_ab = df_val[
(df_val['a']==a)&(df_val['b']==b)&(df_val['theta']==theta)&
(df_val['A1']==A1)&(df_val['A2']==A2)&
(df_val['status']=='Done')
]
if len(df_val_ab)==0:
cx, cy, cz = get_c_vec_vdw(monomer_name,A1,A2,a,b,theta)
cx, cy, cz = np.round(cx,1), np.round(cy,1), np.round(cz,1)
return False,{'a':a,'b':b,'theta':theta, "cx":cx, "cy":cy, "cz":cz }
heri_list.append([a,b,theta]);E_list.append(df_val_ab['E'].values[0])
a_init,b_init,theta_init = heri_list[np.argmin(np.array(E_list))]
if a_init==a_init_prev and b_init==b_init_prev and theta_init==theta_init_prev:
cx, cy, cz = get_c_vec_vdw(monomer_name,A1,A2,a_init,b_init,theta_init)
cx, cy, cz = np.round(cx,1), np.round(cy,1), np.round(cz,1)
return True,{'a':a_init,'b':b_init, 'theta':theta_init, "cx":cx, "cy":cy, "cz":cz }
else:
a_init_prev=a_init;b_init_prev=b_init;theta_init_prev=theta_init
def get_values_from_df(df,index,key):
return df.loc[index,key]
def update_value_in_df(df,index,key,value):
df.loc[index,key]=value
return df
def filter_df(df, dict_filter):
query = []
for k, v in dict_filter.items():
if type(v)==str:
query.append('{} == "{}"'.format(k,v))
else:
query.append('{} == {}'.format(k,v))
df_filtered = df.query(' and '.join(query))
return df_filtered
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--init',action='store_true')
parser.add_argument('--isTest',action='store_true')
parser.add_argument('--auto-dir',type=str,help='path to dir which includes gaussian, gaussview and csv')
parser.add_argument('--monomer-name',type=str,help='monomer name')
parser.add_argument('--num-nodes',type=int,help='num nodes')
args = parser.parse_args()
if args.init:
print("----initial process----")
init_process(args)
print("----main process----")
main_process(args)
print("----finish process----")
|
flexible
|
{
"blob_id": "961bda96e433bb66d592ad1e99c92db0a9ab9fe9",
"index": 8545,
"step-1": "<mask token>\n\n\ndef init_process(args):\n auto_dir = args.auto_dir\n monomer_name = args.monomer_name\n os.makedirs(os.path.join(auto_dir, 'gaussian'), exist_ok=True)\n os.makedirs(os.path.join(auto_dir, 'gaussview'), exist_ok=True)\n\n def get_init_para_csv(auto_dir, monomer_name):\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df = pd.read_csv(\n '/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'\n .format(monomer_name))\n df = df[(df['A2'] == 32) & (df['A1'] <= 0) & (df['A1'] >= -20) & (\n df['theta'] > 45)]\n inner_zip = df[['a', 'b', 'theta', 'A1', 'A2']].values\n print(inner_zip)\n init_para_list = []\n for a, b, theta, A1, A2 in tqdm(inner_zip):\n c = get_c_vec_vdw(monomer_name, A1, A2, a, b, theta)\n init_para_list.append([np.round(a, 1), np.round(b, 1), theta,\n A1, A2, np.round(c[0], 1), np.round(c[1], 1), np.round(c[2],\n 1), 'NotYet'])\n df_init_params = pd.DataFrame(np.array(init_para_list), columns=[\n 'a', 'b', 'theta', 'A1', 'A2', 'cx', 'cy', 'cz', 'status'])\n df_init_params.to_csv(init_params_csv, index=False)\n get_init_para_csv(auto_dir, monomer_name)\n auto_csv_path = os.path.join(auto_dir, 'step3-twist.csv')\n if not os.path.exists(auto_csv_path):\n df_E = pd.DataFrame(columns=['a', 'b', 'theta', 'A1', 'A2', 'cx',\n 'cy', 'cz', 'E', 'E_p', 'E_t', 'machine_type', 'status',\n 'file_name'])\n else:\n df_E = pd.read_csv(auto_csv_path)\n df_E = df_E[df_E['status'] != 'InProgress']\n df_E.to_csv(auto_csv_path, index=False)\n df_init = pd.read_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv')\n )\n df_init['status'] = 'NotYet'\n df_init.to_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv'),\n index=False)\n\n\ndef main_process(args):\n os.chdir(os.path.join(args.auto_dir, 'gaussian'))\n isOver = False\n while not isOver:\n isOver = listen(args)\n time.sleep(1)\n\n\n<mask token>\n\n\ndef update_value_in_df(df, index, key, value):\n df.loc[index, key] = value\n return df\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef init_process(args):\n auto_dir = args.auto_dir\n monomer_name = args.monomer_name\n os.makedirs(os.path.join(auto_dir, 'gaussian'), exist_ok=True)\n os.makedirs(os.path.join(auto_dir, 'gaussview'), exist_ok=True)\n\n def get_init_para_csv(auto_dir, monomer_name):\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df = pd.read_csv(\n '/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'\n .format(monomer_name))\n df = df[(df['A2'] == 32) & (df['A1'] <= 0) & (df['A1'] >= -20) & (\n df['theta'] > 45)]\n inner_zip = df[['a', 'b', 'theta', 'A1', 'A2']].values\n print(inner_zip)\n init_para_list = []\n for a, b, theta, A1, A2 in tqdm(inner_zip):\n c = get_c_vec_vdw(monomer_name, A1, A2, a, b, theta)\n init_para_list.append([np.round(a, 1), np.round(b, 1), theta,\n A1, A2, np.round(c[0], 1), np.round(c[1], 1), np.round(c[2],\n 1), 'NotYet'])\n df_init_params = pd.DataFrame(np.array(init_para_list), columns=[\n 'a', 'b', 'theta', 'A1', 'A2', 'cx', 'cy', 'cz', 'status'])\n df_init_params.to_csv(init_params_csv, index=False)\n get_init_para_csv(auto_dir, monomer_name)\n auto_csv_path = os.path.join(auto_dir, 'step3-twist.csv')\n if not os.path.exists(auto_csv_path):\n df_E = pd.DataFrame(columns=['a', 'b', 'theta', 'A1', 'A2', 'cx',\n 'cy', 'cz', 'E', 'E_p', 'E_t', 'machine_type', 'status',\n 'file_name'])\n else:\n df_E = pd.read_csv(auto_csv_path)\n df_E = df_E[df_E['status'] != 'InProgress']\n df_E.to_csv(auto_csv_path, index=False)\n df_init = pd.read_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv')\n )\n df_init['status'] = 'NotYet'\n df_init.to_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv'),\n index=False)\n\n\ndef main_process(args):\n os.chdir(os.path.join(args.auto_dir, 'gaussian'))\n isOver = False\n while not isOver:\n isOver = listen(args)\n time.sleep(1)\n\n\ndef listen(args):\n auto_dir = args.auto_dir\n monomer_name = args.monomer_name\n num_nodes = args.num_nodes\n isTest = args.isTest\n fixed_param_keys = ['A1', 'A2']\n opt_param_keys = ['a', 'b', 'theta', 'cx', 'cy', 'cz']\n auto_step2_csv = (\n '/home/koyama/Working/interaction/{}/step2-twist/step2-twist.csv'.\n format(monomer_name))\n df_step2 = pd.read_csv(auto_step2_csv)\n auto_csv = os.path.join(auto_dir, 'step3-twist.csv')\n df_E = pd.read_csv(auto_csv)\n df_queue = df_E.loc[df_E['status'] == 'InProgress', ['machine_type',\n 'file_name', 'A1', 'A2', 'a', 'b', 'theta', 'cx', 'cy', 'cz']]\n machine_type_list = df_queue['machine_type'].values.tolist()\n len_queue = len(df_queue)\n maxnum_machine2 = 3\n for idx, row in zip(df_queue.index, df_queue.values):\n machine_type, file_name, A1, A2, a, b, theta, cx, cy, cz = row\n log_filepath = os.path.join(*[auto_dir, 'gaussian', file_name])\n if not os.path.exists(log_filepath):\n continue\n E_list = get_E(log_filepath)\n if len(E_list) != 5:\n continue\n else:\n len_queue -= 1\n machine_type_list.remove(machine_type)\n Ei0, Eip1, Eip2, Eit1, Eit2 = map(float, E_list)\n Eit3 = Eit2\n Eit4 = Eit1\n try:\n Ep, Et = df_step2[(df_step2['A1'] == A1) & (df_step2['A2'] ==\n A2) & (df_step2['theta'] == theta) & (df_step2['a'] ==\n a) & (df_step2['b'] == b)][['E_p', 'E_t']].values[0]\n except IndexError:\n inner_params_dict = {'A1': A1, 'A2': A2, 'a': a, 'b': b,\n 'theta': theta, 'cx': 0, 'cy': 0, 'cz': 0}\n inner_file_name = exec_gjf(auto_dir, monomer_name,\n inner_params_dict, machine_type, isInterlayer=False,\n isTest=isTest)\n time.sleep(200)\n is_inner_over = False\n while not is_inner_over:\n time.sleep(30)\n E_inner_list = get_E(inner_file_name)\n is_inner_over = len(E_inner_list) == 2\n Ep, Et = map(float, E_inner_list)\n df_newline = pd.Series({**inner_params_dict, 'E': 2 * Ep + \n 4 * Et, 'E_p': Ep, 'E_t': Et, 'machine_type':\n machine_type, 'status': 'Done', 'file_name':\n inner_file_name})\n df_step2 = df_step2.append(df_newline, ignore_index=True)\n df_step2.to_csv(auto_step2_csv, index=False)\n E = 4 * Et + 2 * Ep + 2 * (Ei0 + Eip1 + Eip2 + Eit1 + Eit2 +\n Eit3 + Eit4)\n df_E.loc[idx, ['E_p', 'E_t', 'E_i0', 'E_ip1', 'E_ip2', 'E_it1',\n 'E_it2', 'E_it3', 'E_it4', 'E', 'status']] = [Ep, Et, Ei0,\n Eip1, Eip2, Eit1, Eit2, Eit3, Eit4, E, 'Done']\n df_E.to_csv(auto_csv, index=False)\n break\n isAvailable = len_queue < num_nodes\n machine2IsFull = machine_type_list.count(2) >= maxnum_machine2\n machine_type = 1 if machine2IsFull else 2\n if isAvailable:\n params_dict = get_params_dict(auto_dir, num_nodes, fixed_param_keys,\n opt_param_keys, monomer_name)\n if len(params_dict) != 0:\n alreadyCalculated = check_calc_status(auto_dir, params_dict)\n if not alreadyCalculated:\n file_name = exec_gjf(auto_dir, monomer_name, {**params_dict\n }, machine_type, isInterlayer=True, isTest=isTest)\n df_newline = pd.Series({**params_dict, 'E': 0.0, 'E_p': 0.0,\n 'E_t': 0.0, 'E_i0': 0.0, 'E_ip1': 0.0, 'E_ip2': 0.0,\n 'E_it1': 0.0, 'E_it2': 0.0, 'E_it3': 0.0, 'E_it4': 0.0,\n 'machine_type': machine_type, 'status': 'InProgress',\n 'file_name': file_name})\n df_E = df_E.append(df_newline, ignore_index=True)\n df_E.to_csv(auto_csv, index=False)\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df_init_params = pd.read_csv(init_params_csv)\n df_init_params_done = filter_df(df_init_params, {'status': 'Done'})\n isOver = True if len(df_init_params_done) == len(df_init_params) else False\n return isOver\n\n\ndef check_calc_status(auto_dir, params_dict):\n df_E = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))\n if len(df_E) == 0:\n return False\n df_E_filtered = filter_df(df_E, params_dict)\n df_E_filtered = df_E_filtered.reset_index(drop=True)\n try:\n status = get_values_from_df(df_E_filtered, 0, 'status')\n return status == 'Done'\n except KeyError:\n return False\n\n\ndef get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys,\n monomer_name):\n \"\"\"\n 前提:\n step3-twist_init_params.csvとstep3-twist.csvがauto_dirの下にある\n \"\"\"\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df_init_params = pd.read_csv(init_params_csv)\n df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))\n df_init_params_inprogress = df_init_params[df_init_params['status'] ==\n 'InProgress']\n if len(df_init_params_inprogress) < num_nodes:\n df_init_params_notyet = df_init_params[df_init_params['status'] ==\n 'NotYet']\n for index in df_init_params_notyet.index:\n df_init_params = update_value_in_df(df_init_params, index,\n 'status', 'InProgress')\n df_init_params.to_csv(init_params_csv, index=False)\n params_dict = df_init_params.loc[index, fixed_param_keys +\n opt_param_keys].to_dict()\n return params_dict\n for index in df_init_params.index:\n df_init_params = pd.read_csv(init_params_csv)\n init_params_dict = df_init_params.loc[index, fixed_param_keys +\n opt_param_keys].to_dict()\n fixed_params_dict = df_init_params.loc[index, fixed_param_keys\n ].to_dict()\n isDone, opt_params_dict = get_opt_params_dict(df_cur,\n init_params_dict, fixed_params_dict, monomer_name)\n if isDone:\n df_init_params = update_value_in_df(df_init_params, index,\n 'status', 'Done')\n if np.max(df_init_params.index) < index + 1:\n status = 'Done'\n else:\n status = get_values_from_df(df_init_params, index + 1, 'status'\n )\n df_init_params.to_csv(init_params_csv, index=False)\n if status == 'NotYet':\n opt_params_dict = get_values_from_df(df_init_params, index +\n 1, opt_param_keys)\n df_init_params = update_value_in_df(df_init_params, index +\n 1, 'status', 'InProgress')\n df_init_params.to_csv(init_params_csv, index=False)\n return {**fixed_params_dict, **opt_params_dict}\n else:\n continue\n else:\n df_inprogress = filter_df(df_cur, {**fixed_params_dict, **\n opt_params_dict, 'status': 'InProgress'})\n if len(df_inprogress) >= 1:\n continue\n return {**fixed_params_dict, **opt_params_dict}\n return {}\n\n\n<mask token>\n\n\ndef get_values_from_df(df, index, key):\n return df.loc[index, key]\n\n\ndef update_value_in_df(df, index, key, value):\n df.loc[index, key] = value\n return df\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef init_process(args):\n auto_dir = args.auto_dir\n monomer_name = args.monomer_name\n os.makedirs(os.path.join(auto_dir, 'gaussian'), exist_ok=True)\n os.makedirs(os.path.join(auto_dir, 'gaussview'), exist_ok=True)\n\n def get_init_para_csv(auto_dir, monomer_name):\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df = pd.read_csv(\n '/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'\n .format(monomer_name))\n df = df[(df['A2'] == 32) & (df['A1'] <= 0) & (df['A1'] >= -20) & (\n df['theta'] > 45)]\n inner_zip = df[['a', 'b', 'theta', 'A1', 'A2']].values\n print(inner_zip)\n init_para_list = []\n for a, b, theta, A1, A2 in tqdm(inner_zip):\n c = get_c_vec_vdw(monomer_name, A1, A2, a, b, theta)\n init_para_list.append([np.round(a, 1), np.round(b, 1), theta,\n A1, A2, np.round(c[0], 1), np.round(c[1], 1), np.round(c[2],\n 1), 'NotYet'])\n df_init_params = pd.DataFrame(np.array(init_para_list), columns=[\n 'a', 'b', 'theta', 'A1', 'A2', 'cx', 'cy', 'cz', 'status'])\n df_init_params.to_csv(init_params_csv, index=False)\n get_init_para_csv(auto_dir, monomer_name)\n auto_csv_path = os.path.join(auto_dir, 'step3-twist.csv')\n if not os.path.exists(auto_csv_path):\n df_E = pd.DataFrame(columns=['a', 'b', 'theta', 'A1', 'A2', 'cx',\n 'cy', 'cz', 'E', 'E_p', 'E_t', 'machine_type', 'status',\n 'file_name'])\n else:\n df_E = pd.read_csv(auto_csv_path)\n df_E = df_E[df_E['status'] != 'InProgress']\n df_E.to_csv(auto_csv_path, index=False)\n df_init = pd.read_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv')\n )\n df_init['status'] = 'NotYet'\n df_init.to_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv'),\n index=False)\n\n\ndef main_process(args):\n os.chdir(os.path.join(args.auto_dir, 'gaussian'))\n isOver = False\n while not isOver:\n isOver = listen(args)\n time.sleep(1)\n\n\ndef listen(args):\n auto_dir = args.auto_dir\n monomer_name = args.monomer_name\n num_nodes = args.num_nodes\n isTest = args.isTest\n fixed_param_keys = ['A1', 'A2']\n opt_param_keys = ['a', 'b', 'theta', 'cx', 'cy', 'cz']\n auto_step2_csv = (\n '/home/koyama/Working/interaction/{}/step2-twist/step2-twist.csv'.\n format(monomer_name))\n df_step2 = pd.read_csv(auto_step2_csv)\n auto_csv = os.path.join(auto_dir, 'step3-twist.csv')\n df_E = pd.read_csv(auto_csv)\n df_queue = df_E.loc[df_E['status'] == 'InProgress', ['machine_type',\n 'file_name', 'A1', 'A2', 'a', 'b', 'theta', 'cx', 'cy', 'cz']]\n machine_type_list = df_queue['machine_type'].values.tolist()\n len_queue = len(df_queue)\n maxnum_machine2 = 3\n for idx, row in zip(df_queue.index, df_queue.values):\n machine_type, file_name, A1, A2, a, b, theta, cx, cy, cz = row\n log_filepath = os.path.join(*[auto_dir, 'gaussian', file_name])\n if not os.path.exists(log_filepath):\n continue\n E_list = get_E(log_filepath)\n if len(E_list) != 5:\n continue\n else:\n len_queue -= 1\n machine_type_list.remove(machine_type)\n Ei0, Eip1, Eip2, Eit1, Eit2 = map(float, E_list)\n Eit3 = Eit2\n Eit4 = Eit1\n try:\n Ep, Et = df_step2[(df_step2['A1'] == A1) & (df_step2['A2'] ==\n A2) & (df_step2['theta'] == theta) & (df_step2['a'] ==\n a) & (df_step2['b'] == b)][['E_p', 'E_t']].values[0]\n except IndexError:\n inner_params_dict = {'A1': A1, 'A2': A2, 'a': a, 'b': b,\n 'theta': theta, 'cx': 0, 'cy': 0, 'cz': 0}\n inner_file_name = exec_gjf(auto_dir, monomer_name,\n inner_params_dict, machine_type, isInterlayer=False,\n isTest=isTest)\n time.sleep(200)\n is_inner_over = False\n while not is_inner_over:\n time.sleep(30)\n E_inner_list = get_E(inner_file_name)\n is_inner_over = len(E_inner_list) == 2\n Ep, Et = map(float, E_inner_list)\n df_newline = pd.Series({**inner_params_dict, 'E': 2 * Ep + \n 4 * Et, 'E_p': Ep, 'E_t': Et, 'machine_type':\n machine_type, 'status': 'Done', 'file_name':\n inner_file_name})\n df_step2 = df_step2.append(df_newline, ignore_index=True)\n df_step2.to_csv(auto_step2_csv, index=False)\n E = 4 * Et + 2 * Ep + 2 * (Ei0 + Eip1 + Eip2 + Eit1 + Eit2 +\n Eit3 + Eit4)\n df_E.loc[idx, ['E_p', 'E_t', 'E_i0', 'E_ip1', 'E_ip2', 'E_it1',\n 'E_it2', 'E_it3', 'E_it4', 'E', 'status']] = [Ep, Et, Ei0,\n Eip1, Eip2, Eit1, Eit2, Eit3, Eit4, E, 'Done']\n df_E.to_csv(auto_csv, index=False)\n break\n isAvailable = len_queue < num_nodes\n machine2IsFull = machine_type_list.count(2) >= maxnum_machine2\n machine_type = 1 if machine2IsFull else 2\n if isAvailable:\n params_dict = get_params_dict(auto_dir, num_nodes, fixed_param_keys,\n opt_param_keys, monomer_name)\n if len(params_dict) != 0:\n alreadyCalculated = check_calc_status(auto_dir, params_dict)\n if not alreadyCalculated:\n file_name = exec_gjf(auto_dir, monomer_name, {**params_dict\n }, machine_type, isInterlayer=True, isTest=isTest)\n df_newline = pd.Series({**params_dict, 'E': 0.0, 'E_p': 0.0,\n 'E_t': 0.0, 'E_i0': 0.0, 'E_ip1': 0.0, 'E_ip2': 0.0,\n 'E_it1': 0.0, 'E_it2': 0.0, 'E_it3': 0.0, 'E_it4': 0.0,\n 'machine_type': machine_type, 'status': 'InProgress',\n 'file_name': file_name})\n df_E = df_E.append(df_newline, ignore_index=True)\n df_E.to_csv(auto_csv, index=False)\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df_init_params = pd.read_csv(init_params_csv)\n df_init_params_done = filter_df(df_init_params, {'status': 'Done'})\n isOver = True if len(df_init_params_done) == len(df_init_params) else False\n return isOver\n\n\ndef check_calc_status(auto_dir, params_dict):\n df_E = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))\n if len(df_E) == 0:\n return False\n df_E_filtered = filter_df(df_E, params_dict)\n df_E_filtered = df_E_filtered.reset_index(drop=True)\n try:\n status = get_values_from_df(df_E_filtered, 0, 'status')\n return status == 'Done'\n except KeyError:\n return False\n\n\ndef get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys,\n monomer_name):\n \"\"\"\n 前提:\n step3-twist_init_params.csvとstep3-twist.csvがauto_dirの下にある\n \"\"\"\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df_init_params = pd.read_csv(init_params_csv)\n df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))\n df_init_params_inprogress = df_init_params[df_init_params['status'] ==\n 'InProgress']\n if len(df_init_params_inprogress) < num_nodes:\n df_init_params_notyet = df_init_params[df_init_params['status'] ==\n 'NotYet']\n for index in df_init_params_notyet.index:\n df_init_params = update_value_in_df(df_init_params, index,\n 'status', 'InProgress')\n df_init_params.to_csv(init_params_csv, index=False)\n params_dict = df_init_params.loc[index, fixed_param_keys +\n opt_param_keys].to_dict()\n return params_dict\n for index in df_init_params.index:\n df_init_params = pd.read_csv(init_params_csv)\n init_params_dict = df_init_params.loc[index, fixed_param_keys +\n opt_param_keys].to_dict()\n fixed_params_dict = df_init_params.loc[index, fixed_param_keys\n ].to_dict()\n isDone, opt_params_dict = get_opt_params_dict(df_cur,\n init_params_dict, fixed_params_dict, monomer_name)\n if isDone:\n df_init_params = update_value_in_df(df_init_params, index,\n 'status', 'Done')\n if np.max(df_init_params.index) < index + 1:\n status = 'Done'\n else:\n status = get_values_from_df(df_init_params, index + 1, 'status'\n )\n df_init_params.to_csv(init_params_csv, index=False)\n if status == 'NotYet':\n opt_params_dict = get_values_from_df(df_init_params, index +\n 1, opt_param_keys)\n df_init_params = update_value_in_df(df_init_params, index +\n 1, 'status', 'InProgress')\n df_init_params.to_csv(init_params_csv, index=False)\n return {**fixed_params_dict, **opt_params_dict}\n else:\n continue\n else:\n df_inprogress = filter_df(df_cur, {**fixed_params_dict, **\n opt_params_dict, 'status': 'InProgress'})\n if len(df_inprogress) >= 1:\n continue\n return {**fixed_params_dict, **opt_params_dict}\n return {}\n\n\ndef get_opt_params_dict(df_cur, init_params_dict, fixed_params_dict,\n monomer_name):\n df_val = filter_df(df_cur, fixed_params_dict)\n a_init_prev = init_params_dict['a']\n b_init_prev = init_params_dict['b']\n theta_init_prev = init_params_dict['theta']\n A1 = init_params_dict['A1']\n A2 = init_params_dict['A2']\n while True:\n E_list = []\n heri_list = []\n for a in [a_init_prev - 0.1, a_init_prev, a_init_prev + 0.1]:\n for b in [b_init_prev - 0.1, b_init_prev, b_init_prev + 0.1]:\n a = np.round(a, 1)\n b = np.round(b, 1)\n for theta in [theta_init_prev - 0.5, theta_init_prev, \n theta_init_prev + 0.5]:\n df_val_ab = df_val[(df_val['a'] == a) & (df_val['b'] ==\n b) & (df_val['theta'] == theta) & (df_val['A1'] ==\n A1) & (df_val['A2'] == A2) & (df_val['status'] ==\n 'Done')]\n if len(df_val_ab) == 0:\n cx, cy, cz = get_c_vec_vdw(monomer_name, A1, A2, a,\n b, theta)\n cx, cy, cz = np.round(cx, 1), np.round(cy, 1\n ), np.round(cz, 1)\n return False, {'a': a, 'b': b, 'theta': theta, 'cx':\n cx, 'cy': cy, 'cz': cz}\n heri_list.append([a, b, theta])\n E_list.append(df_val_ab['E'].values[0])\n a_init, b_init, theta_init = heri_list[np.argmin(np.array(E_list))]\n if (a_init == a_init_prev and b_init == b_init_prev and theta_init ==\n theta_init_prev):\n cx, cy, cz = get_c_vec_vdw(monomer_name, A1, A2, a_init, b_init,\n theta_init)\n cx, cy, cz = np.round(cx, 1), np.round(cy, 1), np.round(cz, 1)\n return True, {'a': a_init, 'b': b_init, 'theta': theta_init,\n 'cx': cx, 'cy': cy, 'cz': cz}\n else:\n a_init_prev = a_init\n b_init_prev = b_init\n theta_init_prev = theta_init\n\n\ndef get_values_from_df(df, index, key):\n return df.loc[index, key]\n\n\ndef update_value_in_df(df, index, key, value):\n df.loc[index, key] = value\n return df\n\n\ndef filter_df(df, dict_filter):\n query = []\n for k, v in dict_filter.items():\n if type(v) == str:\n query.append('{} == \"{}\"'.format(k, v))\n else:\n query.append('{} == {}'.format(k, v))\n df_filtered = df.query(' and '.join(query))\n return df_filtered\n\n\n<mask token>\n",
"step-4": "<mask token>\nsys.path.append(os.path.join(os.environ['HOME'], 'Working/interaction/'))\n<mask token>\n\n\ndef init_process(args):\n auto_dir = args.auto_dir\n monomer_name = args.monomer_name\n os.makedirs(os.path.join(auto_dir, 'gaussian'), exist_ok=True)\n os.makedirs(os.path.join(auto_dir, 'gaussview'), exist_ok=True)\n\n def get_init_para_csv(auto_dir, monomer_name):\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df = pd.read_csv(\n '/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'\n .format(monomer_name))\n df = df[(df['A2'] == 32) & (df['A1'] <= 0) & (df['A1'] >= -20) & (\n df['theta'] > 45)]\n inner_zip = df[['a', 'b', 'theta', 'A1', 'A2']].values\n print(inner_zip)\n init_para_list = []\n for a, b, theta, A1, A2 in tqdm(inner_zip):\n c = get_c_vec_vdw(monomer_name, A1, A2, a, b, theta)\n init_para_list.append([np.round(a, 1), np.round(b, 1), theta,\n A1, A2, np.round(c[0], 1), np.round(c[1], 1), np.round(c[2],\n 1), 'NotYet'])\n df_init_params = pd.DataFrame(np.array(init_para_list), columns=[\n 'a', 'b', 'theta', 'A1', 'A2', 'cx', 'cy', 'cz', 'status'])\n df_init_params.to_csv(init_params_csv, index=False)\n get_init_para_csv(auto_dir, monomer_name)\n auto_csv_path = os.path.join(auto_dir, 'step3-twist.csv')\n if not os.path.exists(auto_csv_path):\n df_E = pd.DataFrame(columns=['a', 'b', 'theta', 'A1', 'A2', 'cx',\n 'cy', 'cz', 'E', 'E_p', 'E_t', 'machine_type', 'status',\n 'file_name'])\n else:\n df_E = pd.read_csv(auto_csv_path)\n df_E = df_E[df_E['status'] != 'InProgress']\n df_E.to_csv(auto_csv_path, index=False)\n df_init = pd.read_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv')\n )\n df_init['status'] = 'NotYet'\n df_init.to_csv(os.path.join(auto_dir, 'step3-twist_init_params.csv'),\n index=False)\n\n\ndef main_process(args):\n os.chdir(os.path.join(args.auto_dir, 'gaussian'))\n isOver = False\n while not isOver:\n isOver = listen(args)\n time.sleep(1)\n\n\ndef listen(args):\n auto_dir = args.auto_dir\n monomer_name = args.monomer_name\n num_nodes = args.num_nodes\n isTest = args.isTest\n fixed_param_keys = ['A1', 'A2']\n opt_param_keys = ['a', 'b', 'theta', 'cx', 'cy', 'cz']\n auto_step2_csv = (\n '/home/koyama/Working/interaction/{}/step2-twist/step2-twist.csv'.\n format(monomer_name))\n df_step2 = pd.read_csv(auto_step2_csv)\n auto_csv = os.path.join(auto_dir, 'step3-twist.csv')\n df_E = pd.read_csv(auto_csv)\n df_queue = df_E.loc[df_E['status'] == 'InProgress', ['machine_type',\n 'file_name', 'A1', 'A2', 'a', 'b', 'theta', 'cx', 'cy', 'cz']]\n machine_type_list = df_queue['machine_type'].values.tolist()\n len_queue = len(df_queue)\n maxnum_machine2 = 3\n for idx, row in zip(df_queue.index, df_queue.values):\n machine_type, file_name, A1, A2, a, b, theta, cx, cy, cz = row\n log_filepath = os.path.join(*[auto_dir, 'gaussian', file_name])\n if not os.path.exists(log_filepath):\n continue\n E_list = get_E(log_filepath)\n if len(E_list) != 5:\n continue\n else:\n len_queue -= 1\n machine_type_list.remove(machine_type)\n Ei0, Eip1, Eip2, Eit1, Eit2 = map(float, E_list)\n Eit3 = Eit2\n Eit4 = Eit1\n try:\n Ep, Et = df_step2[(df_step2['A1'] == A1) & (df_step2['A2'] ==\n A2) & (df_step2['theta'] == theta) & (df_step2['a'] ==\n a) & (df_step2['b'] == b)][['E_p', 'E_t']].values[0]\n except IndexError:\n inner_params_dict = {'A1': A1, 'A2': A2, 'a': a, 'b': b,\n 'theta': theta, 'cx': 0, 'cy': 0, 'cz': 0}\n inner_file_name = exec_gjf(auto_dir, monomer_name,\n inner_params_dict, machine_type, isInterlayer=False,\n isTest=isTest)\n time.sleep(200)\n is_inner_over = False\n while not is_inner_over:\n time.sleep(30)\n E_inner_list = get_E(inner_file_name)\n is_inner_over = len(E_inner_list) == 2\n Ep, Et = map(float, E_inner_list)\n df_newline = pd.Series({**inner_params_dict, 'E': 2 * Ep + \n 4 * Et, 'E_p': Ep, 'E_t': Et, 'machine_type':\n machine_type, 'status': 'Done', 'file_name':\n inner_file_name})\n df_step2 = df_step2.append(df_newline, ignore_index=True)\n df_step2.to_csv(auto_step2_csv, index=False)\n E = 4 * Et + 2 * Ep + 2 * (Ei0 + Eip1 + Eip2 + Eit1 + Eit2 +\n Eit3 + Eit4)\n df_E.loc[idx, ['E_p', 'E_t', 'E_i0', 'E_ip1', 'E_ip2', 'E_it1',\n 'E_it2', 'E_it3', 'E_it4', 'E', 'status']] = [Ep, Et, Ei0,\n Eip1, Eip2, Eit1, Eit2, Eit3, Eit4, E, 'Done']\n df_E.to_csv(auto_csv, index=False)\n break\n isAvailable = len_queue < num_nodes\n machine2IsFull = machine_type_list.count(2) >= maxnum_machine2\n machine_type = 1 if machine2IsFull else 2\n if isAvailable:\n params_dict = get_params_dict(auto_dir, num_nodes, fixed_param_keys,\n opt_param_keys, monomer_name)\n if len(params_dict) != 0:\n alreadyCalculated = check_calc_status(auto_dir, params_dict)\n if not alreadyCalculated:\n file_name = exec_gjf(auto_dir, monomer_name, {**params_dict\n }, machine_type, isInterlayer=True, isTest=isTest)\n df_newline = pd.Series({**params_dict, 'E': 0.0, 'E_p': 0.0,\n 'E_t': 0.0, 'E_i0': 0.0, 'E_ip1': 0.0, 'E_ip2': 0.0,\n 'E_it1': 0.0, 'E_it2': 0.0, 'E_it3': 0.0, 'E_it4': 0.0,\n 'machine_type': machine_type, 'status': 'InProgress',\n 'file_name': file_name})\n df_E = df_E.append(df_newline, ignore_index=True)\n df_E.to_csv(auto_csv, index=False)\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df_init_params = pd.read_csv(init_params_csv)\n df_init_params_done = filter_df(df_init_params, {'status': 'Done'})\n isOver = True if len(df_init_params_done) == len(df_init_params) else False\n return isOver\n\n\ndef check_calc_status(auto_dir, params_dict):\n df_E = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))\n if len(df_E) == 0:\n return False\n df_E_filtered = filter_df(df_E, params_dict)\n df_E_filtered = df_E_filtered.reset_index(drop=True)\n try:\n status = get_values_from_df(df_E_filtered, 0, 'status')\n return status == 'Done'\n except KeyError:\n return False\n\n\ndef get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys,\n monomer_name):\n \"\"\"\n 前提:\n step3-twist_init_params.csvとstep3-twist.csvがauto_dirの下にある\n \"\"\"\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\n df_init_params = pd.read_csv(init_params_csv)\n df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))\n df_init_params_inprogress = df_init_params[df_init_params['status'] ==\n 'InProgress']\n if len(df_init_params_inprogress) < num_nodes:\n df_init_params_notyet = df_init_params[df_init_params['status'] ==\n 'NotYet']\n for index in df_init_params_notyet.index:\n df_init_params = update_value_in_df(df_init_params, index,\n 'status', 'InProgress')\n df_init_params.to_csv(init_params_csv, index=False)\n params_dict = df_init_params.loc[index, fixed_param_keys +\n opt_param_keys].to_dict()\n return params_dict\n for index in df_init_params.index:\n df_init_params = pd.read_csv(init_params_csv)\n init_params_dict = df_init_params.loc[index, fixed_param_keys +\n opt_param_keys].to_dict()\n fixed_params_dict = df_init_params.loc[index, fixed_param_keys\n ].to_dict()\n isDone, opt_params_dict = get_opt_params_dict(df_cur,\n init_params_dict, fixed_params_dict, monomer_name)\n if isDone:\n df_init_params = update_value_in_df(df_init_params, index,\n 'status', 'Done')\n if np.max(df_init_params.index) < index + 1:\n status = 'Done'\n else:\n status = get_values_from_df(df_init_params, index + 1, 'status'\n )\n df_init_params.to_csv(init_params_csv, index=False)\n if status == 'NotYet':\n opt_params_dict = get_values_from_df(df_init_params, index +\n 1, opt_param_keys)\n df_init_params = update_value_in_df(df_init_params, index +\n 1, 'status', 'InProgress')\n df_init_params.to_csv(init_params_csv, index=False)\n return {**fixed_params_dict, **opt_params_dict}\n else:\n continue\n else:\n df_inprogress = filter_df(df_cur, {**fixed_params_dict, **\n opt_params_dict, 'status': 'InProgress'})\n if len(df_inprogress) >= 1:\n continue\n return {**fixed_params_dict, **opt_params_dict}\n return {}\n\n\ndef get_opt_params_dict(df_cur, init_params_dict, fixed_params_dict,\n monomer_name):\n df_val = filter_df(df_cur, fixed_params_dict)\n a_init_prev = init_params_dict['a']\n b_init_prev = init_params_dict['b']\n theta_init_prev = init_params_dict['theta']\n A1 = init_params_dict['A1']\n A2 = init_params_dict['A2']\n while True:\n E_list = []\n heri_list = []\n for a in [a_init_prev - 0.1, a_init_prev, a_init_prev + 0.1]:\n for b in [b_init_prev - 0.1, b_init_prev, b_init_prev + 0.1]:\n a = np.round(a, 1)\n b = np.round(b, 1)\n for theta in [theta_init_prev - 0.5, theta_init_prev, \n theta_init_prev + 0.5]:\n df_val_ab = df_val[(df_val['a'] == a) & (df_val['b'] ==\n b) & (df_val['theta'] == theta) & (df_val['A1'] ==\n A1) & (df_val['A2'] == A2) & (df_val['status'] ==\n 'Done')]\n if len(df_val_ab) == 0:\n cx, cy, cz = get_c_vec_vdw(monomer_name, A1, A2, a,\n b, theta)\n cx, cy, cz = np.round(cx, 1), np.round(cy, 1\n ), np.round(cz, 1)\n return False, {'a': a, 'b': b, 'theta': theta, 'cx':\n cx, 'cy': cy, 'cz': cz}\n heri_list.append([a, b, theta])\n E_list.append(df_val_ab['E'].values[0])\n a_init, b_init, theta_init = heri_list[np.argmin(np.array(E_list))]\n if (a_init == a_init_prev and b_init == b_init_prev and theta_init ==\n theta_init_prev):\n cx, cy, cz = get_c_vec_vdw(monomer_name, A1, A2, a_init, b_init,\n theta_init)\n cx, cy, cz = np.round(cx, 1), np.round(cy, 1), np.round(cz, 1)\n return True, {'a': a_init, 'b': b_init, 'theta': theta_init,\n 'cx': cx, 'cy': cy, 'cz': cz}\n else:\n a_init_prev = a_init\n b_init_prev = b_init\n theta_init_prev = theta_init\n\n\ndef get_values_from_df(df, index, key):\n return df.loc[index, key]\n\n\ndef update_value_in_df(df, index, key, value):\n df.loc[index, key] = value\n return df\n\n\ndef filter_df(df, dict_filter):\n query = []\n for k, v in dict_filter.items():\n if type(v) == str:\n query.append('{} == \"{}\"'.format(k, v))\n else:\n query.append('{} == {}'.format(k, v))\n df_filtered = df.query(' and '.join(query))\n return df_filtered\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--init', action='store_true')\n parser.add_argument('--isTest', action='store_true')\n parser.add_argument('--auto-dir', type=str, help=\n 'path to dir which includes gaussian, gaussview and csv')\n parser.add_argument('--monomer-name', type=str, help='monomer name')\n parser.add_argument('--num-nodes', type=int, help='num nodes')\n args = parser.parse_args()\n if args.init:\n print('----initial process----')\n init_process(args)\n print('----main process----')\n main_process(args)\n print('----finish process----')\n",
"step-5": "import os\r\nimport pandas as pd\r\nimport time\r\nimport sys\r\nfrom tqdm import tqdm\r\nsys.path.append(os.path.join(os.environ['HOME'],'Working/interaction/'))\r\nfrom src.make import exec_gjf\r\nfrom src.vdw import vdw_R, get_c_vec_vdw\r\nfrom src.utils import get_E\r\nimport argparse\r\nimport numpy as np\r\nfrom scipy import signal\r\nimport scipy.spatial.distance as distance\r\nimport random\r\n\r\ndef init_process(args):\r\n auto_dir = args.auto_dir\r\n monomer_name = args.monomer_name\r\n \r\n os.makedirs(os.path.join(auto_dir,'gaussian'), exist_ok=True)\r\n os.makedirs(os.path.join(auto_dir,'gaussview'), exist_ok=True)\r\n\r\n def get_init_para_csv(auto_dir,monomer_name):\r\n init_params_csv = os.path.join(auto_dir, 'step3-twist_init_params.csv')\r\n df = pd.read_csv('/home/koyama/Working/interaction/{}/step2-twist/step2-twist_min.csv'.format(monomer_name))\r\n# df = df[(df[\"A2\"]==30)&(df[\"A1\"]<=0)&(df[\"A1\"]>=-10)&(df[\"theta\"]>45)]\r\n df = df[(df[\"A2\"]==32)&(df[\"A1\"]<=0)&(df[\"A1\"]>=-20)&(df[\"theta\"]>45)]\r\n \r\n inner_zip = df[['a','b','theta','A1','A2']].values\r\n print(inner_zip)\r\n init_para_list = []\r\n for a,b,theta,A1,A2 in tqdm(inner_zip):\r\n c = get_c_vec_vdw(monomer_name,A1,A2,a,b,theta)\r\n init_para_list.append([np.round(a,1),np.round(b,1),theta,A1,A2,np.round(c[0],1),np.round(c[1],1),np.round(c[2],1),'NotYet'])\r\n \r\n df_init_params = pd.DataFrame(np.array(init_para_list),columns = ['a','b','theta','A1','A2','cx','cy','cz','status'])\r\n df_init_params.to_csv(init_params_csv,index=False)\r\n \r\n get_init_para_csv(auto_dir,monomer_name)\r\n \r\n auto_csv_path = os.path.join(auto_dir,'step3-twist.csv')\r\n if not os.path.exists(auto_csv_path): \r\n df_E = pd.DataFrame(columns = ['a','b','theta','A1','A2','cx','cy','cz','E','E_p','E_t','machine_type','status','file_name'])\r\n else:\r\n df_E = pd.read_csv(auto_csv_path)\r\n df_E = df_E[df_E['status']!='InProgress']\r\n df_E.to_csv(auto_csv_path,index=False)\r\n\r\n df_init=pd.read_csv(os.path.join(auto_dir,'step3-twist_init_params.csv'))\r\n df_init['status']='NotYet'\r\n df_init.to_csv(os.path.join(auto_dir,'step3-twist_init_params.csv'),index=False)\r\n\r\ndef main_process(args):\r\n os.chdir(os.path.join(args.auto_dir,'gaussian'))\r\n isOver = False\r\n while not(isOver):\r\n #check\r\n isOver = listen(args)\r\n time.sleep(1)\r\n\r\ndef listen(args):\r\n auto_dir = args.auto_dir\r\n monomer_name = args.monomer_name\r\n num_nodes = args.num_nodes\r\n isTest = args.isTest\r\n fixed_param_keys = ['A1','A2']\r\n opt_param_keys = ['a','b','theta','cx','cy','cz']\r\n\r\n auto_step2_csv = '/home/koyama/Working/interaction/{}/step2-twist/step2-twist.csv'.format(monomer_name)\r\n df_step2 = pd.read_csv(auto_step2_csv)\r\n \r\n auto_csv = os.path.join(auto_dir,'step3-twist.csv')\r\n df_E = pd.read_csv(auto_csv)\r\n df_queue = df_E.loc[df_E['status']=='InProgress',['machine_type','file_name','A1','A2','a','b','theta','cx','cy','cz']]\r\n machine_type_list = df_queue['machine_type'].values.tolist()\r\n len_queue = len(df_queue)\r\n maxnum_machine2 = 3#int(num_nodes/2)\r\n \r\n for idx,row in zip(df_queue.index,df_queue.values):\r\n machine_type,file_name,A1,A2,a,b,theta,cx,cy,cz = row\r\n log_filepath = os.path.join(*[auto_dir,'gaussian',file_name])\r\n if not(os.path.exists(log_filepath)):#logファイルが生成される直前だとまずいので\r\n continue\r\n E_list=get_E(log_filepath)\r\n if len(E_list)!=5:\r\n continue\r\n else:\r\n len_queue-=1;machine_type_list.remove(machine_type)\r\n Ei0,Eip1,Eip2,Eit1,Eit2=map(float,E_list)\r\n Eit3 = Eit2; Eit4 = Eit1\r\n try:\r\n Ep, Et = df_step2[(df_step2['A1']==A1)&(df_step2['A2']==A2)&(df_step2['theta']==theta)&(df_step2['a']==a)&(df_step2['b']==b)][['E_p','E_t']].values[0]\r\n except IndexError:\r\n inner_params_dict = {\"A1\":A1,\"A2\":A2,\"a\":a,\"b\":b,\"theta\":theta,'cx':0,'cy':0,'cz':0}\r\n inner_file_name = exec_gjf(auto_dir, monomer_name, inner_params_dict, machine_type,isInterlayer=False,isTest=isTest)\r\n time.sleep(200)#1:40で1計算終わる\r\n is_inner_over = False\r\n while not(is_inner_over):\r\n time.sleep(30)#1:40で1計算終わる\r\n E_inner_list=get_E(inner_file_name)\r\n is_inner_over = len(E_inner_list)==2\r\n Ep, Et=map(float,E_inner_list)\r\n df_newline = pd.Series({**inner_params_dict,'E':2*Ep+4*Et,'E_p':Ep,'E_t':Et,'machine_type':machine_type,'status':'Done','file_name':inner_file_name})\r\n df_step2=df_step2.append(df_newline,ignore_index=True)\r\n df_step2.to_csv(auto_step2_csv,index=False)\r\n \r\n E = 4*Et + 2*Ep + 2*(Ei0 + Eip1+ Eip2 + Eit1 + Eit2 + Eit3 + Eit4)\r\n df_E.loc[idx, ['E_p','E_t','E_i0','E_ip1','E_ip2','E_it1','E_it2','E_it3','E_it4','E','status']] = [Ep,Et,Ei0,Eip1,Eip2,Eit1,Eit2,Eit3,Eit4,E,'Done']\r\n df_E.to_csv(auto_csv,index=False)\r\n break#2つ同時に計算終わったりしたらまずいので一個で切る\r\n isAvailable = len_queue < num_nodes \r\n machine2IsFull = machine_type_list.count(2) >= maxnum_machine2\r\n machine_type = 1 if machine2IsFull else 2\r\n if isAvailable:\r\n params_dict = get_params_dict(auto_dir,num_nodes, fixed_param_keys, opt_param_keys, monomer_name)\r\n if len(params_dict)!=0:#終わりがまだ見えないなら\r\n alreadyCalculated = check_calc_status(auto_dir,params_dict)\r\n if not(alreadyCalculated):\r\n file_name = exec_gjf(auto_dir, monomer_name, {**params_dict}, machine_type,isInterlayer=True,isTest=isTest)\r\n df_newline = pd.Series({**params_dict,'E':0.,'E_p':0.,'E_t':0.,'E_i0':0.,'E_ip1':0.,'E_ip2':0.,'E_it1':0.,'E_it2':0.,'E_it3':0.,'E_it4':0.,'machine_type':machine_type,'status':'InProgress','file_name':file_name})\r\n df_E=df_E.append(df_newline,ignore_index=True)\r\n df_E.to_csv(auto_csv,index=False)\r\n \r\n init_params_csv=os.path.join(auto_dir, 'step3-twist_init_params.csv')\r\n df_init_params = pd.read_csv(init_params_csv)\r\n df_init_params_done = filter_df(df_init_params,{'status':'Done'})\r\n isOver = True if len(df_init_params_done)==len(df_init_params) else False\r\n return isOver\r\n\r\ndef check_calc_status(auto_dir,params_dict):\r\n df_E= pd.read_csv(os.path.join(auto_dir,'step3-twist.csv'))\r\n if len(df_E)==0:\r\n return False\r\n df_E_filtered = filter_df(df_E, params_dict)\r\n df_E_filtered = df_E_filtered.reset_index(drop=True)\r\n try:\r\n status = get_values_from_df(df_E_filtered,0,'status')\r\n return status=='Done'\r\n except KeyError:\r\n return False\r\n\r\ndef get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys, monomer_name):\r\n \"\"\"\r\n 前提:\r\n step3-twist_init_params.csvとstep3-twist.csvがauto_dirの下にある\r\n \"\"\"\r\n init_params_csv=os.path.join(auto_dir, 'step3-twist_init_params.csv')\r\n df_init_params = pd.read_csv(init_params_csv)\r\n df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))\r\n df_init_params_inprogress = df_init_params[df_init_params['status']=='InProgress']\r\n \r\n #最初の立ち上がり時\r\n if len(df_init_params_inprogress) < num_nodes:\r\n df_init_params_notyet = df_init_params[df_init_params['status']=='NotYet']\r\n for index in df_init_params_notyet.index:\r\n df_init_params = update_value_in_df(df_init_params,index,'status','InProgress')\r\n df_init_params.to_csv(init_params_csv,index=False)\r\n params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()\r\n return params_dict\r\n for index in df_init_params.index:\r\n df_init_params = pd.read_csv(init_params_csv)\r\n init_params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()\r\n fixed_params_dict = df_init_params.loc[index,fixed_param_keys].to_dict()\r\n isDone, opt_params_dict = get_opt_params_dict(df_cur, init_params_dict,fixed_params_dict, monomer_name)\r\n if isDone:\r\n # df_init_paramsのstatusをupdate\r\n df_init_params = update_value_in_df(df_init_params,index,'status','Done')\r\n if np.max(df_init_params.index) < index+1:\r\n status = 'Done'\r\n else:\r\n status = get_values_from_df(df_init_params,index+1,'status')\r\n df_init_params.to_csv(init_params_csv,index=False)\r\n \r\n if status=='NotYet': \r\n opt_params_dict = get_values_from_df(df_init_params,index+1,opt_param_keys)\r\n df_init_params = update_value_in_df(df_init_params,index+1,'status','InProgress')\r\n df_init_params.to_csv(init_params_csv,index=False)\r\n return {**fixed_params_dict,**opt_params_dict}\r\n else:\r\n continue\r\n\r\n else:\r\n df_inprogress = filter_df(df_cur, {**fixed_params_dict,**opt_params_dict,'status':'InProgress'})\r\n if len(df_inprogress)>=1:\r\n continue\r\n return {**fixed_params_dict,**opt_params_dict}\r\n return {}\r\n \r\ndef get_opt_params_dict(df_cur, init_params_dict,fixed_params_dict, monomer_name):\r\n df_val = filter_df(df_cur, fixed_params_dict)\r\n a_init_prev = init_params_dict['a']; b_init_prev = init_params_dict['b']; theta_init_prev = init_params_dict['theta']\r\n A1 = init_params_dict['A1']; A2 = init_params_dict['A2']\r\n \r\n while True:\r\n E_list=[];heri_list=[]\r\n for a in [a_init_prev-0.1,a_init_prev,a_init_prev+0.1]:\r\n for b in [b_init_prev-0.1,b_init_prev,b_init_prev+0.1]:\r\n a = np.round(a,1);b = np.round(b,1)\r\n for theta in [theta_init_prev-0.5,theta_init_prev,theta_init_prev+0.5]:\r\n df_val_ab = df_val[\r\n (df_val['a']==a)&(df_val['b']==b)&(df_val['theta']==theta)&\r\n (df_val['A1']==A1)&(df_val['A2']==A2)&\r\n (df_val['status']=='Done')\r\n ]\r\n if len(df_val_ab)==0:\r\n cx, cy, cz = get_c_vec_vdw(monomer_name,A1,A2,a,b,theta)\r\n cx, cy, cz = np.round(cx,1), np.round(cy,1), np.round(cz,1)\r\n return False,{'a':a,'b':b,'theta':theta, \"cx\":cx, \"cy\":cy, \"cz\":cz }\r\n heri_list.append([a,b,theta]);E_list.append(df_val_ab['E'].values[0])\r\n a_init,b_init,theta_init = heri_list[np.argmin(np.array(E_list))]\r\n if a_init==a_init_prev and b_init==b_init_prev and theta_init==theta_init_prev:\r\n cx, cy, cz = get_c_vec_vdw(monomer_name,A1,A2,a_init,b_init,theta_init)\r\n cx, cy, cz = np.round(cx,1), np.round(cy,1), np.round(cz,1)\r\n return True,{'a':a_init,'b':b_init, 'theta':theta_init, \"cx\":cx, \"cy\":cy, \"cz\":cz }\r\n else:\r\n a_init_prev=a_init;b_init_prev=b_init;theta_init_prev=theta_init\r\n \r\ndef get_values_from_df(df,index,key):\r\n return df.loc[index,key]\r\n\r\ndef update_value_in_df(df,index,key,value):\r\n df.loc[index,key]=value\r\n return df\r\n\r\ndef filter_df(df, dict_filter):\r\n query = []\r\n for k, v in dict_filter.items():\r\n if type(v)==str:\r\n query.append('{} == \"{}\"'.format(k,v))\r\n else:\r\n query.append('{} == {}'.format(k,v))\r\n df_filtered = df.query(' and '.join(query))\r\n return df_filtered\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n \r\n parser.add_argument('--init',action='store_true')\r\n parser.add_argument('--isTest',action='store_true')\r\n parser.add_argument('--auto-dir',type=str,help='path to dir which includes gaussian, gaussview and csv')\r\n parser.add_argument('--monomer-name',type=str,help='monomer name')\r\n parser.add_argument('--num-nodes',type=int,help='num nodes')\r\n \r\n args = parser.parse_args()\r\n\r\n if args.init:\r\n print(\"----initial process----\")\r\n init_process(args)\r\n \r\n print(\"----main process----\")\r\n main_process(args)\r\n print(\"----finish process----\")\r\n ",
"step-ids": [
3,
7,
9,
10,
12
]
}
|
[
3,
7,
9,
10,
12
] |
<|reserved_special_token_0|>
def test_verify_home_page(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')
eyes.check('FZ IBE Home page', Target.window())
eyes.close(False)
<|reserved_special_token_0|>
def test_verify_manage_booking_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_checkin_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_flight_status_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_verify_home_page(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')
eyes.check('FZ IBE Home page', Target.window())
eyes.close(False)
<|reserved_special_token_0|>
def test_verify_manage_booking_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_checkin_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_flight_status_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_search_ow_results_page(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper .radio-oneway-div').click()
driver.find_element_by_css_selector(
'div.widgetBoxWrapper #airport-destination').click()
driver.find_element_by_css_selector(
".DestinationAirlist li[data-value='MCT']").click()
driver.execute_script(
'date = new Date();date.setDate(date.getDate()+20);document.getElementById("FormModel_DepartureDate").value=""+date'
)
driver.find_element_by_css_selector(
"div.widgetBoxWrapper input[value='Search']").click()
WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By
.CSS_SELECTOR, '.tripSummaryBox')))
eyes.check('FZ Manage Booking Widget', Target.window())
eyes.close(False)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_verify_home_page(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')
eyes.check('FZ IBE Home page', Target.window())
eyes.close(False)
def test_verify_search_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Search Widget')
eyes.check('FZ Search Widget', Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_manage_booking_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_checkin_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_flight_status_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_search_ow_results_page(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper .radio-oneway-div').click()
driver.find_element_by_css_selector(
'div.widgetBoxWrapper #airport-destination').click()
driver.find_element_by_css_selector(
".DestinationAirlist li[data-value='MCT']").click()
driver.execute_script(
'date = new Date();date.setDate(date.getDate()+20);document.getElementById("FormModel_DepartureDate").value=""+date'
)
driver.find_element_by_css_selector(
"div.widgetBoxWrapper input[value='Search']").click()
WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By
.CSS_SELECTOR, '.tripSummaryBox')))
eyes.check('FZ Manage Booking Widget', Target.window())
eyes.close(False)
<|reserved_special_token_1|>
from applitools.selenium import Target, eyes
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
def test_verify_home_page(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')
eyes.check('FZ IBE Home page', Target.window())
eyes.close(False)
def test_verify_search_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Search Widget')
eyes.check('FZ Search Widget', Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_manage_booking_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_checkin_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_flight_status_widget(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()
eyes.check('FZ Manage Booking Widget', Target.region(
'div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_search_ow_results_page(eyes, driver):
eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')
driver.find_element_by_css_selector(
'div.widgetBoxWrapper .radio-oneway-div').click()
driver.find_element_by_css_selector(
'div.widgetBoxWrapper #airport-destination').click()
driver.find_element_by_css_selector(
".DestinationAirlist li[data-value='MCT']").click()
driver.execute_script(
'date = new Date();date.setDate(date.getDate()+20);document.getElementById("FormModel_DepartureDate").value=""+date'
)
driver.find_element_by_css_selector(
"div.widgetBoxWrapper input[value='Search']").click()
WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By
.CSS_SELECTOR, '.tripSummaryBox')))
eyes.check('FZ Manage Booking Widget', Target.window())
eyes.close(False)
<|reserved_special_token_1|>
from applitools.selenium import Target, eyes
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
def test_verify_home_page(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Home Page")
eyes.check("FZ IBE Home page", Target.window())
eyes.close(False)
def test_verify_search_widget(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Search Widget")
eyes.check("FZ Search Widget", Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_manage_booking_widget(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Manage Booking Widget")
driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(2)').click()
eyes.check("FZ Manage Booking Widget", Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_checkin_widget(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Checkin Widget")
driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(3)').click()
eyes.check("FZ Manage Booking Widget", Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_flight_status_widget(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Flight Status Widget")
driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(4)').click()
eyes.check("FZ Manage Booking Widget", Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_search_ow_results_page(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Flight listing page")
driver.find_element_by_css_selector('div.widgetBoxWrapper .radio-oneway-div').click()
driver.find_element_by_css_selector('div.widgetBoxWrapper #airport-destination').click()
driver.find_element_by_css_selector('.DestinationAirlist li[data-value=\'MCT\']').click()
driver.execute_script('date = new Date();date.setDate(date.getDate()+20);document.getElementById("FormModel_DepartureDate").value=""+date')
driver.find_element_by_css_selector("div.widgetBoxWrapper input[value='Search']").click()
WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.tripSummaryBox')))
eyes.check("FZ Manage Booking Widget", Target.window())
eyes.close(False)
|
flexible
|
{
"blob_id": "021efe01c21db4d3bd936ba4eb75dc03dde91cc6",
"index": 1475,
"step-1": "<mask token>\n\n\ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')\n eyes.check('FZ IBE Home page', Target.window())\n eyes.close(False)\n\n\n<mask token>\n\n\ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')\n eyes.check('FZ IBE Home page', Target.window())\n eyes.close(False)\n\n\n<mask token>\n\n\ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_search_ow_results_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper .radio-oneway-div').click()\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper #airport-destination').click()\n driver.find_element_by_css_selector(\n \".DestinationAirlist li[data-value='MCT']\").click()\n driver.execute_script(\n 'date = new Date();date.setDate(date.getDate()+20);document.getElementById(\"FormModel_DepartureDate\").value=\"\"+date'\n )\n driver.find_element_by_css_selector(\n \"div.widgetBoxWrapper input[value='Search']\").click()\n WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By\n .CSS_SELECTOR, '.tripSummaryBox')))\n eyes.check('FZ Manage Booking Widget', Target.window())\n eyes.close(False)\n",
"step-3": "<mask token>\n\n\ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')\n eyes.check('FZ IBE Home page', Target.window())\n eyes.close(False)\n\n\ndef test_verify_search_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Search Widget')\n eyes.check('FZ Search Widget', Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_search_ow_results_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper .radio-oneway-div').click()\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper #airport-destination').click()\n driver.find_element_by_css_selector(\n \".DestinationAirlist li[data-value='MCT']\").click()\n driver.execute_script(\n 'date = new Date();date.setDate(date.getDate()+20);document.getElementById(\"FormModel_DepartureDate\").value=\"\"+date'\n )\n driver.find_element_by_css_selector(\n \"div.widgetBoxWrapper input[value='Search']\").click()\n WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By\n .CSS_SELECTOR, '.tripSummaryBox')))\n eyes.check('FZ Manage Booking Widget', Target.window())\n eyes.close(False)\n",
"step-4": "from applitools.selenium import Target, eyes\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')\n eyes.check('FZ IBE Home page', Target.window())\n eyes.close(False)\n\n\ndef test_verify_search_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Search Widget')\n eyes.check('FZ Search Widget', Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_search_ow_results_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper .radio-oneway-div').click()\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper #airport-destination').click()\n driver.find_element_by_css_selector(\n \".DestinationAirlist li[data-value='MCT']\").click()\n driver.execute_script(\n 'date = new Date();date.setDate(date.getDate()+20);document.getElementById(\"FormModel_DepartureDate\").value=\"\"+date'\n )\n driver.find_element_by_css_selector(\n \"div.widgetBoxWrapper input[value='Search']\").click()\n WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By\n .CSS_SELECTOR, '.tripSummaryBox')))\n eyes.check('FZ Manage Booking Widget', Target.window())\n eyes.close(False)\n",
"step-5": "from applitools.selenium import Target, eyes\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n \ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Home Page\")\n eyes.check(\"FZ IBE Home page\", Target.window())\n eyes.close(False)\n \ndef test_verify_search_widget(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Search Widget\")\n eyes.check(\"FZ Search Widget\", Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n \ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Manage Booking Widget\")\n driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check(\"FZ Manage Booking Widget\", Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n \ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Checkin Widget\")\n driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check(\"FZ Manage Booking Widget\", Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n \ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Flight Status Widget\")\n driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check(\"FZ Manage Booking Widget\", Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n \ndef test_verify_search_ow_results_page(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Flight listing page\")\n driver.find_element_by_css_selector('div.widgetBoxWrapper .radio-oneway-div').click()\n driver.find_element_by_css_selector('div.widgetBoxWrapper #airport-destination').click()\n driver.find_element_by_css_selector('.DestinationAirlist li[data-value=\\'MCT\\']').click()\n driver.execute_script('date = new Date();date.setDate(date.getDate()+20);document.getElementById(\"FormModel_DepartureDate\").value=\"\"+date')\n driver.find_element_by_css_selector(\"div.widgetBoxWrapper input[value='Search']\").click()\n WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.tripSummaryBox')))\n eyes.check(\"FZ Manage Booking Widget\", Target.window())\n eyes.close(False)",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
import os
from unittest import TestCase
class TestMixin(TestCase):
@classmethod
def setUpClass(cls):
cls.base_dir = os.path.dirname(os.path.abspath(__file__))
cls.fixtures_dir = os.path.join(cls.base_dir, 'fixtures')
cls.bam_10xv2_path = os.path.join(cls.fixtures_dir, '10xv2.bam')
cls.fastq_10xv2_paths = [os.path.join(cls.fixtures_dir,
'10xv2_1.fastq.gz'), os.path.join(cls.fixtures_dir,
'10xv2_2.fastq.gz')]
|
normal
|
{
"blob_id": "268a8252f74a2bdafdadae488f98997c91f5607c",
"index": 2686,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass TestMixin(TestCase):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass TestMixin(TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.base_dir = os.path.dirname(os.path.abspath(__file__))\n cls.fixtures_dir = os.path.join(cls.base_dir, 'fixtures')\n cls.bam_10xv2_path = os.path.join(cls.fixtures_dir, '10xv2.bam')\n cls.fastq_10xv2_paths = [os.path.join(cls.fixtures_dir,\n '10xv2_1.fastq.gz'), os.path.join(cls.fixtures_dir,\n '10xv2_2.fastq.gz')]\n",
"step-4": "import os\nfrom unittest import TestCase\n\n\nclass TestMixin(TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.base_dir = os.path.dirname(os.path.abspath(__file__))\n cls.fixtures_dir = os.path.join(cls.base_dir, 'fixtures')\n cls.bam_10xv2_path = os.path.join(cls.fixtures_dir, '10xv2.bam')\n cls.fastq_10xv2_paths = [os.path.join(cls.fixtures_dir,\n '10xv2_1.fastq.gz'), os.path.join(cls.fixtures_dir,\n '10xv2_2.fastq.gz')]\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import numpy as np
import matplotlib.pyplot as plt
import csv
category = ["Ecological Well-being", "Health & Human Services", "Arts & Culture", "Community Building", "Environment"]
arr = np.empty((0, 6), str)
moneyGranted = [[0]*5 for _ in range(6)]
moneyRequested = [[0]*5 for _ in range(6)]
perFull = [[0]*5 for _ in range(6)]
def task5(arr): # function definition; be sure to add your task number after 'task'
# Write your code here
for row in arr:
moneyGranted[int(row[1])-2015][int(row[3])-1] += int(row[4])
moneyRequested[int(row[1])-2015][int(row[3])-1] += int(row[5])
for i in range(6):
for j in range(5):
if moneyRequested[i][j] == 0:
print(i+2015,",",category[j],":", "0.0%")
else:
perFull[i][j] = round((moneyGranted[i][j] / moneyRequested[i][j])*100, 2)
print(i+2015,",",category[j],":", perFull[i][j],"%")
for i in range(6):
graphTitle = "Percentage fulfilled for each category in " + str(i+2015)
plt.title(graphTitle)
plt.bar(category, perFull[i])
plt.show()
with open('CEL_HistoricalGrantInformation_2014-7Oct2020_CSV.csv', newline='') as csvfile: # reading the csv file
reader = csv.DictReader(csvfile)
for row in reader:
arr = np.append(arr, np.array([[row['organization_id'], int(row['year_id']), row['process_id'],
int(row['area_id']), int(row['awarded_id']), int(row['requested_id'])]]), axis=0)
#print(arr)
task5(arr)
|
normal
|
{
"blob_id": "e7b2e716fbcaf761e119003000bf1b16af57a2b7",
"index": 7009,
"step-1": "<mask token>\n\n\ndef task5(arr):\n for row in arr:\n moneyGranted[int(row[1]) - 2015][int(row[3]) - 1] += int(row[4])\n moneyRequested[int(row[1]) - 2015][int(row[3]) - 1] += int(row[5])\n for i in range(6):\n for j in range(5):\n if moneyRequested[i][j] == 0:\n print(i + 2015, ',', category[j], ':', '0.0%')\n else:\n perFull[i][j] = round(moneyGranted[i][j] / moneyRequested[i\n ][j] * 100, 2)\n print(i + 2015, ',', category[j], ':', perFull[i][j], '%')\n for i in range(6):\n graphTitle = 'Percentage fulfilled for each category in ' + str(i +\n 2015)\n plt.title(graphTitle)\n plt.bar(category, perFull[i])\n plt.show()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef task5(arr):\n for row in arr:\n moneyGranted[int(row[1]) - 2015][int(row[3]) - 1] += int(row[4])\n moneyRequested[int(row[1]) - 2015][int(row[3]) - 1] += int(row[5])\n for i in range(6):\n for j in range(5):\n if moneyRequested[i][j] == 0:\n print(i + 2015, ',', category[j], ':', '0.0%')\n else:\n perFull[i][j] = round(moneyGranted[i][j] / moneyRequested[i\n ][j] * 100, 2)\n print(i + 2015, ',', category[j], ':', perFull[i][j], '%')\n for i in range(6):\n graphTitle = 'Percentage fulfilled for each category in ' + str(i +\n 2015)\n plt.title(graphTitle)\n plt.bar(category, perFull[i])\n plt.show()\n\n\nwith open('CEL_HistoricalGrantInformation_2014-7Oct2020_CSV.csv', newline=''\n ) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n arr = np.append(arr, np.array([[row['organization_id'], int(row[\n 'year_id']), row['process_id'], int(row['area_id']), int(row[\n 'awarded_id']), int(row['requested_id'])]]), axis=0)\ntask5(arr)\n",
"step-3": "<mask token>\ncategory = ['Ecological Well-being', 'Health & Human Services',\n 'Arts & Culture', 'Community Building', 'Environment']\narr = np.empty((0, 6), str)\nmoneyGranted = [([0] * 5) for _ in range(6)]\nmoneyRequested = [([0] * 5) for _ in range(6)]\nperFull = [([0] * 5) for _ in range(6)]\n\n\ndef task5(arr):\n for row in arr:\n moneyGranted[int(row[1]) - 2015][int(row[3]) - 1] += int(row[4])\n moneyRequested[int(row[1]) - 2015][int(row[3]) - 1] += int(row[5])\n for i in range(6):\n for j in range(5):\n if moneyRequested[i][j] == 0:\n print(i + 2015, ',', category[j], ':', '0.0%')\n else:\n perFull[i][j] = round(moneyGranted[i][j] / moneyRequested[i\n ][j] * 100, 2)\n print(i + 2015, ',', category[j], ':', perFull[i][j], '%')\n for i in range(6):\n graphTitle = 'Percentage fulfilled for each category in ' + str(i +\n 2015)\n plt.title(graphTitle)\n plt.bar(category, perFull[i])\n plt.show()\n\n\nwith open('CEL_HistoricalGrantInformation_2014-7Oct2020_CSV.csv', newline=''\n ) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n arr = np.append(arr, np.array([[row['organization_id'], int(row[\n 'year_id']), row['process_id'], int(row['area_id']), int(row[\n 'awarded_id']), int(row['requested_id'])]]), axis=0)\ntask5(arr)\n",
"step-4": "import numpy as np\nimport matplotlib.pyplot as plt\nimport csv\ncategory = ['Ecological Well-being', 'Health & Human Services',\n 'Arts & Culture', 'Community Building', 'Environment']\narr = np.empty((0, 6), str)\nmoneyGranted = [([0] * 5) for _ in range(6)]\nmoneyRequested = [([0] * 5) for _ in range(6)]\nperFull = [([0] * 5) for _ in range(6)]\n\n\ndef task5(arr):\n for row in arr:\n moneyGranted[int(row[1]) - 2015][int(row[3]) - 1] += int(row[4])\n moneyRequested[int(row[1]) - 2015][int(row[3]) - 1] += int(row[5])\n for i in range(6):\n for j in range(5):\n if moneyRequested[i][j] == 0:\n print(i + 2015, ',', category[j], ':', '0.0%')\n else:\n perFull[i][j] = round(moneyGranted[i][j] / moneyRequested[i\n ][j] * 100, 2)\n print(i + 2015, ',', category[j], ':', perFull[i][j], '%')\n for i in range(6):\n graphTitle = 'Percentage fulfilled for each category in ' + str(i +\n 2015)\n plt.title(graphTitle)\n plt.bar(category, perFull[i])\n plt.show()\n\n\nwith open('CEL_HistoricalGrantInformation_2014-7Oct2020_CSV.csv', newline=''\n ) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n arr = np.append(arr, np.array([[row['organization_id'], int(row[\n 'year_id']), row['process_id'], int(row['area_id']), int(row[\n 'awarded_id']), int(row['requested_id'])]]), axis=0)\ntask5(arr)\n",
"step-5": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\n\r\ncategory = [\"Ecological Well-being\", \"Health & Human Services\", \"Arts & Culture\", \"Community Building\", \"Environment\"]\r\narr = np.empty((0, 6), str)\r\nmoneyGranted = [[0]*5 for _ in range(6)]\r\nmoneyRequested = [[0]*5 for _ in range(6)]\r\nperFull = [[0]*5 for _ in range(6)]\r\n\r\n\r\ndef task5(arr): # function definition; be sure to add your task number after 'task'\r\n # Write your code here\r\n\r\n for row in arr:\r\n moneyGranted[int(row[1])-2015][int(row[3])-1] += int(row[4])\r\n moneyRequested[int(row[1])-2015][int(row[3])-1] += int(row[5]) \r\n \r\n for i in range(6):\r\n for j in range(5):\r\n if moneyRequested[i][j] == 0:\r\n print(i+2015,\",\",category[j],\":\", \"0.0%\")\r\n else:\r\n perFull[i][j] = round((moneyGranted[i][j] / moneyRequested[i][j])*100, 2)\r\n print(i+2015,\",\",category[j],\":\", perFull[i][j],\"%\")\r\n for i in range(6):\r\n graphTitle = \"Percentage fulfilled for each category in \" + str(i+2015) \r\n plt.title(graphTitle) \r\n plt.bar(category, perFull[i]) \r\n plt.show() \r\n\r\n \r\n\r\nwith open('CEL_HistoricalGrantInformation_2014-7Oct2020_CSV.csv', newline='') as csvfile: # reading the csv file\r\n reader = csv.DictReader(csvfile)\r\n for row in reader:\r\n arr = np.append(arr, np.array([[row['organization_id'], int(row['year_id']), row['process_id'],\r\n int(row['area_id']), int(row['awarded_id']), int(row['requested_id'])]]), axis=0)\r\n\r\n #print(arr)\r\n\r\ntask5(arr)\r\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#Function to remove spaces in a string
def remove(string_input):
return string_input.replace(" ", "")
|
normal
|
{
"blob_id": "f327f408ae2759407ac9f01ad4feff5c6a0845f1",
"index": 9524,
"step-1": "<mask token>\n",
"step-2": "def remove(string_input):\n return string_input.replace(' ', '')\n",
"step-3": "#Function to remove spaces in a string\n\ndef remove(string_input):\n return string_input.replace(\" \", \"\")\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
#tkinter:Label 、Button 、标签、按钮
#详见:
#1、os:https://blog.csdn.net/xxlovesht/article/details/80913193
#2、shutil:https://www.jb51.net/article/157891.htm
#3、tkinter:https://blog.csdn.net/mingshao104/article/details/79591965
# https://blog.csdn.net/sinat_41104353/article/details/79313424
# https://blog.csdn.net/Bugest/article/details/81557112
#import : 使用import xx 可以修改模块对象的属性(无论属性是不是可变类型)
#from xx import x使用from xx import x 只能修改模块对象的属性是可变类型的(不可变类型不能修改,会发生属性错误)
#===========================================《import》======================================================
import re
import os
import shutil
import tkinter as tk
from tkinter import filedialog
import tkinter.messagebox #弹窗库
import sys
import datetime
import socket
curPyDirect = os.getcwd()#获取当前fileOperation.py的路径
curSysTime = datetime.datetime.now().strftime('%F %T')#获取当前系统时间 字符类型 str
#===========================================《window》===========================================
window=tk.Tk()#指定tkinter窗口
window.title('my window')#tkinter窗口名字
window.geometry('600x300')#tkinter窗口大小
#===========================================《Menu》===========================================
#for item in ['新建', '打开', '保存', '另存为']:
# fmenu1.add_command(label=item,command=File_Deal_Event)# 如果该菜单是顶层菜单的一个菜单项,则它添加的是下拉菜单的菜单项。
#===========================================《Menu》 1st:指定一个菜单项,类似于导航栏,顶层菜单
menubar=tk.Menu(window)#指定tkinter菜单
def File_Open_EventC():
#FolderPath = filedialog.askdirectory()#打开提示框,选则文件夹,输出文件夹绝对路径
FilePath = filedialog.askopenfilename(filetypes=( ("C file", "*.c*"),("Text file", "*.txt*"),("HTML files", "*.html;*.htm")))#打开提示框,选则文件,输出文件绝对路径
fp = open(FilePath, 'r')
flag_1 = 0#原括弧
slash_char = '/'
slash_flag = 0
slash_char2 = '/'
slash_flag2 = 0
star_char='*'
star_flag = 0
s1 = []
for s in fp.readlines():
#1.排除/* */
slash_flag = s.find(slash_char)
#1.1 /
if (slash_flag != -1 ):#找到了/
#1.2 *
star_flag = s.find(star_char)
if( star_flag!=-1):#找到了*
if(star_flag - slash_flag == 1):#找到了/*
print(s)
star_flag = 0
slash_flag = 0
slash_flag2 = 0
else:
star_flag = 0
#1.3 /
slash_flag2 = s.find(slash_char2)
if (slash_flag2 != -1 ):
if(slash_flag2 - slash_flag == 1):#找到了//
print(s)
star_flag = 0
slash_flag = 0
slash_flag2 = 0
else:
slash_flag2 = 0
else:
slash_flag = 0
fp.close()
#===========================================《Menu》 2nd:创建菜单栏
#=================第1个菜单项:
fmenu1 = tk.Menu(window)
fmenu1.add_command(label='新建',command=None)
fmenu1.add_command(label='打开',command=File_Open_EventC)
fmenu1.add_command(label='保存',command=None)
fmenu1.add_command(label='另存为',command=None)
#=================第2个菜单项:
fmenu2 = tk.Menu(window)
for item in ['复制', '粘贴', '剪切']:
fmenu2.add_command(label=item)
#=================第3个菜单项:
fmenu3 = tk.Menu(window)
for item in ['默认视图', '新式视图']:
fmenu3.add_command(label=item)
#=================第4个菜单项:
fmenu4 = tk.Menu(window)
fmenu4.add_command(label='版权信息',command=None)
fmenu4.add_command(label='其他说明',command=None)
#===========================================《Menu》 3rd:级联菜单栏
# add_cascade 的一个很重要的属性就是 menu 属性,它指明了要把那个菜单级联到该菜单项上,
# 当然,还必不可少的就是 label 属性,用于指定该菜单项的名称
menubar.add_cascade(label="文件", menu=fmenu1)#菜单项:文件
menubar.add_cascade(label="编辑", menu=fmenu2)#菜单项:编辑
menubar.add_cascade(label="视图", menu=fmenu3)#菜单项:视图
menubar.add_cascade(label="关于", menu=fmenu4)#菜单项:关于
#===========================================《Menu》 4th:激活菜单
#最后可以用窗口的 menu 属性指定我们使用哪一个作为它的顶层菜单
window.config(menu=menubar)
#===============================激活窗口
window.mainloop()
|
normal
|
{
"blob_id": "6c0ca72d7f5d2373a50cd344991ad9f9e3046e8d",
"index": 4087,
"step-1": "<mask token>\n\n\ndef File_Open_EventC():\n FilePath = filedialog.askopenfilename(filetypes=(('C file', '*.c*'), (\n 'Text file', '*.txt*'), ('HTML files', '*.html;*.htm')))\n fp = open(FilePath, 'r')\n flag_1 = 0\n slash_char = '/'\n slash_flag = 0\n slash_char2 = '/'\n slash_flag2 = 0\n star_char = '*'\n star_flag = 0\n s1 = []\n for s in fp.readlines():\n slash_flag = s.find(slash_char)\n if slash_flag != -1:\n star_flag = s.find(star_char)\n if star_flag != -1:\n if star_flag - slash_flag == 1:\n print(s)\n star_flag = 0\n slash_flag = 0\n slash_flag2 = 0\n else:\n star_flag = 0\n slash_flag2 = s.find(slash_char2)\n if slash_flag2 != -1:\n if slash_flag2 - slash_flag == 1:\n print(s)\n star_flag = 0\n slash_flag = 0\n slash_flag2 = 0\n else:\n slash_flag2 = 0\n else:\n slash_flag = 0\n fp.close()\n\n\n<mask token>\n",
"step-2": "<mask token>\nwindow.title('my window')\nwindow.geometry('600x300')\n<mask token>\n\n\ndef File_Open_EventC():\n FilePath = filedialog.askopenfilename(filetypes=(('C file', '*.c*'), (\n 'Text file', '*.txt*'), ('HTML files', '*.html;*.htm')))\n fp = open(FilePath, 'r')\n flag_1 = 0\n slash_char = '/'\n slash_flag = 0\n slash_char2 = '/'\n slash_flag2 = 0\n star_char = '*'\n star_flag = 0\n s1 = []\n for s in fp.readlines():\n slash_flag = s.find(slash_char)\n if slash_flag != -1:\n star_flag = s.find(star_char)\n if star_flag != -1:\n if star_flag - slash_flag == 1:\n print(s)\n star_flag = 0\n slash_flag = 0\n slash_flag2 = 0\n else:\n star_flag = 0\n slash_flag2 = s.find(slash_char2)\n if slash_flag2 != -1:\n if slash_flag2 - slash_flag == 1:\n print(s)\n star_flag = 0\n slash_flag = 0\n slash_flag2 = 0\n else:\n slash_flag2 = 0\n else:\n slash_flag = 0\n fp.close()\n\n\n<mask token>\nfmenu1.add_command(label='新建', command=None)\nfmenu1.add_command(label='打开', command=File_Open_EventC)\nfmenu1.add_command(label='保存', command=None)\nfmenu1.add_command(label='另存为', command=None)\n<mask token>\nfor item in ['复制', '粘贴', '剪切']:\n fmenu2.add_command(label=item)\n<mask token>\nfor item in ['默认视图', '新式视图']:\n fmenu3.add_command(label=item)\n<mask token>\nfmenu4.add_command(label='版权信息', command=None)\nfmenu4.add_command(label='其他说明', command=None)\nmenubar.add_cascade(label='文件', menu=fmenu1)\nmenubar.add_cascade(label='编辑', menu=fmenu2)\nmenubar.add_cascade(label='视图', menu=fmenu3)\nmenubar.add_cascade(label='关于', menu=fmenu4)\nwindow.config(menu=menubar)\nwindow.mainloop()\n",
"step-3": "<mask token>\ncurPyDirect = os.getcwd()\ncurSysTime = datetime.datetime.now().strftime('%F %T')\nwindow = tk.Tk()\nwindow.title('my window')\nwindow.geometry('600x300')\nmenubar = tk.Menu(window)\n\n\ndef File_Open_EventC():\n FilePath = filedialog.askopenfilename(filetypes=(('C file', '*.c*'), (\n 'Text file', '*.txt*'), ('HTML files', '*.html;*.htm')))\n fp = open(FilePath, 'r')\n flag_1 = 0\n slash_char = '/'\n slash_flag = 0\n slash_char2 = '/'\n slash_flag2 = 0\n star_char = '*'\n star_flag = 0\n s1 = []\n for s in fp.readlines():\n slash_flag = s.find(slash_char)\n if slash_flag != -1:\n star_flag = s.find(star_char)\n if star_flag != -1:\n if star_flag - slash_flag == 1:\n print(s)\n star_flag = 0\n slash_flag = 0\n slash_flag2 = 0\n else:\n star_flag = 0\n slash_flag2 = s.find(slash_char2)\n if slash_flag2 != -1:\n if slash_flag2 - slash_flag == 1:\n print(s)\n star_flag = 0\n slash_flag = 0\n slash_flag2 = 0\n else:\n slash_flag2 = 0\n else:\n slash_flag = 0\n fp.close()\n\n\nfmenu1 = tk.Menu(window)\nfmenu1.add_command(label='新建', command=None)\nfmenu1.add_command(label='打开', command=File_Open_EventC)\nfmenu1.add_command(label='保存', command=None)\nfmenu1.add_command(label='另存为', command=None)\nfmenu2 = tk.Menu(window)\nfor item in ['复制', '粘贴', '剪切']:\n fmenu2.add_command(label=item)\nfmenu3 = tk.Menu(window)\nfor item in ['默认视图', '新式视图']:\n fmenu3.add_command(label=item)\nfmenu4 = tk.Menu(window)\nfmenu4.add_command(label='版权信息', command=None)\nfmenu4.add_command(label='其他说明', command=None)\nmenubar.add_cascade(label='文件', menu=fmenu1)\nmenubar.add_cascade(label='编辑', menu=fmenu2)\nmenubar.add_cascade(label='视图', menu=fmenu3)\nmenubar.add_cascade(label='关于', menu=fmenu4)\nwindow.config(menu=menubar)\nwindow.mainloop()\n",
"step-4": "import re\nimport os\nimport shutil\nimport tkinter as tk\nfrom tkinter import filedialog\nimport tkinter.messagebox\nimport sys\nimport datetime\nimport socket\ncurPyDirect = os.getcwd()\ncurSysTime = datetime.datetime.now().strftime('%F %T')\nwindow = tk.Tk()\nwindow.title('my window')\nwindow.geometry('600x300')\nmenubar = tk.Menu(window)\n\n\ndef File_Open_EventC():\n FilePath = filedialog.askopenfilename(filetypes=(('C file', '*.c*'), (\n 'Text file', '*.txt*'), ('HTML files', '*.html;*.htm')))\n fp = open(FilePath, 'r')\n flag_1 = 0\n slash_char = '/'\n slash_flag = 0\n slash_char2 = '/'\n slash_flag2 = 0\n star_char = '*'\n star_flag = 0\n s1 = []\n for s in fp.readlines():\n slash_flag = s.find(slash_char)\n if slash_flag != -1:\n star_flag = s.find(star_char)\n if star_flag != -1:\n if star_flag - slash_flag == 1:\n print(s)\n star_flag = 0\n slash_flag = 0\n slash_flag2 = 0\n else:\n star_flag = 0\n slash_flag2 = s.find(slash_char2)\n if slash_flag2 != -1:\n if slash_flag2 - slash_flag == 1:\n print(s)\n star_flag = 0\n slash_flag = 0\n slash_flag2 = 0\n else:\n slash_flag2 = 0\n else:\n slash_flag = 0\n fp.close()\n\n\nfmenu1 = tk.Menu(window)\nfmenu1.add_command(label='新建', command=None)\nfmenu1.add_command(label='打开', command=File_Open_EventC)\nfmenu1.add_command(label='保存', command=None)\nfmenu1.add_command(label='另存为', command=None)\nfmenu2 = tk.Menu(window)\nfor item in ['复制', '粘贴', '剪切']:\n fmenu2.add_command(label=item)\nfmenu3 = tk.Menu(window)\nfor item in ['默认视图', '新式视图']:\n fmenu3.add_command(label=item)\nfmenu4 = tk.Menu(window)\nfmenu4.add_command(label='版权信息', command=None)\nfmenu4.add_command(label='其他说明', command=None)\nmenubar.add_cascade(label='文件', menu=fmenu1)\nmenubar.add_cascade(label='编辑', menu=fmenu2)\nmenubar.add_cascade(label='视图', menu=fmenu3)\nmenubar.add_cascade(label='关于', menu=fmenu4)\nwindow.config(menu=menubar)\nwindow.mainloop()\n",
"step-5": "#tkinter:Label 、Button 、标签、按钮\r\n#详见:\r\n#1、os:https://blog.csdn.net/xxlovesht/article/details/80913193\r\n#2、shutil:https://www.jb51.net/article/157891.htm\r\n#3、tkinter:https://blog.csdn.net/mingshao104/article/details/79591965 \r\n# https://blog.csdn.net/sinat_41104353/article/details/79313424\r\n# https://blog.csdn.net/Bugest/article/details/81557112\r\n\r\n#import : 使用import xx 可以修改模块对象的属性(无论属性是不是可变类型)\r\n#from xx import x使用from xx import x 只能修改模块对象的属性是可变类型的(不可变类型不能修改,会发生属性错误)\r\n\r\n#===========================================《import》======================================================\r\nimport re\r\nimport os\r\nimport shutil\r\nimport tkinter as tk \r\nfrom tkinter import filedialog\r\n\r\n\r\nimport tkinter.messagebox #弹窗库\r\nimport sys \r\nimport datetime\r\nimport socket\r\n\r\n\r\n\r\ncurPyDirect = os.getcwd()#获取当前fileOperation.py的路径\r\ncurSysTime = datetime.datetime.now().strftime('%F %T')#获取当前系统时间 字符类型 str\r\n\r\n#===========================================《window》===========================================\r\nwindow=tk.Tk()#指定tkinter窗口\r\nwindow.title('my window')#tkinter窗口名字\r\nwindow.geometry('600x300')#tkinter窗口大小\r\n\r\n#===========================================《Menu》===========================================\r\n#for item in ['新建', '打开', '保存', '另存为']:\r\n# fmenu1.add_command(label=item,command=File_Deal_Event)# 如果该菜单是顶层菜单的一个菜单项,则它添加的是下拉菜单的菜单项。\r\n\r\n#===========================================《Menu》 1st:指定一个菜单项,类似于导航栏,顶层菜单\r\nmenubar=tk.Menu(window)#指定tkinter菜单\r\n\r\n \r\n \r\ndef File_Open_EventC():\r\n #FolderPath = filedialog.askdirectory()#打开提示框,选则文件夹,输出文件夹绝对路径\r\n FilePath = filedialog.askopenfilename(filetypes=( (\"C file\", \"*.c*\"),(\"Text file\", \"*.txt*\"),(\"HTML files\", \"*.html;*.htm\")))#打开提示框,选则文件,输出文件绝对路径\r\n fp = open(FilePath, 'r')\r\n \r\n flag_1 = 0#原括弧\r\n slash_char = '/'\r\n slash_flag = 0\r\n \r\n slash_char2 = '/'\r\n slash_flag2 = 0\r\n \r\n star_char='*'\r\n star_flag = 0\r\n s1 = []\r\n for s in fp.readlines():\r\n #1.排除/* */\r\n slash_flag = s.find(slash_char)\r\n #1.1 /\r\n if (slash_flag != -1 ):#找到了/\r\n #1.2 *\r\n star_flag = s.find(star_char)\r\n if( star_flag!=-1):#找到了*\r\n if(star_flag - slash_flag == 1):#找到了/*\r\n print(s)\r\n \r\n star_flag = 0\r\n slash_flag = 0\r\n slash_flag2 = 0\r\n else:\r\n star_flag = 0\r\n \r\n #1.3 /\r\n slash_flag2 = s.find(slash_char2)\r\n if (slash_flag2 != -1 ):\r\n if(slash_flag2 - slash_flag == 1):#找到了//\r\n print(s)\r\n \r\n star_flag = 0\r\n slash_flag = 0\r\n slash_flag2 = 0\r\n else:\r\n slash_flag2 = 0\r\n else:\r\n slash_flag = 0\r\n \r\n fp.close()\r\n \r\n \r\n \r\n \r\n \r\n#===========================================《Menu》 2nd:创建菜单栏\r\n#=================第1个菜单项:\r\nfmenu1 = tk.Menu(window)\r\nfmenu1.add_command(label='新建',command=None)\r\nfmenu1.add_command(label='打开',command=File_Open_EventC)\r\nfmenu1.add_command(label='保存',command=None)\r\nfmenu1.add_command(label='另存为',command=None)\r\n\r\n#=================第2个菜单项:\r\nfmenu2 = tk.Menu(window)\r\nfor item in ['复制', '粘贴', '剪切']:\r\n fmenu2.add_command(label=item)\r\n\r\n#=================第3个菜单项:\r\nfmenu3 = tk.Menu(window)\r\nfor item in ['默认视图', '新式视图']:\r\n fmenu3.add_command(label=item)\r\n\r\n#=================第4个菜单项:\r\nfmenu4 = tk.Menu(window)\r\nfmenu4.add_command(label='版权信息',command=None)\r\nfmenu4.add_command(label='其他说明',command=None)\r\n\r\n#===========================================《Menu》 3rd:级联菜单栏\r\n# add_cascade 的一个很重要的属性就是 menu 属性,它指明了要把那个菜单级联到该菜单项上,\r\n# 当然,还必不可少的就是 label 属性,用于指定该菜单项的名称\r\nmenubar.add_cascade(label=\"文件\", menu=fmenu1)#菜单项:文件\r\nmenubar.add_cascade(label=\"编辑\", menu=fmenu2)#菜单项:编辑\r\nmenubar.add_cascade(label=\"视图\", menu=fmenu3)#菜单项:视图\r\nmenubar.add_cascade(label=\"关于\", menu=fmenu4)#菜单项:关于\r\n\r\n#===========================================《Menu》 4th:激活菜单\r\n#最后可以用窗口的 menu 属性指定我们使用哪一个作为它的顶层菜单\r\nwindow.config(menu=menubar)\r\n\r\n#===============================激活窗口\r\nwindow.mainloop()",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
def ya_headers():
return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'
.format(token_ya)}
def put_folder(path):
url = 'https://cloud-api.yandex.net/v1/disk/resources/'
headers = ya_headers()
params = {'path': path, 'url': url}
response = requests.put(url, headers=headers, params=params)
if response.status_code == 201:
print('папка создана')
elif response.status_code == 409:
print('Папка уже существует. Файлы будут помещены в неё.')
return path
def post_file(file_url, file_name):
upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'
headers = ya_headers()
params = {'path': f'/{file_name}', 'url': file_url}
response = requests.post(upload_url, headers=headers, params=params)
return response.json()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
logging.basicConfig(filename='logo.log', level=logging.DEBUG, filemode='w')
logging.debug('debug message')
logging.info('info message')
<|reserved_special_token_0|>
def ya_headers():
return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'
.format(token_ya)}
def put_folder(path):
url = 'https://cloud-api.yandex.net/v1/disk/resources/'
headers = ya_headers()
params = {'path': path, 'url': url}
response = requests.put(url, headers=headers, params=params)
if response.status_code == 201:
print('папка создана')
elif response.status_code == 409:
print('Папка уже существует. Файлы будут помещены в неё.')
return path
def post_file(file_url, file_name):
upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'
headers = ya_headers()
params = {'path': f'/{file_name}', 'url': file_url}
response = requests.post(upload_url, headers=headers, params=params)
return response.json()
<|reserved_special_token_0|>
for photos in tqdm(res.json()['response']['items']):
sizes = photos['sizes']
for picture in sizes:
size_list.append(picture['type'])
size_list.sort(reverse=True)
for picture1 in sizes:
data_dict = {}
if picture1['type'] == size_list[0]:
href = picture1['url']
filename = photos['likes']['count']
if filename in name_list:
filename = (
f"{photos['likes']['count']}+{datetime.datetime.fromtimestamp(photos['date']).isoformat().replace(':', '|')}"
)
post_file(href, f'{folder_name}/{filename}')
else:
post_file(href, f'{folder_name}/{filename}')
data_dict['file_name'] = filename
data_dict['size'] = picture1['type']
data.append(data_dict)
name_list.append(filename)
size_list.clear()
time.sleep(1)
with open('foto.json', 'w') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
logging.basicConfig(filename='logo.log', level=logging.DEBUG, filemode='w')
logging.debug('debug message')
logging.info('info message')
id_vk = input('введите id пользователя вк: ')
token_vk = input('введите токен вк: ')
url = 'https://api.vk.com/method/photos.get'
params = {'user_id': id_vk, 'access_token': token_vk, 'v': '5.131',
'album_id': 'profile', 'extended': '1', 'photo_sizes': '1'}
res = requests.get(url, params=params)
token_ya = input('введите токен Yandex: ')
def ya_headers():
return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'
.format(token_ya)}
def put_folder(path):
url = 'https://cloud-api.yandex.net/v1/disk/resources/'
headers = ya_headers()
params = {'path': path, 'url': url}
response = requests.put(url, headers=headers, params=params)
if response.status_code == 201:
print('папка создана')
elif response.status_code == 409:
print('Папка уже существует. Файлы будут помещены в неё.')
return path
def post_file(file_url, file_name):
upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'
headers = ya_headers()
params = {'path': f'/{file_name}', 'url': file_url}
response = requests.post(upload_url, headers=headers, params=params)
return response.json()
folder_name = put_folder(input('введите имя папки для загрузки фотографий: '))
name_list = []
data = []
size_list = []
for photos in tqdm(res.json()['response']['items']):
sizes = photos['sizes']
for picture in sizes:
size_list.append(picture['type'])
size_list.sort(reverse=True)
for picture1 in sizes:
data_dict = {}
if picture1['type'] == size_list[0]:
href = picture1['url']
filename = photos['likes']['count']
if filename in name_list:
filename = (
f"{photos['likes']['count']}+{datetime.datetime.fromtimestamp(photos['date']).isoformat().replace(':', '|')}"
)
post_file(href, f'{folder_name}/{filename}')
else:
post_file(href, f'{folder_name}/{filename}')
data_dict['file_name'] = filename
data_dict['size'] = picture1['type']
data.append(data_dict)
name_list.append(filename)
size_list.clear()
time.sleep(1)
with open('foto.json', 'w') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
<|reserved_special_token_1|>
import requests
import datetime
import time
from tqdm import tqdm
import json
import logging
logging.basicConfig(filename='logo.log', level=logging.DEBUG, filemode='w')
logging.debug('debug message')
logging.info('info message')
id_vk = input('введите id пользователя вк: ')
token_vk = input('введите токен вк: ')
url = 'https://api.vk.com/method/photos.get'
params = {'user_id': id_vk, 'access_token': token_vk, 'v': '5.131',
'album_id': 'profile', 'extended': '1', 'photo_sizes': '1'}
res = requests.get(url, params=params)
token_ya = input('введите токен Yandex: ')
def ya_headers():
return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'
.format(token_ya)}
def put_folder(path):
url = 'https://cloud-api.yandex.net/v1/disk/resources/'
headers = ya_headers()
params = {'path': path, 'url': url}
response = requests.put(url, headers=headers, params=params)
if response.status_code == 201:
print('папка создана')
elif response.status_code == 409:
print('Папка уже существует. Файлы будут помещены в неё.')
return path
def post_file(file_url, file_name):
upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'
headers = ya_headers()
params = {'path': f'/{file_name}', 'url': file_url}
response = requests.post(upload_url, headers=headers, params=params)
return response.json()
folder_name = put_folder(input('введите имя папки для загрузки фотографий: '))
name_list = []
data = []
size_list = []
for photos in tqdm(res.json()['response']['items']):
sizes = photos['sizes']
for picture in sizes:
size_list.append(picture['type'])
size_list.sort(reverse=True)
for picture1 in sizes:
data_dict = {}
if picture1['type'] == size_list[0]:
href = picture1['url']
filename = photos['likes']['count']
if filename in name_list:
filename = (
f"{photos['likes']['count']}+{datetime.datetime.fromtimestamp(photos['date']).isoformat().replace(':', '|')}"
)
post_file(href, f'{folder_name}/{filename}')
else:
post_file(href, f'{folder_name}/{filename}')
data_dict['file_name'] = filename
data_dict['size'] = picture1['type']
data.append(data_dict)
name_list.append(filename)
size_list.clear()
time.sleep(1)
with open('foto.json', 'w') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
<|reserved_special_token_1|>
import requests
import datetime
import time
from tqdm import tqdm
import json
import logging
logging.basicConfig(filename='logo.log', level=logging.DEBUG, filemode='w')
logging.debug('debug message')
logging.info('info message')
# from pprint import pprint
id_vk = input('введите id пользователя вк: ')
token_vk = input('введите токен вк: ')
url = 'https://api.vk.com/method/photos.get'
params = {'user_id': id_vk, 'access_token': token_vk, 'v': '5.131','album_id': 'profile', 'extended': '1', 'photo_sizes': '1'}
res = requests.get(url, params=params)
# pprint(res.json())
token_ya = input('введите токен Yandex: ')
def ya_headers():
return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'.format(token_ya)}
def put_folder(path):
url = 'https://cloud-api.yandex.net/v1/disk/resources/'
headers = ya_headers()
params = {'path': path, 'url': url}
response = requests.put(url,headers = headers, params = params)
if response.status_code == 201:
print('папка создана')
elif response.status_code == 409:
print('Папка уже существует. Файлы будут помещены в неё.')
return path
def post_file(file_url, file_name):
upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'
headers = ya_headers()
params = {'path': f'/{file_name}', 'url': file_url}
response = requests.post(upload_url, headers = headers, params = params)
return response.json()
folder_name = put_folder(input("введите имя папки для загрузки фотографий: "))
name_list = []
data = []
size_list = []
for photos in tqdm(res.json()['response']['items']):
sizes = photos['sizes']
for picture in sizes:
size_list.append(picture['type'])
size_list.sort(reverse=True)
for picture1 in sizes:
data_dict = {}
if picture1['type'] == size_list[0]:
href = picture1['url']
filename = photos['likes']['count']
if filename in name_list:
filename = f"{photos['likes']['count']}+{datetime.datetime.fromtimestamp(photos['date']).isoformat().replace(':', '|')}"
post_file(href, f"{folder_name}/{filename}")
else:
post_file(href, f"{folder_name}/{filename}")
data_dict['file_name'] = filename
data_dict['size'] = picture1['type']
data.append(data_dict)
name_list.append(filename)
size_list.clear()
time.sleep(1)
with open ('foto.json', 'w') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
|
flexible
|
{
"blob_id": "a22bc3bdb5e35060eff7f523b90d605ff2dd3878",
"index": 9581,
"step-1": "<mask token>\n\n\ndef ya_headers():\n return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'\n .format(token_ya)}\n\n\ndef put_folder(path):\n url = 'https://cloud-api.yandex.net/v1/disk/resources/'\n headers = ya_headers()\n params = {'path': path, 'url': url}\n response = requests.put(url, headers=headers, params=params)\n if response.status_code == 201:\n print('папка создана')\n elif response.status_code == 409:\n print('Папка уже существует. Файлы будут помещены в неё.')\n return path\n\n\ndef post_file(file_url, file_name):\n upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'\n headers = ya_headers()\n params = {'path': f'/{file_name}', 'url': file_url}\n response = requests.post(upload_url, headers=headers, params=params)\n return response.json()\n\n\n<mask token>\n",
"step-2": "<mask token>\nlogging.basicConfig(filename='logo.log', level=logging.DEBUG, filemode='w')\nlogging.debug('debug message')\nlogging.info('info message')\n<mask token>\n\n\ndef ya_headers():\n return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'\n .format(token_ya)}\n\n\ndef put_folder(path):\n url = 'https://cloud-api.yandex.net/v1/disk/resources/'\n headers = ya_headers()\n params = {'path': path, 'url': url}\n response = requests.put(url, headers=headers, params=params)\n if response.status_code == 201:\n print('папка создана')\n elif response.status_code == 409:\n print('Папка уже существует. Файлы будут помещены в неё.')\n return path\n\n\ndef post_file(file_url, file_name):\n upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'\n headers = ya_headers()\n params = {'path': f'/{file_name}', 'url': file_url}\n response = requests.post(upload_url, headers=headers, params=params)\n return response.json()\n\n\n<mask token>\nfor photos in tqdm(res.json()['response']['items']):\n sizes = photos['sizes']\n for picture in sizes:\n size_list.append(picture['type'])\n size_list.sort(reverse=True)\n for picture1 in sizes:\n data_dict = {}\n if picture1['type'] == size_list[0]:\n href = picture1['url']\n filename = photos['likes']['count']\n if filename in name_list:\n filename = (\n f\"{photos['likes']['count']}+{datetime.datetime.fromtimestamp(photos['date']).isoformat().replace(':', '|')}\"\n )\n post_file(href, f'{folder_name}/{filename}')\n else:\n post_file(href, f'{folder_name}/{filename}')\n data_dict['file_name'] = filename\n data_dict['size'] = picture1['type']\n data.append(data_dict)\n name_list.append(filename)\n size_list.clear()\n time.sleep(1)\nwith open('foto.json', 'w') as f:\n json.dump(data, f, ensure_ascii=False, indent=2)\n",
"step-3": "<mask token>\nlogging.basicConfig(filename='logo.log', level=logging.DEBUG, filemode='w')\nlogging.debug('debug message')\nlogging.info('info message')\nid_vk = input('введите id пользователя вк: ')\ntoken_vk = input('введите токен вк: ')\nurl = 'https://api.vk.com/method/photos.get'\nparams = {'user_id': id_vk, 'access_token': token_vk, 'v': '5.131',\n 'album_id': 'profile', 'extended': '1', 'photo_sizes': '1'}\nres = requests.get(url, params=params)\ntoken_ya = input('введите токен Yandex: ')\n\n\ndef ya_headers():\n return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'\n .format(token_ya)}\n\n\ndef put_folder(path):\n url = 'https://cloud-api.yandex.net/v1/disk/resources/'\n headers = ya_headers()\n params = {'path': path, 'url': url}\n response = requests.put(url, headers=headers, params=params)\n if response.status_code == 201:\n print('папка создана')\n elif response.status_code == 409:\n print('Папка уже существует. Файлы будут помещены в неё.')\n return path\n\n\ndef post_file(file_url, file_name):\n upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'\n headers = ya_headers()\n params = {'path': f'/{file_name}', 'url': file_url}\n response = requests.post(upload_url, headers=headers, params=params)\n return response.json()\n\n\nfolder_name = put_folder(input('введите имя папки для загрузки фотографий: '))\nname_list = []\ndata = []\nsize_list = []\nfor photos in tqdm(res.json()['response']['items']):\n sizes = photos['sizes']\n for picture in sizes:\n size_list.append(picture['type'])\n size_list.sort(reverse=True)\n for picture1 in sizes:\n data_dict = {}\n if picture1['type'] == size_list[0]:\n href = picture1['url']\n filename = photos['likes']['count']\n if filename in name_list:\n filename = (\n f\"{photos['likes']['count']}+{datetime.datetime.fromtimestamp(photos['date']).isoformat().replace(':', '|')}\"\n )\n post_file(href, f'{folder_name}/{filename}')\n else:\n post_file(href, f'{folder_name}/{filename}')\n data_dict['file_name'] = filename\n data_dict['size'] = picture1['type']\n data.append(data_dict)\n name_list.append(filename)\n size_list.clear()\n time.sleep(1)\nwith open('foto.json', 'w') as f:\n json.dump(data, f, ensure_ascii=False, indent=2)\n",
"step-4": "import requests\nimport datetime\nimport time\nfrom tqdm import tqdm\nimport json\nimport logging\nlogging.basicConfig(filename='logo.log', level=logging.DEBUG, filemode='w')\nlogging.debug('debug message')\nlogging.info('info message')\nid_vk = input('введите id пользователя вк: ')\ntoken_vk = input('введите токен вк: ')\nurl = 'https://api.vk.com/method/photos.get'\nparams = {'user_id': id_vk, 'access_token': token_vk, 'v': '5.131',\n 'album_id': 'profile', 'extended': '1', 'photo_sizes': '1'}\nres = requests.get(url, params=params)\ntoken_ya = input('введите токен Yandex: ')\n\n\ndef ya_headers():\n return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'\n .format(token_ya)}\n\n\ndef put_folder(path):\n url = 'https://cloud-api.yandex.net/v1/disk/resources/'\n headers = ya_headers()\n params = {'path': path, 'url': url}\n response = requests.put(url, headers=headers, params=params)\n if response.status_code == 201:\n print('папка создана')\n elif response.status_code == 409:\n print('Папка уже существует. Файлы будут помещены в неё.')\n return path\n\n\ndef post_file(file_url, file_name):\n upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'\n headers = ya_headers()\n params = {'path': f'/{file_name}', 'url': file_url}\n response = requests.post(upload_url, headers=headers, params=params)\n return response.json()\n\n\nfolder_name = put_folder(input('введите имя папки для загрузки фотографий: '))\nname_list = []\ndata = []\nsize_list = []\nfor photos in tqdm(res.json()['response']['items']):\n sizes = photos['sizes']\n for picture in sizes:\n size_list.append(picture['type'])\n size_list.sort(reverse=True)\n for picture1 in sizes:\n data_dict = {}\n if picture1['type'] == size_list[0]:\n href = picture1['url']\n filename = photos['likes']['count']\n if filename in name_list:\n filename = (\n f\"{photos['likes']['count']}+{datetime.datetime.fromtimestamp(photos['date']).isoformat().replace(':', '|')}\"\n )\n post_file(href, f'{folder_name}/{filename}')\n else:\n post_file(href, f'{folder_name}/{filename}')\n data_dict['file_name'] = filename\n data_dict['size'] = picture1['type']\n data.append(data_dict)\n name_list.append(filename)\n size_list.clear()\n time.sleep(1)\nwith open('foto.json', 'w') as f:\n json.dump(data, f, ensure_ascii=False, indent=2)\n",
"step-5": "import requests\nimport datetime\nimport time\nfrom tqdm import tqdm\nimport json\nimport logging\nlogging.basicConfig(filename='logo.log', level=logging.DEBUG, filemode='w')\nlogging.debug('debug message')\nlogging.info('info message')\n\n# from pprint import pprint\nid_vk = input('введите id пользователя вк: ')\ntoken_vk = input('введите токен вк: ')\nurl = 'https://api.vk.com/method/photos.get'\nparams = {'user_id': id_vk, 'access_token': token_vk, 'v': '5.131','album_id': 'profile', 'extended': '1', 'photo_sizes': '1'}\nres = requests.get(url, params=params)\n# pprint(res.json())\n\ntoken_ya = input('введите токен Yandex: ')\n\ndef ya_headers():\n return {'Content-type': 'application/json', 'Authorization': 'OAuth {}'.format(token_ya)}\n\n\ndef put_folder(path):\n url = 'https://cloud-api.yandex.net/v1/disk/resources/'\n headers = ya_headers()\n params = {'path': path, 'url': url}\n response = requests.put(url,headers = headers, params = params)\n \n if response.status_code == 201:\n print('папка создана')\n elif response.status_code == 409:\n print('Папка уже существует. Файлы будут помещены в неё.') \n\n return path\n\n\ndef post_file(file_url, file_name):\n upload_url = 'https://cloud-api.yandex.net/v1/disk/resources/upload'\n headers = ya_headers()\n params = {'path': f'/{file_name}', 'url': file_url}\n response = requests.post(upload_url, headers = headers, params = params)\n return response.json()\n\n\n \nfolder_name = put_folder(input(\"введите имя папки для загрузки фотографий: \"))\nname_list = []\ndata = []\nsize_list = []\n\nfor photos in tqdm(res.json()['response']['items']):\n \n sizes = photos['sizes']\n\n\n for picture in sizes:\n size_list.append(picture['type'])\n size_list.sort(reverse=True)\n \n for picture1 in sizes:\n data_dict = {} \n if picture1['type'] == size_list[0]:\n href = picture1['url']\n filename = photos['likes']['count'] \n if filename in name_list:\n filename = f\"{photos['likes']['count']}+{datetime.datetime.fromtimestamp(photos['date']).isoformat().replace(':', '|')}\"\n post_file(href, f\"{folder_name}/{filename}\") \n else:\n post_file(href, f\"{folder_name}/{filename}\")\n\n data_dict['file_name'] = filename\n data_dict['size'] = picture1['type']\n data.append(data_dict) \n \n \n name_list.append(filename)\n size_list.clear() \n \n time.sleep(1)\nwith open ('foto.json', 'w') as f:\n json.dump(data, f, ensure_ascii=False, indent=2) ",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Test create publication target github"""
from os.path import join as opj
# this must with with and without pygithub
from datalad.api import create_sibling_github
from datalad.api import Dataset
from datalad.support.exceptions import MissingExternalDependency
from datalad.tests.utils import with_tempfile
from nose.tools import assert_raises, assert_in, assert_true, assert_false, \
assert_not_in, assert_equal
from nose import SkipTest
try:
import github as gh
except ImportError:
# make sure that the command complains too
assert_raises(MissingExternalDependency, create_sibling_github, 'some')
raise SkipTest
@with_tempfile
def test_invalid_call(path):
# no dataset
assert_raises(ValueError, create_sibling_github, 'bogus', dataset=path)
ds = Dataset(path).create()
# no user
assert_raises(gh.BadCredentialsException, ds.create_sibling_github, 'bogus', github_user='')
@with_tempfile
def test_dont_trip_over_missing_subds(path):
ds1 = Dataset(opj(path, 'ds1')).create()
ds2 = Dataset(opj(path, 'ds2')).create()
subds2 = ds1.install(source=ds2.path, path='subds2')
assert_true(subds2.is_installed())
assert_in('subds2', ds1.get_subdatasets())
subds2.uninstall(remove_handles=True, remove_history=True)
assert_in('subds2', ds1.get_subdatasets())
assert_false(subds2.is_installed())
# this will deinit the submodule
ds1.save(files=['subds2'])
# see if it wants to talk to github (and fail), or if it trips over something
# before
assert_raises(gh.BadCredentialsException, ds1.create_sibling_github, 'bogus', recursive=True, github_user='')
# inject remote config prior run
assert_not_in('github', ds1.repo.get_remotes())
# fail on existing
ds1.repo.add_remote('github', 'http://nothere')
assert_raises(ValueError, ds1.create_sibling_github, 'bogus', recursive=True, github_user='')
# talk to github when existing is OK
assert_raises(gh.BadCredentialsException, ds1.create_sibling_github, 'bogus', recursive=True, github_user='', existing='reconfigure')
# return happy emptiness when all is skipped
assert_equal(ds1.create_sibling_github('bogus', recursive=True, github_user='', existing='skip'), [])
|
normal
|
{
"blob_id": "035043460805b7fe92e078e05708d368130e3527",
"index": 8965,
"step-1": "<mask token>\n\n\n@with_tempfile\ndef test_invalid_call(path):\n assert_raises(ValueError, create_sibling_github, 'bogus', dataset=path)\n ds = Dataset(path).create()\n assert_raises(gh.BadCredentialsException, ds.create_sibling_github,\n 'bogus', github_user='')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\n@with_tempfile\ndef test_invalid_call(path):\n assert_raises(ValueError, create_sibling_github, 'bogus', dataset=path)\n ds = Dataset(path).create()\n assert_raises(gh.BadCredentialsException, ds.create_sibling_github,\n 'bogus', github_user='')\n\n\n@with_tempfile\ndef test_dont_trip_over_missing_subds(path):\n ds1 = Dataset(opj(path, 'ds1')).create()\n ds2 = Dataset(opj(path, 'ds2')).create()\n subds2 = ds1.install(source=ds2.path, path='subds2')\n assert_true(subds2.is_installed())\n assert_in('subds2', ds1.get_subdatasets())\n subds2.uninstall(remove_handles=True, remove_history=True)\n assert_in('subds2', ds1.get_subdatasets())\n assert_false(subds2.is_installed())\n ds1.save(files=['subds2'])\n assert_raises(gh.BadCredentialsException, ds1.create_sibling_github,\n 'bogus', recursive=True, github_user='')\n assert_not_in('github', ds1.repo.get_remotes())\n ds1.repo.add_remote('github', 'http://nothere')\n assert_raises(ValueError, ds1.create_sibling_github, 'bogus', recursive\n =True, github_user='')\n assert_raises(gh.BadCredentialsException, ds1.create_sibling_github,\n 'bogus', recursive=True, github_user='', existing='reconfigure')\n assert_equal(ds1.create_sibling_github('bogus', recursive=True,\n github_user='', existing='skip'), [])\n",
"step-3": "<mask token>\ntry:\n import github as gh\nexcept ImportError:\n assert_raises(MissingExternalDependency, create_sibling_github, 'some')\n raise SkipTest\n\n\n@with_tempfile\ndef test_invalid_call(path):\n assert_raises(ValueError, create_sibling_github, 'bogus', dataset=path)\n ds = Dataset(path).create()\n assert_raises(gh.BadCredentialsException, ds.create_sibling_github,\n 'bogus', github_user='')\n\n\n@with_tempfile\ndef test_dont_trip_over_missing_subds(path):\n ds1 = Dataset(opj(path, 'ds1')).create()\n ds2 = Dataset(opj(path, 'ds2')).create()\n subds2 = ds1.install(source=ds2.path, path='subds2')\n assert_true(subds2.is_installed())\n assert_in('subds2', ds1.get_subdatasets())\n subds2.uninstall(remove_handles=True, remove_history=True)\n assert_in('subds2', ds1.get_subdatasets())\n assert_false(subds2.is_installed())\n ds1.save(files=['subds2'])\n assert_raises(gh.BadCredentialsException, ds1.create_sibling_github,\n 'bogus', recursive=True, github_user='')\n assert_not_in('github', ds1.repo.get_remotes())\n ds1.repo.add_remote('github', 'http://nothere')\n assert_raises(ValueError, ds1.create_sibling_github, 'bogus', recursive\n =True, github_user='')\n assert_raises(gh.BadCredentialsException, ds1.create_sibling_github,\n 'bogus', recursive=True, github_user='', existing='reconfigure')\n assert_equal(ds1.create_sibling_github('bogus', recursive=True,\n github_user='', existing='skip'), [])\n",
"step-4": "<mask token>\nfrom os.path import join as opj\nfrom datalad.api import create_sibling_github\nfrom datalad.api import Dataset\nfrom datalad.support.exceptions import MissingExternalDependency\nfrom datalad.tests.utils import with_tempfile\nfrom nose.tools import assert_raises, assert_in, assert_true, assert_false, assert_not_in, assert_equal\nfrom nose import SkipTest\ntry:\n import github as gh\nexcept ImportError:\n assert_raises(MissingExternalDependency, create_sibling_github, 'some')\n raise SkipTest\n\n\n@with_tempfile\ndef test_invalid_call(path):\n assert_raises(ValueError, create_sibling_github, 'bogus', dataset=path)\n ds = Dataset(path).create()\n assert_raises(gh.BadCredentialsException, ds.create_sibling_github,\n 'bogus', github_user='')\n\n\n@with_tempfile\ndef test_dont_trip_over_missing_subds(path):\n ds1 = Dataset(opj(path, 'ds1')).create()\n ds2 = Dataset(opj(path, 'ds2')).create()\n subds2 = ds1.install(source=ds2.path, path='subds2')\n assert_true(subds2.is_installed())\n assert_in('subds2', ds1.get_subdatasets())\n subds2.uninstall(remove_handles=True, remove_history=True)\n assert_in('subds2', ds1.get_subdatasets())\n assert_false(subds2.is_installed())\n ds1.save(files=['subds2'])\n assert_raises(gh.BadCredentialsException, ds1.create_sibling_github,\n 'bogus', recursive=True, github_user='')\n assert_not_in('github', ds1.repo.get_remotes())\n ds1.repo.add_remote('github', 'http://nothere')\n assert_raises(ValueError, ds1.create_sibling_github, 'bogus', recursive\n =True, github_user='')\n assert_raises(gh.BadCredentialsException, ds1.create_sibling_github,\n 'bogus', recursive=True, github_user='', existing='reconfigure')\n assert_equal(ds1.create_sibling_github('bogus', recursive=True,\n github_user='', existing='skip'), [])\n",
"step-5": "# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the datalad package for the\n# copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Test create publication target github\"\"\"\n\nfrom os.path import join as opj\n# this must with with and without pygithub\nfrom datalad.api import create_sibling_github\nfrom datalad.api import Dataset\nfrom datalad.support.exceptions import MissingExternalDependency\nfrom datalad.tests.utils import with_tempfile\nfrom nose.tools import assert_raises, assert_in, assert_true, assert_false, \\\n assert_not_in, assert_equal\nfrom nose import SkipTest\n\n\ntry:\n import github as gh\nexcept ImportError:\n # make sure that the command complains too\n assert_raises(MissingExternalDependency, create_sibling_github, 'some')\n raise SkipTest\n\n\n@with_tempfile\ndef test_invalid_call(path):\n # no dataset\n assert_raises(ValueError, create_sibling_github, 'bogus', dataset=path)\n ds = Dataset(path).create()\n # no user\n assert_raises(gh.BadCredentialsException, ds.create_sibling_github, 'bogus', github_user='')\n\n\n@with_tempfile\ndef test_dont_trip_over_missing_subds(path):\n ds1 = Dataset(opj(path, 'ds1')).create()\n ds2 = Dataset(opj(path, 'ds2')).create()\n subds2 = ds1.install(source=ds2.path, path='subds2')\n assert_true(subds2.is_installed())\n assert_in('subds2', ds1.get_subdatasets())\n subds2.uninstall(remove_handles=True, remove_history=True)\n assert_in('subds2', ds1.get_subdatasets())\n assert_false(subds2.is_installed())\n # this will deinit the submodule\n ds1.save(files=['subds2'])\n # see if it wants to talk to github (and fail), or if it trips over something\n # before\n assert_raises(gh.BadCredentialsException, ds1.create_sibling_github, 'bogus', recursive=True, github_user='')\n # inject remote config prior run\n assert_not_in('github', ds1.repo.get_remotes())\n # fail on existing\n ds1.repo.add_remote('github', 'http://nothere')\n assert_raises(ValueError, ds1.create_sibling_github, 'bogus', recursive=True, github_user='')\n # talk to github when existing is OK\n assert_raises(gh.BadCredentialsException, ds1.create_sibling_github, 'bogus', recursive=True, github_user='', existing='reconfigure')\n # return happy emptiness when all is skipped\n assert_equal(ds1.create_sibling_github('bogus', recursive=True, github_user='', existing='skip'), [])\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#!/usr/bin python
import socket
import json
import threading
import sys
from db_util import DBUtil
from cryptoLib import AesCtr,Hmac
class Client(threading.Thread):
def __init__(self, (client_conn, client_addr), sema):
threading.Thread.__init__(self)
self.client_conn = client_conn
self.client_addr = client_addr
self.size = 4096
self.len_of_mac = 12
self.sema = sema
def run(self):
while True:
dataRaw = None
try:
dataRaw = self.client_conn.recv(self.size)
iv,dataEnc,dataHmac=dataRaw.split("nonce")
dataAuth=verHmac(dataEnc,dataHmac)
if not dataAuth:
continue
else:
dataChecked=decrypt(dataEnc,iv)
except socket.error, e:
print(e.message)
if dataRaw is not None:
try:
data = json.loads(dataChecked)
print("Received : " + str(data))
dbutil = DBUtil()
self.sema.acquire()
dbutil.update_database(data)
self.sema.release()
except ValueError:
continue
self.client_conn.close()
break
def verHmac(dataHmac,dataEnc):
hmObj1=Hmac(dataEnc)
l=hmObj1.verifyHmac(dataHmac)
return l
def decrypt(dataEnc,iv):
e2=AesCtr()
unEnc=e2.decryptData(enc,iv)
class Receiver:
def __init__(self,port):
self.host ="127.0.0.1"
#why not "127.0.0.1"
self.port = port
self.threads = list()
self.udp_sock = None
self.semaphore = threading.Semaphore(1)
def get_ip_address(self):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
def create_socket(self):
try:
self.udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp_sock.bind((self.host, self.port))
#self.udp_sock.listen(2)
except socket.error:
if self.udp_sock:
self.udp_sock.close()
print("Failure to open socket")
sys.exit(1)
def run(self):
self.create_socket()
while True:
client = Client(self.udp_sock.accept(), self.semaphore)
client.start()
self.threads.append(client)
def main():
receiver = Receiver(49999)
receiver.run()
if __name__ == '__main__':
main()
|
normal
|
{
"blob_id": "1338d6578a94338c6e75acc025ddddd14097ee10",
"index": 2044,
"step-1": "#!/usr/bin python\n\nimport socket\nimport json\nimport threading\nimport sys\nfrom db_util import DBUtil\nfrom cryptoLib import AesCtr,Hmac\n\n\nclass Client(threading.Thread):\n\tdef __init__(self, (client_conn, client_addr), sema):\n\t\tthreading.Thread.__init__(self)\n\t\tself.client_conn = client_conn\n\t\tself.client_addr = client_addr\n\t\tself.size = 4096\n\t\tself.len_of_mac = 12\n\t\tself.sema = sema\n\n\n\tdef run(self):\n\t\twhile True:\n\t\t\tdataRaw = None\n\t\t\ttry:\n\t\t\t\tdataRaw = self.client_conn.recv(self.size)\n\t\t\t\tiv,dataEnc,dataHmac=dataRaw.split(\"nonce\")\n\t\t\t\tdataAuth=verHmac(dataEnc,dataHmac)\n\t\t\t\tif not dataAuth:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tdataChecked=decrypt(dataEnc,iv)\n\t\t\texcept socket.error, e:\n\t\t\t\tprint(e.message)\n\n\t\t\tif dataRaw is not None:\n\t\t\t\ttry:\n\t\t\t\t\tdata = json.loads(dataChecked)\n\t\t\t\t\tprint(\"Received : \" + str(data))\n\t\t\t\t\tdbutil = DBUtil()\n\t\t\t\t\tself.sema.acquire()\n\t\t\t\t\tdbutil.update_database(data)\n\t\t\t\t\tself.sema.release()\n\t\t\t\texcept ValueError:\n\t\t\t\t\tcontinue\n\n\t\t\tself.client_conn.close()\n\t\t\tbreak\n\tdef verHmac(dataHmac,dataEnc):\n\t\thmObj1=Hmac(dataEnc)\n\t\tl=hmObj1.verifyHmac(dataHmac)\n\t\treturn l\n\t\tdef decrypt(dataEnc,iv):\n\t\te2=AesCtr()\n\t\tunEnc=e2.decryptData(enc,iv)\n\n\n\nclass Receiver:\n\tdef __init__(self,port):\n\t\tself.host =\"127.0.0.1\"\n\t\t#why not \"127.0.0.1\"\n\t\tself.port = port\n\t\tself.threads = list()\n\t\tself.udp_sock = None\n\t\tself.semaphore = threading.Semaphore(1)\n\n\tdef get_ip_address(self):\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\ts.connect((\"8.8.8.8\", 80))\n\t\treturn s.getsockname()[0]\n\n\n\tdef create_socket(self):\n\t\ttry:\n\t\t\tself.udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\t\tself.udp_sock.bind((self.host, self.port))\n\t\t\t#self.udp_sock.listen(2)\n\t\texcept socket.error:\n\t\t\tif self.udp_sock:\n\t\t\t\tself.udp_sock.close()\n\t\t\tprint(\"Failure to open socket\")\n\t\t\tsys.exit(1)\n\n\tdef run(self):\n\t\tself.create_socket()\n\t\twhile True:\n\t\t\tclient = Client(self.udp_sock.accept(), self.semaphore)\n\t\t\tclient.start()\n\t\t\tself.threads.append(client)\n\ndef main():\n\treceiver = Receiver(49999)\n\treceiver.run()\n\nif __name__ == '__main__':\n\tmain()\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
class MRTopVisitorCount(MRJob):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def mapper_sort(self, page, counts):
top = Counter(counts).most_common(1)
yield page, (top[0][0], top[0][1])
def reducer_sort(self, page, visitor_count):
for v in visitor_count:
yield page, v
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class MRTopVisitorCount(MRJob):
def mapper_count(self, _, line):
fields = read_csvLine(line)
yield fields[1], (fields[4], 1)
def reducer_count(self, page, counts):
count = Counter()
for visitor in counts:
count.update({visitor[0]: visitor[1]})
yield page, count
def mapper_sort(self, page, counts):
top = Counter(counts).most_common(1)
yield page, (top[0][0], top[0][1])
def reducer_sort(self, page, visitor_count):
for v in visitor_count:
yield page, v
def steps(self):
return [MRStep(mapper=self.mapper_count, reducer=self.reducer_count
), MRStep(mapper=self.mapper_sort, reducer=self.reducer_sort)]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def read_csvLine(line):
for row in csv.reader([line]):
return row
class MRTopVisitorCount(MRJob):
def mapper_count(self, _, line):
fields = read_csvLine(line)
yield fields[1], (fields[4], 1)
def reducer_count(self, page, counts):
count = Counter()
for visitor in counts:
count.update({visitor[0]: visitor[1]})
yield page, count
def mapper_sort(self, page, counts):
top = Counter(counts).most_common(1)
yield page, (top[0][0], top[0][1])
def reducer_sort(self, page, visitor_count):
for v in visitor_count:
yield page, v
def steps(self):
return [MRStep(mapper=self.mapper_count, reducer=self.reducer_count
), MRStep(mapper=self.mapper_sort, reducer=self.reducer_sort)]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def read_csvLine(line):
for row in csv.reader([line]):
return row
class MRTopVisitorCount(MRJob):
def mapper_count(self, _, line):
fields = read_csvLine(line)
yield fields[1], (fields[4], 1)
def reducer_count(self, page, counts):
count = Counter()
for visitor in counts:
count.update({visitor[0]: visitor[1]})
yield page, count
def mapper_sort(self, page, counts):
top = Counter(counts).most_common(1)
yield page, (top[0][0], top[0][1])
def reducer_sort(self, page, visitor_count):
for v in visitor_count:
yield page, v
def steps(self):
return [MRStep(mapper=self.mapper_count, reducer=self.reducer_count
), MRStep(mapper=self.mapper_sort, reducer=self.reducer_sort)]
if __name__ == '__main__':
MRPageFreqCount.run()
<|reserved_special_token_1|>
from mrjob.job import MRJob
from mrjob.step import MRStep
from collections import Counter
import csv
def read_csvLine(line):
# Given a comma delimited string, return fields
for row in csv.reader([line]):
return row
class MRTopVisitorCount(MRJob):
# Mapper1: emit page_id, 1
def mapper_count(self, _, line):
fields = read_csvLine(line)
yield fields[1], (fields[4], 1)
# Reducer1: aggregate page_id
def reducer_count(self, page, counts):
count = Counter()
for visitor in counts:
count.update({visitor[0]:visitor[1]})
yield page, count
# Mapper2: invert page and counts to sort
def mapper_sort(self, page, counts):
top = Counter(counts).most_common(1)
yield page, (top[0][0], top[0][1])
# Reducer2: identity
def reducer_sort(self, page, visitor_count):
for v in visitor_count:
yield page, v
# Multi-step pipeline definition
def steps(self):
return [
MRStep(mapper=self.mapper_count,
reducer=self.reducer_count),
MRStep(mapper=self.mapper_sort,
reducer=self.reducer_sort)]
if __name__ == '__main__':
MRPageFreqCount.run()
|
flexible
|
{
"blob_id": "471ce1eeb3293a424de74e25f36b76699a97ec2b",
"index": 7039,
"step-1": "<mask token>\n\n\nclass MRTopVisitorCount(MRJob):\n <mask token>\n <mask token>\n\n def mapper_sort(self, page, counts):\n top = Counter(counts).most_common(1)\n yield page, (top[0][0], top[0][1])\n\n def reducer_sort(self, page, visitor_count):\n for v in visitor_count:\n yield page, v\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass MRTopVisitorCount(MRJob):\n\n def mapper_count(self, _, line):\n fields = read_csvLine(line)\n yield fields[1], (fields[4], 1)\n\n def reducer_count(self, page, counts):\n count = Counter()\n for visitor in counts:\n count.update({visitor[0]: visitor[1]})\n yield page, count\n\n def mapper_sort(self, page, counts):\n top = Counter(counts).most_common(1)\n yield page, (top[0][0], top[0][1])\n\n def reducer_sort(self, page, visitor_count):\n for v in visitor_count:\n yield page, v\n\n def steps(self):\n return [MRStep(mapper=self.mapper_count, reducer=self.reducer_count\n ), MRStep(mapper=self.mapper_sort, reducer=self.reducer_sort)]\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef read_csvLine(line):\n for row in csv.reader([line]):\n return row\n\n\nclass MRTopVisitorCount(MRJob):\n\n def mapper_count(self, _, line):\n fields = read_csvLine(line)\n yield fields[1], (fields[4], 1)\n\n def reducer_count(self, page, counts):\n count = Counter()\n for visitor in counts:\n count.update({visitor[0]: visitor[1]})\n yield page, count\n\n def mapper_sort(self, page, counts):\n top = Counter(counts).most_common(1)\n yield page, (top[0][0], top[0][1])\n\n def reducer_sort(self, page, visitor_count):\n for v in visitor_count:\n yield page, v\n\n def steps(self):\n return [MRStep(mapper=self.mapper_count, reducer=self.reducer_count\n ), MRStep(mapper=self.mapper_sort, reducer=self.reducer_sort)]\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\ndef read_csvLine(line):\n for row in csv.reader([line]):\n return row\n\n\nclass MRTopVisitorCount(MRJob):\n\n def mapper_count(self, _, line):\n fields = read_csvLine(line)\n yield fields[1], (fields[4], 1)\n\n def reducer_count(self, page, counts):\n count = Counter()\n for visitor in counts:\n count.update({visitor[0]: visitor[1]})\n yield page, count\n\n def mapper_sort(self, page, counts):\n top = Counter(counts).most_common(1)\n yield page, (top[0][0], top[0][1])\n\n def reducer_sort(self, page, visitor_count):\n for v in visitor_count:\n yield page, v\n\n def steps(self):\n return [MRStep(mapper=self.mapper_count, reducer=self.reducer_count\n ), MRStep(mapper=self.mapper_sort, reducer=self.reducer_sort)]\n\n\nif __name__ == '__main__':\n MRPageFreqCount.run()\n",
"step-5": "from mrjob.job import MRJob\nfrom mrjob.step import MRStep\nfrom collections import Counter\nimport csv\n\ndef read_csvLine(line):\n # Given a comma delimited string, return fields\n for row in csv.reader([line]):\n return row\n\nclass MRTopVisitorCount(MRJob):\n \n # Mapper1: emit page_id, 1\n def mapper_count(self, _, line):\n fields = read_csvLine(line)\n yield fields[1], (fields[4], 1)\n\n # Reducer1: aggregate page_id\n def reducer_count(self, page, counts):\n count = Counter()\n for visitor in counts:\n count.update({visitor[0]:visitor[1]})\n yield page, count\n \n # Mapper2: invert page and counts to sort\n def mapper_sort(self, page, counts):\n top = Counter(counts).most_common(1)\n yield page, (top[0][0], top[0][1])\n \n # Reducer2: identity\n def reducer_sort(self, page, visitor_count):\n for v in visitor_count:\n yield page, v\n \n # Multi-step pipeline definition\n def steps(self):\n return [\n MRStep(mapper=self.mapper_count,\n reducer=self.reducer_count),\n MRStep(mapper=self.mapper_sort,\n reducer=self.reducer_sort)]\n \n \n \n\nif __name__ == '__main__':\n MRPageFreqCount.run()",
"step-ids": [
3,
6,
7,
8,
10
]
}
|
[
3,
6,
7,
8,
10
] |
from datetime import date
def solution(mon: int, day: int) -> str:
return date(2016, mon, day).strftime("%a").upper()
|
normal
|
{
"blob_id": "67385d6d58cc79037660be546d41ea9ba1f790fa",
"index": 5043,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef solution(mon: int, day: int) ->str:\n return date(2016, mon, day).strftime('%a').upper()\n",
"step-3": "from datetime import date\n\n\ndef solution(mon: int, day: int) ->str:\n return date(2016, mon, day).strftime('%a').upper()\n",
"step-4": "from datetime import date\n\ndef solution(mon: int, day: int) -> str:\n return date(2016, mon, day).strftime(\"%a\").upper()\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def get_analyse(curse):
"""
要求curse数据中index为时间,columns为策略名称,每一列为该策略净值
"""
qf_drawdown = []
qf_yeild = []
qf_std = []
date = curse.index
y = curse.copy()
for i in curse.columns:
y['max2here'] = y[i].expanding().max()
y['dd2here'] = y[i] / y['max2here']
remain = y.sort_values(by='dd2here').iloc[0]['dd2here']
end_date = y.sort_values(by='dd2here').iloc[0]
drawdown = round((1 - remain) * 100, 2)
qf_drawdown.append(drawdown)
daylenth = len(date) - 1
yeild = round((y[i][daylenth] ** (52 / daylenth) - 1) * 100, 2)
qf_yeild.append(yeild)
y1 = y[i]
r1 = y1 / y1.shift(1) - 1
std = round(np.nanstd(r1) * 52 ** 0.5 * 100, 2)
qf_std.append(std)
drawdown = pd.DataFrame(qf_drawdown, index=curse.columns, columns=['最大回撤'])
drawdown['年化收益率'] = qf_yeild
drawdown['Calmar比率'] = drawdown['年化收益率'] / drawdown['最大回撤']
drawdown['年波动率'] = qf_std
drawdown['夏普比率'] = drawdown['年化收益率'] / drawdown['年波动率']
return drawdown
<|reserved_special_token_1|>
def get_analyse(curse):
'''
要求curse数据中index为时间,columns为策略名称,每一列为该策略净值
'''
qf_drawdown = []
qf_yeild = []
qf_std = []
date = curse.index
y = curse.copy()
for i in curse.columns:
# 计算当前日之前的资金曲线最高点
y["max2here"] = y[i].expanding().max()
# 计算历史最高值到当日的剩余量
y["dd2here"] = y[i] / y["max2here"]
# 计算完回撤后剩余量的最小值(即最大回撤的剩余量),以及最大回撤的结束时间
remain = y.sort_values(by="dd2here").iloc[0]["dd2here"]
end_date = y.sort_values(by="dd2here").iloc[0]
drawdown = round((1 - remain) * 100, 2)
qf_drawdown.append(drawdown)
daylenth = len(date) - 1
yeild = round(((y[i][daylenth]) ** (52 / daylenth) - 1) * 100, 2)
qf_yeild.append(yeild)
y1 = y[i]
r1 = y1 / y1.shift(1) - 1
std = round(np.nanstd(r1) * 52 ** 0.5 * 100, 2)
qf_std.append(std)
drawdown = pd.DataFrame(qf_drawdown, index=curse.columns, columns=["最大回撤"])
drawdown["年化收益率"] = qf_yeild
drawdown["Calmar比率"] = drawdown["年化收益率"] / drawdown["最大回撤"]
drawdown["年波动率"] = qf_std
drawdown["夏普比率"] = drawdown["年化收益率"] / drawdown["年波动率"]
return drawdown
|
flexible
|
{
"blob_id": "56d90835e64bd80fd9a6bb3a9b414e154d314d4a",
"index": 5108,
"step-1": "<mask token>\n",
"step-2": "def get_analyse(curse):\n \"\"\"\n 要求curse数据中index为时间,columns为策略名称,每一列为该策略净值\n\n \"\"\"\n qf_drawdown = []\n qf_yeild = []\n qf_std = []\n date = curse.index\n y = curse.copy()\n for i in curse.columns:\n y['max2here'] = y[i].expanding().max()\n y['dd2here'] = y[i] / y['max2here']\n remain = y.sort_values(by='dd2here').iloc[0]['dd2here']\n end_date = y.sort_values(by='dd2here').iloc[0]\n drawdown = round((1 - remain) * 100, 2)\n qf_drawdown.append(drawdown)\n daylenth = len(date) - 1\n yeild = round((y[i][daylenth] ** (52 / daylenth) - 1) * 100, 2)\n qf_yeild.append(yeild)\n y1 = y[i]\n r1 = y1 / y1.shift(1) - 1\n std = round(np.nanstd(r1) * 52 ** 0.5 * 100, 2)\n qf_std.append(std)\n drawdown = pd.DataFrame(qf_drawdown, index=curse.columns, columns=['最大回撤'])\n drawdown['年化收益率'] = qf_yeild\n drawdown['Calmar比率'] = drawdown['年化收益率'] / drawdown['最大回撤']\n drawdown['年波动率'] = qf_std\n drawdown['夏普比率'] = drawdown['年化收益率'] / drawdown['年波动率']\n return drawdown\n",
"step-3": "\r\ndef get_analyse(curse):\r\n '''\r\n 要求curse数据中index为时间,columns为策略名称,每一列为该策略净值\r\n\r\n '''\r\n qf_drawdown = []\r\n qf_yeild = []\r\n qf_std = []\r\n date = curse.index\r\n y = curse.copy()\r\n for i in curse.columns:\r\n # 计算当前日之前的资金曲线最高点\r\n y[\"max2here\"] = y[i].expanding().max()\r\n # 计算历史最高值到当日的剩余量\r\n y[\"dd2here\"] = y[i] / y[\"max2here\"]\r\n\r\n # 计算完回撤后剩余量的最小值(即最大回撤的剩余量),以及最大回撤的结束时间\r\n remain = y.sort_values(by=\"dd2here\").iloc[0][\"dd2here\"]\r\n end_date = y.sort_values(by=\"dd2here\").iloc[0]\r\n drawdown = round((1 - remain) * 100, 2)\r\n qf_drawdown.append(drawdown)\r\n daylenth = len(date) - 1\r\n yeild = round(((y[i][daylenth]) ** (52 / daylenth) - 1) * 100, 2)\r\n qf_yeild.append(yeild)\r\n y1 = y[i]\r\n r1 = y1 / y1.shift(1) - 1\r\n std = round(np.nanstd(r1) * 52 ** 0.5 * 100, 2)\r\n qf_std.append(std)\r\n drawdown = pd.DataFrame(qf_drawdown, index=curse.columns, columns=[\"最大回撤\"])\r\n drawdown[\"年化收益率\"] = qf_yeild\r\n drawdown[\"Calmar比率\"] = drawdown[\"年化收益率\"] / drawdown[\"最大回撤\"]\r\n drawdown[\"年波动率\"] = qf_std\r\n drawdown[\"夏普比率\"] = drawdown[\"年化收益率\"] / drawdown[\"年波动率\"]\r\n return drawdown",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='idcard', fields=[('id',
models.AutoField(auto_created=True, primary_key=True, serialize=
False, verbose_name='ID')), ('name', models.CharField(max_length=20,
null=True)), ('employment_id', models.CharField(max_length=20, null
=True)), ('customer_account_no', models.CharField(max_length=20,
null=True)), ('circle', models.CharField(max_length=20, null=True)),
('company_name', models.CharField(max_length=20, null=True)), (
'department', models.CharField(max_length=20, null=True)), (
'certificate_no', models.CharField(max_length=20)), ('date', models
.CharField(max_length=20, null=True))])]
<|reserved_special_token_1|>
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='idcard', fields=[('id',
models.AutoField(auto_created=True, primary_key=True, serialize=
False, verbose_name='ID')), ('name', models.CharField(max_length=20,
null=True)), ('employment_id', models.CharField(max_length=20, null
=True)), ('customer_account_no', models.CharField(max_length=20,
null=True)), ('circle', models.CharField(max_length=20, null=True)),
('company_name', models.CharField(max_length=20, null=True)), (
'department', models.CharField(max_length=20, null=True)), (
'certificate_no', models.CharField(max_length=20)), ('date', models
.CharField(max_length=20, null=True))])]
<|reserved_special_token_1|>
# Generated by Django 3.0.5 on 2020-05-12 13:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='idcard',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20, null=True)),
('employment_id', models.CharField(max_length=20, null=True)),
('customer_account_no', models.CharField(max_length=20, null=True)),
('circle', models.CharField(max_length=20, null=True)),
('company_name', models.CharField(max_length=20, null=True)),
('department', models.CharField(max_length=20, null=True)),
('certificate_no', models.CharField(max_length=20)),
('date', models.CharField(max_length=20, null=True)),
],
),
]
|
flexible
|
{
"blob_id": "422873f89468b1faabed96f72f463b6294b85276",
"index": 5314,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='idcard', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('name', models.CharField(max_length=20,\n null=True)), ('employment_id', models.CharField(max_length=20, null\n =True)), ('customer_account_no', models.CharField(max_length=20,\n null=True)), ('circle', models.CharField(max_length=20, null=True)),\n ('company_name', models.CharField(max_length=20, null=True)), (\n 'department', models.CharField(max_length=20, null=True)), (\n 'certificate_no', models.CharField(max_length=20)), ('date', models\n .CharField(max_length=20, null=True))])]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='idcard', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('name', models.CharField(max_length=20,\n null=True)), ('employment_id', models.CharField(max_length=20, null\n =True)), ('customer_account_no', models.CharField(max_length=20,\n null=True)), ('circle', models.CharField(max_length=20, null=True)),\n ('company_name', models.CharField(max_length=20, null=True)), (\n 'department', models.CharField(max_length=20, null=True)), (\n 'certificate_no', models.CharField(max_length=20)), ('date', models\n .CharField(max_length=20, null=True))])]\n",
"step-5": "# Generated by Django 3.0.5 on 2020-05-12 13:26\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='idcard',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=20, null=True)),\n ('employment_id', models.CharField(max_length=20, null=True)),\n ('customer_account_no', models.CharField(max_length=20, null=True)),\n ('circle', models.CharField(max_length=20, null=True)),\n ('company_name', models.CharField(max_length=20, null=True)),\n ('department', models.CharField(max_length=20, null=True)),\n ('certificate_no', models.CharField(max_length=20)),\n ('date', models.CharField(max_length=20, null=True)),\n ],\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import boto3
import json
from botocore.exceptions import ClientError
# upload_to_s3("abc.png", 1)
def upload_to_s3(file_name, node_number):
try:
key_info_json = open("awsinfo.json").read()
except FileNotFoundError:
print("awsinfo.json is not exist in dir.")
exit(-1)
data=json.loads(key_info_json)
s3 = boto3.client(
's3',
aws_access_key_id = data['accessKeyId'],
aws_secret_access_key = data['secretAccessKey']
)
with open(file_name, "rb") as f:
s3.upload_fileobj(f,"capstone12", str(node_number)+"/"+file_name,
ExtraArgs={'ACL' : 'public-read-write'}
)
print("File Upload Complete to " + str(node_number) + "/" + file_name)
|
normal
|
{
"blob_id": "2f0d611fecdb5717029938d2ec2cd2db345b8f3a",
"index": 8176,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef upload_to_s3(file_name, node_number):\n try:\n key_info_json = open('awsinfo.json').read()\n except FileNotFoundError:\n print('awsinfo.json is not exist in dir.')\n exit(-1)\n data = json.loads(key_info_json)\n s3 = boto3.client('s3', aws_access_key_id=data['accessKeyId'],\n aws_secret_access_key=data['secretAccessKey'])\n with open(file_name, 'rb') as f:\n s3.upload_fileobj(f, 'capstone12', str(node_number) + '/' +\n file_name, ExtraArgs={'ACL': 'public-read-write'})\n print('File Upload Complete to ' + str(node_number) + '/' + file_name)\n",
"step-3": "import boto3\nimport json\nfrom botocore.exceptions import ClientError\n\n\ndef upload_to_s3(file_name, node_number):\n try:\n key_info_json = open('awsinfo.json').read()\n except FileNotFoundError:\n print('awsinfo.json is not exist in dir.')\n exit(-1)\n data = json.loads(key_info_json)\n s3 = boto3.client('s3', aws_access_key_id=data['accessKeyId'],\n aws_secret_access_key=data['secretAccessKey'])\n with open(file_name, 'rb') as f:\n s3.upload_fileobj(f, 'capstone12', str(node_number) + '/' +\n file_name, ExtraArgs={'ACL': 'public-read-write'})\n print('File Upload Complete to ' + str(node_number) + '/' + file_name)\n",
"step-4": "import boto3\r\nimport json\r\nfrom botocore.exceptions import ClientError\r\n\r\n# upload_to_s3(\"abc.png\", 1)\r\ndef upload_to_s3(file_name, node_number):\r\n try:\r\n key_info_json = open(\"awsinfo.json\").read()\r\n except FileNotFoundError:\r\n print(\"awsinfo.json is not exist in dir.\")\r\n exit(-1)\r\n\r\n data=json.loads(key_info_json)\r\n\r\n s3 = boto3.client(\r\n 's3',\r\n aws_access_key_id = data['accessKeyId'],\r\n aws_secret_access_key = data['secretAccessKey']\r\n )\r\n\r\n with open(file_name, \"rb\") as f:\r\n s3.upload_fileobj(f,\"capstone12\", str(node_number)+\"/\"+file_name,\r\n ExtraArgs={'ACL' : 'public-read-write'}\r\n )\r\n print(\"File Upload Complete to \" + str(node_number) + \"/\" + file_name)",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
/Users/alyssaliguori/anaconda3/lib/python3.7/tokenize.py
|
normal
|
{
"blob_id": "601ef4e1000348059dcfe8d34eec5f28368f2464",
"index": 8855,
"step-1": "/Users/alyssaliguori/anaconda3/lib/python3.7/tokenize.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
def get_na(dataset):
na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()
na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(
).sum()
return {'male': na_males, 'female': na_females}
def get_counts(dataset):
return dataset.groupby(['Sex', 'AgeGroup']).size()
def generate_age_groups(num, freq):
age_groups = {}
for sex in ['male', 'female']:
relfreq = freq[sex] / freq[sex].sum()
age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex],
replace=True, p=relfreq)
return age_groups
def insert_age_group_values(dataset, age_groups):
for sex in ['male', 'female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]
)
tmp['AgeGroup'] = age_groups[sex]
dataset = dataset.combine_first(tmp)
return dataset
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
get_ipython().magic(u'matplotlib inline')
sns.set_style('whitegrid')
<|reserved_special_token_0|>
print(train_df.columns.values)
train_df.head()
train_df.head(3).T
train_df.info()
print('-' * 40)
test_df.info()
train_df.describe()
train_df.describe(include=['O'])
train_df[train_df.Age == 10].stack()
plt.subplot(211)
sns.countplot(x='Sex', data=train_df, palette='Greens_d')
plt.subplot(212)
sns.barplot(x='Sex', y='Survived', data=train_df, palette='Greens_d')
train_df.groupby('Sex').size()
train_df.groupby(['Sex'])['Survived'].mean().sort_values()
plt.subplots(figsize=(8, 6))
plt.subplot(211)
sns.countplot(x='Pclass', data=train_df, palette='Purples_d')
plt.subplot(212)
sns.barplot(x='Pclass', y='Survived', data=train_df, palette='Purples_d')
train_df.groupby(['Pclass']).size()
train_df.groupby(['Pclass'])['Survived'].mean().sort_values(ascending=False)
train_df.groupby('Age').size().head(25)
<|reserved_special_token_0|>
plt.subplots(figsize=(18, 6))
plt.subplot(311)
sns.kdeplot(age['Age'], shade=True, cut=0)
plt.subplot(312)
sns.countplot(x='Age', data=age, palette='GnBu_d')
plt.subplot(313)
sns.barplot(x='Age', y='Survived', data=age, ci=None, palette='Oranges_d')
<|reserved_special_token_0|>
train_df.groupby('AgeGroup')['Survived'].mean()
train_df[['Survived', 'AgeGroup', 'Sex']].groupby(['Sex', 'AgeGroup']).mean()
sns.factorplot(x='AgeGroup', col='Sex', data=train_df, kind='count')
sns.factorplot(x='AgeGroup', y='Survived', col='Sex', data=train_df, kind='bar'
)
<|reserved_special_token_0|>
plt.subplot(211)
sns.countplot(x='FamilySize', data=train_df)
plt.subplot(212)
sns.barplot(x='FamilySize', y='Survived', data=train_df)
<|reserved_special_token_0|>
train_df[['PassengerId', 'Name', 'Cabin', 'Deck']].head(2).T
plt.subplots(figsize=(8, 6))
plt.subplot(211)
sns.countplot(x='Deck', data=train_df)
plt.subplot(212)
sns.barplot(x='Deck', y='Survived', data=train_df)
def get_na(dataset):
na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()
na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(
).sum()
return {'male': na_males, 'female': na_females}
def get_counts(dataset):
return dataset.groupby(['Sex', 'AgeGroup']).size()
def generate_age_groups(num, freq):
age_groups = {}
for sex in ['male', 'female']:
relfreq = freq[sex] / freq[sex].sum()
age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex],
replace=True, p=relfreq)
return age_groups
def insert_age_group_values(dataset, age_groups):
for sex in ['male', 'female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]
)
tmp['AgeGroup'] = age_groups[sex]
dataset = dataset.combine_first(tmp)
return dataset
<|reserved_special_token_0|>
counts['female']
<|reserved_special_token_0|>
age_groups['female']
<|reserved_special_token_0|>
train_df.info()
print('-' * 40)
<|reserved_special_token_0|>
test_df.info()
<|reserved_special_token_0|>
train_df[['Name', 'Sex', 'Female']].head(2).T
<|reserved_special_token_0|>
train_df[['Name', 'Pclass', 'PClass_1', 'PClass_2']].head(2).T
<|reserved_special_token_0|>
test_df['Fare'].fillna(test_df['Fare'].median(), inplace=True)
print(train_df.groupby('Embarked').size().sort_values())
<|reserved_special_token_0|>
train_df.drop(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
'Parch', 'Ticket', 'Cabin', 'Fare', 'Embarked', 'Deck', 'AgeGroup'],
axis=1, inplace=True)
test_df.drop(['Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket',
'Cabin', 'Fare', 'Embarked', 'AgeGroup'], axis=1, inplace=True)
train_df.head(10).T
<|reserved_special_token_0|>
X_train.shape, Y_train.shape, X_test.shape
<|reserved_special_token_0|>
acc_log
logreg.fit(X_train, Y_train)
<|reserved_special_token_0|>
coeff_df.sort_values(by='Correlation', ascending=False)
<|reserved_special_token_0|>
acc_gaussian
<|reserved_special_token_0|>
acc_perceptron
<|reserved_special_token_0|>
acc_neural_net
<|reserved_special_token_0|>
acc_sgd
<|reserved_special_token_0|>
acc_linear_svc
<|reserved_special_token_0|>
acc_svc
<|reserved_special_token_0|>
acc_decision_tree
<|reserved_special_token_0|>
acc_random_forest
<|reserved_special_token_0|>
acc_ada_boost
<|reserved_special_token_0|>
acc_knn
<|reserved_special_token_0|>
models.sort_values(by='Score', ascending=False)
random_forest.fit(X_train, Y_train)
<|reserved_special_token_0|>
submission.to_csv('titanic_submission_1.csv', index=False)
<|reserved_special_token_0|>
random_forest.fit(X_train, Y_train)
<|reserved_special_token_0|>
acc_random_forest
<|reserved_special_token_1|>
<|reserved_special_token_0|>
get_ipython().magic(u'matplotlib inline')
sns.set_style('whitegrid')
<|reserved_special_token_0|>
train_df = pd.read_csv('../input/train.csv')
test_df = pd.read_csv('../input/test.csv')
combine = [train_df, test_df]
print(train_df.columns.values)
train_df.head()
train_df.head(3).T
train_df.info()
print('-' * 40)
test_df.info()
train_df.describe()
train_df.describe(include=['O'])
train_df[train_df.Age == 10].stack()
plt.subplot(211)
sns.countplot(x='Sex', data=train_df, palette='Greens_d')
plt.subplot(212)
sns.barplot(x='Sex', y='Survived', data=train_df, palette='Greens_d')
train_df.groupby('Sex').size()
train_df.groupby(['Sex'])['Survived'].mean().sort_values()
plt.subplots(figsize=(8, 6))
plt.subplot(211)
sns.countplot(x='Pclass', data=train_df, palette='Purples_d')
plt.subplot(212)
sns.barplot(x='Pclass', y='Survived', data=train_df, palette='Purples_d')
train_df.groupby(['Pclass']).size()
train_df.groupby(['Pclass'])['Survived'].mean().sort_values(ascending=False)
train_df.groupby('Age').size().head(25)
age = train_df[['Age', 'Survived']].dropna()
age['Age'] = age['Age'].astype(int)
plt.subplots(figsize=(18, 6))
plt.subplot(311)
sns.kdeplot(age['Age'], shade=True, cut=0)
plt.subplot(312)
sns.countplot(x='Age', data=age, palette='GnBu_d')
plt.subplot(313)
sns.barplot(x='Age', y='Survived', data=age, ci=None, palette='Oranges_d')
train_df['AgeGroup'] = pd.cut(train_df['Age'], [0, 4, 15, 25, 35, 45, 65, 100])
test_df['AgeGroup'] = pd.cut(test_df['Age'], [0, 4, 15, 25, 35, 45, 65, 100])
train_df.groupby('AgeGroup')['Survived'].mean()
train_df[['Survived', 'AgeGroup', 'Sex']].groupby(['Sex', 'AgeGroup']).mean()
sns.factorplot(x='AgeGroup', col='Sex', data=train_df, kind='count')
sns.factorplot(x='AgeGroup', y='Survived', col='Sex', data=train_df, kind='bar'
)
train_df['FamilySize'] = train_df['SibSp'] + train_df['Parch'] + 1
test_df['FamilySize'] = test_df['SibSp'] + test_df['Parch'] + 1
plt.subplot(211)
sns.countplot(x='FamilySize', data=train_df)
plt.subplot(212)
sns.barplot(x='FamilySize', y='Survived', data=train_df)
train_df['Deck'] = train_df['Cabin'].dropna().apply(lambda x: str(x)[0])
train_df[['PassengerId', 'Name', 'Cabin', 'Deck']].head(2).T
plt.subplots(figsize=(8, 6))
plt.subplot(211)
sns.countplot(x='Deck', data=train_df)
plt.subplot(212)
sns.barplot(x='Deck', y='Survived', data=train_df)
def get_na(dataset):
na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()
na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(
).sum()
return {'male': na_males, 'female': na_females}
def get_counts(dataset):
return dataset.groupby(['Sex', 'AgeGroup']).size()
def generate_age_groups(num, freq):
age_groups = {}
for sex in ['male', 'female']:
relfreq = freq[sex] / freq[sex].sum()
age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex],
replace=True, p=relfreq)
return age_groups
def insert_age_group_values(dataset, age_groups):
for sex in ['male', 'female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]
)
tmp['AgeGroup'] = age_groups[sex]
dataset = dataset.combine_first(tmp)
return dataset
na = get_na(train_df)
counts = get_counts(train_df)
counts['female']
age_groups = generate_age_groups(na, counts)
age_groups['female']
train_df = insert_age_group_values(train_df, age_groups)
train_df.info()
print('-' * 40)
na = get_na(test_df)
counts = get_counts(train_df)
age_groups = generate_age_groups(na, counts)
test_df = insert_age_group_values(test_df, age_groups)
test_df.info()
dummy = pd.get_dummies(train_df['Sex'])
dummy.columns = ['Female', 'Male']
train_df = train_df.join(dummy['Female'])
dummy = pd.get_dummies(test_df['Sex'])
dummy.columns = ['Female', 'Male']
test_df = test_df.join(dummy['Female'])
train_df[['Name', 'Sex', 'Female']].head(2).T
dummy = pd.get_dummies(train_df['Pclass'])
dummy.columns = ['PClass_1', 'PClass_2', 'PClass_3']
train_df = train_df.join(dummy[['PClass_1', 'PClass_2']])
dummy = pd.get_dummies(test_df['Pclass'])
dummy.columns = ['PClass_1', 'PClass_2', 'PClass_3']
test_df = test_df.join(dummy[['PClass_1', 'PClass_2']])
train_df[['Name', 'Pclass', 'PClass_1', 'PClass_2']].head(2).T
dummy = pd.get_dummies(train_df['AgeGroup'])
dummy.columns = ['Ages_4', 'Ages_15', 'Ages_25', 'Ages_35', 'Ages_45',
'Ages_65', 'Ages_100']
train_df = train_df.join(dummy)
dummy = pd.get_dummies(test_df['AgeGroup'])
dummy.columns = ['Ages_4', 'Ages_15', 'Ages_25', 'Ages_35', 'Ages_45',
'Ages_65', 'Ages_100']
test_df = test_df.join(dummy)
test_df['Fare'].fillna(test_df['Fare'].median(), inplace=True)
print(train_df.groupby('Embarked').size().sort_values())
train_df['Embarked'] = train_df['Embarked'].fillna('S')
dummy = pd.get_dummies(train_df['Embarked'])
dummy.columns = ['Port_C', 'Port_Q', 'Port_S']
dummy = pd.get_dummies(test_df['Embarked'])
dummy.columns = ['Port_C', 'Port_Q', 'Port_S']
train_df.drop(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
'Parch', 'Ticket', 'Cabin', 'Fare', 'Embarked', 'Deck', 'AgeGroup'],
axis=1, inplace=True)
test_df.drop(['Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket',
'Cabin', 'Fare', 'Embarked', 'AgeGroup'], axis=1, inplace=True)
train_df.head(10).T
X_train = train_df.drop('Survived', axis=1)
Y_train = train_df['Survived']
X_test = test_df.drop('PassengerId', axis=1).copy()
X_train.shape, Y_train.shape, X_test.shape
logreg = LogisticRegression()
scores = cross_val_score(logreg, X_train, Y_train, cv=10)
acc_log = round(scores.mean() * 100, 2)
acc_log
logreg.fit(X_train, Y_train)
coeff_df = pd.DataFrame(train_df.columns.delete(0))
coeff_df.columns = ['Feature']
coeff_df['Correlation'] = pd.Series(logreg.coef_[0])
coeff_df.sort_values(by='Correlation', ascending=False)
gaussian = GaussianNB()
scores = cross_val_score(gaussian, X_train, Y_train, cv=10)
acc_gaussian = round(scores.mean() * 100, 2)
acc_gaussian
perceptron = Perceptron()
scores = cross_val_score(perceptron, X_train, Y_train, cv=10)
acc_perceptron = round(scores.mean() * 100, 2)
acc_perceptron
neural_net = MLPClassifier()
scores = cross_val_score(neural_net, X_train, Y_train, cv=10)
acc_neural_net = round(scores.mean() * 100, 2)
acc_neural_net
sgd = SGDClassifier()
scores = cross_val_score(sgd, X_train, Y_train, cv=10)
acc_sgd = round(scores.mean() * 100, 2)
acc_sgd
linear_svc = LinearSVC()
scores = cross_val_score(linear_svc, X_train, Y_train, cv=10)
acc_linear_svc = round(scores.mean() * 100, 2)
acc_linear_svc
svc = SVC()
scores = cross_val_score(svc, X_train, Y_train, cv=10)
acc_svc = round(scores.mean() * 100, 2)
acc_svc
decision_tree = DecisionTreeClassifier()
scores = cross_val_score(decision_tree, X_train, Y_train, cv=10)
acc_decision_tree = round(scores.mean() * 100, 2)
acc_decision_tree
random_forest = RandomForestClassifier(n_estimators=100)
scores = cross_val_score(random_forest, X_train, Y_train, cv=10)
acc_random_forest = round(scores.mean() * 100, 2)
acc_random_forest
ada_boost = AdaBoostClassifier(n_estimators=100)
scores = cross_val_score(ada_boost, X_train, Y_train, cv=10)
acc_ada_boost = round(scores.mean() * 100, 2)
acc_ada_boost
knn = KNeighborsClassifier(n_neighbors=5)
scores = cross_val_score(knn, X_train, Y_train, cv=10)
acc_knn = round(scores.mean() * 100, 2)
acc_knn
models = pd.DataFrame({'Model': ['Support Vector Machine', 'kNN',
'Logistic Regression', 'Random Forest', 'Naive Bayes', 'Perceptron',
'Stochastic Gradient Descent', 'Linear SVC', 'Decision Tree',
'AdaBoost', 'Neural Network'], 'Score': [acc_svc, acc_knn, acc_log,
acc_random_forest, acc_gaussian, acc_perceptron, acc_sgd,
acc_linear_svc, acc_decision_tree, acc_ada_boost, acc_neural_net]})
models.sort_values(by='Score', ascending=False)
random_forest.fit(X_train, Y_train)
Y_pred = random_forest.predict(X_test)
submission = pd.DataFrame({'PassengerId': test_df['PassengerId'],
'Survived': Y_pred})
submission.to_csv('titanic_submission_1.csv', index=False)
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, Y_train)
acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
acc_random_forest
<|reserved_special_token_1|>
import pandas as pd
import numpy as np
import random as rnd
import matplotlib.pyplot as plt
import seaborn as sns
get_ipython().magic(u'matplotlib inline')
sns.set_style('whitegrid')
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.neural_network import MLPClassifier
train_df = pd.read_csv('../input/train.csv')
test_df = pd.read_csv('../input/test.csv')
combine = [train_df, test_df]
print(train_df.columns.values)
train_df.head()
train_df.head(3).T
train_df.info()
print('-' * 40)
test_df.info()
train_df.describe()
train_df.describe(include=['O'])
train_df[train_df.Age == 10].stack()
plt.subplot(211)
sns.countplot(x='Sex', data=train_df, palette='Greens_d')
plt.subplot(212)
sns.barplot(x='Sex', y='Survived', data=train_df, palette='Greens_d')
train_df.groupby('Sex').size()
train_df.groupby(['Sex'])['Survived'].mean().sort_values()
plt.subplots(figsize=(8, 6))
plt.subplot(211)
sns.countplot(x='Pclass', data=train_df, palette='Purples_d')
plt.subplot(212)
sns.barplot(x='Pclass', y='Survived', data=train_df, palette='Purples_d')
train_df.groupby(['Pclass']).size()
train_df.groupby(['Pclass'])['Survived'].mean().sort_values(ascending=False)
train_df.groupby('Age').size().head(25)
age = train_df[['Age', 'Survived']].dropna()
age['Age'] = age['Age'].astype(int)
plt.subplots(figsize=(18, 6))
plt.subplot(311)
sns.kdeplot(age['Age'], shade=True, cut=0)
plt.subplot(312)
sns.countplot(x='Age', data=age, palette='GnBu_d')
plt.subplot(313)
sns.barplot(x='Age', y='Survived', data=age, ci=None, palette='Oranges_d')
train_df['AgeGroup'] = pd.cut(train_df['Age'], [0, 4, 15, 25, 35, 45, 65, 100])
test_df['AgeGroup'] = pd.cut(test_df['Age'], [0, 4, 15, 25, 35, 45, 65, 100])
train_df.groupby('AgeGroup')['Survived'].mean()
train_df[['Survived', 'AgeGroup', 'Sex']].groupby(['Sex', 'AgeGroup']).mean()
sns.factorplot(x='AgeGroup', col='Sex', data=train_df, kind='count')
sns.factorplot(x='AgeGroup', y='Survived', col='Sex', data=train_df, kind='bar'
)
train_df['FamilySize'] = train_df['SibSp'] + train_df['Parch'] + 1
test_df['FamilySize'] = test_df['SibSp'] + test_df['Parch'] + 1
plt.subplot(211)
sns.countplot(x='FamilySize', data=train_df)
plt.subplot(212)
sns.barplot(x='FamilySize', y='Survived', data=train_df)
train_df['Deck'] = train_df['Cabin'].dropna().apply(lambda x: str(x)[0])
train_df[['PassengerId', 'Name', 'Cabin', 'Deck']].head(2).T
plt.subplots(figsize=(8, 6))
plt.subplot(211)
sns.countplot(x='Deck', data=train_df)
plt.subplot(212)
sns.barplot(x='Deck', y='Survived', data=train_df)
def get_na(dataset):
na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()
na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(
).sum()
return {'male': na_males, 'female': na_females}
def get_counts(dataset):
return dataset.groupby(['Sex', 'AgeGroup']).size()
def generate_age_groups(num, freq):
age_groups = {}
for sex in ['male', 'female']:
relfreq = freq[sex] / freq[sex].sum()
age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex],
replace=True, p=relfreq)
return age_groups
def insert_age_group_values(dataset, age_groups):
for sex in ['male', 'female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]
)
tmp['AgeGroup'] = age_groups[sex]
dataset = dataset.combine_first(tmp)
return dataset
na = get_na(train_df)
counts = get_counts(train_df)
counts['female']
age_groups = generate_age_groups(na, counts)
age_groups['female']
train_df = insert_age_group_values(train_df, age_groups)
train_df.info()
print('-' * 40)
na = get_na(test_df)
counts = get_counts(train_df)
age_groups = generate_age_groups(na, counts)
test_df = insert_age_group_values(test_df, age_groups)
test_df.info()
dummy = pd.get_dummies(train_df['Sex'])
dummy.columns = ['Female', 'Male']
train_df = train_df.join(dummy['Female'])
dummy = pd.get_dummies(test_df['Sex'])
dummy.columns = ['Female', 'Male']
test_df = test_df.join(dummy['Female'])
train_df[['Name', 'Sex', 'Female']].head(2).T
dummy = pd.get_dummies(train_df['Pclass'])
dummy.columns = ['PClass_1', 'PClass_2', 'PClass_3']
train_df = train_df.join(dummy[['PClass_1', 'PClass_2']])
dummy = pd.get_dummies(test_df['Pclass'])
dummy.columns = ['PClass_1', 'PClass_2', 'PClass_3']
test_df = test_df.join(dummy[['PClass_1', 'PClass_2']])
train_df[['Name', 'Pclass', 'PClass_1', 'PClass_2']].head(2).T
dummy = pd.get_dummies(train_df['AgeGroup'])
dummy.columns = ['Ages_4', 'Ages_15', 'Ages_25', 'Ages_35', 'Ages_45',
'Ages_65', 'Ages_100']
train_df = train_df.join(dummy)
dummy = pd.get_dummies(test_df['AgeGroup'])
dummy.columns = ['Ages_4', 'Ages_15', 'Ages_25', 'Ages_35', 'Ages_45',
'Ages_65', 'Ages_100']
test_df = test_df.join(dummy)
test_df['Fare'].fillna(test_df['Fare'].median(), inplace=True)
print(train_df.groupby('Embarked').size().sort_values())
train_df['Embarked'] = train_df['Embarked'].fillna('S')
dummy = pd.get_dummies(train_df['Embarked'])
dummy.columns = ['Port_C', 'Port_Q', 'Port_S']
dummy = pd.get_dummies(test_df['Embarked'])
dummy.columns = ['Port_C', 'Port_Q', 'Port_S']
train_df.drop(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
'Parch', 'Ticket', 'Cabin', 'Fare', 'Embarked', 'Deck', 'AgeGroup'],
axis=1, inplace=True)
test_df.drop(['Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket',
'Cabin', 'Fare', 'Embarked', 'AgeGroup'], axis=1, inplace=True)
train_df.head(10).T
X_train = train_df.drop('Survived', axis=1)
Y_train = train_df['Survived']
X_test = test_df.drop('PassengerId', axis=1).copy()
X_train.shape, Y_train.shape, X_test.shape
logreg = LogisticRegression()
scores = cross_val_score(logreg, X_train, Y_train, cv=10)
acc_log = round(scores.mean() * 100, 2)
acc_log
logreg.fit(X_train, Y_train)
coeff_df = pd.DataFrame(train_df.columns.delete(0))
coeff_df.columns = ['Feature']
coeff_df['Correlation'] = pd.Series(logreg.coef_[0])
coeff_df.sort_values(by='Correlation', ascending=False)
gaussian = GaussianNB()
scores = cross_val_score(gaussian, X_train, Y_train, cv=10)
acc_gaussian = round(scores.mean() * 100, 2)
acc_gaussian
perceptron = Perceptron()
scores = cross_val_score(perceptron, X_train, Y_train, cv=10)
acc_perceptron = round(scores.mean() * 100, 2)
acc_perceptron
neural_net = MLPClassifier()
scores = cross_val_score(neural_net, X_train, Y_train, cv=10)
acc_neural_net = round(scores.mean() * 100, 2)
acc_neural_net
sgd = SGDClassifier()
scores = cross_val_score(sgd, X_train, Y_train, cv=10)
acc_sgd = round(scores.mean() * 100, 2)
acc_sgd
linear_svc = LinearSVC()
scores = cross_val_score(linear_svc, X_train, Y_train, cv=10)
acc_linear_svc = round(scores.mean() * 100, 2)
acc_linear_svc
svc = SVC()
scores = cross_val_score(svc, X_train, Y_train, cv=10)
acc_svc = round(scores.mean() * 100, 2)
acc_svc
decision_tree = DecisionTreeClassifier()
scores = cross_val_score(decision_tree, X_train, Y_train, cv=10)
acc_decision_tree = round(scores.mean() * 100, 2)
acc_decision_tree
random_forest = RandomForestClassifier(n_estimators=100)
scores = cross_val_score(random_forest, X_train, Y_train, cv=10)
acc_random_forest = round(scores.mean() * 100, 2)
acc_random_forest
ada_boost = AdaBoostClassifier(n_estimators=100)
scores = cross_val_score(ada_boost, X_train, Y_train, cv=10)
acc_ada_boost = round(scores.mean() * 100, 2)
acc_ada_boost
knn = KNeighborsClassifier(n_neighbors=5)
scores = cross_val_score(knn, X_train, Y_train, cv=10)
acc_knn = round(scores.mean() * 100, 2)
acc_knn
models = pd.DataFrame({'Model': ['Support Vector Machine', 'kNN',
'Logistic Regression', 'Random Forest', 'Naive Bayes', 'Perceptron',
'Stochastic Gradient Descent', 'Linear SVC', 'Decision Tree',
'AdaBoost', 'Neural Network'], 'Score': [acc_svc, acc_knn, acc_log,
acc_random_forest, acc_gaussian, acc_perceptron, acc_sgd,
acc_linear_svc, acc_decision_tree, acc_ada_boost, acc_neural_net]})
models.sort_values(by='Score', ascending=False)
random_forest.fit(X_train, Y_train)
Y_pred = random_forest.predict(X_test)
submission = pd.DataFrame({'PassengerId': test_df['PassengerId'],
'Survived': Y_pred})
submission.to_csv('titanic_submission_1.csv', index=False)
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, Y_train)
acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
acc_random_forest
<|reserved_special_token_1|>
#!/usr/bin/env python
# coding: utf-8
# Predicting Surviving the Sinking of the Titanic
# -----------------------------------------------
#
#
# This represents my first attempt at training up some classifiers for the titanic dataset.
# In[ ]:
# data analysis and wrangling
import pandas as pd
import numpy as np
import random as rnd
# visualization
import matplotlib.pyplot as plt
import seaborn as sns
get_ipython().magic(u'matplotlib inline')
sns.set_style("whitegrid")
# machine learning
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.neural_network import MLPClassifier
# In[ ]:
# get titanic & test csv files as a DataFrame
train_df = pd.read_csv("../input/train.csv")
test_df = pd.read_csv("../input/test.csv")
combine = [train_df, test_df]
# # Data exploration #
#
# First get some summary statistics about the datasets.
# In[ ]:
# view column labels
print(train_df.columns.values)
# In[ ]:
# preview the data
train_df.head()
# Now transpose the first few rows in order to see all attributes more easily as row labels.
# In[ ]:
train_df.head(3).T
# In[ ]:
# missing values, data types
train_df.info()
print('-'*40)
test_df.info()
# The above info shows that columns (from training data) with missing/empty values are:
#
# - Age (177 missing values)
# - Cabin (687 missing values)
# - Embarked (2 missing values)
# In[ ]:
# describe numeric columns
train_df.describe()
# In the training dataset there are 891 passengers with an overall survival rate of 38.4%.
# The oldest person is 80 years and the youngest is 5 months (0.42*12). The average fare is 32.20 dollars but the median fare is 14.45. This suggests outliers at the upper end of the fare, and indeed the maximum fare is $512.33.
# In[ ]:
# describe categorical columns
train_df.describe(include=['O'])
# In[ ]:
# just for fun, examine the records of ten year olds (there are only two)
train_df[train_df.Age == 10].stack()
# # Detailed data investigation #
#
# A closer look at each of the attributes (columns) and their relationship to survival.
# ##Sex##
#
# Sex is a *nominal* attribute with two categories (i.e. it is dichotomous). Let's plot some counts and survival rates by sex. Note that survival values are 0/1, thus rates can be be calculated simply via the mean survive value.
# In[ ]:
# count passengers by sex
plt.subplot(211) # 3 digit convenience notation for arguments (last digit represents plot number)
sns.countplot(x='Sex', data=train_df, palette='Greens_d')
# survival rate by sex
# note that barplot plots mean() on y by default
plt.subplot(212)
sns.barplot(x='Sex', y='Survived', data=train_df, palette='Greens_d')
# **Observations:**
#
# - Many more males than females
# - Survival rate of females much greater than males
#
# Let's get the actual numbers below using pandas.
# In[ ]:
# count passengers by sex
train_df.groupby('Sex').size()
# In[ ]:
# survival rates by sex
train_df.groupby(['Sex'])['Survived'].mean().sort_values()
# Thus, 18.9% of males (from the training set) survived compared to 74.2% of females.
# ##Passenger class##
#
# Passenger class (Pclass) is an *ordinal* attribute with three categories, 1, 2 and 3. The three categories have an order (representing socioeconomic status) but although the categories are given numeric labels, this attribute *is not* numeric! To see this, consider that 3rd class = 1st + 2nd class is a nonsense. This will be important later when we construct features. Again, let's plot some counts and survival rates.
# In[ ]:
# size of groups in passenger class
plt.subplots(figsize=(8,6))
plt.subplot(211)
sns.countplot(x='Pclass', data=train_df, palette='Purples_d') # _d = dark palette
# survival rate by sex
plt.subplot(212)
sns.barplot(x='Pclass', y='Survived', data=train_df, palette='Purples_d')
# **Observations:**
#
# - Three classes
# - Most passengers travelled by 3rd class (more than half; see below)
# - Survival rate increases with class
#
# Again, let's get the actual numbers below using pandas.
# In[ ]:
# count passengers by passenger class
train_df.groupby(['Pclass']).size()
# In[ ]:
# survival rates by passenger class
train_df.groupby(['Pclass'])['Survived'].mean().sort_values(ascending=False)
# ##Age##
#
# Age is a *ratio* attribute (it is properly numeric, see [Types of data measurement scales][1]). Ages < 1 indicate age in months.
#
#
# [1]: http://www.mymarketresearchmethods.com/types-of-data-nominal-ordinal-interval-ratio/
# In[ ]:
# count the number of passengers for first 25 ages
train_df.groupby('Age').size().head(25)
# another way to do the above
#train_df['Age'].value_counts().sort_index().head(25)
# In[ ]:
# convert ages to ints
age = train_df[['Age','Survived']].dropna() # returns a copy with blanks removed
age['Age'] = age['Age'].astype(int) # floors floats
# count passengers by age (smoothed via gaussian kernels)
plt.subplots(figsize=(18,6))
plt.subplot(311)
sns.kdeplot(age['Age'], shade=True, cut=0)
# count passengers by age (no smoothing)
plt.subplot(312)
sns.countplot(x='Age', data=age, palette='GnBu_d')
# survival rates by age
plt.subplot(313)
sns.barplot(x='Age', y='Survived', data=age, ci=None, palette='Oranges_d') # takes mean by default
# Observations:
#
# - Under 16s tend to have the highest survival rates
# - Very high survival rates at 53, 63 and 80
# - Survival of over 16s is fairly noisy. Possible that survival might increase with age.
# ## Survival by age group and sex ##
#
# Now let's look at survival by age groups *and* sex to see if any patterns become clearer.
# In[ ]:
# bin age into groups
train_df['AgeGroup'] = pd.cut(train_df['Age'],[0,4,15,25,35,45,65,100])
test_df['AgeGroup'] = pd.cut(test_df['Age'],[0,4,15,25,35,45,65,100])
# survival by age group
train_df.groupby('AgeGroup')['Survived'].mean()
# In[ ]:
# survival by age group and sex
train_df[['Survived','AgeGroup', 'Sex']].groupby(['Sex', 'AgeGroup']).mean()
# In[ ]:
# count passengers by age group and sex
sns.factorplot(x='AgeGroup', col='Sex', data=train_df, kind='count')
# survival by age group and sex
sns.factorplot(x='AgeGroup', y='Survived', col='Sex', data=train_df, kind='bar')
# The relationship between survival and age group looks very different for males and females:
#
# - Males: survival rates increase *inversely* with age for (0, 25] and (25, 100). That is, younger boys fare better than older boys and younger men survive more than older men.
# - Females: no obvious relationship between surviving and age. In particular, girls and baby girls do not fare better than women; in fact, girls (4, 15] have the *lowest* survival rates of females.
#
# A feature space containing (child, man, woman) would do a decent job of representing this relationship to survivability.
#
# Non-linear classifiers (e.g. decision trees, multi-layer nn, nearest neighbour) applied to both sex and age group might do even better because of the noticeable relationship between survivability and age group for males.
# ## Family Size##
#
# We create a new feature, FamilySize, that sums Parch and SibSp. This will enable us to drop Parch and SibSp from the datasets.
# In[ ]:
# calculate family size
train_df['FamilySize'] = train_df['SibSp'] + train_df['Parch'] + 1
test_df['FamilySize'] = test_df['SibSp'] + test_df['Parch'] + 1
# count passengers by age group and sex
plt.subplot(211)
sns.countplot(x='FamilySize', data=train_df)
# survival by age group and sex
plt.subplot(212)
sns.barplot(x='FamilySize', y='Survived', data=train_df)
# Survival increases with family size, until families of size 4. Family sizes of 5 and above have reduced survival.
# Deck
# ----
#
# Cabin might be conceivably be related to survival, but unfortunately most values are missing. Nevertheless, by way of an exercise, we will extract the feature, Deck, from cabin by taking the first character of the label and analyze survival rates by deck.
# In[ ]:
# deck is the first letter of cabin
train_df['Deck'] = train_df['Cabin'].dropna().apply(lambda x: str(x)[0])
train_df[['PassengerId','Name', 'Cabin', 'Deck']].head(2).T
# In[ ]:
# count passengers by the deck their cabin is on
plt.subplots(figsize=(8,6))
plt.subplot(211)
sns.countplot(x='Deck', data=train_df)
# survival rate by deck
plt.subplot(212)
sns.barplot(x='Deck', y='Survived', data=train_df)
# ## Other attributes ##
# For this first attempt, I am ignoring the attributes below as they seem unlikely to be related to survival:
#
# - PassengerId
# - Name (however, extracting titles from names might be informative)
# - Ticket
# - Fare (could be related to socioeconomic status but we already have a class attribute)
# - Embarked
# # Data wrangling - Age group#
#
# Fill missing age group values. We don't want to drop them as this would lose many rows. Instead, we will randomly generate age groups according to the frequency that they occur in the data. We will calculate the frequency separately for males and females.
# In[ ]:
# number of males/females without an age
def get_na(dataset):
na_males = dataset[dataset.Sex == 'male'].loc[:,'AgeGroup'].isnull().sum()
na_females = dataset[dataset.Sex == 'female'].loc[:,'AgeGroup'].isnull().sum()
return {'male': na_males, 'female': na_females}
# number of males and females by age group
def get_counts(dataset):
return dataset.groupby(['Sex', 'AgeGroup']).size()
# randomly generate a list of age groups based on age group frequency (for each sex separately)
def generate_age_groups(num, freq):
age_groups = {}
for sex in ['male','female']:
relfreq = freq[sex] / freq[sex].sum()
age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex], replace=True, p=relfreq)
return age_groups
# insert the new age group values
def insert_age_group_values(dataset, age_groups):
for sex in ['male','female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]) # filter on sex and null ages
tmp['AgeGroup'] = age_groups[sex] # index age group values
dataset = dataset.combine_first(tmp) # uses tmp to fill holes
return dataset
# fill holes for train_df
na = get_na(train_df)
counts = get_counts(train_df)
counts['female']
age_groups = generate_age_groups(na, counts)
age_groups['female']
train_df = insert_age_group_values(train_df, age_groups)
train_df.info() # check all nulls have been filled
print('-'*40)
# repeat for test_df
na = get_na(test_df)
counts = get_counts(train_df) # reuse the frequencies taken over the training data as it is larger
age_groups = generate_age_groups(na, counts)
test_df = insert_age_group_values(test_df, age_groups)
test_df.info() # check all nulls have been filled
# # Feature engineering #
#
# Now that we've explored the data let's create some features:
#
# - **Sex:** Convert to a single binary feature, Female. No need to create a feature for Male, that would be redundant.
# - **Pclass:** Convert to two binary features, PClass_1 and PClass_2. Similar to Male above, having a PClass_3 would be redundant.
# - **Age group:** The age attribute binned using separators [0, 4, 15, 25, 35, 45, 65, 100]. Convert to a number of binary features, one for each age group.
# - **Family size:** The sum of SibSp and Parch plus 1.
# In[ ]:
# Sex -> Female
# training set
dummy = pd.get_dummies(train_df['Sex'])
dummy.columns = ['Female','Male']
train_df = train_df.join(dummy['Female'])
# test set
dummy = pd.get_dummies(test_df['Sex'])
dummy.columns = ['Female','Male']
test_df = test_df.join(dummy['Female'])
train_df[['Name', 'Sex', 'Female']].head(2).T
#train_df.columns
# In[ ]:
# Pclass -> PClass_1, PClass_2
# training set
dummy = pd.get_dummies(train_df['Pclass'])
dummy.columns = ['PClass_1','PClass_2','PClass_3']
train_df = train_df.join(dummy[['PClass_1', 'PClass_2']])
# test set
dummy = pd.get_dummies(test_df['Pclass'])
dummy.columns = ['PClass_1','PClass_2','PClass_3']
test_df = test_df.join(dummy[['PClass_1', 'PClass_2']])
train_df[['Name', 'Pclass', 'PClass_1', 'PClass_2']].head(2).T
#train_df.columns
# In[ ]:
# AgeGroup -> binary features
# training set
dummy = pd.get_dummies(train_df['AgeGroup'])
dummy.columns = ['Ages_4','Ages_15','Ages_25','Ages_35','Ages_45','Ages_65','Ages_100']
train_df = train_df.join(dummy)
# test set
dummy = pd.get_dummies(test_df['AgeGroup'])
dummy.columns = ['Ages_4','Ages_15','Ages_25','Ages_35','Ages_45','Ages_65','Ages_100']
test_df = test_df.join(dummy)
# ## Experimental features ##
# Some additional features to explore.
# In[ ]:
# Fare
# there is a single missing "Fare" value
test_df['Fare'].fillna(test_df['Fare'].median(), inplace=True)
# convert from float to int (floor)
#train_df['Fare'] = train_df['Fare'].astype(int)
#test_df['Fare'] = test_df['Fare'].astype(int)
# In[ ]:
# Embarked -> PortC, PortQ
# Fill missing values with the most occurred value
print(train_df.groupby('Embarked').size().sort_values())
train_df['Embarked'] = train_df['Embarked'].fillna('S')
# training set
dummy = pd.get_dummies(train_df['Embarked'])
#dummy.columns
dummy.columns = ['Port_C','Port_Q','Port_S']
#train_df = train_df.join(dummy[['Port_C','Port_Q']])
# test set
dummy = pd.get_dummies(test_df['Embarked'])
dummy.columns = ['Port_C','Port_Q','Port_S']
#test_df = test_df.join(dummy[['Port_C','Port_Q']])
# ## Dropping attributes ##
# Drop unused attributes to avoid detecting spurious relationships.
# In[ ]:
# drop the attributes that will be unused
train_df.drop(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age',
'SibSp', 'Parch', 'Ticket', 'Cabin', 'Fare',
'Embarked', 'Deck', 'AgeGroup'], axis=1, inplace=True)
test_df.drop(['Pclass', 'Name', 'Sex', 'Age',
'SibSp', 'Parch', 'Ticket', 'Cabin', 'Fare',
'Embarked', 'AgeGroup'], axis=1, inplace=True)
train_df.head(10).T
# The sample above shows the features and their values for the first ten training examples.
# # Modeling #
#
# Our task is a binary classification problem: we want to formulate a relationship that predicts an output (Survived or not) from engineered features (Sex, Age group, Family size...). This is type of learning is supervised learning, since a model will be trained on a dataset containing pairs of inputs and outputs.
#
# Suitable methods for performing classification include:
#
# - Logistic Regression*
# - Perceptron*
# - Support Vector Machines (SVMs)*
# - Naive Bayes classifier*
# - KNN or k-Nearest Neighbors
# - Decision Tree
# - Random Forrest
# - Artificial neural network
# - Relevance Vector Machine
#
# The methods marked * either discover linear classification boundaries (logistic regression, perceptron, and SVMs if using linear kernels) or assume no relationship between features (naive bayes) and thus are not expected to perform as well (see the section above on the relationship between survival, age group and sex).
# ## Training data ##
# Let's use cross validation to perform the evaluation. This method will give a reasonable indication of predictive accuracy as evaluation will take place on data that is not seen during training. The package **`sklearn.model_selection`** includes support for cross validation.
# In[ ]:
# split the datasets into matched input and ouput pairs
X_train = train_df.drop("Survived", axis=1) # X = inputs
Y_train = train_df["Survived"] # Y = outputs
X_test = test_df.drop("PassengerId", axis=1).copy()
X_train.shape, Y_train.shape, X_test.shape
# Model fitting
# ----------
# (Some of this section is based on [this titanic tutorial][1].)
#
# Logistic Regression is a useful model to run early in the workflow. Logistic regression measures the relationship between the categorical dependent variable (feature) and one or more independent variables (features) by estimating probabilities using a logistic function, which is the cumulative logistic distribution. See [Logistic regression on Wikipedia][2].
#
# Note the confidence score generated by the model based on our training dataset.
#
#
# [1]: https://www.kaggle.com/startupsci/titanic/titanic-data-science-solutions
# [2]: https://en.wikipedia.org/wiki/Logistic_regression
# In[ ]:
# Logistic Regression
logreg = LogisticRegression()
scores = cross_val_score(logreg, X_train, Y_train, cv=10)
acc_log = round(scores.mean() * 100, 2)
acc_log
#Y_pred = logreg.predict(X_test)
# We can use Logistic Regression to validate our assumptions and decisions for feature creating and completing goals. This can be done by calculating the coefficient of the features in the decision function.
# Positive coefficients increase the log-odds of the response (and thus increase the probability), and negative coefficients decrease the log-odds of the response (and thus decrease the probability).
# In[ ]:
logreg.fit(X_train, Y_train)
coeff_df = pd.DataFrame(train_df.columns.delete(0))
coeff_df.columns = ['Feature']
coeff_df["Correlation"] = pd.Series(logreg.coef_[0])
coeff_df.sort_values(by='Correlation', ascending=False)
# In[ ]:
# Gaussian Naive Bayes
gaussian = GaussianNB()
scores = cross_val_score(gaussian, X_train, Y_train, cv=10)
acc_gaussian = round(scores.mean() * 100, 2)
acc_gaussian
# In[ ]:
# Perceptron (a single layer neural net)
perceptron = Perceptron()
scores = cross_val_score(perceptron, X_train, Y_train, cv=10)
acc_perceptron = round(scores.mean() * 100, 2)
acc_perceptron
# In[ ]:
# Neural Network (a multi layer neural net)
neural_net = MLPClassifier()
scores = cross_val_score(neural_net, X_train, Y_train, cv=10)
acc_neural_net = round(scores.mean() * 100, 2)
acc_neural_net
# In[ ]:
# Stochastic Gradient Descent
sgd = SGDClassifier()
scores = cross_val_score(sgd, X_train, Y_train, cv=10)
acc_sgd = round(scores.mean() * 100, 2)
acc_sgd
# In[ ]:
# Linear SVC
linear_svc = LinearSVC()
scores = cross_val_score(linear_svc, X_train, Y_train, cv=10)
acc_linear_svc = round(scores.mean() * 100, 2)
acc_linear_svc
# In[ ]:
# Support Vector Machine
svc = SVC() # uses a rbf kernel by default (i.e. can discover non-linear boundaries)
scores = cross_val_score(svc, X_train, Y_train, cv=10)
acc_svc = round(scores.mean() * 100, 2)
acc_svc
# In[ ]:
# Decision Tree
decision_tree = DecisionTreeClassifier()
scores = cross_val_score(decision_tree, X_train, Y_train, cv=10)
acc_decision_tree = round(scores.mean() * 100, 2)
acc_decision_tree
# In[ ]:
# Random Forest - an ensemble model
random_forest = RandomForestClassifier(n_estimators=100)
scores = cross_val_score(random_forest, X_train, Y_train, cv=10)
acc_random_forest = round(scores.mean() * 100, 2)
acc_random_forest
# In[ ]:
# AdaBoost - an ensemble method
ada_boost = AdaBoostClassifier(n_estimators=100)
scores = cross_val_score(ada_boost, X_train, Y_train, cv=10)
acc_ada_boost = round(scores.mean() * 100, 2)
acc_ada_boost
# In[ ]:
# k-Nearest Neighbors - a non-parametric method
knn = KNeighborsClassifier(n_neighbors = 5)
scores = cross_val_score(knn, X_train, Y_train, cv=10)
acc_knn = round(scores.mean() * 100, 2)
acc_knn
# Model evaluation
# ----------------
#
# We now rank the models and choose a high performing one for our problem. The Support Vector Machine consistently tops the chart.
#
# Decision Tree and Random Forest also both score high, but we prefer Random Forest as it avoids overfitting to the training set better than a decision tree and is therefore likely to perform better on the test dataset.
# In[ ]:
models = pd.DataFrame({
'Model': ['Support Vector Machine', 'kNN', 'Logistic Regression',
'Random Forest', 'Naive Bayes', 'Perceptron',
'Stochastic Gradient Descent', 'Linear SVC',
'Decision Tree', 'AdaBoost', 'Neural Network'],
'Score': [acc_svc, acc_knn, acc_log,
acc_random_forest, acc_gaussian, acc_perceptron,
acc_sgd, acc_linear_svc, acc_decision_tree,
acc_ada_boost, acc_neural_net]})
models.sort_values(by='Score', ascending=False)
# In[ ]:
# using random forest for submission
random_forest.fit(X_train, Y_train)
Y_pred = random_forest.predict(X_test)
submission = pd.DataFrame({
"PassengerId": test_df["PassengerId"],
"Survived": Y_pred
})
submission.to_csv('titanic_submission_1.csv', index=False)
#pd.set_option('display.max_rows', len(submission))
#submission
# Use cross validation to assess predictive accuracy
# --------------------------------------------------
#
# We can easily improve the above scores by evaluating on the training data (compare the random forest scores above and below). However, scores produced like this are not truly indicative of predictive accuracy and should be avoided. To see why, consider that a classifier that simply memorizes each input and output pair will score perfectly but be unable to generalise to other examples.
#
# In[ ]:
# Random Forest : scoring on training data
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, Y_train)
acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
acc_random_forest
# What next?
# -------------------------------
#
# **_More feature exploration:_**
# Including *Fare* significantly increases the best accuracy to about 92% when *fare* is floored and 94% otherwise. Additionally including *Embarked* brings it up to 95%. It may worth be investigating if any relationship between these attributes and survival can be detected, especially for *fare*.
#
# Other possibilities for features include *Deck* and *Title*, which can be extracted from *Cabin* and *Name* respectively.
#
# Could also try two or more overlapping binnings for age groups (e.g. bins as defined by cutting on [0,4,15,25,35,45,65,100] and [10,20,30,40,55,100]). If going down this path, focus on introducing extra bins for age groups that contain many passengers and have a steeper gradient on the survival curve (such as for the twenties, e.g. cut on [10,20,30]).
#
# **_Refitting:_**
# Most of the models above used their default parameters. Choose a few promising models and attempt to optimize their (hyper-)parameters. The sklearn library used above offers a couple of ways to do this automatically (via grid search and cross-validated models, see [Model selection][1] and [Tuning the hyper-parameters of an estimator][2]).
#
#
# [1]: http://scikit-learn.org/stable/tutorial/statistical_inference/model_selection.html
# [2]: http://scikit-learn.org/stable/modules/grid_search.html#grid-search
|
flexible
|
{
"blob_id": "05f143e28ff9c7397376ad598529c1dfb7528ee3",
"index": 7269,
"step-1": "<mask token>\n\n\ndef get_na(dataset):\n na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()\n na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(\n ).sum()\n return {'male': na_males, 'female': na_females}\n\n\ndef get_counts(dataset):\n return dataset.groupby(['Sex', 'AgeGroup']).size()\n\n\ndef generate_age_groups(num, freq):\n age_groups = {}\n for sex in ['male', 'female']:\n relfreq = freq[sex] / freq[sex].sum()\n age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex],\n replace=True, p=relfreq)\n return age_groups\n\n\ndef insert_age_group_values(dataset, age_groups):\n for sex in ['male', 'female']:\n tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]\n )\n tmp['AgeGroup'] = age_groups[sex]\n dataset = dataset.combine_first(tmp)\n return dataset\n\n\n<mask token>\n",
"step-2": "<mask token>\nget_ipython().magic(u'matplotlib inline')\nsns.set_style('whitegrid')\n<mask token>\nprint(train_df.columns.values)\ntrain_df.head()\ntrain_df.head(3).T\ntrain_df.info()\nprint('-' * 40)\ntest_df.info()\ntrain_df.describe()\ntrain_df.describe(include=['O'])\ntrain_df[train_df.Age == 10].stack()\nplt.subplot(211)\nsns.countplot(x='Sex', data=train_df, palette='Greens_d')\nplt.subplot(212)\nsns.barplot(x='Sex', y='Survived', data=train_df, palette='Greens_d')\ntrain_df.groupby('Sex').size()\ntrain_df.groupby(['Sex'])['Survived'].mean().sort_values()\nplt.subplots(figsize=(8, 6))\nplt.subplot(211)\nsns.countplot(x='Pclass', data=train_df, palette='Purples_d')\nplt.subplot(212)\nsns.barplot(x='Pclass', y='Survived', data=train_df, palette='Purples_d')\ntrain_df.groupby(['Pclass']).size()\ntrain_df.groupby(['Pclass'])['Survived'].mean().sort_values(ascending=False)\ntrain_df.groupby('Age').size().head(25)\n<mask token>\nplt.subplots(figsize=(18, 6))\nplt.subplot(311)\nsns.kdeplot(age['Age'], shade=True, cut=0)\nplt.subplot(312)\nsns.countplot(x='Age', data=age, palette='GnBu_d')\nplt.subplot(313)\nsns.barplot(x='Age', y='Survived', data=age, ci=None, palette='Oranges_d')\n<mask token>\ntrain_df.groupby('AgeGroup')['Survived'].mean()\ntrain_df[['Survived', 'AgeGroup', 'Sex']].groupby(['Sex', 'AgeGroup']).mean()\nsns.factorplot(x='AgeGroup', col='Sex', data=train_df, kind='count')\nsns.factorplot(x='AgeGroup', y='Survived', col='Sex', data=train_df, kind='bar'\n )\n<mask token>\nplt.subplot(211)\nsns.countplot(x='FamilySize', data=train_df)\nplt.subplot(212)\nsns.barplot(x='FamilySize', y='Survived', data=train_df)\n<mask token>\ntrain_df[['PassengerId', 'Name', 'Cabin', 'Deck']].head(2).T\nplt.subplots(figsize=(8, 6))\nplt.subplot(211)\nsns.countplot(x='Deck', data=train_df)\nplt.subplot(212)\nsns.barplot(x='Deck', y='Survived', data=train_df)\n\n\ndef get_na(dataset):\n na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()\n na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(\n ).sum()\n return {'male': na_males, 'female': na_females}\n\n\ndef get_counts(dataset):\n return dataset.groupby(['Sex', 'AgeGroup']).size()\n\n\ndef generate_age_groups(num, freq):\n age_groups = {}\n for sex in ['male', 'female']:\n relfreq = freq[sex] / freq[sex].sum()\n age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex],\n replace=True, p=relfreq)\n return age_groups\n\n\ndef insert_age_group_values(dataset, age_groups):\n for sex in ['male', 'female']:\n tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]\n )\n tmp['AgeGroup'] = age_groups[sex]\n dataset = dataset.combine_first(tmp)\n return dataset\n\n\n<mask token>\ncounts['female']\n<mask token>\nage_groups['female']\n<mask token>\ntrain_df.info()\nprint('-' * 40)\n<mask token>\ntest_df.info()\n<mask token>\ntrain_df[['Name', 'Sex', 'Female']].head(2).T\n<mask token>\ntrain_df[['Name', 'Pclass', 'PClass_1', 'PClass_2']].head(2).T\n<mask token>\ntest_df['Fare'].fillna(test_df['Fare'].median(), inplace=True)\nprint(train_df.groupby('Embarked').size().sort_values())\n<mask token>\ntrain_df.drop(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',\n 'Parch', 'Ticket', 'Cabin', 'Fare', 'Embarked', 'Deck', 'AgeGroup'],\n axis=1, inplace=True)\ntest_df.drop(['Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket',\n 'Cabin', 'Fare', 'Embarked', 'AgeGroup'], axis=1, inplace=True)\ntrain_df.head(10).T\n<mask token>\nX_train.shape, Y_train.shape, X_test.shape\n<mask token>\nacc_log\nlogreg.fit(X_train, Y_train)\n<mask token>\ncoeff_df.sort_values(by='Correlation', ascending=False)\n<mask token>\nacc_gaussian\n<mask token>\nacc_perceptron\n<mask token>\nacc_neural_net\n<mask token>\nacc_sgd\n<mask token>\nacc_linear_svc\n<mask token>\nacc_svc\n<mask token>\nacc_decision_tree\n<mask token>\nacc_random_forest\n<mask token>\nacc_ada_boost\n<mask token>\nacc_knn\n<mask token>\nmodels.sort_values(by='Score', ascending=False)\nrandom_forest.fit(X_train, Y_train)\n<mask token>\nsubmission.to_csv('titanic_submission_1.csv', index=False)\n<mask token>\nrandom_forest.fit(X_train, Y_train)\n<mask token>\nacc_random_forest\n",
"step-3": "<mask token>\nget_ipython().magic(u'matplotlib inline')\nsns.set_style('whitegrid')\n<mask token>\ntrain_df = pd.read_csv('../input/train.csv')\ntest_df = pd.read_csv('../input/test.csv')\ncombine = [train_df, test_df]\nprint(train_df.columns.values)\ntrain_df.head()\ntrain_df.head(3).T\ntrain_df.info()\nprint('-' * 40)\ntest_df.info()\ntrain_df.describe()\ntrain_df.describe(include=['O'])\ntrain_df[train_df.Age == 10].stack()\nplt.subplot(211)\nsns.countplot(x='Sex', data=train_df, palette='Greens_d')\nplt.subplot(212)\nsns.barplot(x='Sex', y='Survived', data=train_df, palette='Greens_d')\ntrain_df.groupby('Sex').size()\ntrain_df.groupby(['Sex'])['Survived'].mean().sort_values()\nplt.subplots(figsize=(8, 6))\nplt.subplot(211)\nsns.countplot(x='Pclass', data=train_df, palette='Purples_d')\nplt.subplot(212)\nsns.barplot(x='Pclass', y='Survived', data=train_df, palette='Purples_d')\ntrain_df.groupby(['Pclass']).size()\ntrain_df.groupby(['Pclass'])['Survived'].mean().sort_values(ascending=False)\ntrain_df.groupby('Age').size().head(25)\nage = train_df[['Age', 'Survived']].dropna()\nage['Age'] = age['Age'].astype(int)\nplt.subplots(figsize=(18, 6))\nplt.subplot(311)\nsns.kdeplot(age['Age'], shade=True, cut=0)\nplt.subplot(312)\nsns.countplot(x='Age', data=age, palette='GnBu_d')\nplt.subplot(313)\nsns.barplot(x='Age', y='Survived', data=age, ci=None, palette='Oranges_d')\ntrain_df['AgeGroup'] = pd.cut(train_df['Age'], [0, 4, 15, 25, 35, 45, 65, 100])\ntest_df['AgeGroup'] = pd.cut(test_df['Age'], [0, 4, 15, 25, 35, 45, 65, 100])\ntrain_df.groupby('AgeGroup')['Survived'].mean()\ntrain_df[['Survived', 'AgeGroup', 'Sex']].groupby(['Sex', 'AgeGroup']).mean()\nsns.factorplot(x='AgeGroup', col='Sex', data=train_df, kind='count')\nsns.factorplot(x='AgeGroup', y='Survived', col='Sex', data=train_df, kind='bar'\n )\ntrain_df['FamilySize'] = train_df['SibSp'] + train_df['Parch'] + 1\ntest_df['FamilySize'] = test_df['SibSp'] + test_df['Parch'] + 1\nplt.subplot(211)\nsns.countplot(x='FamilySize', data=train_df)\nplt.subplot(212)\nsns.barplot(x='FamilySize', y='Survived', data=train_df)\ntrain_df['Deck'] = train_df['Cabin'].dropna().apply(lambda x: str(x)[0])\ntrain_df[['PassengerId', 'Name', 'Cabin', 'Deck']].head(2).T\nplt.subplots(figsize=(8, 6))\nplt.subplot(211)\nsns.countplot(x='Deck', data=train_df)\nplt.subplot(212)\nsns.barplot(x='Deck', y='Survived', data=train_df)\n\n\ndef get_na(dataset):\n na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()\n na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(\n ).sum()\n return {'male': na_males, 'female': na_females}\n\n\ndef get_counts(dataset):\n return dataset.groupby(['Sex', 'AgeGroup']).size()\n\n\ndef generate_age_groups(num, freq):\n age_groups = {}\n for sex in ['male', 'female']:\n relfreq = freq[sex] / freq[sex].sum()\n age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex],\n replace=True, p=relfreq)\n return age_groups\n\n\ndef insert_age_group_values(dataset, age_groups):\n for sex in ['male', 'female']:\n tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]\n )\n tmp['AgeGroup'] = age_groups[sex]\n dataset = dataset.combine_first(tmp)\n return dataset\n\n\nna = get_na(train_df)\ncounts = get_counts(train_df)\ncounts['female']\nage_groups = generate_age_groups(na, counts)\nage_groups['female']\ntrain_df = insert_age_group_values(train_df, age_groups)\ntrain_df.info()\nprint('-' * 40)\nna = get_na(test_df)\ncounts = get_counts(train_df)\nage_groups = generate_age_groups(na, counts)\ntest_df = insert_age_group_values(test_df, age_groups)\ntest_df.info()\ndummy = pd.get_dummies(train_df['Sex'])\ndummy.columns = ['Female', 'Male']\ntrain_df = train_df.join(dummy['Female'])\ndummy = pd.get_dummies(test_df['Sex'])\ndummy.columns = ['Female', 'Male']\ntest_df = test_df.join(dummy['Female'])\ntrain_df[['Name', 'Sex', 'Female']].head(2).T\ndummy = pd.get_dummies(train_df['Pclass'])\ndummy.columns = ['PClass_1', 'PClass_2', 'PClass_3']\ntrain_df = train_df.join(dummy[['PClass_1', 'PClass_2']])\ndummy = pd.get_dummies(test_df['Pclass'])\ndummy.columns = ['PClass_1', 'PClass_2', 'PClass_3']\ntest_df = test_df.join(dummy[['PClass_1', 'PClass_2']])\ntrain_df[['Name', 'Pclass', 'PClass_1', 'PClass_2']].head(2).T\ndummy = pd.get_dummies(train_df['AgeGroup'])\ndummy.columns = ['Ages_4', 'Ages_15', 'Ages_25', 'Ages_35', 'Ages_45',\n 'Ages_65', 'Ages_100']\ntrain_df = train_df.join(dummy)\ndummy = pd.get_dummies(test_df['AgeGroup'])\ndummy.columns = ['Ages_4', 'Ages_15', 'Ages_25', 'Ages_35', 'Ages_45',\n 'Ages_65', 'Ages_100']\ntest_df = test_df.join(dummy)\ntest_df['Fare'].fillna(test_df['Fare'].median(), inplace=True)\nprint(train_df.groupby('Embarked').size().sort_values())\ntrain_df['Embarked'] = train_df['Embarked'].fillna('S')\ndummy = pd.get_dummies(train_df['Embarked'])\ndummy.columns = ['Port_C', 'Port_Q', 'Port_S']\ndummy = pd.get_dummies(test_df['Embarked'])\ndummy.columns = ['Port_C', 'Port_Q', 'Port_S']\ntrain_df.drop(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',\n 'Parch', 'Ticket', 'Cabin', 'Fare', 'Embarked', 'Deck', 'AgeGroup'],\n axis=1, inplace=True)\ntest_df.drop(['Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket',\n 'Cabin', 'Fare', 'Embarked', 'AgeGroup'], axis=1, inplace=True)\ntrain_df.head(10).T\nX_train = train_df.drop('Survived', axis=1)\nY_train = train_df['Survived']\nX_test = test_df.drop('PassengerId', axis=1).copy()\nX_train.shape, Y_train.shape, X_test.shape\nlogreg = LogisticRegression()\nscores = cross_val_score(logreg, X_train, Y_train, cv=10)\nacc_log = round(scores.mean() * 100, 2)\nacc_log\nlogreg.fit(X_train, Y_train)\ncoeff_df = pd.DataFrame(train_df.columns.delete(0))\ncoeff_df.columns = ['Feature']\ncoeff_df['Correlation'] = pd.Series(logreg.coef_[0])\ncoeff_df.sort_values(by='Correlation', ascending=False)\ngaussian = GaussianNB()\nscores = cross_val_score(gaussian, X_train, Y_train, cv=10)\nacc_gaussian = round(scores.mean() * 100, 2)\nacc_gaussian\nperceptron = Perceptron()\nscores = cross_val_score(perceptron, X_train, Y_train, cv=10)\nacc_perceptron = round(scores.mean() * 100, 2)\nacc_perceptron\nneural_net = MLPClassifier()\nscores = cross_val_score(neural_net, X_train, Y_train, cv=10)\nacc_neural_net = round(scores.mean() * 100, 2)\nacc_neural_net\nsgd = SGDClassifier()\nscores = cross_val_score(sgd, X_train, Y_train, cv=10)\nacc_sgd = round(scores.mean() * 100, 2)\nacc_sgd\nlinear_svc = LinearSVC()\nscores = cross_val_score(linear_svc, X_train, Y_train, cv=10)\nacc_linear_svc = round(scores.mean() * 100, 2)\nacc_linear_svc\nsvc = SVC()\nscores = cross_val_score(svc, X_train, Y_train, cv=10)\nacc_svc = round(scores.mean() * 100, 2)\nacc_svc\ndecision_tree = DecisionTreeClassifier()\nscores = cross_val_score(decision_tree, X_train, Y_train, cv=10)\nacc_decision_tree = round(scores.mean() * 100, 2)\nacc_decision_tree\nrandom_forest = RandomForestClassifier(n_estimators=100)\nscores = cross_val_score(random_forest, X_train, Y_train, cv=10)\nacc_random_forest = round(scores.mean() * 100, 2)\nacc_random_forest\nada_boost = AdaBoostClassifier(n_estimators=100)\nscores = cross_val_score(ada_boost, X_train, Y_train, cv=10)\nacc_ada_boost = round(scores.mean() * 100, 2)\nacc_ada_boost\nknn = KNeighborsClassifier(n_neighbors=5)\nscores = cross_val_score(knn, X_train, Y_train, cv=10)\nacc_knn = round(scores.mean() * 100, 2)\nacc_knn\nmodels = pd.DataFrame({'Model': ['Support Vector Machine', 'kNN',\n 'Logistic Regression', 'Random Forest', 'Naive Bayes', 'Perceptron',\n 'Stochastic Gradient Descent', 'Linear SVC', 'Decision Tree',\n 'AdaBoost', 'Neural Network'], 'Score': [acc_svc, acc_knn, acc_log,\n acc_random_forest, acc_gaussian, acc_perceptron, acc_sgd,\n acc_linear_svc, acc_decision_tree, acc_ada_boost, acc_neural_net]})\nmodels.sort_values(by='Score', ascending=False)\nrandom_forest.fit(X_train, Y_train)\nY_pred = random_forest.predict(X_test)\nsubmission = pd.DataFrame({'PassengerId': test_df['PassengerId'],\n 'Survived': Y_pred})\nsubmission.to_csv('titanic_submission_1.csv', index=False)\nrandom_forest = RandomForestClassifier(n_estimators=100)\nrandom_forest.fit(X_train, Y_train)\nacc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)\nacc_random_forest\n",
"step-4": "import pandas as pd\nimport numpy as np\nimport random as rnd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().magic(u'matplotlib inline')\nsns.set_style('whitegrid')\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.neural_network import MLPClassifier\ntrain_df = pd.read_csv('../input/train.csv')\ntest_df = pd.read_csv('../input/test.csv')\ncombine = [train_df, test_df]\nprint(train_df.columns.values)\ntrain_df.head()\ntrain_df.head(3).T\ntrain_df.info()\nprint('-' * 40)\ntest_df.info()\ntrain_df.describe()\ntrain_df.describe(include=['O'])\ntrain_df[train_df.Age == 10].stack()\nplt.subplot(211)\nsns.countplot(x='Sex', data=train_df, palette='Greens_d')\nplt.subplot(212)\nsns.barplot(x='Sex', y='Survived', data=train_df, palette='Greens_d')\ntrain_df.groupby('Sex').size()\ntrain_df.groupby(['Sex'])['Survived'].mean().sort_values()\nplt.subplots(figsize=(8, 6))\nplt.subplot(211)\nsns.countplot(x='Pclass', data=train_df, palette='Purples_d')\nplt.subplot(212)\nsns.barplot(x='Pclass', y='Survived', data=train_df, palette='Purples_d')\ntrain_df.groupby(['Pclass']).size()\ntrain_df.groupby(['Pclass'])['Survived'].mean().sort_values(ascending=False)\ntrain_df.groupby('Age').size().head(25)\nage = train_df[['Age', 'Survived']].dropna()\nage['Age'] = age['Age'].astype(int)\nplt.subplots(figsize=(18, 6))\nplt.subplot(311)\nsns.kdeplot(age['Age'], shade=True, cut=0)\nplt.subplot(312)\nsns.countplot(x='Age', data=age, palette='GnBu_d')\nplt.subplot(313)\nsns.barplot(x='Age', y='Survived', data=age, ci=None, palette='Oranges_d')\ntrain_df['AgeGroup'] = pd.cut(train_df['Age'], [0, 4, 15, 25, 35, 45, 65, 100])\ntest_df['AgeGroup'] = pd.cut(test_df['Age'], [0, 4, 15, 25, 35, 45, 65, 100])\ntrain_df.groupby('AgeGroup')['Survived'].mean()\ntrain_df[['Survived', 'AgeGroup', 'Sex']].groupby(['Sex', 'AgeGroup']).mean()\nsns.factorplot(x='AgeGroup', col='Sex', data=train_df, kind='count')\nsns.factorplot(x='AgeGroup', y='Survived', col='Sex', data=train_df, kind='bar'\n )\ntrain_df['FamilySize'] = train_df['SibSp'] + train_df['Parch'] + 1\ntest_df['FamilySize'] = test_df['SibSp'] + test_df['Parch'] + 1\nplt.subplot(211)\nsns.countplot(x='FamilySize', data=train_df)\nplt.subplot(212)\nsns.barplot(x='FamilySize', y='Survived', data=train_df)\ntrain_df['Deck'] = train_df['Cabin'].dropna().apply(lambda x: str(x)[0])\ntrain_df[['PassengerId', 'Name', 'Cabin', 'Deck']].head(2).T\nplt.subplots(figsize=(8, 6))\nplt.subplot(211)\nsns.countplot(x='Deck', data=train_df)\nplt.subplot(212)\nsns.barplot(x='Deck', y='Survived', data=train_df)\n\n\ndef get_na(dataset):\n na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()\n na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(\n ).sum()\n return {'male': na_males, 'female': na_females}\n\n\ndef get_counts(dataset):\n return dataset.groupby(['Sex', 'AgeGroup']).size()\n\n\ndef generate_age_groups(num, freq):\n age_groups = {}\n for sex in ['male', 'female']:\n relfreq = freq[sex] / freq[sex].sum()\n age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex],\n replace=True, p=relfreq)\n return age_groups\n\n\ndef insert_age_group_values(dataset, age_groups):\n for sex in ['male', 'female']:\n tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]\n )\n tmp['AgeGroup'] = age_groups[sex]\n dataset = dataset.combine_first(tmp)\n return dataset\n\n\nna = get_na(train_df)\ncounts = get_counts(train_df)\ncounts['female']\nage_groups = generate_age_groups(na, counts)\nage_groups['female']\ntrain_df = insert_age_group_values(train_df, age_groups)\ntrain_df.info()\nprint('-' * 40)\nna = get_na(test_df)\ncounts = get_counts(train_df)\nage_groups = generate_age_groups(na, counts)\ntest_df = insert_age_group_values(test_df, age_groups)\ntest_df.info()\ndummy = pd.get_dummies(train_df['Sex'])\ndummy.columns = ['Female', 'Male']\ntrain_df = train_df.join(dummy['Female'])\ndummy = pd.get_dummies(test_df['Sex'])\ndummy.columns = ['Female', 'Male']\ntest_df = test_df.join(dummy['Female'])\ntrain_df[['Name', 'Sex', 'Female']].head(2).T\ndummy = pd.get_dummies(train_df['Pclass'])\ndummy.columns = ['PClass_1', 'PClass_2', 'PClass_3']\ntrain_df = train_df.join(dummy[['PClass_1', 'PClass_2']])\ndummy = pd.get_dummies(test_df['Pclass'])\ndummy.columns = ['PClass_1', 'PClass_2', 'PClass_3']\ntest_df = test_df.join(dummy[['PClass_1', 'PClass_2']])\ntrain_df[['Name', 'Pclass', 'PClass_1', 'PClass_2']].head(2).T\ndummy = pd.get_dummies(train_df['AgeGroup'])\ndummy.columns = ['Ages_4', 'Ages_15', 'Ages_25', 'Ages_35', 'Ages_45',\n 'Ages_65', 'Ages_100']\ntrain_df = train_df.join(dummy)\ndummy = pd.get_dummies(test_df['AgeGroup'])\ndummy.columns = ['Ages_4', 'Ages_15', 'Ages_25', 'Ages_35', 'Ages_45',\n 'Ages_65', 'Ages_100']\ntest_df = test_df.join(dummy)\ntest_df['Fare'].fillna(test_df['Fare'].median(), inplace=True)\nprint(train_df.groupby('Embarked').size().sort_values())\ntrain_df['Embarked'] = train_df['Embarked'].fillna('S')\ndummy = pd.get_dummies(train_df['Embarked'])\ndummy.columns = ['Port_C', 'Port_Q', 'Port_S']\ndummy = pd.get_dummies(test_df['Embarked'])\ndummy.columns = ['Port_C', 'Port_Q', 'Port_S']\ntrain_df.drop(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',\n 'Parch', 'Ticket', 'Cabin', 'Fare', 'Embarked', 'Deck', 'AgeGroup'],\n axis=1, inplace=True)\ntest_df.drop(['Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket',\n 'Cabin', 'Fare', 'Embarked', 'AgeGroup'], axis=1, inplace=True)\ntrain_df.head(10).T\nX_train = train_df.drop('Survived', axis=1)\nY_train = train_df['Survived']\nX_test = test_df.drop('PassengerId', axis=1).copy()\nX_train.shape, Y_train.shape, X_test.shape\nlogreg = LogisticRegression()\nscores = cross_val_score(logreg, X_train, Y_train, cv=10)\nacc_log = round(scores.mean() * 100, 2)\nacc_log\nlogreg.fit(X_train, Y_train)\ncoeff_df = pd.DataFrame(train_df.columns.delete(0))\ncoeff_df.columns = ['Feature']\ncoeff_df['Correlation'] = pd.Series(logreg.coef_[0])\ncoeff_df.sort_values(by='Correlation', ascending=False)\ngaussian = GaussianNB()\nscores = cross_val_score(gaussian, X_train, Y_train, cv=10)\nacc_gaussian = round(scores.mean() * 100, 2)\nacc_gaussian\nperceptron = Perceptron()\nscores = cross_val_score(perceptron, X_train, Y_train, cv=10)\nacc_perceptron = round(scores.mean() * 100, 2)\nacc_perceptron\nneural_net = MLPClassifier()\nscores = cross_val_score(neural_net, X_train, Y_train, cv=10)\nacc_neural_net = round(scores.mean() * 100, 2)\nacc_neural_net\nsgd = SGDClassifier()\nscores = cross_val_score(sgd, X_train, Y_train, cv=10)\nacc_sgd = round(scores.mean() * 100, 2)\nacc_sgd\nlinear_svc = LinearSVC()\nscores = cross_val_score(linear_svc, X_train, Y_train, cv=10)\nacc_linear_svc = round(scores.mean() * 100, 2)\nacc_linear_svc\nsvc = SVC()\nscores = cross_val_score(svc, X_train, Y_train, cv=10)\nacc_svc = round(scores.mean() * 100, 2)\nacc_svc\ndecision_tree = DecisionTreeClassifier()\nscores = cross_val_score(decision_tree, X_train, Y_train, cv=10)\nacc_decision_tree = round(scores.mean() * 100, 2)\nacc_decision_tree\nrandom_forest = RandomForestClassifier(n_estimators=100)\nscores = cross_val_score(random_forest, X_train, Y_train, cv=10)\nacc_random_forest = round(scores.mean() * 100, 2)\nacc_random_forest\nada_boost = AdaBoostClassifier(n_estimators=100)\nscores = cross_val_score(ada_boost, X_train, Y_train, cv=10)\nacc_ada_boost = round(scores.mean() * 100, 2)\nacc_ada_boost\nknn = KNeighborsClassifier(n_neighbors=5)\nscores = cross_val_score(knn, X_train, Y_train, cv=10)\nacc_knn = round(scores.mean() * 100, 2)\nacc_knn\nmodels = pd.DataFrame({'Model': ['Support Vector Machine', 'kNN',\n 'Logistic Regression', 'Random Forest', 'Naive Bayes', 'Perceptron',\n 'Stochastic Gradient Descent', 'Linear SVC', 'Decision Tree',\n 'AdaBoost', 'Neural Network'], 'Score': [acc_svc, acc_knn, acc_log,\n acc_random_forest, acc_gaussian, acc_perceptron, acc_sgd,\n acc_linear_svc, acc_decision_tree, acc_ada_boost, acc_neural_net]})\nmodels.sort_values(by='Score', ascending=False)\nrandom_forest.fit(X_train, Y_train)\nY_pred = random_forest.predict(X_test)\nsubmission = pd.DataFrame({'PassengerId': test_df['PassengerId'],\n 'Survived': Y_pred})\nsubmission.to_csv('titanic_submission_1.csv', index=False)\nrandom_forest = RandomForestClassifier(n_estimators=100)\nrandom_forest.fit(X_train, Y_train)\nacc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)\nacc_random_forest\n",
"step-5": "#!/usr/bin/env python\n# coding: utf-8\n\n# Predicting Surviving the Sinking of the Titanic\n# -----------------------------------------------\n# \n# \n# This represents my first attempt at training up some classifiers for the titanic dataset.\n\n# In[ ]:\n\n\n# data analysis and wrangling\nimport pandas as pd\nimport numpy as np\nimport random as rnd\n\n# visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().magic(u'matplotlib inline')\nsns.set_style(\"whitegrid\")\n\n# machine learning\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.neural_network import MLPClassifier\n\n\n# In[ ]:\n\n\n# get titanic & test csv files as a DataFrame\ntrain_df = pd.read_csv(\"../input/train.csv\")\ntest_df = pd.read_csv(\"../input/test.csv\")\ncombine = [train_df, test_df]\n\n\n# # Data exploration #\n# \n# First get some summary statistics about the datasets.\n\n# In[ ]:\n\n\n# view column labels\nprint(train_df.columns.values)\n\n\n# In[ ]:\n\n\n# preview the data\ntrain_df.head()\n\n\n# Now transpose the first few rows in order to see all attributes more easily as row labels.\n\n# In[ ]:\n\n\ntrain_df.head(3).T\n\n\n# In[ ]:\n\n\n# missing values, data types\ntrain_df.info()\nprint('-'*40)\ntest_df.info()\n\n\n# The above info shows that columns (from training data) with missing/empty values are:\n# \n# - Age (177 missing values)\n# - Cabin (687 missing values)\n# - Embarked (2 missing values)\n\n# In[ ]:\n\n\n# describe numeric columns\ntrain_df.describe()\n\n\n# In the training dataset there are 891 passengers with an overall survival rate of 38.4%.\n# The oldest person is 80 years and the youngest is 5 months (0.42*12). The average fare is 32.20 dollars but the median fare is 14.45. This suggests outliers at the upper end of the fare, and indeed the maximum fare is $512.33.\n\n# In[ ]:\n\n\n# describe categorical columns\ntrain_df.describe(include=['O'])\n\n\n# In[ ]:\n\n\n# just for fun, examine the records of ten year olds (there are only two) \ntrain_df[train_df.Age == 10].stack()\n\n\n# # Detailed data investigation #\n# \n# A closer look at each of the attributes (columns) and their relationship to survival.\n\n# ##Sex##\n# \n# Sex is a *nominal* attribute with two categories (i.e. it is dichotomous). Let's plot some counts and survival rates by sex. Note that survival values are 0/1, thus rates can be be calculated simply via the mean survive value.\n\n# In[ ]:\n\n\n# count passengers by sex\nplt.subplot(211) # 3 digit convenience notation for arguments (last digit represents plot number)\nsns.countplot(x='Sex', data=train_df, palette='Greens_d')\n\n# survival rate by sex\n# note that barplot plots mean() on y by default\nplt.subplot(212)\nsns.barplot(x='Sex', y='Survived', data=train_df, palette='Greens_d') \n\n\n# **Observations:**\n# \n# - Many more males than females\n# - Survival rate of females much greater than males\n# \n# Let's get the actual numbers below using pandas.\n\n# In[ ]:\n\n\n# count passengers by sex\ntrain_df.groupby('Sex').size()\n\n\n# In[ ]:\n\n\n# survival rates by sex\ntrain_df.groupby(['Sex'])['Survived'].mean().sort_values()\n\n\n# Thus, 18.9% of males (from the training set) survived compared to 74.2% of females.\n\n# ##Passenger class##\n# \n# Passenger class (Pclass) is an *ordinal* attribute with three categories, 1, 2 and 3. The three categories have an order (representing socioeconomic status) but although the categories are given numeric labels, this attribute *is not* numeric! To see this, consider that 3rd class = 1st + 2nd class is a nonsense. This will be important later when we construct features. Again, let's plot some counts and survival rates.\n\n# In[ ]:\n\n\n# size of groups in passenger class\nplt.subplots(figsize=(8,6))\nplt.subplot(211) \nsns.countplot(x='Pclass', data=train_df, palette='Purples_d') # _d = dark palette\n\n# survival rate by sex\nplt.subplot(212)\nsns.barplot(x='Pclass', y='Survived', data=train_df, palette='Purples_d') \n\n\n# **Observations:**\n# \n# - Three classes\n# - Most passengers travelled by 3rd class (more than half; see below)\n# - Survival rate increases with class\n# \n# Again, let's get the actual numbers below using pandas.\n\n# In[ ]:\n\n\n# count passengers by passenger class\ntrain_df.groupby(['Pclass']).size()\n\n\n# In[ ]:\n\n\n# survival rates by passenger class\ntrain_df.groupby(['Pclass'])['Survived'].mean().sort_values(ascending=False)\n\n\n# ##Age##\n# \n# Age is a *ratio* attribute (it is properly numeric, see [Types of data measurement scales][1]). Ages < 1 indicate age in months.\n# \n# \n# [1]: http://www.mymarketresearchmethods.com/types-of-data-nominal-ordinal-interval-ratio/\n\n# In[ ]:\n\n\n# count the number of passengers for first 25 ages\ntrain_df.groupby('Age').size().head(25)\n\n# another way to do the above\n#train_df['Age'].value_counts().sort_index().head(25) \n\n\n# In[ ]:\n\n\n# convert ages to ints\nage = train_df[['Age','Survived']].dropna() # returns a copy with blanks removed\nage['Age'] = age['Age'].astype(int) # floors floats\n\n# count passengers by age (smoothed via gaussian kernels)\nplt.subplots(figsize=(18,6))\nplt.subplot(311)\nsns.kdeplot(age['Age'], shade=True, cut=0)\n\n# count passengers by age (no smoothing)\nplt.subplot(312)\nsns.countplot(x='Age', data=age, palette='GnBu_d')\n\n# survival rates by age\nplt.subplot(313)\nsns.barplot(x='Age', y='Survived', data=age, ci=None, palette='Oranges_d') # takes mean by default\n\n\n# Observations:\n# \n# - Under 16s tend to have the highest survival rates\n# - Very high survival rates at 53, 63 and 80\n# - Survival of over 16s is fairly noisy. Possible that survival might increase with age.\n\n# ## Survival by age group and sex ##\n# \n# Now let's look at survival by age groups *and* sex to see if any patterns become clearer.\n\n# In[ ]:\n\n\n# bin age into groups\ntrain_df['AgeGroup'] = pd.cut(train_df['Age'],[0,4,15,25,35,45,65,100])\ntest_df['AgeGroup'] = pd.cut(test_df['Age'],[0,4,15,25,35,45,65,100])\n\n# survival by age group\ntrain_df.groupby('AgeGroup')['Survived'].mean()\n\n\n# In[ ]:\n\n\n# survival by age group and sex\ntrain_df[['Survived','AgeGroup', 'Sex']].groupby(['Sex', 'AgeGroup']).mean()\n\n\n# In[ ]:\n\n\n# count passengers by age group and sex\nsns.factorplot(x='AgeGroup', col='Sex', data=train_df, kind='count')\n\n# survival by age group and sex\nsns.factorplot(x='AgeGroup', y='Survived', col='Sex', data=train_df, kind='bar')\n\n\n# The relationship between survival and age group looks very different for males and females:\n# \n# - Males: survival rates increase *inversely* with age for (0, 25] and (25, 100). That is, younger boys fare better than older boys and younger men survive more than older men. \n# - Females: no obvious relationship between surviving and age. In particular, girls and baby girls do not fare better than women; in fact, girls (4, 15] have the *lowest* survival rates of females. \n# \n# A feature space containing (child, man, woman) would do a decent job of representing this relationship to survivability. \n# \n# Non-linear classifiers (e.g. decision trees, multi-layer nn, nearest neighbour) applied to both sex and age group might do even better because of the noticeable relationship between survivability and age group for males. \n\n# ## Family Size##\n# \n# We create a new feature, FamilySize, that sums Parch and SibSp. This will enable us to drop Parch and SibSp from the datasets.\n\n# In[ ]:\n\n\n# calculate family size\ntrain_df['FamilySize'] = train_df['SibSp'] + train_df['Parch'] + 1\ntest_df['FamilySize'] = test_df['SibSp'] + test_df['Parch'] + 1\n\n# count passengers by age group and sex\nplt.subplot(211)\nsns.countplot(x='FamilySize', data=train_df)\n\n# survival by age group and sex\nplt.subplot(212)\nsns.barplot(x='FamilySize', y='Survived', data=train_df)\n\n\n# Survival increases with family size, until families of size 4. Family sizes of 5 and above have reduced survival.\n\n# Deck\n# ----\n# \n# Cabin might be conceivably be related to survival, but unfortunately most values are missing. Nevertheless, by way of an exercise, we will extract the feature, Deck, from cabin by taking the first character of the label and analyze survival rates by deck.\n\n# In[ ]:\n\n\n# deck is the first letter of cabin\ntrain_df['Deck'] = train_df['Cabin'].dropna().apply(lambda x: str(x)[0])\ntrain_df[['PassengerId','Name', 'Cabin', 'Deck']].head(2).T\n\n\n# In[ ]:\n\n\n# count passengers by the deck their cabin is on\nplt.subplots(figsize=(8,6))\nplt.subplot(211) \nsns.countplot(x='Deck', data=train_df)\n\n# survival rate by deck\nplt.subplot(212)\nsns.barplot(x='Deck', y='Survived', data=train_df) \n\n\n# ## Other attributes ##\n# For this first attempt, I am ignoring the attributes below as they seem unlikely to be related to survival:\n# \n# - PassengerId\n# - Name (however, extracting titles from names might be informative)\n# - Ticket\n# - Fare (could be related to socioeconomic status but we already have a class attribute)\n# - Embarked\n\n# # Data wrangling - Age group#\n# \n# Fill missing age group values. We don't want to drop them as this would lose many rows. Instead, we will randomly generate age groups according to the frequency that they occur in the data. We will calculate the frequency separately for males and females.\n\n# In[ ]:\n\n\n# number of males/females without an age\ndef get_na(dataset):\n na_males = dataset[dataset.Sex == 'male'].loc[:,'AgeGroup'].isnull().sum()\n na_females = dataset[dataset.Sex == 'female'].loc[:,'AgeGroup'].isnull().sum()\n return {'male': na_males, 'female': na_females}\n\n# number of males and females by age group\ndef get_counts(dataset):\n return dataset.groupby(['Sex', 'AgeGroup']).size()\n\n# randomly generate a list of age groups based on age group frequency (for each sex separately) \ndef generate_age_groups(num, freq):\n age_groups = {}\n for sex in ['male','female']:\n relfreq = freq[sex] / freq[sex].sum()\n age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex], replace=True, p=relfreq) \n return age_groups\n\n# insert the new age group values\ndef insert_age_group_values(dataset, age_groups):\n for sex in ['male','female']:\n tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]) # filter on sex and null ages \n tmp['AgeGroup'] = age_groups[sex] # index age group values\n dataset = dataset.combine_first(tmp) # uses tmp to fill holes\n return dataset\n\n# fill holes for train_df\nna = get_na(train_df)\ncounts = get_counts(train_df)\ncounts['female']\nage_groups = generate_age_groups(na, counts)\nage_groups['female']\ntrain_df = insert_age_group_values(train_df, age_groups)\ntrain_df.info() # check all nulls have been filled \nprint('-'*40)\n\n# repeat for test_df\nna = get_na(test_df)\ncounts = get_counts(train_df) # reuse the frequencies taken over the training data as it is larger\nage_groups = generate_age_groups(na, counts)\ntest_df = insert_age_group_values(test_df, age_groups)\ntest_df.info() # check all nulls have been filled \n\n\n# # Feature engineering #\n# \n# Now that we've explored the data let's create some features:\n# \n# - **Sex:** Convert to a single binary feature, Female. No need to create a feature for Male, that would be redundant.\n# - **Pclass:** Convert to two binary features, PClass_1 and PClass_2. Similar to Male above, having a PClass_3 would be redundant.\n# - **Age group:** The age attribute binned using separators [0, 4, 15, 25, 35, 45, 65, 100]. Convert to a number of binary features, one for each age group.\n# - **Family size:** The sum of SibSp and Parch plus 1.\n\n# In[ ]:\n\n\n# Sex -> Female\n\n# training set\ndummy = pd.get_dummies(train_df['Sex'])\ndummy.columns = ['Female','Male']\ntrain_df = train_df.join(dummy['Female'])\n\n# test set\ndummy = pd.get_dummies(test_df['Sex'])\ndummy.columns = ['Female','Male']\ntest_df = test_df.join(dummy['Female'])\n\ntrain_df[['Name', 'Sex', 'Female']].head(2).T\n#train_df.columns\n\n\n# In[ ]:\n\n\n# Pclass -> PClass_1, PClass_2\n\n# training set\ndummy = pd.get_dummies(train_df['Pclass'])\ndummy.columns = ['PClass_1','PClass_2','PClass_3']\ntrain_df = train_df.join(dummy[['PClass_1', 'PClass_2']])\n\n# test set\ndummy = pd.get_dummies(test_df['Pclass'])\ndummy.columns = ['PClass_1','PClass_2','PClass_3']\ntest_df = test_df.join(dummy[['PClass_1', 'PClass_2']])\n\ntrain_df[['Name', 'Pclass', 'PClass_1', 'PClass_2']].head(2).T\n#train_df.columns\n\n\n# In[ ]:\n\n\n# AgeGroup -> binary features\n\n# training set\ndummy = pd.get_dummies(train_df['AgeGroup'])\ndummy.columns = ['Ages_4','Ages_15','Ages_25','Ages_35','Ages_45','Ages_65','Ages_100']\ntrain_df = train_df.join(dummy)\n\n# test set\ndummy = pd.get_dummies(test_df['AgeGroup'])\ndummy.columns = ['Ages_4','Ages_15','Ages_25','Ages_35','Ages_45','Ages_65','Ages_100']\ntest_df = test_df.join(dummy)\n\n\n# ## Experimental features ##\n# Some additional features to explore.\n\n# In[ ]:\n\n\n# Fare\n\n# there is a single missing \"Fare\" value\ntest_df['Fare'].fillna(test_df['Fare'].median(), inplace=True)\n\n# convert from float to int (floor)\n#train_df['Fare'] = train_df['Fare'].astype(int)\n#test_df['Fare'] = test_df['Fare'].astype(int)\n\n\n# In[ ]:\n\n\n# Embarked -> PortC, PortQ\n\n# Fill missing values with the most occurred value\nprint(train_df.groupby('Embarked').size().sort_values())\ntrain_df['Embarked'] = train_df['Embarked'].fillna('S')\n\n# training set\ndummy = pd.get_dummies(train_df['Embarked'])\n#dummy.columns\ndummy.columns = ['Port_C','Port_Q','Port_S']\n#train_df = train_df.join(dummy[['Port_C','Port_Q']])\n\n# test set\ndummy = pd.get_dummies(test_df['Embarked'])\ndummy.columns = ['Port_C','Port_Q','Port_S']\n#test_df = test_df.join(dummy[['Port_C','Port_Q']])\n\n\n# ## Dropping attributes ##\n# Drop unused attributes to avoid detecting spurious relationships.\n\n# In[ ]:\n\n\n# drop the attributes that will be unused\ntrain_df.drop(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', \n 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Fare', \n 'Embarked', 'Deck', 'AgeGroup'], axis=1, inplace=True)\n\ntest_df.drop(['Pclass', 'Name', 'Sex', 'Age', \n 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Fare',\n 'Embarked', 'AgeGroup'], axis=1, inplace=True)\n\ntrain_df.head(10).T\n\n\n# The sample above shows the features and their values for the first ten training examples.\n\n# # Modeling #\n# \n# Our task is a binary classification problem: we want to formulate a relationship that predicts an output (Survived or not) from engineered features (Sex, Age group, Family size...). This is type of learning is supervised learning, since a model will be trained on a dataset containing pairs of inputs and outputs. \n# \n# Suitable methods for performing classification include:\n# \n# - Logistic Regression*\n# - Perceptron*\n# - Support Vector Machines (SVMs)* \n# - Naive Bayes classifier* \n# - KNN or k-Nearest Neighbors\n# - Decision Tree\n# - Random Forrest\n# - Artificial neural network\n# - Relevance Vector Machine\n# \n# The methods marked * either discover linear classification boundaries (logistic regression, perceptron, and SVMs if using linear kernels) or assume no relationship between features (naive bayes) and thus are not expected to perform as well (see the section above on the relationship between survival, age group and sex).\n\n# ## Training data ##\n# Let's use cross validation to perform the evaluation. This method will give a reasonable indication of predictive accuracy as evaluation will take place on data that is not seen during training. The package **`sklearn.model_selection`** includes support for cross validation.\n\n# In[ ]:\n\n\n# split the datasets into matched input and ouput pairs\nX_train = train_df.drop(\"Survived\", axis=1) # X = inputs\nY_train = train_df[\"Survived\"] # Y = outputs\nX_test = test_df.drop(\"PassengerId\", axis=1).copy()\nX_train.shape, Y_train.shape, X_test.shape\n\n\n# Model fitting\n# ----------\n# (Some of this section is based on [this titanic tutorial][1].)\n# \n# Logistic Regression is a useful model to run early in the workflow. Logistic regression measures the relationship between the categorical dependent variable (feature) and one or more independent variables (features) by estimating probabilities using a logistic function, which is the cumulative logistic distribution. See [Logistic regression on Wikipedia][2].\n# \n# Note the confidence score generated by the model based on our training dataset.\n# \n# \n# [1]: https://www.kaggle.com/startupsci/titanic/titanic-data-science-solutions\n# [2]: https://en.wikipedia.org/wiki/Logistic_regression\n\n# In[ ]:\n\n\n# Logistic Regression\n\nlogreg = LogisticRegression()\nscores = cross_val_score(logreg, X_train, Y_train, cv=10)\nacc_log = round(scores.mean() * 100, 2)\nacc_log\n#Y_pred = logreg.predict(X_test)\n\n\n# We can use Logistic Regression to validate our assumptions and decisions for feature creating and completing goals. This can be done by calculating the coefficient of the features in the decision function.\n# Positive coefficients increase the log-odds of the response (and thus increase the probability), and negative coefficients decrease the log-odds of the response (and thus decrease the probability).\n\n# In[ ]:\n\n\nlogreg.fit(X_train, Y_train)\ncoeff_df = pd.DataFrame(train_df.columns.delete(0))\ncoeff_df.columns = ['Feature']\ncoeff_df[\"Correlation\"] = pd.Series(logreg.coef_[0])\n\ncoeff_df.sort_values(by='Correlation', ascending=False)\n\n\n# In[ ]:\n\n\n# Gaussian Naive Bayes\n\ngaussian = GaussianNB()\nscores = cross_val_score(gaussian, X_train, Y_train, cv=10)\nacc_gaussian = round(scores.mean() * 100, 2)\nacc_gaussian\n\n\n# In[ ]:\n\n\n# Perceptron (a single layer neural net)\n\nperceptron = Perceptron()\nscores = cross_val_score(perceptron, X_train, Y_train, cv=10)\nacc_perceptron = round(scores.mean() * 100, 2)\nacc_perceptron\n\n\n# In[ ]:\n\n\n# Neural Network (a multi layer neural net)\n\nneural_net = MLPClassifier()\nscores = cross_val_score(neural_net, X_train, Y_train, cv=10)\nacc_neural_net = round(scores.mean() * 100, 2)\nacc_neural_net\n\n\n# In[ ]:\n\n\n# Stochastic Gradient Descent\n\nsgd = SGDClassifier()\nscores = cross_val_score(sgd, X_train, Y_train, cv=10)\nacc_sgd = round(scores.mean() * 100, 2)\nacc_sgd\n\n\n# In[ ]:\n\n\n# Linear SVC\n\nlinear_svc = LinearSVC()\nscores = cross_val_score(linear_svc, X_train, Y_train, cv=10)\nacc_linear_svc = round(scores.mean() * 100, 2)\nacc_linear_svc\n\n\n# In[ ]:\n\n\n# Support Vector Machine\n\nsvc = SVC() # uses a rbf kernel by default (i.e. can discover non-linear boundaries)\nscores = cross_val_score(svc, X_train, Y_train, cv=10)\nacc_svc = round(scores.mean() * 100, 2)\nacc_svc\n\n\n# In[ ]:\n\n\n# Decision Tree\n\ndecision_tree = DecisionTreeClassifier()\nscores = cross_val_score(decision_tree, X_train, Y_train, cv=10)\nacc_decision_tree = round(scores.mean() * 100, 2)\nacc_decision_tree\n\n\n# In[ ]:\n\n\n# Random Forest - an ensemble model\n\nrandom_forest = RandomForestClassifier(n_estimators=100)\nscores = cross_val_score(random_forest, X_train, Y_train, cv=10)\nacc_random_forest = round(scores.mean() * 100, 2)\nacc_random_forest\n\n\n# In[ ]:\n\n\n# AdaBoost - an ensemble method\n\nada_boost = AdaBoostClassifier(n_estimators=100)\nscores = cross_val_score(ada_boost, X_train, Y_train, cv=10)\nacc_ada_boost = round(scores.mean() * 100, 2)\nacc_ada_boost\n\n\n# In[ ]:\n\n\n# k-Nearest Neighbors - a non-parametric method\n\nknn = KNeighborsClassifier(n_neighbors = 5)\nscores = cross_val_score(knn, X_train, Y_train, cv=10)\nacc_knn = round(scores.mean() * 100, 2)\nacc_knn\n\n\n# Model evaluation\n# ----------------\n# \n# We now rank the models and choose a high performing one for our problem. The Support Vector Machine consistently tops the chart. \n# \n# Decision Tree and Random Forest also both score high, but we prefer Random Forest as it avoids overfitting to the training set better than a decision tree and is therefore likely to perform better on the test dataset.\n\n# In[ ]:\n\n\nmodels = pd.DataFrame({\n 'Model': ['Support Vector Machine', 'kNN', 'Logistic Regression', \n 'Random Forest', 'Naive Bayes', 'Perceptron', \n 'Stochastic Gradient Descent', 'Linear SVC', \n 'Decision Tree', 'AdaBoost', 'Neural Network'],\n 'Score': [acc_svc, acc_knn, acc_log, \n acc_random_forest, acc_gaussian, acc_perceptron, \n acc_sgd, acc_linear_svc, acc_decision_tree, \n acc_ada_boost, acc_neural_net]})\nmodels.sort_values(by='Score', ascending=False)\n\n\n# In[ ]:\n\n\n# using random forest for submission\nrandom_forest.fit(X_train, Y_train)\nY_pred = random_forest.predict(X_test)\n\nsubmission = pd.DataFrame({\n \"PassengerId\": test_df[\"PassengerId\"],\n \"Survived\": Y_pred\n })\nsubmission.to_csv('titanic_submission_1.csv', index=False)\n#pd.set_option('display.max_rows', len(submission))\n#submission\n\n\n# Use cross validation to assess predictive accuracy\n# --------------------------------------------------\n# \n# We can easily improve the above scores by evaluating on the training data (compare the random forest scores above and below). However, scores produced like this are not truly indicative of predictive accuracy and should be avoided. To see why, consider that a classifier that simply memorizes each input and output pair will score perfectly but be unable to generalise to other examples. \n# \n\n# In[ ]:\n\n\n# Random Forest : scoring on training data\n\nrandom_forest = RandomForestClassifier(n_estimators=100)\nrandom_forest.fit(X_train, Y_train)\nacc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)\nacc_random_forest\n\n\n# What next? \n# -------------------------------\n# \n# **_More feature exploration:_**\n# Including *Fare* significantly increases the best accuracy to about 92% when *fare* is floored and 94% otherwise. Additionally including *Embarked* brings it up to 95%. It may worth be investigating if any relationship between these attributes and survival can be detected, especially for *fare*.\n# \n# Other possibilities for features include *Deck* and *Title*, which can be extracted from *Cabin* and *Name* respectively.\n# \n# Could also try two or more overlapping binnings for age groups (e.g. bins as defined by cutting on [0,4,15,25,35,45,65,100] and [10,20,30,40,55,100]). If going down this path, focus on introducing extra bins for age groups that contain many passengers and have a steeper gradient on the survival curve (such as for the twenties, e.g. cut on [10,20,30]).\n# \n# **_Refitting:_**\n# Most of the models above used their default parameters. Choose a few promising models and attempt to optimize their (hyper-)parameters. The sklearn library used above offers a couple of ways to do this automatically (via grid search and cross-validated models, see [Model selection][1] and [Tuning the hyper-parameters of an estimator][2]).\n# \n# \n# [1]: http://scikit-learn.org/stable/tutorial/statistical_inference/model_selection.html\n# [2]: http://scikit-learn.org/stable/modules/grid_search.html#grid-search\n",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
##Linear Queue Data Structure
#Main Queue Class
class LinearQueue():
def __init__(self, length):
#When initiating, user defines the length.
#The head and tail pointers are set at -1 (i.e. not pointing to anything, index beginning at zero)
#The queue is set as a series of None objects in a list the length the user gave
self._length = length
self._head = self._tail = -1
self._queue = [None]*self._length
def enqueue(self, *args):
#Enqueue - Adds value to Queue (First-In)
#Arguments are taken as a tuple of any length and are processed one at a time
for i in args:
if not self.isFull():
#The queue is checked if it is full. If it isn't, the value is added to the end of the queue and the tail is updated.
self._tail += 1
self._queue[self._tail] = i
else:
#Otherwise, if the list is full, the loop breaks and no more values are taken from the arguments.
break
def dequeue(self):
#Dequeue - Take value from Queue (First Out)
if self.isEmpty() or (self._tail == self._head):
#If the queue is empty or the head and tail point at the same position, None is returned
return None
else:
#If the queue is not empty, the value being pointed to by the head pointer is returned and the head pointer shifts up one
#To emulate a real Queue, this value is not removed, however it is ignored
self._head += 1
self._dequeueValue = self._queue[self._head]
return self._dequeueValue
def isFull(self):
return self._tail == (self._length-1) #If the tail pointer is the same as the length (minus one) of the queue then it is full. If not, it isn't full.
def isEmpty(self):
return self._tail == self._head == -1 #If the head and tail pointers are both -1, then the queue is empty. If not, it isn't empty.
#Test with a Queue of Length 5 named 'q'
print("Creating Linear Queue of 5 with No Values")
q = LinearQueue(5)
print("empty",q.isEmpty())
print("Enqueuing 1, 2, 3")
q.enqueue(1, 2, 3)
print("full",q.isFull())
print("empty",q.isEmpty())
print("dequeuing 1, 2, 3")
for i in range(0,3):
print("dequeuing",q.dequeue())
print("empty",q.isEmpty())
print("Enqueuing 4, 5")
q.enqueue(4, 5)
print("full",q.isFull())
print("empty",q.isEmpty())
print("dequeuing all")
for i in range(0,2):
print("dequeuing",q.dequeue())
print("full",q.isFull())
print("empty",q.isEmpty())
print("dequeuing extra value (should return None)")
print("dequeuing",q.dequeue())
|
normal
|
{
"blob_id": "0efac7d9d1a9180eafa8c9c4e3a42b4c68e718a2",
"index": 4597,
"step-1": "class LinearQueue:\n <mask token>\n\n def enqueue(self, *args):\n for i in args:\n if not self.isFull():\n self._tail += 1\n self._queue[self._tail] = i\n else:\n break\n\n def dequeue(self):\n if self.isEmpty() or self._tail == self._head:\n return None\n else:\n self._head += 1\n self._dequeueValue = self._queue[self._head]\n return self._dequeueValue\n\n def isFull(self):\n return self._tail == self._length - 1\n <mask token>\n\n\n<mask token>\n",
"step-2": "class LinearQueue:\n\n def __init__(self, length):\n self._length = length\n self._head = self._tail = -1\n self._queue = [None] * self._length\n\n def enqueue(self, *args):\n for i in args:\n if not self.isFull():\n self._tail += 1\n self._queue[self._tail] = i\n else:\n break\n\n def dequeue(self):\n if self.isEmpty() or self._tail == self._head:\n return None\n else:\n self._head += 1\n self._dequeueValue = self._queue[self._head]\n return self._dequeueValue\n\n def isFull(self):\n return self._tail == self._length - 1\n\n def isEmpty(self):\n return self._tail == self._head == -1\n\n\n<mask token>\n",
"step-3": "class LinearQueue:\n\n def __init__(self, length):\n self._length = length\n self._head = self._tail = -1\n self._queue = [None] * self._length\n\n def enqueue(self, *args):\n for i in args:\n if not self.isFull():\n self._tail += 1\n self._queue[self._tail] = i\n else:\n break\n\n def dequeue(self):\n if self.isEmpty() or self._tail == self._head:\n return None\n else:\n self._head += 1\n self._dequeueValue = self._queue[self._head]\n return self._dequeueValue\n\n def isFull(self):\n return self._tail == self._length - 1\n\n def isEmpty(self):\n return self._tail == self._head == -1\n\n\nprint('Creating Linear Queue of 5 with No Values')\n<mask token>\nprint('empty', q.isEmpty())\nprint('Enqueuing 1, 2, 3')\nq.enqueue(1, 2, 3)\nprint('full', q.isFull())\nprint('empty', q.isEmpty())\nprint('dequeuing 1, 2, 3')\nfor i in range(0, 3):\n print('dequeuing', q.dequeue())\nprint('empty', q.isEmpty())\nprint('Enqueuing 4, 5')\nq.enqueue(4, 5)\nprint('full', q.isFull())\nprint('empty', q.isEmpty())\nprint('dequeuing all')\nfor i in range(0, 2):\n print('dequeuing', q.dequeue())\nprint('full', q.isFull())\nprint('empty', q.isEmpty())\nprint('dequeuing extra value (should return None)')\nprint('dequeuing', q.dequeue())\n",
"step-4": "class LinearQueue:\n\n def __init__(self, length):\n self._length = length\n self._head = self._tail = -1\n self._queue = [None] * self._length\n\n def enqueue(self, *args):\n for i in args:\n if not self.isFull():\n self._tail += 1\n self._queue[self._tail] = i\n else:\n break\n\n def dequeue(self):\n if self.isEmpty() or self._tail == self._head:\n return None\n else:\n self._head += 1\n self._dequeueValue = self._queue[self._head]\n return self._dequeueValue\n\n def isFull(self):\n return self._tail == self._length - 1\n\n def isEmpty(self):\n return self._tail == self._head == -1\n\n\nprint('Creating Linear Queue of 5 with No Values')\nq = LinearQueue(5)\nprint('empty', q.isEmpty())\nprint('Enqueuing 1, 2, 3')\nq.enqueue(1, 2, 3)\nprint('full', q.isFull())\nprint('empty', q.isEmpty())\nprint('dequeuing 1, 2, 3')\nfor i in range(0, 3):\n print('dequeuing', q.dequeue())\nprint('empty', q.isEmpty())\nprint('Enqueuing 4, 5')\nq.enqueue(4, 5)\nprint('full', q.isFull())\nprint('empty', q.isEmpty())\nprint('dequeuing all')\nfor i in range(0, 2):\n print('dequeuing', q.dequeue())\nprint('full', q.isFull())\nprint('empty', q.isEmpty())\nprint('dequeuing extra value (should return None)')\nprint('dequeuing', q.dequeue())\n",
"step-5": "##Linear Queue Data Structure\n\n#Main Queue Class\nclass LinearQueue():\n def __init__(self, length):\n #When initiating, user defines the length.\n #The head and tail pointers are set at -1 (i.e. not pointing to anything, index beginning at zero)\n #The queue is set as a series of None objects in a list the length the user gave\n self._length = length\n self._head = self._tail = -1\n self._queue = [None]*self._length\n def enqueue(self, *args):\n #Enqueue - Adds value to Queue (First-In)\n #Arguments are taken as a tuple of any length and are processed one at a time\n for i in args:\n if not self.isFull():\n #The queue is checked if it is full. If it isn't, the value is added to the end of the queue and the tail is updated.\n self._tail += 1\n self._queue[self._tail] = i\n else:\n #Otherwise, if the list is full, the loop breaks and no more values are taken from the arguments.\n break\n def dequeue(self):\n #Dequeue - Take value from Queue (First Out)\n if self.isEmpty() or (self._tail == self._head):\n #If the queue is empty or the head and tail point at the same position, None is returned\n return None\n else:\n #If the queue is not empty, the value being pointed to by the head pointer is returned and the head pointer shifts up one\n #To emulate a real Queue, this value is not removed, however it is ignored\n self._head += 1\n self._dequeueValue = self._queue[self._head]\n return self._dequeueValue\n def isFull(self):\n return self._tail == (self._length-1) #If the tail pointer is the same as the length (minus one) of the queue then it is full. If not, it isn't full.\n def isEmpty(self):\n return self._tail == self._head == -1 #If the head and tail pointers are both -1, then the queue is empty. If not, it isn't empty.\n\n#Test with a Queue of Length 5 named 'q'\nprint(\"Creating Linear Queue of 5 with No Values\")\nq = LinearQueue(5)\nprint(\"empty\",q.isEmpty())\nprint(\"Enqueuing 1, 2, 3\")\nq.enqueue(1, 2, 3)\nprint(\"full\",q.isFull())\nprint(\"empty\",q.isEmpty())\nprint(\"dequeuing 1, 2, 3\")\nfor i in range(0,3):\n print(\"dequeuing\",q.dequeue())\nprint(\"empty\",q.isEmpty())\nprint(\"Enqueuing 4, 5\")\nq.enqueue(4, 5)\nprint(\"full\",q.isFull())\nprint(\"empty\",q.isEmpty())\nprint(\"dequeuing all\")\nfor i in range(0,2):\n print(\"dequeuing\",q.dequeue())\nprint(\"full\",q.isFull())\nprint(\"empty\",q.isEmpty())\nprint(\"dequeuing extra value (should return None)\")\nprint(\"dequeuing\",q.dequeue())\n",
"step-ids": [
4,
6,
7,
8,
9
]
}
|
[
4,
6,
7,
8,
9
] |
<|reserved_special_token_0|>
def read():
file_list = os.listdir(data_path)
result_list = []
for file in file_list:
with open(data_path + file) as f:
content = f.readlines()
dict = {}
dict['title'] = content[0]
dict['name'] = content[1]
dict['date'] = content[2]
dict['feedback'] = content[3]
result_list.append(dict)
f.close()
return result_list
def send(list):
for dict in list:
response = requests.post(url, json=dict)
if response.status_code == 200:
forDEBUG('SEND_SUCC', dict['title'])
else:
forDEBUG('SEND_FAIL', dict['title'])
def forDEBUG(p1, p2):
print('DEBUG:: {}, {}'.format(p1, p2))
def action():
plist = read()
send(plist)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def read():
file_list = os.listdir(data_path)
result_list = []
for file in file_list:
with open(data_path + file) as f:
content = f.readlines()
dict = {}
dict['title'] = content[0]
dict['name'] = content[1]
dict['date'] = content[2]
dict['feedback'] = content[3]
result_list.append(dict)
f.close()
return result_list
def send(list):
for dict in list:
response = requests.post(url, json=dict)
if response.status_code == 200:
forDEBUG('SEND_SUCC', dict['title'])
else:
forDEBUG('SEND_FAIL', dict['title'])
def forDEBUG(p1, p2):
print('DEBUG:: {}, {}'.format(p1, p2))
def action():
plist = read()
send(plist)
action()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
external_ip = 'xx'
data_path = '/data/feedback/'
url = 'http://{}/feedback/'.format(external_ip)
def read():
file_list = os.listdir(data_path)
result_list = []
for file in file_list:
with open(data_path + file) as f:
content = f.readlines()
dict = {}
dict['title'] = content[0]
dict['name'] = content[1]
dict['date'] = content[2]
dict['feedback'] = content[3]
result_list.append(dict)
f.close()
return result_list
def send(list):
for dict in list:
response = requests.post(url, json=dict)
if response.status_code == 200:
forDEBUG('SEND_SUCC', dict['title'])
else:
forDEBUG('SEND_FAIL', dict['title'])
def forDEBUG(p1, p2):
print('DEBUG:: {}, {}'.format(p1, p2))
def action():
plist = read()
send(plist)
action()
<|reserved_special_token_1|>
import os
import requests
external_ip = 'xx'
data_path = '/data/feedback/'
url = 'http://{}/feedback/'.format(external_ip)
def read():
file_list = os.listdir(data_path)
result_list = []
for file in file_list:
with open(data_path + file) as f:
content = f.readlines()
dict = {}
dict['title'] = content[0]
dict['name'] = content[1]
dict['date'] = content[2]
dict['feedback'] = content[3]
result_list.append(dict)
f.close()
return result_list
def send(list):
for dict in list:
response = requests.post(url, json=dict)
if response.status_code == 200:
forDEBUG('SEND_SUCC', dict['title'])
else:
forDEBUG('SEND_FAIL', dict['title'])
def forDEBUG(p1, p2):
print('DEBUG:: {}, {}'.format(p1, p2))
def action():
plist = read()
send(plist)
action()
<|reserved_special_token_1|>
#! /usr/bin/env python3
import os
import requests
# import json
external_ip = "xx"
data_path = "/data/feedback/"
url = "http://{}/feedback/".format(external_ip)
def read():
# read file
file_list = os.listdir(data_path)
result_list = []
for file in file_list:
with open(data_path + file) as f:
# read line, title, name, date, feedback
content = f.readlines()
# envolope to dictionary
dict = {}
dict["title"] = content[0]
dict["name"] = content[1]
dict["date"] = content[2]
dict["feedback"] = content[3]
result_list.append(dict)
f.close()
return result_list
def send(list):
for dict in list:
response = requests.post(url, json=dict)
if(response.status_code == 200):
forDEBUG("SEND_SUCC", dict["title"])
else:
forDEBUG("SEND_FAIL", dict["title"])
def forDEBUG(p1, p2):
print("DEBUG:: {}, {}".format(p1, p2))
def action():
plist = read()
send(plist)
action()
|
flexible
|
{
"blob_id": "6f1bb9fde9ed9667ab81baa9e8ec965d711a0556",
"index": 9853,
"step-1": "<mask token>\n\n\ndef read():\n file_list = os.listdir(data_path)\n result_list = []\n for file in file_list:\n with open(data_path + file) as f:\n content = f.readlines()\n dict = {}\n dict['title'] = content[0]\n dict['name'] = content[1]\n dict['date'] = content[2]\n dict['feedback'] = content[3]\n result_list.append(dict)\n f.close()\n return result_list\n\n\ndef send(list):\n for dict in list:\n response = requests.post(url, json=dict)\n if response.status_code == 200:\n forDEBUG('SEND_SUCC', dict['title'])\n else:\n forDEBUG('SEND_FAIL', dict['title'])\n\n\ndef forDEBUG(p1, p2):\n print('DEBUG:: {}, {}'.format(p1, p2))\n\n\ndef action():\n plist = read()\n send(plist)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef read():\n file_list = os.listdir(data_path)\n result_list = []\n for file in file_list:\n with open(data_path + file) as f:\n content = f.readlines()\n dict = {}\n dict['title'] = content[0]\n dict['name'] = content[1]\n dict['date'] = content[2]\n dict['feedback'] = content[3]\n result_list.append(dict)\n f.close()\n return result_list\n\n\ndef send(list):\n for dict in list:\n response = requests.post(url, json=dict)\n if response.status_code == 200:\n forDEBUG('SEND_SUCC', dict['title'])\n else:\n forDEBUG('SEND_FAIL', dict['title'])\n\n\ndef forDEBUG(p1, p2):\n print('DEBUG:: {}, {}'.format(p1, p2))\n\n\ndef action():\n plist = read()\n send(plist)\n\n\naction()\n",
"step-3": "<mask token>\nexternal_ip = 'xx'\ndata_path = '/data/feedback/'\nurl = 'http://{}/feedback/'.format(external_ip)\n\n\ndef read():\n file_list = os.listdir(data_path)\n result_list = []\n for file in file_list:\n with open(data_path + file) as f:\n content = f.readlines()\n dict = {}\n dict['title'] = content[0]\n dict['name'] = content[1]\n dict['date'] = content[2]\n dict['feedback'] = content[3]\n result_list.append(dict)\n f.close()\n return result_list\n\n\ndef send(list):\n for dict in list:\n response = requests.post(url, json=dict)\n if response.status_code == 200:\n forDEBUG('SEND_SUCC', dict['title'])\n else:\n forDEBUG('SEND_FAIL', dict['title'])\n\n\ndef forDEBUG(p1, p2):\n print('DEBUG:: {}, {}'.format(p1, p2))\n\n\ndef action():\n plist = read()\n send(plist)\n\n\naction()\n",
"step-4": "import os\nimport requests\nexternal_ip = 'xx'\ndata_path = '/data/feedback/'\nurl = 'http://{}/feedback/'.format(external_ip)\n\n\ndef read():\n file_list = os.listdir(data_path)\n result_list = []\n for file in file_list:\n with open(data_path + file) as f:\n content = f.readlines()\n dict = {}\n dict['title'] = content[0]\n dict['name'] = content[1]\n dict['date'] = content[2]\n dict['feedback'] = content[3]\n result_list.append(dict)\n f.close()\n return result_list\n\n\ndef send(list):\n for dict in list:\n response = requests.post(url, json=dict)\n if response.status_code == 200:\n forDEBUG('SEND_SUCC', dict['title'])\n else:\n forDEBUG('SEND_FAIL', dict['title'])\n\n\ndef forDEBUG(p1, p2):\n print('DEBUG:: {}, {}'.format(p1, p2))\n\n\ndef action():\n plist = read()\n send(plist)\n\n\naction()\n",
"step-5": "#! /usr/bin/env python3\n\nimport os\nimport requests\n# import json\n\nexternal_ip = \"xx\"\ndata_path = \"/data/feedback/\"\nurl = \"http://{}/feedback/\".format(external_ip)\n\ndef read():\n # read file\n file_list = os.listdir(data_path)\n\n result_list = []\n for file in file_list:\n with open(data_path + file) as f:\n # read line, title, name, date, feedback\n content = f.readlines()\n # envolope to dictionary\n dict = {}\n dict[\"title\"] = content[0]\n dict[\"name\"] = content[1]\n dict[\"date\"] = content[2]\n dict[\"feedback\"] = content[3]\n result_list.append(dict)\n f.close()\n return result_list\n\n \ndef send(list):\n for dict in list:\n response = requests.post(url, json=dict)\n if(response.status_code == 200):\n forDEBUG(\"SEND_SUCC\", dict[\"title\"])\n else:\n forDEBUG(\"SEND_FAIL\", dict[\"title\"])\n\ndef forDEBUG(p1, p2):\n print(\"DEBUG:: {}, {}\".format(p1, p2))\n\ndef action():\n plist = read()\n send(plist)\n\naction()",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
import string
import random
file_one_time_pad = open("encryption_file.txt","r")
p_text = file_one_time_pad.read()
file_one_time_pad.close()
print(p_text)
p_text = str.lower(p_text)
main_text = []
p_text_numerical = []
temp_key = [21,25,20,15,16,14,10,26,24,9,8,13]
alphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
main_key = []
cipher_text = []
cipher_text_numerical = []
length_p_text = len(p_text)
length_temp_key = len(temp_key)
random_alpha = 0
decipher_text = []
decipher_numerical = []
##Getting the numerical values of the text
for i in p_text:
main_text.append(i)
for i in range(length_p_text):
for j in range(25):
if main_text[i] == alphabets[j]:
p_text_numerical.append(j)
break
##Generating keys dynamically
if length_p_text == length_temp_key:
for i in range(length_temp_key-1):
main_key.append(temp_key[i])
elif length_p_text < length_temp_key:
for i in range(length_p_text-1):
main_key.append(temp_key[i])
else:
for i in range(length_temp_key-1):
main_key.append(temp_key[i])
diff = length_p_text - length_temp_key
for i in range(diff):
random_alpha = random.choice(temp_key)
main_key.append(random_alpha)
print("The main key is :: \n")
print(main_key)
print("The length of p_text_numerical:: \t",len(p_text_numerical))
print("\n")
print("The length of the main_key is :: \t",len(main_key))
## Ciphering algorithm
for i in range(length_p_text-1):
cipher_text_numerical.append(abs(p_text_numerical[i]+main_key[i]))
print("The cipherred text is :: \n")
print(cipher_text_numerical)
## Deciphering algorithm
length_cipher = len(cipher_text_numerical)
for i in range(length_cipher):
decipher_numerical.append(cipher_text_numerical[i] - main_key[i])
print("The decipherred numerical::\n")
print(decipher_numerical)
temp = 0
for i in range(length_p_text-1):
temp = decipher_numerical[i]
decipher_text.append(alphabets[temp])
deciphered_one = ""
for i in decipher_text:
deciphered_one = deciphered_one + i
file_encrypt = open("encryption_file.txt","w")
file_encrypt.write(deciphered_one)
file_encrypt.close()
print("The deciphered text is ::\n")
print(decipher_text)
|
normal
|
{
"blob_id": "4b647d37d390a4df42f29bbfc7e4bae4e77c5828",
"index": 8935,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfile_one_time_pad.close()\nprint(p_text)\n<mask token>\nfor i in p_text:\n main_text.append(i)\nfor i in range(length_p_text):\n for j in range(25):\n if main_text[i] == alphabets[j]:\n p_text_numerical.append(j)\n break\nif length_p_text == length_temp_key:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\nelif length_p_text < length_temp_key:\n for i in range(length_p_text - 1):\n main_key.append(temp_key[i])\nelse:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\n diff = length_p_text - length_temp_key\n for i in range(diff):\n random_alpha = random.choice(temp_key)\n main_key.append(random_alpha)\nprint('The main key is :: \\n')\nprint(main_key)\nprint('The length of p_text_numerical:: \\t', len(p_text_numerical))\nprint('\\n')\nprint('The length of the main_key is :: \\t', len(main_key))\nfor i in range(length_p_text - 1):\n cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))\nprint('The cipherred text is :: \\n')\nprint(cipher_text_numerical)\n<mask token>\nfor i in range(length_cipher):\n decipher_numerical.append(cipher_text_numerical[i] - main_key[i])\nprint('The decipherred numerical::\\n')\nprint(decipher_numerical)\n<mask token>\nfor i in range(length_p_text - 1):\n temp = decipher_numerical[i]\n decipher_text.append(alphabets[temp])\n<mask token>\nfor i in decipher_text:\n deciphered_one = deciphered_one + i\n<mask token>\nfile_encrypt.write(deciphered_one)\nfile_encrypt.close()\nprint('The deciphered text is ::\\n')\nprint(decipher_text)\n",
"step-3": "<mask token>\nfile_one_time_pad = open('encryption_file.txt', 'r')\np_text = file_one_time_pad.read()\nfile_one_time_pad.close()\nprint(p_text)\np_text = str.lower(p_text)\nmain_text = []\np_text_numerical = []\ntemp_key = [21, 25, 20, 15, 16, 14, 10, 26, 24, 9, 8, 13]\nalphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',\n 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\nmain_key = []\ncipher_text = []\ncipher_text_numerical = []\nlength_p_text = len(p_text)\nlength_temp_key = len(temp_key)\nrandom_alpha = 0\ndecipher_text = []\ndecipher_numerical = []\nfor i in p_text:\n main_text.append(i)\nfor i in range(length_p_text):\n for j in range(25):\n if main_text[i] == alphabets[j]:\n p_text_numerical.append(j)\n break\nif length_p_text == length_temp_key:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\nelif length_p_text < length_temp_key:\n for i in range(length_p_text - 1):\n main_key.append(temp_key[i])\nelse:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\n diff = length_p_text - length_temp_key\n for i in range(diff):\n random_alpha = random.choice(temp_key)\n main_key.append(random_alpha)\nprint('The main key is :: \\n')\nprint(main_key)\nprint('The length of p_text_numerical:: \\t', len(p_text_numerical))\nprint('\\n')\nprint('The length of the main_key is :: \\t', len(main_key))\nfor i in range(length_p_text - 1):\n cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))\nprint('The cipherred text is :: \\n')\nprint(cipher_text_numerical)\nlength_cipher = len(cipher_text_numerical)\nfor i in range(length_cipher):\n decipher_numerical.append(cipher_text_numerical[i] - main_key[i])\nprint('The decipherred numerical::\\n')\nprint(decipher_numerical)\ntemp = 0\nfor i in range(length_p_text - 1):\n temp = decipher_numerical[i]\n decipher_text.append(alphabets[temp])\ndeciphered_one = ''\nfor i in decipher_text:\n deciphered_one = deciphered_one + i\nfile_encrypt = open('encryption_file.txt', 'w')\nfile_encrypt.write(deciphered_one)\nfile_encrypt.close()\nprint('The deciphered text is ::\\n')\nprint(decipher_text)\n",
"step-4": "import string\nimport random\nfile_one_time_pad = open('encryption_file.txt', 'r')\np_text = file_one_time_pad.read()\nfile_one_time_pad.close()\nprint(p_text)\np_text = str.lower(p_text)\nmain_text = []\np_text_numerical = []\ntemp_key = [21, 25, 20, 15, 16, 14, 10, 26, 24, 9, 8, 13]\nalphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',\n 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\nmain_key = []\ncipher_text = []\ncipher_text_numerical = []\nlength_p_text = len(p_text)\nlength_temp_key = len(temp_key)\nrandom_alpha = 0\ndecipher_text = []\ndecipher_numerical = []\nfor i in p_text:\n main_text.append(i)\nfor i in range(length_p_text):\n for j in range(25):\n if main_text[i] == alphabets[j]:\n p_text_numerical.append(j)\n break\nif length_p_text == length_temp_key:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\nelif length_p_text < length_temp_key:\n for i in range(length_p_text - 1):\n main_key.append(temp_key[i])\nelse:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\n diff = length_p_text - length_temp_key\n for i in range(diff):\n random_alpha = random.choice(temp_key)\n main_key.append(random_alpha)\nprint('The main key is :: \\n')\nprint(main_key)\nprint('The length of p_text_numerical:: \\t', len(p_text_numerical))\nprint('\\n')\nprint('The length of the main_key is :: \\t', len(main_key))\nfor i in range(length_p_text - 1):\n cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))\nprint('The cipherred text is :: \\n')\nprint(cipher_text_numerical)\nlength_cipher = len(cipher_text_numerical)\nfor i in range(length_cipher):\n decipher_numerical.append(cipher_text_numerical[i] - main_key[i])\nprint('The decipherred numerical::\\n')\nprint(decipher_numerical)\ntemp = 0\nfor i in range(length_p_text - 1):\n temp = decipher_numerical[i]\n decipher_text.append(alphabets[temp])\ndeciphered_one = ''\nfor i in decipher_text:\n deciphered_one = deciphered_one + i\nfile_encrypt = open('encryption_file.txt', 'w')\nfile_encrypt.write(deciphered_one)\nfile_encrypt.close()\nprint('The deciphered text is ::\\n')\nprint(decipher_text)\n",
"step-5": "import string\nimport random\n\nfile_one_time_pad = open(\"encryption_file.txt\",\"r\")\np_text = file_one_time_pad.read()\nfile_one_time_pad.close()\nprint(p_text)\np_text = str.lower(p_text)\nmain_text = []\np_text_numerical = []\ntemp_key = [21,25,20,15,16,14,10,26,24,9,8,13]\nalphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\nmain_key = []\ncipher_text = []\ncipher_text_numerical = []\nlength_p_text = len(p_text)\nlength_temp_key = len(temp_key)\nrandom_alpha = 0\ndecipher_text = []\ndecipher_numerical = []\n\n\n\n##Getting the numerical values of the text\nfor i in p_text:\n\tmain_text.append(i)\n\nfor i in range(length_p_text):\n\tfor j in range(25):\n\t\tif main_text[i] == alphabets[j]:\n\t\t\tp_text_numerical.append(j)\n\t\t\tbreak \n\n\n##Generating keys dynamically\nif length_p_text == length_temp_key:\n\tfor i in range(length_temp_key-1):\n\t\tmain_key.append(temp_key[i])\nelif length_p_text < length_temp_key:\n\tfor i in range(length_p_text-1):\n\t\tmain_key.append(temp_key[i])\nelse:\n\tfor i in range(length_temp_key-1):\n\t\tmain_key.append(temp_key[i])\n\tdiff = length_p_text - length_temp_key\n\tfor i in range(diff):\n\t\trandom_alpha = random.choice(temp_key)\n\t\tmain_key.append(random_alpha)\nprint(\"The main key is :: \\n\")\nprint(main_key)\nprint(\"The length of p_text_numerical:: \\t\",len(p_text_numerical))\nprint(\"\\n\")\nprint(\"The length of the main_key is :: \\t\",len(main_key))\n\n## Ciphering algorithm\n\nfor i in range(length_p_text-1):\n\tcipher_text_numerical.append(abs(p_text_numerical[i]+main_key[i]))\nprint(\"The cipherred text is :: \\n\")\nprint(cipher_text_numerical)\n\n\n## Deciphering algorithm\nlength_cipher = len(cipher_text_numerical)\nfor i in range(length_cipher):\n\tdecipher_numerical.append(cipher_text_numerical[i] - main_key[i])\nprint(\"The decipherred numerical::\\n\")\nprint(decipher_numerical)\n\ntemp = 0\nfor i in range(length_p_text-1):\n\ttemp = decipher_numerical[i]\t\n\tdecipher_text.append(alphabets[temp])\n\ndeciphered_one = \"\"\nfor i in decipher_text:\n\tdeciphered_one = deciphered_one + i\n\nfile_encrypt = open(\"encryption_file.txt\",\"w\")\nfile_encrypt.write(deciphered_one)\nfile_encrypt.close()\nprint(\"The deciphered text is ::\\n\")\nprint(decipher_text)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from django.db import models
class Professor(models.Model):
nome = models.CharField(max_length=100)
apelido = models.CharField(max_length=30)
descricao = models.TextField(max_length=1000)
def __str__(self):
return self.nome
class ImagemProfessor(models.Model):
professor = models.ForeignKey(Professor, on_delete=models.CASCADE)
foto = models.ImageField(upload_to='fotos/%d/%m/%Y/', blank=True)
|
normal
|
{
"blob_id": "acb879cb72e5b3ac897a271dc680e4ca763d2122",
"index": 7541,
"step-1": "<mask token>\n\n\nclass ImagemProfessor(models.Model):\n professor = models.ForeignKey(Professor, on_delete=models.CASCADE)\n foto = models.ImageField(upload_to='fotos/%d/%m/%Y/', blank=True)\n",
"step-2": "<mask token>\n\n\nclass Professor(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass ImagemProfessor(models.Model):\n professor = models.ForeignKey(Professor, on_delete=models.CASCADE)\n foto = models.ImageField(upload_to='fotos/%d/%m/%Y/', blank=True)\n",
"step-3": "<mask token>\n\n\nclass Professor(models.Model):\n nome = models.CharField(max_length=100)\n apelido = models.CharField(max_length=30)\n descricao = models.TextField(max_length=1000)\n\n def __str__(self):\n return self.nome\n\n\nclass ImagemProfessor(models.Model):\n professor = models.ForeignKey(Professor, on_delete=models.CASCADE)\n foto = models.ImageField(upload_to='fotos/%d/%m/%Y/', blank=True)\n",
"step-4": "from django.db import models\n\n\nclass Professor(models.Model):\n nome = models.CharField(max_length=100)\n apelido = models.CharField(max_length=30)\n descricao = models.TextField(max_length=1000)\n\n def __str__(self):\n return self.nome\n\n\nclass ImagemProfessor(models.Model):\n professor = models.ForeignKey(Professor, on_delete=models.CASCADE)\n foto = models.ImageField(upload_to='fotos/%d/%m/%Y/', blank=True)\n",
"step-5": null,
"step-ids": [
2,
3,
5,
6
]
}
|
[
2,
3,
5,
6
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def begin_chat(request, id=None):
check = check_if_auth_user(request)
if not check:
messages.error(request, 'Perform login first to start chatting')
return redirect('home:welcome')
current_user = User.objects.filter(user_id=check)[0]
other_user = get_object_or_404(User, auto_id=id)
sql = """SELECT * FROM chat_start_chat
WHERE chat_sender='{0}' and chat_reciever='{1}'
OR chat_sender='{1}' and chat_reciever='{0}';"""
chat_list = Chat.objects.raw(sql.format(current_user.user_id,
other_user.user_id))
context_data = {'user': current_user, 'other_user': other_user,
'chatmessage_list': chat_list}
return render(request, 'chat.html', context_data)
<|reserved_special_token_1|>
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.contrib import messages
from User.models import User, check_if_auth_user
from .models import Chat
def begin_chat(request, id=None):
check = check_if_auth_user(request)
if not check:
messages.error(request, 'Perform login first to start chatting')
return redirect('home:welcome')
current_user = User.objects.filter(user_id=check)[0]
other_user = get_object_or_404(User, auto_id=id)
sql = """SELECT * FROM chat_start_chat
WHERE chat_sender='{0}' and chat_reciever='{1}'
OR chat_sender='{1}' and chat_reciever='{0}';"""
chat_list = Chat.objects.raw(sql.format(current_user.user_id,
other_user.user_id))
context_data = {'user': current_user, 'other_user': other_user,
'chatmessage_list': chat_list}
return render(request, 'chat.html', context_data)
<|reserved_special_token_1|>
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.contrib import messages
# Create your views here.
from User.models import User, check_if_auth_user
from .models import Chat
# def recv_chat(request, id = None):
# check = check_if_auth_user(request)
# if not check:
# messages.error(request, "Perform login first to start chatting")
# return redirect("home:welcome")
# current_user = User.objects.filter(user_id = check)[0]
# other_user = get_object_or_404(User, auto_id = id)
# message = request.POST.get('chat_msg')
# try:
# if current_user and other_user and message:
# #sql = """INSERT INTO User_user( name, user_id, user_pwd, contact, address)
# # Values(%s,%s,%s,%s,%s)""" % ( name, email, pwd, con, add)
# chat = Chat(
# chat_sender = current_user.user_id,
# chat_reciever = other_user.user_id,
# message = message)
# chat.save()
# return redirect(chat.get_return_url())
# except Exception,error:
# messages.error(request, "Some Internal Error. Try again")
# return redirect(chat.get_return_url())
def begin_chat(request, id = None):
check = check_if_auth_user(request)
if not check:
messages.error(request, "Perform login first to start chatting")
return redirect("home:welcome")
current_user = User.objects.filter(user_id = check)[0]
other_user = get_object_or_404(User, auto_id = id)
sql = """SELECT * FROM chat_start_chat
WHERE chat_sender='{0}' and chat_reciever='{1}'
OR chat_sender='{1}' and chat_reciever='{0}';"""
chat_list = Chat.objects.raw(sql.format(current_user.user_id,other_user.user_id))
context_data = {
"user" : current_user,
"other_user" : other_user,
"chatmessage_list": chat_list,
}
return render(request, "chat.html",context_data)
|
flexible
|
{
"blob_id": "9dfb3f58127b30467651ac4209277cd947643c65",
"index": 7411,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef begin_chat(request, id=None):\n check = check_if_auth_user(request)\n if not check:\n messages.error(request, 'Perform login first to start chatting')\n return redirect('home:welcome')\n current_user = User.objects.filter(user_id=check)[0]\n other_user = get_object_or_404(User, auto_id=id)\n sql = \"\"\"SELECT * FROM chat_start_chat\n\t\t\t WHERE chat_sender='{0}' and chat_reciever='{1}'\n\t\t\t OR chat_sender='{1}' and chat_reciever='{0}';\"\"\"\n chat_list = Chat.objects.raw(sql.format(current_user.user_id,\n other_user.user_id))\n context_data = {'user': current_user, 'other_user': other_user,\n 'chatmessage_list': chat_list}\n return render(request, 'chat.html', context_data)\n",
"step-3": "from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.contrib import messages\nfrom User.models import User, check_if_auth_user\nfrom .models import Chat\n\n\ndef begin_chat(request, id=None):\n check = check_if_auth_user(request)\n if not check:\n messages.error(request, 'Perform login first to start chatting')\n return redirect('home:welcome')\n current_user = User.objects.filter(user_id=check)[0]\n other_user = get_object_or_404(User, auto_id=id)\n sql = \"\"\"SELECT * FROM chat_start_chat\n\t\t\t WHERE chat_sender='{0}' and chat_reciever='{1}'\n\t\t\t OR chat_sender='{1}' and chat_reciever='{0}';\"\"\"\n chat_list = Chat.objects.raw(sql.format(current_user.user_id,\n other_user.user_id))\n context_data = {'user': current_user, 'other_user': other_user,\n 'chatmessage_list': chat_list}\n return render(request, 'chat.html', context_data)\n",
"step-4": "from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.contrib import messages\n# Create your views here.\nfrom User.models import User, check_if_auth_user\nfrom .models import Chat\n\n# def recv_chat(request, id = None):\n# \tcheck = check_if_auth_user(request)\n# \tif not check:\n# \t\tmessages.error(request, \"Perform login first to start chatting\")\n# \t\treturn redirect(\"home:welcome\")\n\n# \tcurrent_user = User.objects.filter(user_id = check)[0]\n# \tother_user = get_object_or_404(User, auto_id = id)\n# \tmessage = request.POST.get('chat_msg')\n\n# \ttry:\n# \t\tif current_user and other_user and message:\n# \t\t\t#sql = \"\"\"INSERT INTO User_user( name, user_id, user_pwd, contact, address) \n# \t\t\t#\t\tValues(%s,%s,%s,%s,%s)\"\"\" % ( name, email, pwd, con, add)\n# \t\t\tchat = Chat(\n# \t\t\t\t\tchat_sender = current_user.user_id,\n# \t\t\t\t\tchat_reciever = other_user.user_id,\n# \t\t\t\t\tmessage = message)\n# \t\t\tchat.save()\n# \t\t\treturn redirect(chat.get_return_url())\n# \texcept Exception,error:\n# \t\tmessages.error(request, \"Some Internal Error. Try again\")\n# \treturn redirect(chat.get_return_url())\n\n\ndef begin_chat(request, id = None):\n\tcheck = check_if_auth_user(request)\n\tif not check:\n\t\tmessages.error(request, \"Perform login first to start chatting\")\n\t\treturn redirect(\"home:welcome\")\n\tcurrent_user = User.objects.filter(user_id = check)[0]\n\tother_user = get_object_or_404(User, auto_id = id)\n\t\n\tsql = \"\"\"SELECT * FROM chat_start_chat\n\t\t\t WHERE chat_sender='{0}' and chat_reciever='{1}'\n\t\t\t OR chat_sender='{1}' and chat_reciever='{0}';\"\"\"\n\n\tchat_list = Chat.objects.raw(sql.format(current_user.user_id,other_user.user_id))\n\tcontext_data = {\n\t\t\"user\" : current_user,\n\t\t\"other_user\" : other_user,\n\t\t\"chatmessage_list\": chat_list,\n\t}\n\treturn render(request, \"chat.html\",context_data)\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
urlpatterns = [path('', views.home), path('teams', views.showTeams), path(
'teams/new', views.new), path('teams/<teamname>', views.showSpecificTeam)]
<|reserved_special_token_1|>
from django.urls import path
from . import views
urlpatterns = [path('', views.home), path('teams', views.showTeams), path(
'teams/new', views.new), path('teams/<teamname>', views.showSpecificTeam)]
<|reserved_special_token_1|>
from django.urls import path
from . import views
urlpatterns = [
# @app.route("/")
path('', views.home),
path("teams", views.showTeams),
path("teams/new", views.new),
path("teams/<teamname>", views.showSpecificTeam),
# path("allfood", views.showAllFoodItems),
# path("team/<teamname>", views.showSpecificTeam)
]
|
flexible
|
{
"blob_id": "e267108177841110493061a4f84ae3d29850d028",
"index": 1853,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [path('', views.home), path('teams', views.showTeams), path(\n 'teams/new', views.new), path('teams/<teamname>', views.showSpecificTeam)]\n",
"step-3": "from django.urls import path\nfrom . import views\nurlpatterns = [path('', views.home), path('teams', views.showTeams), path(\n 'teams/new', views.new), path('teams/<teamname>', views.showSpecificTeam)]\n",
"step-4": "from django.urls import path \nfrom . import views\n\n\nurlpatterns = [\n # @app.route(\"/\")\n path('', views.home),\n path(\"teams\", views.showTeams),\n path(\"teams/new\", views.new),\n path(\"teams/<teamname>\", views.showSpecificTeam),\n # path(\"allfood\", views.showAllFoodItems),\n # path(\"team/<teamname>\", views.showSpecificTeam) \n]",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from fabric.api import local,run
INSTALL_STEPS = ['yes | sudo apt-get install libmysqlclient-dev python-dev python-mysqldb python-virtualenv',
'virtualenv --no-site-packages env',
'. env/bin/activate;pip install -r requirements.txt']
def deps_local():
for step in INSTALL_STEPS:
local(step)
def deps_remote():
for step in INSTALL_STEPS:
run(step)
|
normal
|
{
"blob_id": "d64140466e62b78506d0f200f451649023697a3b",
"index": 1386,
"step-1": "<mask token>\n\n\ndef deps_remote():\n for step in INSTALL_STEPS:\n run(step)\n",
"step-2": "<mask token>\n\n\ndef deps_local():\n for step in INSTALL_STEPS:\n local(step)\n\n\ndef deps_remote():\n for step in INSTALL_STEPS:\n run(step)\n",
"step-3": "<mask token>\nINSTALL_STEPS = [\n 'yes | sudo apt-get install libmysqlclient-dev\\t python-dev python-mysqldb python-virtualenv'\n , 'virtualenv --no-site-packages env',\n '. env/bin/activate;pip install -r requirements.txt']\n\n\ndef deps_local():\n for step in INSTALL_STEPS:\n local(step)\n\n\ndef deps_remote():\n for step in INSTALL_STEPS:\n run(step)\n",
"step-4": "from fabric.api import local, run\nINSTALL_STEPS = [\n 'yes | sudo apt-get install libmysqlclient-dev\\t python-dev python-mysqldb python-virtualenv'\n , 'virtualenv --no-site-packages env',\n '. env/bin/activate;pip install -r requirements.txt']\n\n\ndef deps_local():\n for step in INSTALL_STEPS:\n local(step)\n\n\ndef deps_remote():\n for step in INSTALL_STEPS:\n run(step)\n",
"step-5": "from fabric.api import local,run\nINSTALL_STEPS = ['yes | sudo apt-get install libmysqlclient-dev\t python-dev python-mysqldb python-virtualenv',\n 'virtualenv --no-site-packages env',\n '. env/bin/activate;pip install -r requirements.txt']\ndef deps_local():\n for step in INSTALL_STEPS:\n \tlocal(step)\ndef deps_remote():\n for step in INSTALL_STEPS:\n \trun(step)\t\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='Personal', fields=[(
'post_apply', models.CharField(max_length=150)), ('department',
models.CharField(max_length=50)), ('application_no', models.
BigAutoField(db_column='APPLICATION_NO', primary_key=True,
serialize=False)), ('email', models.EmailField(max_length=254)), (
'category', models.CharField(max_length=30)), ('pwd_status', models
.CharField(max_length=5)), ('internal_candidate', models.
BooleanField()), ('profile_image', models.ImageField(upload_to='')),
('first_name', models.CharField(max_length=100)), ('middle_name',
models.CharField(max_length=100)), ('last_name', models.CharField(
max_length=100)), ('father_name', models.CharField(max_length=100)),
('dob', models.DateField()), ('age', models.IntegerField()), (
'aadhar_card', models.BigIntegerField()), ('gender', models.
CharField(max_length=10)), ('nationality', models.CharField(
max_length=20)), ('marital_status', models.CharField(max_length=10)
), ('correspondence_address', models.CharField(max_length=200)), (
'permanent_address', models.CharField(max_length=200)), ('mobile',
models.CharField(max_length=10)), ('areas_of_specialization',
models.TextField(max_length=300)), ('phd_thesis_title', models.
CharField(max_length=200)), ('date_of_acquiring_phd', models.
DateField())])]
<|reserved_special_token_1|>
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='Personal', fields=[(
'post_apply', models.CharField(max_length=150)), ('department',
models.CharField(max_length=50)), ('application_no', models.
BigAutoField(db_column='APPLICATION_NO', primary_key=True,
serialize=False)), ('email', models.EmailField(max_length=254)), (
'category', models.CharField(max_length=30)), ('pwd_status', models
.CharField(max_length=5)), ('internal_candidate', models.
BooleanField()), ('profile_image', models.ImageField(upload_to='')),
('first_name', models.CharField(max_length=100)), ('middle_name',
models.CharField(max_length=100)), ('last_name', models.CharField(
max_length=100)), ('father_name', models.CharField(max_length=100)),
('dob', models.DateField()), ('age', models.IntegerField()), (
'aadhar_card', models.BigIntegerField()), ('gender', models.
CharField(max_length=10)), ('nationality', models.CharField(
max_length=20)), ('marital_status', models.CharField(max_length=10)
), ('correspondence_address', models.CharField(max_length=200)), (
'permanent_address', models.CharField(max_length=200)), ('mobile',
models.CharField(max_length=10)), ('areas_of_specialization',
models.TextField(max_length=300)), ('phd_thesis_title', models.
CharField(max_length=200)), ('date_of_acquiring_phd', models.
DateField())])]
<|reserved_special_token_1|>
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-01-15 17:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Personal',
fields=[
('post_apply', models.CharField(max_length=150)),
('department', models.CharField(max_length=50)),
('application_no', models.BigAutoField(db_column='APPLICATION_NO', primary_key=True, serialize=False)),
('email', models.EmailField(max_length=254)),
('category', models.CharField(max_length=30)),
('pwd_status', models.CharField(max_length=5)),
('internal_candidate', models.BooleanField()),
('profile_image', models.ImageField(upload_to='')),
('first_name', models.CharField(max_length=100)),
('middle_name', models.CharField(max_length=100)),
('last_name', models.CharField(max_length=100)),
('father_name', models.CharField(max_length=100)),
('dob', models.DateField()),
('age', models.IntegerField()),
('aadhar_card', models.BigIntegerField()),
('gender', models.CharField(max_length=10)),
('nationality', models.CharField(max_length=20)),
('marital_status', models.CharField(max_length=10)),
('correspondence_address', models.CharField(max_length=200)),
('permanent_address', models.CharField(max_length=200)),
('mobile', models.CharField(max_length=10)),
('areas_of_specialization', models.TextField(max_length=300)),
('phd_thesis_title', models.CharField(max_length=200)),
('date_of_acquiring_phd', models.DateField()),
],
),
]
|
flexible
|
{
"blob_id": "4acdde648b5ec32c078579e725e6ae035298f25a",
"index": 3997,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='Personal', fields=[(\n 'post_apply', models.CharField(max_length=150)), ('department',\n models.CharField(max_length=50)), ('application_no', models.\n BigAutoField(db_column='APPLICATION_NO', primary_key=True,\n serialize=False)), ('email', models.EmailField(max_length=254)), (\n 'category', models.CharField(max_length=30)), ('pwd_status', models\n .CharField(max_length=5)), ('internal_candidate', models.\n BooleanField()), ('profile_image', models.ImageField(upload_to='')),\n ('first_name', models.CharField(max_length=100)), ('middle_name',\n models.CharField(max_length=100)), ('last_name', models.CharField(\n max_length=100)), ('father_name', models.CharField(max_length=100)),\n ('dob', models.DateField()), ('age', models.IntegerField()), (\n 'aadhar_card', models.BigIntegerField()), ('gender', models.\n CharField(max_length=10)), ('nationality', models.CharField(\n max_length=20)), ('marital_status', models.CharField(max_length=10)\n ), ('correspondence_address', models.CharField(max_length=200)), (\n 'permanent_address', models.CharField(max_length=200)), ('mobile',\n models.CharField(max_length=10)), ('areas_of_specialization',\n models.TextField(max_length=300)), ('phd_thesis_title', models.\n CharField(max_length=200)), ('date_of_acquiring_phd', models.\n DateField())])]\n",
"step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='Personal', fields=[(\n 'post_apply', models.CharField(max_length=150)), ('department',\n models.CharField(max_length=50)), ('application_no', models.\n BigAutoField(db_column='APPLICATION_NO', primary_key=True,\n serialize=False)), ('email', models.EmailField(max_length=254)), (\n 'category', models.CharField(max_length=30)), ('pwd_status', models\n .CharField(max_length=5)), ('internal_candidate', models.\n BooleanField()), ('profile_image', models.ImageField(upload_to='')),\n ('first_name', models.CharField(max_length=100)), ('middle_name',\n models.CharField(max_length=100)), ('last_name', models.CharField(\n max_length=100)), ('father_name', models.CharField(max_length=100)),\n ('dob', models.DateField()), ('age', models.IntegerField()), (\n 'aadhar_card', models.BigIntegerField()), ('gender', models.\n CharField(max_length=10)), ('nationality', models.CharField(\n max_length=20)), ('marital_status', models.CharField(max_length=10)\n ), ('correspondence_address', models.CharField(max_length=200)), (\n 'permanent_address', models.CharField(max_length=200)), ('mobile',\n models.CharField(max_length=10)), ('areas_of_specialization',\n models.TextField(max_length=300)), ('phd_thesis_title', models.\n CharField(max_length=200)), ('date_of_acquiring_phd', models.\n DateField())])]\n",
"step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.9 on 2018-01-15 17:27\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Personal',\n fields=[\n ('post_apply', models.CharField(max_length=150)),\n ('department', models.CharField(max_length=50)),\n ('application_no', models.BigAutoField(db_column='APPLICATION_NO', primary_key=True, serialize=False)),\n ('email', models.EmailField(max_length=254)),\n ('category', models.CharField(max_length=30)),\n ('pwd_status', models.CharField(max_length=5)),\n ('internal_candidate', models.BooleanField()),\n ('profile_image', models.ImageField(upload_to='')),\n ('first_name', models.CharField(max_length=100)),\n ('middle_name', models.CharField(max_length=100)),\n ('last_name', models.CharField(max_length=100)),\n ('father_name', models.CharField(max_length=100)),\n ('dob', models.DateField()),\n ('age', models.IntegerField()),\n ('aadhar_card', models.BigIntegerField()),\n ('gender', models.CharField(max_length=10)),\n ('nationality', models.CharField(max_length=20)),\n ('marital_status', models.CharField(max_length=10)),\n ('correspondence_address', models.CharField(max_length=200)),\n ('permanent_address', models.CharField(max_length=200)),\n ('mobile', models.CharField(max_length=10)),\n ('areas_of_specialization', models.TextField(max_length=300)),\n ('phd_thesis_title', models.CharField(max_length=200)),\n ('date_of_acquiring_phd', models.DateField()),\n ],\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# SPDX-FileCopyrightText: 2019-2021 Python201 Contributors
# SPDX-License-Identifier: MIT
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
import datetime
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
year = datetime.datetime.now().year
project = 'python201'
copyright = f'2019-{year} Geoffrey Lentner, 2018 Ashwin Srinath'
author = 'Geoffrey Lentner, Ashwin Srinath'
version = '0.0.1'
release = '0.0.1'
# -- General configuration ---------------------------------------------------
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.mathjax',
'sphinx.ext.githubpages',
'sphinx.ext.autodoc',
'IPython.sphinxext.ipython_directive',
'IPython.sphinxext.ipython_console_highlighting',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output -------------------------------------------------
html_theme = 'pydata_sphinx_theme'
html_logo = '_static/logo.png'
html_favicon = '_static/favicon.ico'
html_static_path = ['']
html_theme_options = {
'external_links': [],
'github_url': 'https://github.com/glentner/python201',
}
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {}
latex_documents = [
(master_doc, 'python-201.tex', 'python-201 Documentation',
'Geoffrey Lentner, Ashwin Srinath', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# manual pages options
man_pages = [(
'manpage',
'cumprod',
'Compute cumulative product of a sequence of numbers.',
'Geoffrey Lentner <glentner@purdue.edu>.',
'1'
),
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'python-201', 'python-201 Documentation',
author, 'python-201', 'One line description of project.',
'Miscellaneous'),
]
# -- Extension configuration -------------------------------------------------
intersphinx_mapping = {'https://docs.python.org/3/': None}
# export variables with epilogue
rst_epilog = f"""
.. |release| replace:: {release}
.. |copyright| replace:: {copyright}
"""
|
normal
|
{
"blob_id": "1ead23c6ea4e66b24e60598ae20606e24fa41482",
"index": 1024,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nyear = datetime.datetime.now().year\nproject = 'python201'\ncopyright = f'2019-{year} Geoffrey Lentner, 2018 Ashwin Srinath'\nauthor = 'Geoffrey Lentner, Ashwin Srinath'\nversion = '0.0.1'\nrelease = '0.0.1'\nextensions = ['sphinx.ext.intersphinx', 'sphinx.ext.mathjax',\n 'sphinx.ext.githubpages', 'sphinx.ext.autodoc',\n 'IPython.sphinxext.ipython_directive',\n 'IPython.sphinxext.ipython_console_highlighting']\ntemplates_path = ['_templates']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nlanguage = None\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\npygments_style = 'sphinx'\nhtml_theme = 'pydata_sphinx_theme'\nhtml_logo = '_static/logo.png'\nhtml_favicon = '_static/favicon.ico'\nhtml_static_path = ['']\nhtml_theme_options = {'external_links': [], 'github_url':\n 'https://github.com/glentner/python201'}\nlatex_elements = {}\nlatex_documents = [(master_doc, 'python-201.tex',\n 'python-201 Documentation', 'Geoffrey Lentner, Ashwin Srinath', 'manual')]\nman_pages = [('manpage', 'cumprod',\n 'Compute cumulative product of a sequence of numbers.',\n 'Geoffrey Lentner <glentner@purdue.edu>.', '1')]\ntexinfo_documents = [(master_doc, 'python-201', 'python-201 Documentation',\n author, 'python-201', 'One line description of project.', 'Miscellaneous')]\nintersphinx_mapping = {'https://docs.python.org/3/': None}\nrst_epilog = f\"\"\"\n.. |release| replace:: {release}\n.. |copyright| replace:: {copyright}\n\"\"\"\n",
"step-3": "import datetime\nyear = datetime.datetime.now().year\nproject = 'python201'\ncopyright = f'2019-{year} Geoffrey Lentner, 2018 Ashwin Srinath'\nauthor = 'Geoffrey Lentner, Ashwin Srinath'\nversion = '0.0.1'\nrelease = '0.0.1'\nextensions = ['sphinx.ext.intersphinx', 'sphinx.ext.mathjax',\n 'sphinx.ext.githubpages', 'sphinx.ext.autodoc',\n 'IPython.sphinxext.ipython_directive',\n 'IPython.sphinxext.ipython_console_highlighting']\ntemplates_path = ['_templates']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nlanguage = None\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\npygments_style = 'sphinx'\nhtml_theme = 'pydata_sphinx_theme'\nhtml_logo = '_static/logo.png'\nhtml_favicon = '_static/favicon.ico'\nhtml_static_path = ['']\nhtml_theme_options = {'external_links': [], 'github_url':\n 'https://github.com/glentner/python201'}\nlatex_elements = {}\nlatex_documents = [(master_doc, 'python-201.tex',\n 'python-201 Documentation', 'Geoffrey Lentner, Ashwin Srinath', 'manual')]\nman_pages = [('manpage', 'cumprod',\n 'Compute cumulative product of a sequence of numbers.',\n 'Geoffrey Lentner <glentner@purdue.edu>.', '1')]\ntexinfo_documents = [(master_doc, 'python-201', 'python-201 Documentation',\n author, 'python-201', 'One line description of project.', 'Miscellaneous')]\nintersphinx_mapping = {'https://docs.python.org/3/': None}\nrst_epilog = f\"\"\"\n.. |release| replace:: {release}\n.. |copyright| replace:: {copyright}\n\"\"\"\n",
"step-4": "# SPDX-FileCopyrightText: 2019-2021 Python201 Contributors\n# SPDX-License-Identifier: MIT\n#\n# Configuration file for the Sphinx documentation builder.\n#\n# This file does only contain a selection of the most common options. For a\n# full list see the documentation:\n# http://www.sphinx-doc.org/en/master/config\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\nimport datetime\n# sys.path.insert(0, os.path.abspath('.'))\n\n\n# -- Project information -----------------------------------------------------\n\nyear = datetime.datetime.now().year\nproject = 'python201'\ncopyright = f'2019-{year} Geoffrey Lentner, 2018 Ashwin Srinath'\nauthor = 'Geoffrey Lentner, Ashwin Srinath'\n\nversion = '0.0.1'\nrelease = '0.0.1'\n\n\n# -- General configuration ---------------------------------------------------\n\nextensions = [\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.githubpages',\n 'sphinx.ext.autodoc',\n 'IPython.sphinxext.ipython_directive',\n 'IPython.sphinxext.ipython_console_highlighting',\n]\n\ntemplates_path = ['_templates']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nlanguage = None\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path .\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n\n# -- Options for HTML output -------------------------------------------------\n\nhtml_theme = 'pydata_sphinx_theme'\nhtml_logo = '_static/logo.png'\nhtml_favicon = '_static/favicon.ico'\nhtml_static_path = ['']\nhtml_theme_options = {\n 'external_links': [],\n 'github_url': 'https://github.com/glentner/python201',\n}\n\n\n# -- Options for LaTeX output ------------------------------------------------\n\nlatex_elements = {}\nlatex_documents = [\n (master_doc, 'python-201.tex', 'python-201 Documentation',\n 'Geoffrey Lentner, Ashwin Srinath', 'manual'),\n]\n\n\n# -- Options for manual page output ------------------------------------------\n\n# manual pages options\nman_pages = [(\n 'manpage',\n 'cumprod',\n 'Compute cumulative product of a sequence of numbers.',\n 'Geoffrey Lentner <glentner@purdue.edu>.',\n '1'\n),\n]\n\n\n# -- Options for Texinfo output ----------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'python-201', 'python-201 Documentation',\n author, 'python-201', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n\n# -- Extension configuration -------------------------------------------------\nintersphinx_mapping = {'https://docs.python.org/3/': None}\n\n# export variables with epilogue\nrst_epilog = f\"\"\"\n.. |release| replace:: {release}\n.. |copyright| replace:: {copyright}\n\"\"\"\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from nltk.tokenize import sent_tokenize
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
import networkx as nx
def summarize(text):
sentences_token = sent_tokenize(text)
#Feature Extraction
vectorizer = CountVectorizer(min_df=1,decode_error='replace')
sent_bow = vectorizer.fit_transform(sentences_token)
transformer = TfidfTransformer(norm='l2', smooth_idf=True, use_idf=True)
sent_tfidf = transformer.fit_transform(sent_bow)
similarity_graph = sent_tfidf * sent_tfidf.T
nx_graph = nx.from_scipy_sparse_matrix(similarity_graph)
scores = nx.pagerank(nx_graph)
text_rank_graph = sorted(((scores[i],s) for i,s in enumerate(sentences_token)), reverse=True)
number_of_sents = int(0.4*len(text_rank_graph))
del text_rank_graph[number_of_sents:]
summary = ' '.join(word for _,word in text_rank_graph)
return summary
|
normal
|
{
"blob_id": "b75ebcd278ae92274bbbe8d1ce5cb3bb7fa14a2c",
"index": 9637,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef summarize(text):\n sentences_token = sent_tokenize(text)\n vectorizer = CountVectorizer(min_df=1, decode_error='replace')\n sent_bow = vectorizer.fit_transform(sentences_token)\n transformer = TfidfTransformer(norm='l2', smooth_idf=True, use_idf=True)\n sent_tfidf = transformer.fit_transform(sent_bow)\n similarity_graph = sent_tfidf * sent_tfidf.T\n nx_graph = nx.from_scipy_sparse_matrix(similarity_graph)\n scores = nx.pagerank(nx_graph)\n text_rank_graph = sorted(((scores[i], s) for i, s in enumerate(\n sentences_token)), reverse=True)\n number_of_sents = int(0.4 * len(text_rank_graph))\n del text_rank_graph[number_of_sents:]\n summary = ' '.join(word for _, word in text_rank_graph)\n return summary\n",
"step-3": "from nltk.tokenize import sent_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nimport networkx as nx\n\n\ndef summarize(text):\n sentences_token = sent_tokenize(text)\n vectorizer = CountVectorizer(min_df=1, decode_error='replace')\n sent_bow = vectorizer.fit_transform(sentences_token)\n transformer = TfidfTransformer(norm='l2', smooth_idf=True, use_idf=True)\n sent_tfidf = transformer.fit_transform(sent_bow)\n similarity_graph = sent_tfidf * sent_tfidf.T\n nx_graph = nx.from_scipy_sparse_matrix(similarity_graph)\n scores = nx.pagerank(nx_graph)\n text_rank_graph = sorted(((scores[i], s) for i, s in enumerate(\n sentences_token)), reverse=True)\n number_of_sents = int(0.4 * len(text_rank_graph))\n del text_rank_graph[number_of_sents:]\n summary = ' '.join(word for _, word in text_rank_graph)\n return summary\n",
"step-4": "from nltk.tokenize import sent_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nimport networkx as nx\n\ndef summarize(text):\n \n sentences_token = sent_tokenize(text)\n \n #Feature Extraction\n vectorizer = CountVectorizer(min_df=1,decode_error='replace')\n sent_bow = vectorizer.fit_transform(sentences_token)\n transformer = TfidfTransformer(norm='l2', smooth_idf=True, use_idf=True)\n sent_tfidf = transformer.fit_transform(sent_bow)\n \n similarity_graph = sent_tfidf * sent_tfidf.T\n \n nx_graph = nx.from_scipy_sparse_matrix(similarity_graph)\n scores = nx.pagerank(nx_graph)\n text_rank_graph = sorted(((scores[i],s) for i,s in enumerate(sentences_token)), reverse=True)\n number_of_sents = int(0.4*len(text_rank_graph))\n del text_rank_graph[number_of_sents:]\n summary = ' '.join(word for _,word in text_rank_graph)\n \n return summary\n \n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
@pytest.mark.slow
def test_x_noise_reg():
x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),
scale_diag=abs(x_train))
y_train = noise.sample().numpy()
too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,
16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)
too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)
x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),
scale_diag=abs(x_test))
y_test = noise.sample().numpy()
out1 = too_much_noise.pdf(x_test, y_test).numpy()
out2 = too_much_noise.pdf(x_test, y_test).numpy()
assert all(out1 == out2)
little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,
16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)
little_noise.fit(x_train, y_train, epochs=700, verbose=0)
little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)
) / 700.0
too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)
) / 700.0
assert little_noise_score > too_much_noise_score
def test_y_noise_reg():
x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(
(10, 3))
y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(
(10, 3))
noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),
trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))
noise.fit(x_train, y_train, epochs=10, verbose=0)
input_model = noise._get_input_model()
y1 = input_model(y_train, training=False).numpy()
y2 = input_model(y_train, training=False).numpy()
assert np.all(y1 == y2)
y1 = input_model(y_train, training=True).numpy()
y2 = input_model(y_train, training=True).numpy()
assert not np.all(y1 == y2)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
tf.random.set_seed(22)
np.random.seed(22)
@pytest.mark.slow
def test_x_noise_reg():
x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),
scale_diag=abs(x_train))
y_train = noise.sample().numpy()
too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,
16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)
too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)
x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),
scale_diag=abs(x_test))
y_test = noise.sample().numpy()
out1 = too_much_noise.pdf(x_test, y_test).numpy()
out2 = too_much_noise.pdf(x_test, y_test).numpy()
assert all(out1 == out2)
little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,
16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)
little_noise.fit(x_train, y_train, epochs=700, verbose=0)
little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)
) / 700.0
too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)
) / 700.0
assert little_noise_score > too_much_noise_score
def test_y_noise_reg():
x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(
(10, 3))
y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(
(10, 3))
noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),
trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))
noise.fit(x_train, y_train, epochs=10, verbose=0)
input_model = noise._get_input_model()
y1 = input_model(y_train, training=False).numpy()
y2 = input_model(y_train, training=False).numpy()
assert np.all(y1 == y2)
y1 = input_model(y_train, training=True).numpy()
y2 = input_model(y_train, training=True).numpy()
assert not np.all(y1 == y2)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
tfd = tfp.distributions
tf.random.set_seed(22)
np.random.seed(22)
@pytest.mark.slow
def test_x_noise_reg():
x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),
scale_diag=abs(x_train))
y_train = noise.sample().numpy()
too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,
16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)
too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)
x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),
scale_diag=abs(x_test))
y_test = noise.sample().numpy()
out1 = too_much_noise.pdf(x_test, y_test).numpy()
out2 = too_much_noise.pdf(x_test, y_test).numpy()
assert all(out1 == out2)
little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,
16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)
little_noise.fit(x_train, y_train, epochs=700, verbose=0)
little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)
) / 700.0
too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)
) / 700.0
assert little_noise_score > too_much_noise_score
def test_y_noise_reg():
x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(
(10, 3))
y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(
(10, 3))
noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),
trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))
noise.fit(x_train, y_train, epochs=10, verbose=0)
input_model = noise._get_input_model()
y1 = input_model(y_train, training=False).numpy()
y2 = input_model(y_train, training=False).numpy()
assert np.all(y1 == y2)
y1 = input_model(y_train, training=True).numpy()
y2 = input_model(y_train, training=True).numpy()
assert not np.all(y1 == y2)
<|reserved_special_token_1|>
import tensorflow as tf
import tensorflow_probability as tfp
import pytest
import numpy as np
from estimators import NormalizingFlowNetwork
tfd = tfp.distributions
tf.random.set_seed(22)
np.random.seed(22)
@pytest.mark.slow
def test_x_noise_reg():
x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),
scale_diag=abs(x_train))
y_train = noise.sample().numpy()
too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,
16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)
too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)
x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),
scale_diag=abs(x_test))
y_test = noise.sample().numpy()
out1 = too_much_noise.pdf(x_test, y_test).numpy()
out2 = too_much_noise.pdf(x_test, y_test).numpy()
assert all(out1 == out2)
little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,
16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)
little_noise.fit(x_train, y_train, epochs=700, verbose=0)
little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)
) / 700.0
too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)
) / 700.0
assert little_noise_score > too_much_noise_score
def test_y_noise_reg():
x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(
(10, 3))
y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(
(10, 3))
noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),
trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))
noise.fit(x_train, y_train, epochs=10, verbose=0)
input_model = noise._get_input_model()
y1 = input_model(y_train, training=False).numpy()
y2 = input_model(y_train, training=False).numpy()
assert np.all(y1 == y2)
y1 = input_model(y_train, training=True).numpy()
y2 = input_model(y_train, training=True).numpy()
assert not np.all(y1 == y2)
<|reserved_special_token_1|>
import tensorflow as tf
import tensorflow_probability as tfp
import pytest
import numpy as np
from estimators import NormalizingFlowNetwork
tfd = tfp.distributions
tf.random.set_seed(22)
np.random.seed(22)
@pytest.mark.slow
def test_x_noise_reg():
x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train), scale_diag=abs(x_train))
y_train = noise.sample().numpy()
too_much_noise = NormalizingFlowNetwork(
1,
n_flows=2,
hidden_sizes=(16, 16),
noise_reg=("fixed_rate", 3.0),
trainable_base_dist=True,
)
too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)
x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))
noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test), scale_diag=abs(x_test))
y_test = noise.sample().numpy()
out1 = too_much_noise.pdf(x_test, y_test).numpy()
out2 = too_much_noise.pdf(x_test, y_test).numpy()
# making sure that the noise regularisation is deactivated in testing mode
assert all(out1 == out2)
little_noise = NormalizingFlowNetwork(
1,
n_flows=2,
hidden_sizes=(16, 16),
noise_reg=("rule_of_thumb", 0.1),
trainable_base_dist=True,
)
little_noise.fit(x_train, y_train, epochs=700, verbose=0)
little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)) / 700.0
too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)) / 700.0
assert little_noise_score > too_much_noise_score
def test_y_noise_reg():
x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape((10, 3))
y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape((10, 3))
noise = NormalizingFlowNetwork(
3,
n_flows=3,
hidden_sizes=(16, 16),
trainable_base_dist=True,
noise_reg=("fixed_rate", 1.0),
)
noise.fit(x_train, y_train, epochs=10, verbose=0)
input_model = noise._get_input_model()
# y_input should not include randomness during evaluation
y1 = input_model(y_train, training=False).numpy()
y2 = input_model(y_train, training=False).numpy()
assert np.all(y1 == y2)
# loss should include randomness during learning
y1 = input_model(y_train, training=True).numpy()
y2 = input_model(y_train, training=True).numpy()
assert not np.all(y1 == y2)
|
flexible
|
{
"blob_id": "303a8609cb21c60a416160264c3d3da805674920",
"index": 777,
"step-1": "<mask token>\n\n\n@pytest.mark.slow\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),\n trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n input_model = noise._get_input_model()\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n",
"step-2": "<mask token>\ntf.random.set_seed(22)\nnp.random.seed(22)\n\n\n@pytest.mark.slow\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),\n trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n input_model = noise._get_input_model()\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n",
"step-3": "<mask token>\ntfd = tfp.distributions\ntf.random.set_seed(22)\nnp.random.seed(22)\n\n\n@pytest.mark.slow\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),\n trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n input_model = noise._get_input_model()\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n",
"step-4": "import tensorflow as tf\nimport tensorflow_probability as tfp\nimport pytest\nimport numpy as np\nfrom estimators import NormalizingFlowNetwork\ntfd = tfp.distributions\ntf.random.set_seed(22)\nnp.random.seed(22)\n\n\n@pytest.mark.slow\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),\n trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n input_model = noise._get_input_model()\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n",
"step-5": "import tensorflow as tf\nimport tensorflow_probability as tfp\nimport pytest\nimport numpy as np\nfrom estimators import NormalizingFlowNetwork\n\ntfd = tfp.distributions\ntf.random.set_seed(22)\nnp.random.seed(22)\n\n\n@pytest.mark.slow\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train), scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n\n too_much_noise = NormalizingFlowNetwork(\n 1,\n n_flows=2,\n hidden_sizes=(16, 16),\n noise_reg=(\"fixed_rate\", 3.0),\n trainable_base_dist=True,\n )\n\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test), scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n # making sure that the noise regularisation is deactivated in testing mode\n assert all(out1 == out2)\n\n little_noise = NormalizingFlowNetwork(\n 1,\n n_flows=2,\n hidden_sizes=(16, 16),\n noise_reg=(\"rule_of_thumb\", 0.1),\n trainable_base_dist=True,\n )\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape((10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape((10, 3))\n\n noise = NormalizingFlowNetwork(\n 3,\n n_flows=3,\n hidden_sizes=(16, 16),\n trainable_base_dist=True,\n noise_reg=(\"fixed_rate\", 1.0),\n )\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n\n input_model = noise._get_input_model()\n # y_input should not include randomness during evaluation\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n\n # loss should include randomness during learning\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
class SequenceHeuristic(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class SequenceHeuristic(object):
def __init__(self, minChanges, minDuration, noMotionDelay):
self._minChanges = minChanges
self._minDuration = minDuration
self._noMotionDelay = noMotionDelay
self._duration = 0
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class SequenceHeuristic(object):
def __init__(self, minChanges, minDuration, noMotionDelay):
self._minChanges = minChanges
self._minDuration = minDuration
self._noMotionDelay = noMotionDelay
self._duration = 0
def isValid(self, image, data):
numOfChanges = data['numOfChanges']
if numOfChanges >= self._minChanges:
self._duration += 1
if self._duration >= self._minDuration:
return True
elif self._duration > 0:
self._duration -= 1
elif self._noMotionDelay:
time.sleep(self._noMotionDelay / 1000.0)
return False
<|reserved_special_token_1|>
import time
class SequenceHeuristic(object):
def __init__(self, minChanges, minDuration, noMotionDelay):
self._minChanges = minChanges
self._minDuration = minDuration
self._noMotionDelay = noMotionDelay
self._duration = 0
def isValid(self, image, data):
numOfChanges = data['numOfChanges']
if numOfChanges >= self._minChanges:
self._duration += 1
if self._duration >= self._minDuration:
return True
elif self._duration > 0:
self._duration -= 1
elif self._noMotionDelay:
time.sleep(self._noMotionDelay / 1000.0)
return False
<|reserved_special_token_1|>
import time
class SequenceHeuristic(object):
def __init__(self, minChanges, minDuration, noMotionDelay):
self._minChanges = minChanges
self._minDuration = minDuration
self._noMotionDelay = noMotionDelay
self._duration = 0
def isValid(self, image, data):
numOfChanges = data['numOfChanges']
if numOfChanges >= self._minChanges:
self._duration += 1
if self._duration >= self._minDuration:
return True
else:
if self._duration > 0: # No sleep if duration is in effect
self._duration -= 1
else:
if self._noMotionDelay:
time.sleep(self._noMotionDelay/1000.0)
return False
|
flexible
|
{
"blob_id": "e07bd4cd13209bff8bc1119a619a2954abd52592",
"index": 1515,
"step-1": "<mask token>\n\n\nclass SequenceHeuristic(object):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass SequenceHeuristic(object):\n\n def __init__(self, minChanges, minDuration, noMotionDelay):\n self._minChanges = minChanges\n self._minDuration = minDuration\n self._noMotionDelay = noMotionDelay\n self._duration = 0\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass SequenceHeuristic(object):\n\n def __init__(self, minChanges, minDuration, noMotionDelay):\n self._minChanges = minChanges\n self._minDuration = minDuration\n self._noMotionDelay = noMotionDelay\n self._duration = 0\n\n def isValid(self, image, data):\n numOfChanges = data['numOfChanges']\n if numOfChanges >= self._minChanges:\n self._duration += 1\n if self._duration >= self._minDuration:\n return True\n elif self._duration > 0:\n self._duration -= 1\n elif self._noMotionDelay:\n time.sleep(self._noMotionDelay / 1000.0)\n return False\n",
"step-4": "import time\n\n\nclass SequenceHeuristic(object):\n\n def __init__(self, minChanges, minDuration, noMotionDelay):\n self._minChanges = minChanges\n self._minDuration = minDuration\n self._noMotionDelay = noMotionDelay\n self._duration = 0\n\n def isValid(self, image, data):\n numOfChanges = data['numOfChanges']\n if numOfChanges >= self._minChanges:\n self._duration += 1\n if self._duration >= self._minDuration:\n return True\n elif self._duration > 0:\n self._duration -= 1\n elif self._noMotionDelay:\n time.sleep(self._noMotionDelay / 1000.0)\n return False\n",
"step-5": "import time\n\nclass SequenceHeuristic(object):\n def __init__(self, minChanges, minDuration, noMotionDelay):\n self._minChanges = minChanges\n self._minDuration = minDuration\n self._noMotionDelay = noMotionDelay\n self._duration = 0\n \n def isValid(self, image, data):\n numOfChanges = data['numOfChanges']\n if numOfChanges >= self._minChanges:\n self._duration += 1\n if self._duration >= self._minDuration:\n return True\n else:\n if self._duration > 0: # No sleep if duration is in effect\n self._duration -= 1\n else:\n if self._noMotionDelay:\n time.sleep(self._noMotionDelay/1000.0)\n return False\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
# Generated by Django 3.2.7 on 2021-09-23 07:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sms_consumer', '0006_auto_20210923_0733'),
]
operations = [
migrations.RemoveField(
model_name='smslogmodel',
name='hello',
),
]
|
normal
|
{
"blob_id": "fc9742ceb3c38a5f8c1ad1f030d76103ba0a7a81",
"index": 3857,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('sms_consumer', '0006_auto_20210923_0733')]\n operations = [migrations.RemoveField(model_name='smslogmodel', name=\n 'hello')]\n",
"step-4": "from django.db import migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [('sms_consumer', '0006_auto_20210923_0733')]\n operations = [migrations.RemoveField(model_name='smslogmodel', name=\n 'hello')]\n",
"step-5": "# Generated by Django 3.2.7 on 2021-09-23 07:33\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sms_consumer', '0006_auto_20210923_0733'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='smslogmodel',\n name='hello',\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
with open('testfile_short1.csv', 'r') as original:
data = original.read()
for i in range(2):
with open('testfile_short3.csv', 'a') as modified:
modified.write(data)
<|reserved_special_token_1|>
import pandas as pd
from sqlalchemy import create_engine
with open('testfile_short1.csv', 'r') as original:
data = original.read()
for i in range(2):
with open('testfile_short3.csv', 'a') as modified:
modified.write(data)
<|reserved_special_token_1|>
import pandas as pd
from sqlalchemy import create_engine
# file = 'testfile.csv'
# print(pd.read_csv(file, nrows=5))
with open('testfile_short1.csv', 'r') as original: data = original.read()
for i in range(2):
with open('testfile_short3.csv', 'a') as modified: modified.write(data)
|
flexible
|
{
"blob_id": "d7b45e76f150107cd62be160e8938f17dad90623",
"index": 58,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('testfile_short1.csv', 'r') as original:\n data = original.read()\nfor i in range(2):\n with open('testfile_short3.csv', 'a') as modified:\n modified.write(data)\n",
"step-3": "import pandas as pd\nfrom sqlalchemy import create_engine\nwith open('testfile_short1.csv', 'r') as original:\n data = original.read()\nfor i in range(2):\n with open('testfile_short3.csv', 'a') as modified:\n modified.write(data)\n",
"step-4": "import pandas as pd\nfrom sqlalchemy import create_engine\n# file = 'testfile.csv'\n\n# print(pd.read_csv(file, nrows=5))\n\nwith open('testfile_short1.csv', 'r') as original: data = original.read()\nfor i in range(2):\n with open('testfile_short3.csv', 'a') as modified: modified.write(data)",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def getdata(url):
data = requests.get(url)
return data.text
def get_json():
file_path = staticfiles_storage.path('coordinates.json')
with open(file_path, 'r') as f:
data = json.load(f)
html_doc = getdata('https://www.mygov.in/covid-19')
soup = BeautifulSoup(html_doc, 'html.parser')
k = soup.tbody.get_text()
k = ('\n' + k).split('\n\n')[1:-1]
datarow = {}
for index, item in enumerate(k):
value = item.split('\n')
datarow[value[1].lower()] = {'coordinates': list(data.values())[
index], 'confirmed': value[2], 'active': value[3], 'recovered':
value[4], 'deceased': value[5]}
return datarow
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def getdata(url):
data = requests.get(url)
return data.text
def get_json():
file_path = staticfiles_storage.path('coordinates.json')
with open(file_path, 'r') as f:
data = json.load(f)
html_doc = getdata('https://www.mygov.in/covid-19')
soup = BeautifulSoup(html_doc, 'html.parser')
k = soup.tbody.get_text()
k = ('\n' + k).split('\n\n')[1:-1]
datarow = {}
for index, item in enumerate(k):
value = item.split('\n')
datarow[value[1].lower()] = {'coordinates': list(data.values())[
index], 'confirmed': value[2], 'active': value[3], 'recovered':
value[4], 'deceased': value[5]}
return datarow
<|reserved_special_token_0|>
@api_view(['GET'])
def coordinates(request):
url = (
'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'
)
resp = requests.get(url)
data = json.loads(resp.text)
return Response(data, status=status.HTTP_200_OK)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def getdata(url):
data = requests.get(url)
return data.text
def get_json():
file_path = staticfiles_storage.path('coordinates.json')
with open(file_path, 'r') as f:
data = json.load(f)
html_doc = getdata('https://www.mygov.in/covid-19')
soup = BeautifulSoup(html_doc, 'html.parser')
k = soup.tbody.get_text()
k = ('\n' + k).split('\n\n')[1:-1]
datarow = {}
for index, item in enumerate(k):
value = item.split('\n')
datarow[value[1].lower()] = {'coordinates': list(data.values())[
index], 'confirmed': value[2], 'active': value[3], 'recovered':
value[4], 'deceased': value[5]}
return datarow
@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def get_map_josn(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
data = get_json()
print('Responsed')
return Response(data, status=status.HTTP_200_OK)
@api_view(['GET'])
def coordinates(request):
url = (
'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'
)
resp = requests.get(url)
data = json.loads(resp.text)
return Response(data, status=status.HTTP_200_OK)
<|reserved_special_token_1|>
from django.shortcuts import render
import requests
from bs4 import BeautifulSoup
import json
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework import status
from django.contrib.staticfiles.storage import staticfiles_storage
from user.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
def getdata(url):
data = requests.get(url)
return data.text
def get_json():
file_path = staticfiles_storage.path('coordinates.json')
with open(file_path, 'r') as f:
data = json.load(f)
html_doc = getdata('https://www.mygov.in/covid-19')
soup = BeautifulSoup(html_doc, 'html.parser')
k = soup.tbody.get_text()
k = ('\n' + k).split('\n\n')[1:-1]
datarow = {}
for index, item in enumerate(k):
value = item.split('\n')
datarow[value[1].lower()] = {'coordinates': list(data.values())[
index], 'confirmed': value[2], 'active': value[3], 'recovered':
value[4], 'deceased': value[5]}
return datarow
@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def get_map_josn(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
data = get_json()
print('Responsed')
return Response(data, status=status.HTTP_200_OK)
@api_view(['GET'])
def coordinates(request):
url = (
'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'
)
resp = requests.get(url)
data = json.loads(resp.text)
return Response(data, status=status.HTTP_200_OK)
<|reserved_special_token_1|>
from django.shortcuts import render
import requests
from bs4 import BeautifulSoup
import json
from rest_framework.response import Response
from rest_framework.decorators import api_view,authentication_classes,permission_classes
from rest_framework import status
from django.contrib.staticfiles.storage import staticfiles_storage
from user.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
# Create your views here.
def getdata(url):
data = requests.get(url)
return data.text
def get_json():
file_path = staticfiles_storage.path('coordinates.json')
with open(file_path,'r') as f:
data = json.load(f)
html_doc = getdata("https://www.mygov.in/covid-19")
soup = BeautifulSoup(html_doc, 'html.parser')
k = soup.tbody.get_text()
k = (("\n"+k).split("\n\n"))[1:-1]
datarow = {}
for index,item in enumerate(k):
value = item.split("\n")
datarow[value[1].lower()] = {
'coordinates':list(data.values())[index],
'confirmed':value[2],
'active':value[3],
'recovered':value[4],
'deceased':value[5]
}
return datarow
@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def get_map_josn(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
data = get_json()
print('Responsed')
return Response(data,status=status.HTTP_200_OK)
@api_view(['GET'])
def coordinates(request):
url = 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'
resp = requests.get(url)
data = json.loads(resp.text)
return Response(data,status=status.HTTP_200_OK)
|
flexible
|
{
"blob_id": "ed80f5f898548ca012779543051ccff5b34e4fcc",
"index": 730,
"step-1": "<mask token>\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path, 'r') as f:\n data = json.load(f)\n html_doc = getdata('https://www.mygov.in/covid-19')\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ('\\n' + k).split('\\n\\n')[1:-1]\n datarow = {}\n for index, item in enumerate(k):\n value = item.split('\\n')\n datarow[value[1].lower()] = {'coordinates': list(data.values())[\n index], 'confirmed': value[2], 'active': value[3], 'recovered':\n value[4], 'deceased': value[5]}\n return datarow\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path, 'r') as f:\n data = json.load(f)\n html_doc = getdata('https://www.mygov.in/covid-19')\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ('\\n' + k).split('\\n\\n')[1:-1]\n datarow = {}\n for index, item in enumerate(k):\n value = item.split('\\n')\n datarow[value[1].lower()] = {'coordinates': list(data.values())[\n index], 'confirmed': value[2], 'active': value[3], 'recovered':\n value[4], 'deceased': value[5]}\n return datarow\n\n\n<mask token>\n\n\n@api_view(['GET'])\ndef coordinates(request):\n url = (\n 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n )\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data, status=status.HTTP_200_OK)\n",
"step-3": "<mask token>\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path, 'r') as f:\n data = json.load(f)\n html_doc = getdata('https://www.mygov.in/covid-19')\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ('\\n' + k).split('\\n\\n')[1:-1]\n datarow = {}\n for index, item in enumerate(k):\n value = item.split('\\n')\n datarow[value[1].lower()] = {'coordinates': list(data.values())[\n index], 'confirmed': value[2], 'active': value[3], 'recovered':\n value[4], 'deceased': value[5]}\n return datarow\n\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef get_map_josn(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n data = get_json()\n print('Responsed')\n return Response(data, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef coordinates(request):\n url = (\n 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n )\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data, status=status.HTTP_200_OK)\n",
"step-4": "from django.shortcuts import render\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes\nfrom rest_framework import status\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom user.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path, 'r') as f:\n data = json.load(f)\n html_doc = getdata('https://www.mygov.in/covid-19')\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ('\\n' + k).split('\\n\\n')[1:-1]\n datarow = {}\n for index, item in enumerate(k):\n value = item.split('\\n')\n datarow[value[1].lower()] = {'coordinates': list(data.values())[\n index], 'confirmed': value[2], 'active': value[3], 'recovered':\n value[4], 'deceased': value[5]}\n return datarow\n\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef get_map_josn(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n data = get_json()\n print('Responsed')\n return Response(data, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef coordinates(request):\n url = (\n 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n )\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data, status=status.HTTP_200_OK)\n",
"step-5": "from django.shortcuts import render\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view,authentication_classes,permission_classes\nfrom rest_framework import status\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom user.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\n\n# Create your views here.\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path,'r') as f:\n data = json.load(f)\n\n html_doc = getdata(\"https://www.mygov.in/covid-19\")\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ((\"\\n\"+k).split(\"\\n\\n\"))[1:-1]\n\n datarow = {}\n for index,item in enumerate(k):\n value = item.split(\"\\n\")\n datarow[value[1].lower()] = {\n 'coordinates':list(data.values())[index],\n 'confirmed':value[2],\n 'active':value[3],\n 'recovered':value[4],\n 'deceased':value[5]\n }\n return datarow\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef get_map_josn(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n data = get_json()\n print('Responsed')\n return Response(data,status=status.HTTP_200_OK)\n\n@api_view(['GET'])\ndef coordinates(request):\n url = 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data,status=status.HTTP_200_OK)",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
class EVALUATOR(object):
def __init__(self, detector, data):
self.detector = detector
self.data = data
self.gt = self.data.gt
self.image_ids, self.bboxes, self.prob, self.annotations = (self.
prepare())
self.precision, self.recall = self.pr_curve()
def prepare(self):
image_ids, bboxes, prob = [], [], []
annotations = {}
for i in tqdm(range(self.data.num_batch), desc='batch forward'):
img_batch, bbox_batch = self.data.get_batch()
results = self.detector.detect_batch(img_batch)
for ii in range(len(results)):
boxes_filtered, probs_filtered = results[ii]
image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))
bboxes.extend(boxes_filtered)
prob.extend(probs_filtered)
if bbox_batch[ii]['id'] not in annotations:
annotations[bbox_batch[ii]['id']] = copy.deepcopy(
bbox_batch[ii]['bbox_det'])
sorted_ind = np.argsort(prob)[::-1]
sorted_prob = np.sort(prob)[::-1]
BB = np.array(bboxes)
BB = BB[sorted_ind, :]
image_ids = [image_ids[x] for x in sorted_ind]
return image_ids, BB, sorted_prob, annotations
def pr_curve(self):
nd = len(self.image_ids)
tp = np.zeros(nd)
fp = np.zeros(nd)
for d in tqdm(range(nd), desc='painting PR curve'):
R = self.annotations[self.image_ids[d]]
bb = self.bboxes[d, :].astype(float)
ovmax = -np.inf
BBGT = R['bboxes'].astype(float)
if BBGT.size > 0:
ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[
2] / 2)
iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[
3] / 2)
ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[
2] / 2)
iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[
3] / 2)
iw = np.maximum(ixmax - ixmin + 1.0, 0.0)
ih = np.maximum(iymax - iymin + 1.0, 0.0)
inters = iw * ih
uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters
overlaps = inters / uni
ovmax = np.max(overlaps)
jmax = np.argmax(overlaps)
if ovmax > cfg.IOU_THRESHOLD_GT:
if not R['det'][jmax]:
tp[d] = 1.0
R['det'][jmax] = 1
else:
fp[d] = 1.0
else:
fp[d] = 1.0
fp = np.cumsum(fp)
tp = np.cumsum(tp)
rec = tp / float(self.gt)
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
return prec, rec
def eval(self, use_07_metric=False):
""" ap = eval(rec, prec, [use_07_metric])
Compute AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
ap = 0.0
for t in np.arange(0.0, 1.1, 0.1):
if np.sum(self.recall >= t) == 0:
p = 0
else:
p = np.max(self.precision[self.recall >= t])
ap = ap + p / 11.0
else:
mrec = np.concatenate(([0.0], self.recall, [1.0]))
mpre = np.concatenate(([0.0], self.precision, [0.0]))
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
i = np.where(mrec[1:] != mrec[:-1])[0]
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class EVALUATOR(object):
def __init__(self, detector, data):
self.detector = detector
self.data = data
self.gt = self.data.gt
self.image_ids, self.bboxes, self.prob, self.annotations = (self.
prepare())
self.precision, self.recall = self.pr_curve()
def prepare(self):
image_ids, bboxes, prob = [], [], []
annotations = {}
for i in tqdm(range(self.data.num_batch), desc='batch forward'):
img_batch, bbox_batch = self.data.get_batch()
results = self.detector.detect_batch(img_batch)
for ii in range(len(results)):
boxes_filtered, probs_filtered = results[ii]
image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))
bboxes.extend(boxes_filtered)
prob.extend(probs_filtered)
if bbox_batch[ii]['id'] not in annotations:
annotations[bbox_batch[ii]['id']] = copy.deepcopy(
bbox_batch[ii]['bbox_det'])
sorted_ind = np.argsort(prob)[::-1]
sorted_prob = np.sort(prob)[::-1]
BB = np.array(bboxes)
BB = BB[sorted_ind, :]
image_ids = [image_ids[x] for x in sorted_ind]
return image_ids, BB, sorted_prob, annotations
def pr_curve(self):
nd = len(self.image_ids)
tp = np.zeros(nd)
fp = np.zeros(nd)
for d in tqdm(range(nd), desc='painting PR curve'):
R = self.annotations[self.image_ids[d]]
bb = self.bboxes[d, :].astype(float)
ovmax = -np.inf
BBGT = R['bboxes'].astype(float)
if BBGT.size > 0:
ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[
2] / 2)
iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[
3] / 2)
ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[
2] / 2)
iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[
3] / 2)
iw = np.maximum(ixmax - ixmin + 1.0, 0.0)
ih = np.maximum(iymax - iymin + 1.0, 0.0)
inters = iw * ih
uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters
overlaps = inters / uni
ovmax = np.max(overlaps)
jmax = np.argmax(overlaps)
if ovmax > cfg.IOU_THRESHOLD_GT:
if not R['det'][jmax]:
tp[d] = 1.0
R['det'][jmax] = 1
else:
fp[d] = 1.0
else:
fp[d] = 1.0
fp = np.cumsum(fp)
tp = np.cumsum(tp)
rec = tp / float(self.gt)
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
return prec, rec
def eval(self, use_07_metric=False):
""" ap = eval(rec, prec, [use_07_metric])
Compute AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
ap = 0.0
for t in np.arange(0.0, 1.1, 0.1):
if np.sum(self.recall >= t) == 0:
p = 0
else:
p = np.max(self.precision[self.recall >= t])
ap = ap + p / 11.0
else:
mrec = np.concatenate(([0.0], self.recall, [1.0]))
mpre = np.concatenate(([0.0], self.precision, [0.0]))
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
i = np.where(mrec[1:] != mrec[:-1])[0]
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-ims', '--image_size', default=512, type=int)
parser.add_argument('-g', '--gpu', type=str)
parser.add_argument('-c', '--cpu', action='store_true', help='use cpu')
parser.add_argument('-ds', '--data_source', default='all', type=str,
choices=['coco', 'pascal', 'all'])
parser.add_argument('-ef', '--eval_file', type=str, required=True)
parser.add_argument('-lf', '--log_file', type=str)
parser.add_argument('-al', '--auto_all', action='store_true')
parser.add_argument('--weights', default='hg_yolo-240000', type=str)
parser.add_argument('--weight_dir', default=
'../log_bbox_hm/0.8_0.08_0.03_conv_fc_l2_0.005_bhm5', type=str)
args = parser.parse_args()
if args.gpu:
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
if args.cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = ''
if not args.auto_all:
strings = get_config(args.weight_dir)
net = HOURGLASSYOLONet('eval')
detector = Detector(net, os.path.join(args.weight_dir, args.weights))
data = PASCAL_VAL()
evaluator = EVALUATOR(detector, data)
ap = evaluator.eval()
log = Logger(args.eval_file, level='debug')
log.logger.info('\n calculate single ap from {} {}\n'.format(args.
weight_dir, args.weights))
log.logger.info('Data sc:{} AP:{} Weights:{} {}'.format(data.
__class__.__name__, ap, args.weights, strings))
else:
data_source = ds_config(args)
log = Logger(args.eval_file, level='debug')
log.logger.info('\n calculate ap from {}\n'.format(args.eval_file))
model_start = 'hg_yolo'
rootdir = '../' + args.log_file
root_list = os.listdir(rootdir)
root_list.sort()
for path in root_list:
model_dir = os.path.join(rootdir, path)
models = os.listdir(model_dir)
models = filter(lambda x: x.startswith(model_start), models)
models = list(set(map(lambda x: x.split('.')[0], models)))
models.sort(key=lambda x: int(x[8:]))
for data in data_source:
for model in models:
strings = get_config(model_dir)
tf.reset_default_graph()
net = HOURGLASSYOLONet('eval')
detector = Detector(net, os.path.join(model_dir, model))
evaluator = EVALUATOR(detector, data)
ap = evaluator.eval()
log.logger.info('Data sc:{} AP:{:<5.5f} Weights:{} {}'
.format(data.__class__.__name__, ap, model, strings))
detector.sess.close()
del net
del detector
del evaluator
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
with context():
import argparse
import numpy as np
from model.hourglass_yolo_net_multi_gpu import HOURGLASSYOLONet
from evaluator.Eutils.pascal_val import PASCAL_VAL
from evaluator.Eutils.detector import Detector
import utils.config as cfg
from utils.logger import Logger
from utils.config_utils import get_config, ds_config
from tqdm import tqdm
import tensorflow as tf
import copy
import os
class EVALUATOR(object):
def __init__(self, detector, data):
self.detector = detector
self.data = data
self.gt = self.data.gt
self.image_ids, self.bboxes, self.prob, self.annotations = (self.
prepare())
self.precision, self.recall = self.pr_curve()
def prepare(self):
image_ids, bboxes, prob = [], [], []
annotations = {}
for i in tqdm(range(self.data.num_batch), desc='batch forward'):
img_batch, bbox_batch = self.data.get_batch()
results = self.detector.detect_batch(img_batch)
for ii in range(len(results)):
boxes_filtered, probs_filtered = results[ii]
image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))
bboxes.extend(boxes_filtered)
prob.extend(probs_filtered)
if bbox_batch[ii]['id'] not in annotations:
annotations[bbox_batch[ii]['id']] = copy.deepcopy(
bbox_batch[ii]['bbox_det'])
sorted_ind = np.argsort(prob)[::-1]
sorted_prob = np.sort(prob)[::-1]
BB = np.array(bboxes)
BB = BB[sorted_ind, :]
image_ids = [image_ids[x] for x in sorted_ind]
return image_ids, BB, sorted_prob, annotations
def pr_curve(self):
nd = len(self.image_ids)
tp = np.zeros(nd)
fp = np.zeros(nd)
for d in tqdm(range(nd), desc='painting PR curve'):
R = self.annotations[self.image_ids[d]]
bb = self.bboxes[d, :].astype(float)
ovmax = -np.inf
BBGT = R['bboxes'].astype(float)
if BBGT.size > 0:
ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[
2] / 2)
iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[
3] / 2)
ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[
2] / 2)
iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[
3] / 2)
iw = np.maximum(ixmax - ixmin + 1.0, 0.0)
ih = np.maximum(iymax - iymin + 1.0, 0.0)
inters = iw * ih
uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters
overlaps = inters / uni
ovmax = np.max(overlaps)
jmax = np.argmax(overlaps)
if ovmax > cfg.IOU_THRESHOLD_GT:
if not R['det'][jmax]:
tp[d] = 1.0
R['det'][jmax] = 1
else:
fp[d] = 1.0
else:
fp[d] = 1.0
fp = np.cumsum(fp)
tp = np.cumsum(tp)
rec = tp / float(self.gt)
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
return prec, rec
def eval(self, use_07_metric=False):
""" ap = eval(rec, prec, [use_07_metric])
Compute AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
ap = 0.0
for t in np.arange(0.0, 1.1, 0.1):
if np.sum(self.recall >= t) == 0:
p = 0
else:
p = np.max(self.precision[self.recall >= t])
ap = ap + p / 11.0
else:
mrec = np.concatenate(([0.0], self.recall, [1.0]))
mpre = np.concatenate(([0.0], self.precision, [0.0]))
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
i = np.where(mrec[1:] != mrec[:-1])[0]
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-ims', '--image_size', default=512, type=int)
parser.add_argument('-g', '--gpu', type=str)
parser.add_argument('-c', '--cpu', action='store_true', help='use cpu')
parser.add_argument('-ds', '--data_source', default='all', type=str,
choices=['coco', 'pascal', 'all'])
parser.add_argument('-ef', '--eval_file', type=str, required=True)
parser.add_argument('-lf', '--log_file', type=str)
parser.add_argument('-al', '--auto_all', action='store_true')
parser.add_argument('--weights', default='hg_yolo-240000', type=str)
parser.add_argument('--weight_dir', default=
'../log_bbox_hm/0.8_0.08_0.03_conv_fc_l2_0.005_bhm5', type=str)
args = parser.parse_args()
if args.gpu:
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
if args.cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = ''
if not args.auto_all:
strings = get_config(args.weight_dir)
net = HOURGLASSYOLONet('eval')
detector = Detector(net, os.path.join(args.weight_dir, args.weights))
data = PASCAL_VAL()
evaluator = EVALUATOR(detector, data)
ap = evaluator.eval()
log = Logger(args.eval_file, level='debug')
log.logger.info('\n calculate single ap from {} {}\n'.format(args.
weight_dir, args.weights))
log.logger.info('Data sc:{} AP:{} Weights:{} {}'.format(data.
__class__.__name__, ap, args.weights, strings))
else:
data_source = ds_config(args)
log = Logger(args.eval_file, level='debug')
log.logger.info('\n calculate ap from {}\n'.format(args.eval_file))
model_start = 'hg_yolo'
rootdir = '../' + args.log_file
root_list = os.listdir(rootdir)
root_list.sort()
for path in root_list:
model_dir = os.path.join(rootdir, path)
models = os.listdir(model_dir)
models = filter(lambda x: x.startswith(model_start), models)
models = list(set(map(lambda x: x.split('.')[0], models)))
models.sort(key=lambda x: int(x[8:]))
for data in data_source:
for model in models:
strings = get_config(model_dir)
tf.reset_default_graph()
net = HOURGLASSYOLONet('eval')
detector = Detector(net, os.path.join(model_dir, model))
evaluator = EVALUATOR(detector, data)
ap = evaluator.eval()
log.logger.info('Data sc:{} AP:{:<5.5f} Weights:{} {}'
.format(data.__class__.__name__, ap, model, strings))
detector.sess.close()
del net
del detector
del evaluator
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
from Eutils.pathmagic import context
with context():
import argparse
import numpy as np
from model.hourglass_yolo_net_multi_gpu import HOURGLASSYOLONet
from evaluator.Eutils.pascal_val import PASCAL_VAL
from evaluator.Eutils.detector import Detector
import utils.config as cfg
from utils.logger import Logger
from utils.config_utils import get_config, ds_config
from tqdm import tqdm
import tensorflow as tf
import copy
import os
class EVALUATOR(object):
def __init__(self, detector, data):
self.detector = detector
self.data = data
self.gt = self.data.gt
self.image_ids, self.bboxes, self.prob, self.annotations = (self.
prepare())
self.precision, self.recall = self.pr_curve()
def prepare(self):
image_ids, bboxes, prob = [], [], []
annotations = {}
for i in tqdm(range(self.data.num_batch), desc='batch forward'):
img_batch, bbox_batch = self.data.get_batch()
results = self.detector.detect_batch(img_batch)
for ii in range(len(results)):
boxes_filtered, probs_filtered = results[ii]
image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))
bboxes.extend(boxes_filtered)
prob.extend(probs_filtered)
if bbox_batch[ii]['id'] not in annotations:
annotations[bbox_batch[ii]['id']] = copy.deepcopy(
bbox_batch[ii]['bbox_det'])
sorted_ind = np.argsort(prob)[::-1]
sorted_prob = np.sort(prob)[::-1]
BB = np.array(bboxes)
BB = BB[sorted_ind, :]
image_ids = [image_ids[x] for x in sorted_ind]
return image_ids, BB, sorted_prob, annotations
def pr_curve(self):
nd = len(self.image_ids)
tp = np.zeros(nd)
fp = np.zeros(nd)
for d in tqdm(range(nd), desc='painting PR curve'):
R = self.annotations[self.image_ids[d]]
bb = self.bboxes[d, :].astype(float)
ovmax = -np.inf
BBGT = R['bboxes'].astype(float)
if BBGT.size > 0:
ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[
2] / 2)
iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[
3] / 2)
ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[
2] / 2)
iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[
3] / 2)
iw = np.maximum(ixmax - ixmin + 1.0, 0.0)
ih = np.maximum(iymax - iymin + 1.0, 0.0)
inters = iw * ih
uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters
overlaps = inters / uni
ovmax = np.max(overlaps)
jmax = np.argmax(overlaps)
if ovmax > cfg.IOU_THRESHOLD_GT:
if not R['det'][jmax]:
tp[d] = 1.0
R['det'][jmax] = 1
else:
fp[d] = 1.0
else:
fp[d] = 1.0
fp = np.cumsum(fp)
tp = np.cumsum(tp)
rec = tp / float(self.gt)
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
return prec, rec
def eval(self, use_07_metric=False):
""" ap = eval(rec, prec, [use_07_metric])
Compute AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
ap = 0.0
for t in np.arange(0.0, 1.1, 0.1):
if np.sum(self.recall >= t) == 0:
p = 0
else:
p = np.max(self.precision[self.recall >= t])
ap = ap + p / 11.0
else:
mrec = np.concatenate(([0.0], self.recall, [1.0]))
mpre = np.concatenate(([0.0], self.precision, [0.0]))
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
i = np.where(mrec[1:] != mrec[:-1])[0]
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-ims', '--image_size', default=512, type=int)
parser.add_argument('-g', '--gpu', type=str)
parser.add_argument('-c', '--cpu', action='store_true', help='use cpu')
parser.add_argument('-ds', '--data_source', default='all', type=str,
choices=['coco', 'pascal', 'all'])
parser.add_argument('-ef', '--eval_file', type=str, required=True)
parser.add_argument('-lf', '--log_file', type=str)
parser.add_argument('-al', '--auto_all', action='store_true')
parser.add_argument('--weights', default='hg_yolo-240000', type=str)
parser.add_argument('--weight_dir', default=
'../log_bbox_hm/0.8_0.08_0.03_conv_fc_l2_0.005_bhm5', type=str)
args = parser.parse_args()
if args.gpu:
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
if args.cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = ''
if not args.auto_all:
strings = get_config(args.weight_dir)
net = HOURGLASSYOLONet('eval')
detector = Detector(net, os.path.join(args.weight_dir, args.weights))
data = PASCAL_VAL()
evaluator = EVALUATOR(detector, data)
ap = evaluator.eval()
log = Logger(args.eval_file, level='debug')
log.logger.info('\n calculate single ap from {} {}\n'.format(args.
weight_dir, args.weights))
log.logger.info('Data sc:{} AP:{} Weights:{} {}'.format(data.
__class__.__name__, ap, args.weights, strings))
else:
data_source = ds_config(args)
log = Logger(args.eval_file, level='debug')
log.logger.info('\n calculate ap from {}\n'.format(args.eval_file))
model_start = 'hg_yolo'
rootdir = '../' + args.log_file
root_list = os.listdir(rootdir)
root_list.sort()
for path in root_list:
model_dir = os.path.join(rootdir, path)
models = os.listdir(model_dir)
models = filter(lambda x: x.startswith(model_start), models)
models = list(set(map(lambda x: x.split('.')[0], models)))
models.sort(key=lambda x: int(x[8:]))
for data in data_source:
for model in models:
strings = get_config(model_dir)
tf.reset_default_graph()
net = HOURGLASSYOLONet('eval')
detector = Detector(net, os.path.join(model_dir, model))
evaluator = EVALUATOR(detector, data)
ap = evaluator.eval()
log.logger.info('Data sc:{} AP:{:<5.5f} Weights:{} {}'
.format(data.__class__.__name__, ap, model, strings))
detector.sess.close()
del net
del detector
del evaluator
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
from Eutils.pathmagic import context
with context():
import argparse
import numpy as np
from model.hourglass_yolo_net_multi_gpu import HOURGLASSYOLONet
from evaluator.Eutils.pascal_val import PASCAL_VAL
# from evaluator.Eutils.coco_val import COCO_VAL
from evaluator.Eutils.detector import Detector
import utils.config as cfg
from utils.logger import Logger
from utils.config_utils import get_config,ds_config
from tqdm import tqdm
import tensorflow as tf
import copy
import os
# import cv2
# from evaluator.Eutils.draw_result import draw_result
class EVALUATOR(object):
def __init__(self, detector, data):
self.detector = detector
self.data = data
self.gt = self.data.gt
self.image_ids, self.bboxes, \
self.prob, self.annotations = self.prepare()
self.precision, self.recall = self.pr_curve()
def prepare(self):
image_ids, bboxes, prob = [], [], []
annotations = {}
# while img_batch:
for i in tqdm(range(self.data.num_batch), desc='batch forward'):
# print("{:5}th batch".format(i))
img_batch, bbox_batch = self.data.get_batch()
results = self.detector.detect_batch(img_batch)
for ii in range(len(results)):
boxes_filtered, probs_filtered = results[ii]
# bbox_gt = bbox_batch[ii]['bbox_det']['bboxes']
# filter_mat_probs = np.array(probs_filtered >= cfg.THRESHOLD, dtype='bool')
# filter_mat_probs = np.nonzero(filter_mat_probs)
# boxes_ft_prob = boxes_filtered[filter_mat_probs]
# probs_ft_prob = probs_filtered[filter_mat_probs]
# image = img_batch[ii]
# draw_result(image, bbox_gt, (0, 0, 255))
# draw_result(image, boxes_ft_prob, (255, 0, 0))
# cv2.imshow('Image', image)
# cv2.waitKey(0)
image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))
bboxes.extend(boxes_filtered)
prob.extend(probs_filtered)
if bbox_batch[ii]['id'] not in annotations:
annotations[bbox_batch[ii]['id']] = copy.deepcopy(bbox_batch[ii]['bbox_det'])
sorted_ind = np.argsort(prob)[::-1]
sorted_prob = np.sort(prob)[::-1]
BB = np.array(bboxes)
BB = BB[sorted_ind, :]
image_ids = [image_ids[x] for x in sorted_ind]
return image_ids, BB, sorted_prob, annotations
def pr_curve(self):
nd = len(self.image_ids)
tp = np.zeros(nd)
fp = np.zeros(nd)
for d in tqdm(range(nd), desc='painting PR curve'):
# for d in range(nd):
R = self.annotations[self.image_ids[d]]
bb = self.bboxes[d, :].astype(float)
ovmax = -np.inf
BBGT = R['bboxes'].astype(float)
if BBGT.size > 0:
# compute overlaps
# intersection
ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[2] / 2)
iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[3] / 2)
ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[2] / 2)
iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[3] / 2)
iw = np.maximum(ixmax - ixmin + 1., 0.)
ih = np.maximum(iymax - iymin + 1., 0.)
inters = iw * ih
# union
uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters
overlaps = inters / uni
ovmax = np.max(overlaps)
jmax = np.argmax(overlaps)
if ovmax > cfg.IOU_THRESHOLD_GT:
if not R['det'][jmax]:
tp[d] = 1.
R['det'][jmax] = 1
else:
fp[d] = 1.
else:
fp[d] = 1.
# compute precision recall
fp = np.cumsum(fp)
tp = np.cumsum(tp)
rec = tp / float(self.gt)
# avoid divide by zero in case the first detection matches a difficult
# ground truth
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
return prec, rec
def eval(self, use_07_metric=False):
""" ap = eval(rec, prec, [use_07_metric])
Compute AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
# 11 point metric
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(self.recall >= t) == 0:
p = 0
else:
p = np.max(self.precision[self.recall >= t])
ap = ap + p / 11.
else:
# correct AP calculation
# first append sentinel values at the end
mrec = np.concatenate(([0.], self.recall, [1.]))
mpre = np.concatenate(([0.], self.precision, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# to calculate area under PR curve, look for points
# where X axis (recall) changes value
i = np.where(mrec[1:] != mrec[:-1])[0]
# and sum (\Delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-ims', '--image_size', default=512, type=int)
parser.add_argument('-g','--gpu', type=str)
parser.add_argument('-c', '--cpu', action='store_true', help='use cpu')
parser.add_argument('-ds', '--data_source', default='all', type=str, choices=['coco', 'pascal', 'all'])
parser.add_argument('-ef', '--eval_file', type=str, required=True)
parser.add_argument('-lf', '--log_file', type=str)
parser.add_argument('-al', '--auto_all', action='store_true')
# when calculate single model
parser.add_argument('--weights', default="hg_yolo-240000", type=str)
parser.add_argument('--weight_dir', default='../log_bbox_hm/0.8_0.08_0.03_conv_fc_l2_0.005_bhm5', type=str)
args = parser.parse_args()
if args.gpu:
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
if args.cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = ''
if not args.auto_all:
strings = get_config(args.weight_dir)
net = HOURGLASSYOLONet('eval')
detector = Detector(net, os.path.join(args.weight_dir, args.weights))
# data = COCO_VAL()
data = PASCAL_VAL()
evaluator = EVALUATOR(detector, data)
ap = evaluator.eval()
log = Logger(args.eval_file, level='debug')
log.logger.info('\n calculate single ap from {} {}\n'.format(args.weight_dir, args.weights))
log.logger.info('Data sc:{} AP:{} Weights:{} {}'.format(
data.__class__.__name__, ap, args.weights, strings))
else:
data_source = ds_config(args)
log = Logger(args.eval_file, level='debug')
log.logger.info('\n calculate ap from {}\n'.format(args.eval_file))
model_start = 'hg_yolo'
rootdir = '../' + args.log_file
root_list = os.listdir(rootdir) # 列出文件夹下所有的目录与文件
root_list.sort()
for path in root_list:
model_dir = os.path.join(rootdir, path)
models = os.listdir(model_dir)
models = filter(lambda x: x.startswith(model_start), models)
models = list(set(map(lambda x: x.split('.')[0], models)))
models.sort(key=lambda x: int(x[8:]))
for data in data_source:
for model in models:
strings = get_config(model_dir)
tf.reset_default_graph()
net = HOURGLASSYOLONet('eval')
detector = Detector(net, os.path.join(model_dir, model))
evaluator = EVALUATOR(detector, data)
ap = evaluator.eval()
log.logger.info('Data sc:{} AP:{:<5.5f} Weights:{} {}'.format(
data.__class__.__name__, ap, model, strings))
detector.sess.close()
del net
del detector
del evaluator
if __name__ == '__main__':
main()
# print(os.path.realpath('.'))
# print(os.path.dirname(os.path.realpath('.')))
# print(os.sep)
#
# print(os.path.dirname(os.path.realpath('.')).split(os.sep))
|
flexible
|
{
"blob_id": "3bb6305ceb1491db57c7f8b03e438398644c8f90",
"index": 8124,
"step-1": "<mask token>\n\n\nclass EVALUATOR(object):\n\n def __init__(self, detector, data):\n self.detector = detector\n self.data = data\n self.gt = self.data.gt\n self.image_ids, self.bboxes, self.prob, self.annotations = (self.\n prepare())\n self.precision, self.recall = self.pr_curve()\n\n def prepare(self):\n image_ids, bboxes, prob = [], [], []\n annotations = {}\n for i in tqdm(range(self.data.num_batch), desc='batch forward'):\n img_batch, bbox_batch = self.data.get_batch()\n results = self.detector.detect_batch(img_batch)\n for ii in range(len(results)):\n boxes_filtered, probs_filtered = results[ii]\n image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))\n bboxes.extend(boxes_filtered)\n prob.extend(probs_filtered)\n if bbox_batch[ii]['id'] not in annotations:\n annotations[bbox_batch[ii]['id']] = copy.deepcopy(\n bbox_batch[ii]['bbox_det'])\n sorted_ind = np.argsort(prob)[::-1]\n sorted_prob = np.sort(prob)[::-1]\n BB = np.array(bboxes)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n return image_ids, BB, sorted_prob, annotations\n\n def pr_curve(self):\n nd = len(self.image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n for d in tqdm(range(nd), desc='painting PR curve'):\n R = self.annotations[self.image_ids[d]]\n bb = self.bboxes[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bboxes'].astype(float)\n if BBGT.size > 0:\n ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[\n 2] / 2)\n iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[\n 3] / 2)\n ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[\n 2] / 2)\n iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[\n 3] / 2)\n iw = np.maximum(ixmax - ixmin + 1.0, 0.0)\n ih = np.maximum(iymax - iymin + 1.0, 0.0)\n inters = iw * ih\n uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n if ovmax > cfg.IOU_THRESHOLD_GT:\n if not R['det'][jmax]:\n tp[d] = 1.0\n R['det'][jmax] = 1\n else:\n fp[d] = 1.0\n else:\n fp[d] = 1.0\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(self.gt)\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n return prec, rec\n\n def eval(self, use_07_metric=False):\n \"\"\" ap = eval(rec, prec, [use_07_metric])\n Compute AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:False).\n \"\"\"\n if use_07_metric:\n ap = 0.0\n for t in np.arange(0.0, 1.1, 0.1):\n if np.sum(self.recall >= t) == 0:\n p = 0\n else:\n p = np.max(self.precision[self.recall >= t])\n ap = ap + p / 11.0\n else:\n mrec = np.concatenate(([0.0], self.recall, [1.0]))\n mpre = np.concatenate(([0.0], self.precision, [0.0]))\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n i = np.where(mrec[1:] != mrec[:-1])[0]\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass EVALUATOR(object):\n\n def __init__(self, detector, data):\n self.detector = detector\n self.data = data\n self.gt = self.data.gt\n self.image_ids, self.bboxes, self.prob, self.annotations = (self.\n prepare())\n self.precision, self.recall = self.pr_curve()\n\n def prepare(self):\n image_ids, bboxes, prob = [], [], []\n annotations = {}\n for i in tqdm(range(self.data.num_batch), desc='batch forward'):\n img_batch, bbox_batch = self.data.get_batch()\n results = self.detector.detect_batch(img_batch)\n for ii in range(len(results)):\n boxes_filtered, probs_filtered = results[ii]\n image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))\n bboxes.extend(boxes_filtered)\n prob.extend(probs_filtered)\n if bbox_batch[ii]['id'] not in annotations:\n annotations[bbox_batch[ii]['id']] = copy.deepcopy(\n bbox_batch[ii]['bbox_det'])\n sorted_ind = np.argsort(prob)[::-1]\n sorted_prob = np.sort(prob)[::-1]\n BB = np.array(bboxes)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n return image_ids, BB, sorted_prob, annotations\n\n def pr_curve(self):\n nd = len(self.image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n for d in tqdm(range(nd), desc='painting PR curve'):\n R = self.annotations[self.image_ids[d]]\n bb = self.bboxes[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bboxes'].astype(float)\n if BBGT.size > 0:\n ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[\n 2] / 2)\n iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[\n 3] / 2)\n ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[\n 2] / 2)\n iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[\n 3] / 2)\n iw = np.maximum(ixmax - ixmin + 1.0, 0.0)\n ih = np.maximum(iymax - iymin + 1.0, 0.0)\n inters = iw * ih\n uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n if ovmax > cfg.IOU_THRESHOLD_GT:\n if not R['det'][jmax]:\n tp[d] = 1.0\n R['det'][jmax] = 1\n else:\n fp[d] = 1.0\n else:\n fp[d] = 1.0\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(self.gt)\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n return prec, rec\n\n def eval(self, use_07_metric=False):\n \"\"\" ap = eval(rec, prec, [use_07_metric])\n Compute AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:False).\n \"\"\"\n if use_07_metric:\n ap = 0.0\n for t in np.arange(0.0, 1.1, 0.1):\n if np.sum(self.recall >= t) == 0:\n p = 0\n else:\n p = np.max(self.precision[self.recall >= t])\n ap = ap + p / 11.0\n else:\n mrec = np.concatenate(([0.0], self.recall, [1.0]))\n mpre = np.concatenate(([0.0], self.precision, [0.0]))\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n i = np.where(mrec[1:] != mrec[:-1])[0]\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-ims', '--image_size', default=512, type=int)\n parser.add_argument('-g', '--gpu', type=str)\n parser.add_argument('-c', '--cpu', action='store_true', help='use cpu')\n parser.add_argument('-ds', '--data_source', default='all', type=str,\n choices=['coco', 'pascal', 'all'])\n parser.add_argument('-ef', '--eval_file', type=str, required=True)\n parser.add_argument('-lf', '--log_file', type=str)\n parser.add_argument('-al', '--auto_all', action='store_true')\n parser.add_argument('--weights', default='hg_yolo-240000', type=str)\n parser.add_argument('--weight_dir', default=\n '../log_bbox_hm/0.8_0.08_0.03_conv_fc_l2_0.005_bhm5', type=str)\n args = parser.parse_args()\n if args.gpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n if args.cpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = ''\n if not args.auto_all:\n strings = get_config(args.weight_dir)\n net = HOURGLASSYOLONet('eval')\n detector = Detector(net, os.path.join(args.weight_dir, args.weights))\n data = PASCAL_VAL()\n evaluator = EVALUATOR(detector, data)\n ap = evaluator.eval()\n log = Logger(args.eval_file, level='debug')\n log.logger.info('\\n calculate single ap from {} {}\\n'.format(args.\n weight_dir, args.weights))\n log.logger.info('Data sc:{} AP:{} Weights:{} {}'.format(data.\n __class__.__name__, ap, args.weights, strings))\n else:\n data_source = ds_config(args)\n log = Logger(args.eval_file, level='debug')\n log.logger.info('\\n calculate ap from {}\\n'.format(args.eval_file))\n model_start = 'hg_yolo'\n rootdir = '../' + args.log_file\n root_list = os.listdir(rootdir)\n root_list.sort()\n for path in root_list:\n model_dir = os.path.join(rootdir, path)\n models = os.listdir(model_dir)\n models = filter(lambda x: x.startswith(model_start), models)\n models = list(set(map(lambda x: x.split('.')[0], models)))\n models.sort(key=lambda x: int(x[8:]))\n for data in data_source:\n for model in models:\n strings = get_config(model_dir)\n tf.reset_default_graph()\n net = HOURGLASSYOLONet('eval')\n detector = Detector(net, os.path.join(model_dir, model))\n evaluator = EVALUATOR(detector, data)\n ap = evaluator.eval()\n log.logger.info('Data sc:{} AP:{:<5.5f} Weights:{} {}'\n .format(data.__class__.__name__, ap, model, strings))\n detector.sess.close()\n del net\n del detector\n del evaluator\n\n\n<mask token>\n",
"step-3": "<mask token>\nwith context():\n import argparse\n import numpy as np\n from model.hourglass_yolo_net_multi_gpu import HOURGLASSYOLONet\n from evaluator.Eutils.pascal_val import PASCAL_VAL\n from evaluator.Eutils.detector import Detector\n import utils.config as cfg\n from utils.logger import Logger\n from utils.config_utils import get_config, ds_config\n from tqdm import tqdm\n import tensorflow as tf\n import copy\n import os\n\n\nclass EVALUATOR(object):\n\n def __init__(self, detector, data):\n self.detector = detector\n self.data = data\n self.gt = self.data.gt\n self.image_ids, self.bboxes, self.prob, self.annotations = (self.\n prepare())\n self.precision, self.recall = self.pr_curve()\n\n def prepare(self):\n image_ids, bboxes, prob = [], [], []\n annotations = {}\n for i in tqdm(range(self.data.num_batch), desc='batch forward'):\n img_batch, bbox_batch = self.data.get_batch()\n results = self.detector.detect_batch(img_batch)\n for ii in range(len(results)):\n boxes_filtered, probs_filtered = results[ii]\n image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))\n bboxes.extend(boxes_filtered)\n prob.extend(probs_filtered)\n if bbox_batch[ii]['id'] not in annotations:\n annotations[bbox_batch[ii]['id']] = copy.deepcopy(\n bbox_batch[ii]['bbox_det'])\n sorted_ind = np.argsort(prob)[::-1]\n sorted_prob = np.sort(prob)[::-1]\n BB = np.array(bboxes)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n return image_ids, BB, sorted_prob, annotations\n\n def pr_curve(self):\n nd = len(self.image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n for d in tqdm(range(nd), desc='painting PR curve'):\n R = self.annotations[self.image_ids[d]]\n bb = self.bboxes[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bboxes'].astype(float)\n if BBGT.size > 0:\n ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[\n 2] / 2)\n iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[\n 3] / 2)\n ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[\n 2] / 2)\n iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[\n 3] / 2)\n iw = np.maximum(ixmax - ixmin + 1.0, 0.0)\n ih = np.maximum(iymax - iymin + 1.0, 0.0)\n inters = iw * ih\n uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n if ovmax > cfg.IOU_THRESHOLD_GT:\n if not R['det'][jmax]:\n tp[d] = 1.0\n R['det'][jmax] = 1\n else:\n fp[d] = 1.0\n else:\n fp[d] = 1.0\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(self.gt)\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n return prec, rec\n\n def eval(self, use_07_metric=False):\n \"\"\" ap = eval(rec, prec, [use_07_metric])\n Compute AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:False).\n \"\"\"\n if use_07_metric:\n ap = 0.0\n for t in np.arange(0.0, 1.1, 0.1):\n if np.sum(self.recall >= t) == 0:\n p = 0\n else:\n p = np.max(self.precision[self.recall >= t])\n ap = ap + p / 11.0\n else:\n mrec = np.concatenate(([0.0], self.recall, [1.0]))\n mpre = np.concatenate(([0.0], self.precision, [0.0]))\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n i = np.where(mrec[1:] != mrec[:-1])[0]\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-ims', '--image_size', default=512, type=int)\n parser.add_argument('-g', '--gpu', type=str)\n parser.add_argument('-c', '--cpu', action='store_true', help='use cpu')\n parser.add_argument('-ds', '--data_source', default='all', type=str,\n choices=['coco', 'pascal', 'all'])\n parser.add_argument('-ef', '--eval_file', type=str, required=True)\n parser.add_argument('-lf', '--log_file', type=str)\n parser.add_argument('-al', '--auto_all', action='store_true')\n parser.add_argument('--weights', default='hg_yolo-240000', type=str)\n parser.add_argument('--weight_dir', default=\n '../log_bbox_hm/0.8_0.08_0.03_conv_fc_l2_0.005_bhm5', type=str)\n args = parser.parse_args()\n if args.gpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n if args.cpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = ''\n if not args.auto_all:\n strings = get_config(args.weight_dir)\n net = HOURGLASSYOLONet('eval')\n detector = Detector(net, os.path.join(args.weight_dir, args.weights))\n data = PASCAL_VAL()\n evaluator = EVALUATOR(detector, data)\n ap = evaluator.eval()\n log = Logger(args.eval_file, level='debug')\n log.logger.info('\\n calculate single ap from {} {}\\n'.format(args.\n weight_dir, args.weights))\n log.logger.info('Data sc:{} AP:{} Weights:{} {}'.format(data.\n __class__.__name__, ap, args.weights, strings))\n else:\n data_source = ds_config(args)\n log = Logger(args.eval_file, level='debug')\n log.logger.info('\\n calculate ap from {}\\n'.format(args.eval_file))\n model_start = 'hg_yolo'\n rootdir = '../' + args.log_file\n root_list = os.listdir(rootdir)\n root_list.sort()\n for path in root_list:\n model_dir = os.path.join(rootdir, path)\n models = os.listdir(model_dir)\n models = filter(lambda x: x.startswith(model_start), models)\n models = list(set(map(lambda x: x.split('.')[0], models)))\n models.sort(key=lambda x: int(x[8:]))\n for data in data_source:\n for model in models:\n strings = get_config(model_dir)\n tf.reset_default_graph()\n net = HOURGLASSYOLONet('eval')\n detector = Detector(net, os.path.join(model_dir, model))\n evaluator = EVALUATOR(detector, data)\n ap = evaluator.eval()\n log.logger.info('Data sc:{} AP:{:<5.5f} Weights:{} {}'\n .format(data.__class__.__name__, ap, model, strings))\n detector.sess.close()\n del net\n del detector\n del evaluator\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "from Eutils.pathmagic import context\nwith context():\n import argparse\n import numpy as np\n from model.hourglass_yolo_net_multi_gpu import HOURGLASSYOLONet\n from evaluator.Eutils.pascal_val import PASCAL_VAL\n from evaluator.Eutils.detector import Detector\n import utils.config as cfg\n from utils.logger import Logger\n from utils.config_utils import get_config, ds_config\n from tqdm import tqdm\n import tensorflow as tf\n import copy\n import os\n\n\nclass EVALUATOR(object):\n\n def __init__(self, detector, data):\n self.detector = detector\n self.data = data\n self.gt = self.data.gt\n self.image_ids, self.bboxes, self.prob, self.annotations = (self.\n prepare())\n self.precision, self.recall = self.pr_curve()\n\n def prepare(self):\n image_ids, bboxes, prob = [], [], []\n annotations = {}\n for i in tqdm(range(self.data.num_batch), desc='batch forward'):\n img_batch, bbox_batch = self.data.get_batch()\n results = self.detector.detect_batch(img_batch)\n for ii in range(len(results)):\n boxes_filtered, probs_filtered = results[ii]\n image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))\n bboxes.extend(boxes_filtered)\n prob.extend(probs_filtered)\n if bbox_batch[ii]['id'] not in annotations:\n annotations[bbox_batch[ii]['id']] = copy.deepcopy(\n bbox_batch[ii]['bbox_det'])\n sorted_ind = np.argsort(prob)[::-1]\n sorted_prob = np.sort(prob)[::-1]\n BB = np.array(bboxes)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n return image_ids, BB, sorted_prob, annotations\n\n def pr_curve(self):\n nd = len(self.image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n for d in tqdm(range(nd), desc='painting PR curve'):\n R = self.annotations[self.image_ids[d]]\n bb = self.bboxes[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bboxes'].astype(float)\n if BBGT.size > 0:\n ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[\n 2] / 2)\n iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[\n 3] / 2)\n ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[\n 2] / 2)\n iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[\n 3] / 2)\n iw = np.maximum(ixmax - ixmin + 1.0, 0.0)\n ih = np.maximum(iymax - iymin + 1.0, 0.0)\n inters = iw * ih\n uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n if ovmax > cfg.IOU_THRESHOLD_GT:\n if not R['det'][jmax]:\n tp[d] = 1.0\n R['det'][jmax] = 1\n else:\n fp[d] = 1.0\n else:\n fp[d] = 1.0\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(self.gt)\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n return prec, rec\n\n def eval(self, use_07_metric=False):\n \"\"\" ap = eval(rec, prec, [use_07_metric])\n Compute AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:False).\n \"\"\"\n if use_07_metric:\n ap = 0.0\n for t in np.arange(0.0, 1.1, 0.1):\n if np.sum(self.recall >= t) == 0:\n p = 0\n else:\n p = np.max(self.precision[self.recall >= t])\n ap = ap + p / 11.0\n else:\n mrec = np.concatenate(([0.0], self.recall, [1.0]))\n mpre = np.concatenate(([0.0], self.precision, [0.0]))\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n i = np.where(mrec[1:] != mrec[:-1])[0]\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-ims', '--image_size', default=512, type=int)\n parser.add_argument('-g', '--gpu', type=str)\n parser.add_argument('-c', '--cpu', action='store_true', help='use cpu')\n parser.add_argument('-ds', '--data_source', default='all', type=str,\n choices=['coco', 'pascal', 'all'])\n parser.add_argument('-ef', '--eval_file', type=str, required=True)\n parser.add_argument('-lf', '--log_file', type=str)\n parser.add_argument('-al', '--auto_all', action='store_true')\n parser.add_argument('--weights', default='hg_yolo-240000', type=str)\n parser.add_argument('--weight_dir', default=\n '../log_bbox_hm/0.8_0.08_0.03_conv_fc_l2_0.005_bhm5', type=str)\n args = parser.parse_args()\n if args.gpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n if args.cpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = ''\n if not args.auto_all:\n strings = get_config(args.weight_dir)\n net = HOURGLASSYOLONet('eval')\n detector = Detector(net, os.path.join(args.weight_dir, args.weights))\n data = PASCAL_VAL()\n evaluator = EVALUATOR(detector, data)\n ap = evaluator.eval()\n log = Logger(args.eval_file, level='debug')\n log.logger.info('\\n calculate single ap from {} {}\\n'.format(args.\n weight_dir, args.weights))\n log.logger.info('Data sc:{} AP:{} Weights:{} {}'.format(data.\n __class__.__name__, ap, args.weights, strings))\n else:\n data_source = ds_config(args)\n log = Logger(args.eval_file, level='debug')\n log.logger.info('\\n calculate ap from {}\\n'.format(args.eval_file))\n model_start = 'hg_yolo'\n rootdir = '../' + args.log_file\n root_list = os.listdir(rootdir)\n root_list.sort()\n for path in root_list:\n model_dir = os.path.join(rootdir, path)\n models = os.listdir(model_dir)\n models = filter(lambda x: x.startswith(model_start), models)\n models = list(set(map(lambda x: x.split('.')[0], models)))\n models.sort(key=lambda x: int(x[8:]))\n for data in data_source:\n for model in models:\n strings = get_config(model_dir)\n tf.reset_default_graph()\n net = HOURGLASSYOLONet('eval')\n detector = Detector(net, os.path.join(model_dir, model))\n evaluator = EVALUATOR(detector, data)\n ap = evaluator.eval()\n log.logger.info('Data sc:{} AP:{:<5.5f} Weights:{} {}'\n .format(data.__class__.__name__, ap, model, strings))\n detector.sess.close()\n del net\n del detector\n del evaluator\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "from Eutils.pathmagic import context\nwith context():\n import argparse\n import numpy as np\n from model.hourglass_yolo_net_multi_gpu import HOURGLASSYOLONet\n from evaluator.Eutils.pascal_val import PASCAL_VAL\n # from evaluator.Eutils.coco_val import COCO_VAL\n from evaluator.Eutils.detector import Detector\n import utils.config as cfg\n from utils.logger import Logger\n from utils.config_utils import get_config,ds_config\n from tqdm import tqdm\n import tensorflow as tf\n import copy\n import os\n\n\n# import cv2\n# from evaluator.Eutils.draw_result import draw_result\n\n\nclass EVALUATOR(object):\n\n def __init__(self, detector, data):\n self.detector = detector\n self.data = data\n self.gt = self.data.gt\n self.image_ids, self.bboxes, \\\n self.prob, self.annotations = self.prepare()\n self.precision, self.recall = self.pr_curve()\n\n def prepare(self):\n image_ids, bboxes, prob = [], [], []\n annotations = {}\n # while img_batch:\n for i in tqdm(range(self.data.num_batch), desc='batch forward'):\n # print(\"{:5}th batch\".format(i))\n img_batch, bbox_batch = self.data.get_batch()\n results = self.detector.detect_batch(img_batch)\n for ii in range(len(results)):\n boxes_filtered, probs_filtered = results[ii]\n # bbox_gt = bbox_batch[ii]['bbox_det']['bboxes']\n # filter_mat_probs = np.array(probs_filtered >= cfg.THRESHOLD, dtype='bool')\n # filter_mat_probs = np.nonzero(filter_mat_probs)\n # boxes_ft_prob = boxes_filtered[filter_mat_probs]\n # probs_ft_prob = probs_filtered[filter_mat_probs]\n # image = img_batch[ii]\n # draw_result(image, bbox_gt, (0, 0, 255))\n # draw_result(image, boxes_ft_prob, (255, 0, 0))\n # cv2.imshow('Image', image)\n # cv2.waitKey(0)\n image_ids.extend([bbox_batch[ii]['id']] * len(boxes_filtered))\n bboxes.extend(boxes_filtered)\n prob.extend(probs_filtered)\n if bbox_batch[ii]['id'] not in annotations:\n annotations[bbox_batch[ii]['id']] = copy.deepcopy(bbox_batch[ii]['bbox_det'])\n sorted_ind = np.argsort(prob)[::-1]\n sorted_prob = np.sort(prob)[::-1]\n BB = np.array(bboxes)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n return image_ids, BB, sorted_prob, annotations\n\n def pr_curve(self):\n nd = len(self.image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n for d in tqdm(range(nd), desc='painting PR curve'):\n # for d in range(nd):\n R = self.annotations[self.image_ids[d]]\n bb = self.bboxes[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bboxes'].astype(float)\n\n if BBGT.size > 0:\n # compute overlaps\n # intersection\n ixmin = np.maximum(BBGT[:, 0] - BBGT[:, 2] / 2, bb[0] - bb[2] / 2)\n iymin = np.maximum(BBGT[:, 1] - BBGT[:, 3] / 2, bb[1] - bb[3] / 2)\n ixmax = np.minimum(BBGT[:, 0] + BBGT[:, 2] / 2, bb[0] + bb[2] / 2)\n iymax = np.minimum(BBGT[:, 1] + BBGT[:, 3] / 2, bb[1] + bb[3] / 2)\n iw = np.maximum(ixmax - ixmin + 1., 0.)\n ih = np.maximum(iymax - iymin + 1., 0.)\n inters = iw * ih\n\n # union\n uni = bb[2] * bb[3] + BBGT[:, 2] * BBGT[:, 3] - inters\n\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n if ovmax > cfg.IOU_THRESHOLD_GT:\n if not R['det'][jmax]:\n tp[d] = 1.\n R['det'][jmax] = 1\n else:\n fp[d] = 1.\n else:\n fp[d] = 1.\n\n # compute precision recall\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(self.gt)\n # avoid divide by zero in case the first detection matches a difficult\n # ground truth\n\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n return prec, rec\n\n def eval(self, use_07_metric=False):\n \"\"\" ap = eval(rec, prec, [use_07_metric])\n Compute AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:False).\n \"\"\"\n\n if use_07_metric:\n # 11 point metric\n ap = 0.\n for t in np.arange(0., 1.1, 0.1):\n if np.sum(self.recall >= t) == 0:\n p = 0\n else:\n p = np.max(self.precision[self.recall >= t])\n ap = ap + p / 11.\n else:\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], self.recall, [1.]))\n mpre = np.concatenate(([0.], self.precision, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n\n return ap\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-ims', '--image_size', default=512, type=int)\n parser.add_argument('-g','--gpu', type=str)\n parser.add_argument('-c', '--cpu', action='store_true', help='use cpu')\n parser.add_argument('-ds', '--data_source', default='all', type=str, choices=['coco', 'pascal', 'all'])\n parser.add_argument('-ef', '--eval_file', type=str, required=True)\n parser.add_argument('-lf', '--log_file', type=str)\n parser.add_argument('-al', '--auto_all', action='store_true')\n # when calculate single model\n parser.add_argument('--weights', default=\"hg_yolo-240000\", type=str)\n parser.add_argument('--weight_dir', default='../log_bbox_hm/0.8_0.08_0.03_conv_fc_l2_0.005_bhm5', type=str)\n args = parser.parse_args()\n if args.gpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n if args.cpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = ''\n if not args.auto_all:\n strings = get_config(args.weight_dir)\n\n net = HOURGLASSYOLONet('eval')\n detector = Detector(net, os.path.join(args.weight_dir, args.weights))\n # data = COCO_VAL()\n data = PASCAL_VAL()\n evaluator = EVALUATOR(detector, data)\n ap = evaluator.eval()\n log = Logger(args.eval_file, level='debug')\n log.logger.info('\\n calculate single ap from {} {}\\n'.format(args.weight_dir, args.weights))\n log.logger.info('Data sc:{} AP:{} Weights:{} {}'.format(\n data.__class__.__name__, ap, args.weights, strings))\n else:\n data_source = ds_config(args)\n log = Logger(args.eval_file, level='debug')\n log.logger.info('\\n calculate ap from {}\\n'.format(args.eval_file))\n model_start = 'hg_yolo'\n rootdir = '../' + args.log_file\n root_list = os.listdir(rootdir) # 列出文件夹下所有的目录与文件\n root_list.sort()\n for path in root_list:\n model_dir = os.path.join(rootdir, path)\n models = os.listdir(model_dir)\n models = filter(lambda x: x.startswith(model_start), models)\n models = list(set(map(lambda x: x.split('.')[0], models)))\n models.sort(key=lambda x: int(x[8:]))\n for data in data_source:\n for model in models:\n strings = get_config(model_dir)\n tf.reset_default_graph()\n net = HOURGLASSYOLONet('eval')\n detector = Detector(net, os.path.join(model_dir, model))\n evaluator = EVALUATOR(detector, data)\n ap = evaluator.eval()\n log.logger.info('Data sc:{} AP:{:<5.5f} Weights:{} {}'.format(\n data.__class__.__name__, ap, model, strings))\n detector.sess.close()\n del net\n del detector\n del evaluator\n\n\nif __name__ == '__main__':\n main()\n # print(os.path.realpath('.'))\n # print(os.path.dirname(os.path.realpath('.')))\n # print(os.sep)\n #\n # print(os.path.dirname(os.path.realpath('.')).split(os.sep))\n\n",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
<|reserved_special_token_0|>
def funct(string):
dict = {}
for i in string:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
return dict
<|reserved_special_token_0|>
def counter():
string = input('Input your string :')
result = Counter(string)
return result
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def funct(string):
dict = {}
for i in string:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
return dict
print(funct(string))
<|reserved_special_token_0|>
def counter():
string = input('Input your string :')
result = Counter(string)
return result
print(counter())
<|reserved_special_token_1|>
string = input('Input your string: ')
def funct(string):
dict = {}
for i in string:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
return dict
print(funct(string))
<|reserved_special_token_0|>
def counter():
string = input('Input your string :')
result = Counter(string)
return result
print(counter())
<|reserved_special_token_1|>
string = input('Input your string: ')
def funct(string):
dict = {}
for i in string:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
return dict
print(funct(string))
from collections import Counter
def counter():
string = input('Input your string :')
result = Counter(string)
return result
print(counter())
<|reserved_special_token_1|>
# Write a function that receives a string as a parameter and returns a dictionary in which the keys are the characters in the character string and the values are the number of occurrences of that character in the given text.
# Example: For string "Ana has apples." given as a parameter the function will return the dictionary: {'A': 1, '': 2, 'n': 1, 'a': 2, 'r': 2, '.': 1}.
# varianta 1
string=input("Input your string: ")
def funct(string):
dict={}
for i in string:
if i in dict:
dict[i]+=1
else:
dict[i]= 1
return dict
print(funct(string))
# varianta 2
from collections import Counter
def counter():
string=input("Input your string :")
result=Counter(string)
return result
print(counter())
|
flexible
|
{
"blob_id": "14807568af046594644095a2682e0eba4f445b26",
"index": 8053,
"step-1": "<mask token>\n\n\ndef funct(string):\n dict = {}\n for i in string:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n return dict\n\n\n<mask token>\n\n\ndef counter():\n string = input('Input your string :')\n result = Counter(string)\n return result\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef funct(string):\n dict = {}\n for i in string:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n return dict\n\n\nprint(funct(string))\n<mask token>\n\n\ndef counter():\n string = input('Input your string :')\n result = Counter(string)\n return result\n\n\nprint(counter())\n",
"step-3": "string = input('Input your string: ')\n\n\ndef funct(string):\n dict = {}\n for i in string:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n return dict\n\n\nprint(funct(string))\n<mask token>\n\n\ndef counter():\n string = input('Input your string :')\n result = Counter(string)\n return result\n\n\nprint(counter())\n",
"step-4": "string = input('Input your string: ')\n\n\ndef funct(string):\n dict = {}\n for i in string:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n return dict\n\n\nprint(funct(string))\nfrom collections import Counter\n\n\ndef counter():\n string = input('Input your string :')\n result = Counter(string)\n return result\n\n\nprint(counter())\n",
"step-5": "# Write a function that receives a string as a parameter and returns a dictionary in which the keys are the characters in the character string and the values are the number of occurrences of that character in the given text.\n# Example: For string \"Ana has apples.\" given as a parameter the function will return the dictionary: {'A': 1, '': 2, 'n': 1, 'a': 2, 'r': 2, '.': 1}.\n\n# varianta 1\nstring=input(\"Input your string: \")\ndef funct(string):\n dict={}\n for i in string:\n if i in dict:\n dict[i]+=1\n else:\n dict[i]= 1\n return dict\nprint(funct(string))\n\n# varianta 2\nfrom collections import Counter\ndef counter():\n string=input(\"Input your string :\")\n result=Counter(string)\n return result\nprint(counter())",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import numpy as np
import matplotlib.pyplot as plt
import netCDF4
import xarray as xr
import metpy
from datetime import datetime
import datetime as dt
from metpy.units import units
import scipy.ndimage as ndimage
from metpy.plots import USCOUNTIES
import cartopy
from scipy.ndimage.filters import generic_filter as gf
def mkdir_p(mypath):
'''Creates a directory. equivalent to using mkdir -p on the command line'''
from errno import EEXIST
from os import makedirs,path
try:
makedirs(mypath)
except OSError as exc: # Python >2.5
if exc.errno == EEXIST and path.isdir(mypath):
pass
else: raise
startTime=datetime.now()
m_date='20200903'
m_hour='12'
year = startTime.year
if startTime.month <10:
month = '0'+str(startTime.month)
else:
month = str(startTime.month)
if startTime.day <10:
day = '0'+str(startTime.day)
else:
day = str(startTime.day)
if startTime.hour <10:
hour = '0'+str(startTime.hour)
else:
hour = str(startTime.hour)
mdate = str(year)+str(month)+str(day)
def get_init_hr(hour):
if int(hour) <6:
init_hour = '00'
elif int(hour) <11:
init_hour = '06'
elif int(hour) <17:
init_hour = '12'
elif int(hour) <22:
init_hour = '18'
else:
init_hour = '00'
return(init_hour)
url = 'http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs'+mdate+'/gfs_0p25_1hr_'+get_init_hr(hour)+'z'
init_hour = get_init_hr(hour)
'''
for i in range(119):
fhr = i+1
'''
# Create new directory
output_dir = str(year)+str(month)+str(day)+'_'+str(init_hour)+'00'
mkdir_p(output_dir)
mkdir_p(output_dir+'/GFS')
#Parse data using MetPy
ds = xr.open_dataset(url)
init_hr = dt.datetime(int(year),int(month),int(day),int(init_hour))
times = ds['tmp2m'].metpy.time
init_time = ds['time'][0]
lats = np.arange(15,70,0.25)
lons = np.arange(220,330,0.25)
for i in range(1,120):
fc_hr = init_hr+dt.timedelta(hours=1*i)
forecast_hour = times[0].values
data = ds.metpy.parse_cf()
data = data.isel(time=i)
#Rename variables to useful things
data = data.rename({
'absvprs':'avort',
'hgtprs':'gph',
'rhprs':'rh',
'tmpprs':'temp',
'ugrdprs':'u',
'vgrdprs': 'v',
})
vertical, = data['temp'].metpy.coordinates('vertical')
time = data['temp'].metpy.time
zH5_crs = data['temp'].metpy.cartopy_crs
t5 = data['temp'].sel(lev=500.0,lat=lats,lon=lons)
u5 = data['u'].sel(lev=500.0,lat=lats,lon=lons).squeeze()*1.94384449
v5 = data['v'].sel(lev=500.0,lat=lats,lon=lons).squeeze()*1.94384449
av5 = data['avort'].sel(lev=500.0,lat=lats,lon=lons).squeeze()*1e5
rh5 = data['rh'].sel(lev=500.0,lat=lats,lon=lons).squeeze()
h5 = data['gph'].sel(lev=500.0,lat=lats,lon=lons).squeeze()
x, y = t5.metpy.coordinates('x', 'y')
lat, lon = xr.broadcast(y, x)
wind_slice = slice(5,-5,5)
########## SET UP FIGURE ##################################################
fig = plt.figure(figsize=(15,15))
ax1 = fig.add_subplot(111, projection = zH5_crs)
ax1.coastlines(resolution='10m')
ax1.add_feature(cfeature.BORDERS.with_scale('10m'))
ax1.add_feature(cfeature.STATES.with_scale('10m'))
#fig.suptitle("NAM Forecast valid at " + time[0].dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=36)
########## PLOTTING #######################################################
h5c = ax1.contour(x,y,h5,colors='dimgray', levels = range(4800,6200,60),linewidths=1.5)
t5c = ax1.contour(x,y,t5,colors='r', levels = range(-60,0,5),linestyles='dashed',linewidths=1)
a5c = ax1.contourf(x,y,av5,cmap='autumn_r',levels=range(10,60,2),alpha=0.8,extend='max')
a5cb = fig.colorbar(a5c, orientation = 'horizontal', aspect = 80, ax = ax1, pad = 0.01,
extendrect=False, ticks = range(10,61,5))
a5cb.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize = 12)
ax1.barbs(x[wind_slice],y[wind_slice],u5[wind_slice,wind_slice],v5[wind_slice,wind_slice], length=7)
#h_contour = ax1.contour(x, y, mslpc, colors='dimgray', levels=range(940,1040,4),linewidths=2)
#h_contour.clabel(fontsize=14, colors='dimgray', inline=1, inline_spacing=4, fmt='%i mb', rightside_up=True, use_clabeltext=True)
ax1.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',fontsize=16)
ax1.set_title('\n Valid: '+time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='right')
ax1.set_title('\n GFS Init: '+init_time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='left')
ax1.set_extent((265, 300, 25, 50))#, crs = zH5_crs) # Set a title and show the plot
plt.savefig(output_dir+'/GFS/gfs_hrly_h5vort_'+str(i)+'.png')
plt.clf()
plt.close()
########## PLOT 2 #######################################################
wind_slice_s = slice (10,-10,10)
fig2 = plt.figure(figsize=(15,15))
ax2 = fig2.add_subplot(111,projection=zH5_crs)
ax2.coastlines(resolution='50m')
ax2.add_feature(cfeature.BORDERS.with_scale('50m'))
ax2.add_feature(cfeature.STATES.with_scale('50m'))
h5c2 = ax2.contour(x,y,h5,colors='dimgray', levels = range(4800,6200,60),linewidths=1.5)
t5c2 = ax2.contour(x,y,t5,colors='r', levels = range(-60,0,5),linestyles='dashed',linewidths=1)
a5c2 = ax2.contourf(x,y,av5,cmap='autumn_r',levels=range(10,65,2),alpha=0.8)
a5cb2 = fig2.colorbar(a5c2, orientation = 'horizontal', aspect = 80, ax = ax2, pad = 0.01,
extendrect=False, ticks = range(10,60,5))
a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize = 12)
ax2.barbs(x[wind_slice_s],y[wind_slice_s],u5[wind_slice_s,wind_slice_s],v5[wind_slice_s,wind_slice_s], length=7)
#h_contour = ax1.contour(x, y, mslpc, colors='dimgray', levels=range(940,1040,4),linewidths=2)
#h_contour.clabel(fontsize=14, colors='dimgray', inline=1, inline_spacing=4, fmt='%i mb', rightside_up=True, use_clabeltext=True)
ax2.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',fontsize=16)
ax2.set_title('\n Valid: '+time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='right')
ax2.set_title('\n GFS Init: '+init_time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='left')
ax2.set_extent((225, 300, 20, 65))#, crs = zH5_crs) # Set a title and show the plot
plt.savefig(output_dir+'/GFS/gfs_hrly_h5vortCONUS_v2_'+str(i)+'.png')
########## PLOT 3 #######################################################
wind_slice_s = slice (10,-10,10)
fig3 = plt.figure(figsize=(15,15))
ax3 = fig3.add_subplot(111,projection=zH5_crs)
ax3.coastlines(resolution='50m')
ax3.add_feature(cfeature.BORDERS.with_scale('50m'))
ax3.add_feature(cfeature.STATES.with_scale('50m'))
h5c2 = ax3.contour(x,y,h5,colors='dimgray', levels = range(4800,6200,60),linewidths=1.5)
t5c2 = ax3.contour(x,y,t5,colors='r', levels = range(-60,0,5),linestyles='dashed',linewidths=1)
a5c2 = ax3.contourf(x,y,av5,cmap='autumn_r',levels=range(10,65,2),alpha=0.8)
a5cb2 = fig3.colorbar(a5c2, orientation = 'horizontal', aspect = 80, ax = ax3, pad = 0.01,
extendrect=False, ticks = range(10,60,5))
a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize = 12)
ax3.barbs(x[wind_slice_s],y[wind_slice_s],u5[wind_slice_s,wind_slice_s],v5[wind_slice_s,wind_slice_s], length=7)
#h_contour = ax1.contour(x, y, mslpc, colors='dimgray', levels=range(940,1040,4),linewidths=2)
#h_contour.clabel(fontsize=14, colors='dimgray', inline=1, inline_spacing=4, fmt='%i mb', rightside_up=True, use_clabeltext=True)
ax3.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',fontsize=16)
ax3.set_title('\n Valid: '+time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='right')
ax3.set_title('\n GFS Init: '+init_time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='left')
ax3.set_extent((260, 320, 20, 65))#, crs = zH5_crs) # Set a title and show the plot
plt.savefig(output_dir+'/GFS/gfs_hrly_h5vortC_ec_v1_'+str(i)+'.png')
fcst_hr = str(0)
print('Hour '+str(i)+' completed!')
plt.close()
timeelapsed = datetime.now()-startTime
print(timeelapsed)
'''
url= 'http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs20200903/gfs_0p25_1hr_12z'
ds = xr.open_dataset(url)
t2m_ds = ds['tmp2m']
init_hr = t2m_ds['time'][0].values
#fc_hr = t2m.ds['time'][i].values
lats = np.arange(20,50,0.25)
lons = np.arange(240,300,0.25)
t2m = t2m_ds.sel(time = init_hr, lat = lats, lon = lons)
print(t2m)
fig = plt.figure(figsize = (12,12))
fig.clf()
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
ax.set_extent((240,300, 20, 50), crs = ccrs.PlateCarree())
t2m_c = ax.contourf(t2m, cmap='RdPu')
plt.savefig('testingnomads6.png')
'''
|
normal
|
{
"blob_id": "8771f71a69f3afdc5de4d38db6efe61b553ae880",
"index": 9396,
"step-1": "<mask token>\n\n\ndef mkdir_p(mypath):\n \"\"\"Creates a directory. equivalent to using mkdir -p on the command line\"\"\"\n from errno import EEXIST\n from os import makedirs, path\n try:\n makedirs(mypath)\n except OSError as exc:\n if exc.errno == EEXIST and path.isdir(mypath):\n pass\n else:\n raise\n\n\n<mask token>\n\n\ndef get_init_hr(hour):\n if int(hour) < 6:\n init_hour = '00'\n elif int(hour) < 11:\n init_hour = '06'\n elif int(hour) < 17:\n init_hour = '12'\n elif int(hour) < 22:\n init_hour = '18'\n else:\n init_hour = '00'\n return init_hour\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef mkdir_p(mypath):\n \"\"\"Creates a directory. equivalent to using mkdir -p on the command line\"\"\"\n from errno import EEXIST\n from os import makedirs, path\n try:\n makedirs(mypath)\n except OSError as exc:\n if exc.errno == EEXIST and path.isdir(mypath):\n pass\n else:\n raise\n\n\n<mask token>\nif startTime.month < 10:\n month = '0' + str(startTime.month)\nelse:\n month = str(startTime.month)\nif startTime.day < 10:\n day = '0' + str(startTime.day)\nelse:\n day = str(startTime.day)\nif startTime.hour < 10:\n hour = '0' + str(startTime.hour)\nelse:\n hour = str(startTime.hour)\n<mask token>\n\n\ndef get_init_hr(hour):\n if int(hour) < 6:\n init_hour = '00'\n elif int(hour) < 11:\n init_hour = '06'\n elif int(hour) < 17:\n init_hour = '12'\n elif int(hour) < 22:\n init_hour = '18'\n else:\n init_hour = '00'\n return init_hour\n\n\n<mask token>\nmkdir_p(output_dir)\nmkdir_p(output_dir + '/GFS')\n<mask token>\nfor i in range(1, 120):\n fc_hr = init_hr + dt.timedelta(hours=1 * i)\n forecast_hour = times[0].values\n data = ds.metpy.parse_cf()\n data = data.isel(time=i)\n data = data.rename({'absvprs': 'avort', 'hgtprs': 'gph', 'rhprs': 'rh',\n 'tmpprs': 'temp', 'ugrdprs': 'u', 'vgrdprs': 'v'})\n vertical, = data['temp'].metpy.coordinates('vertical')\n time = data['temp'].metpy.time\n zH5_crs = data['temp'].metpy.cartopy_crs\n t5 = data['temp'].sel(lev=500.0, lat=lats, lon=lons)\n u5 = data['u'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 1.94384449\n v5 = data['v'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 1.94384449\n av5 = data['avort'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 100000.0\n rh5 = data['rh'].sel(lev=500.0, lat=lats, lon=lons).squeeze()\n h5 = data['gph'].sel(lev=500.0, lat=lats, lon=lons).squeeze()\n x, y = t5.metpy.coordinates('x', 'y')\n lat, lon = xr.broadcast(y, x)\n wind_slice = slice(5, -5, 5)\n fig = plt.figure(figsize=(15, 15))\n ax1 = fig.add_subplot(111, projection=zH5_crs)\n ax1.coastlines(resolution='10m')\n ax1.add_feature(cfeature.BORDERS.with_scale('10m'))\n ax1.add_feature(cfeature.STATES.with_scale('10m'))\n h5c = ax1.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200, \n 60), linewidths=1.5)\n t5c = ax1.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c = ax1.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 60, 2),\n alpha=0.8, extend='max')\n a5cb = fig.colorbar(a5c, orientation='horizontal', aspect=80, ax=ax1,\n pad=0.01, extendrect=False, ticks=range(10, 61, 5))\n a5cb.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax1.barbs(x[wind_slice], y[wind_slice], u5[wind_slice, wind_slice], v5[\n wind_slice, wind_slice], length=7)\n ax1.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax1.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax1.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax1.set_extent((265, 300, 25, 50))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vort_' + str(i) + '.png')\n plt.clf()\n plt.close()\n wind_slice_s = slice(10, -10, 10)\n fig2 = plt.figure(figsize=(15, 15))\n ax2 = fig2.add_subplot(111, projection=zH5_crs)\n ax2.coastlines(resolution='50m')\n ax2.add_feature(cfeature.BORDERS.with_scale('50m'))\n ax2.add_feature(cfeature.STATES.with_scale('50m'))\n h5c2 = ax2.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200,\n 60), linewidths=1.5)\n t5c2 = ax2.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c2 = ax2.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 65, 2),\n alpha=0.8)\n a5cb2 = fig2.colorbar(a5c2, orientation='horizontal', aspect=80, ax=ax2,\n pad=0.01, extendrect=False, ticks=range(10, 60, 5))\n a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax2.barbs(x[wind_slice_s], y[wind_slice_s], u5[wind_slice_s,\n wind_slice_s], v5[wind_slice_s, wind_slice_s], length=7)\n ax2.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax2.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax2.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax2.set_extent((225, 300, 20, 65))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vortCONUS_v2_' + str(i) + '.png')\n wind_slice_s = slice(10, -10, 10)\n fig3 = plt.figure(figsize=(15, 15))\n ax3 = fig3.add_subplot(111, projection=zH5_crs)\n ax3.coastlines(resolution='50m')\n ax3.add_feature(cfeature.BORDERS.with_scale('50m'))\n ax3.add_feature(cfeature.STATES.with_scale('50m'))\n h5c2 = ax3.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200,\n 60), linewidths=1.5)\n t5c2 = ax3.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c2 = ax3.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 65, 2),\n alpha=0.8)\n a5cb2 = fig3.colorbar(a5c2, orientation='horizontal', aspect=80, ax=ax3,\n pad=0.01, extendrect=False, ticks=range(10, 60, 5))\n a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax3.barbs(x[wind_slice_s], y[wind_slice_s], u5[wind_slice_s,\n wind_slice_s], v5[wind_slice_s, wind_slice_s], length=7)\n ax3.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax3.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax3.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax3.set_extent((260, 320, 20, 65))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vortC_ec_v1_' + str(i) + '.png')\n fcst_hr = str(0)\n print('Hour ' + str(i) + ' completed!')\n plt.close()\n timeelapsed = datetime.now() - startTime\n print(timeelapsed)\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef mkdir_p(mypath):\n \"\"\"Creates a directory. equivalent to using mkdir -p on the command line\"\"\"\n from errno import EEXIST\n from os import makedirs, path\n try:\n makedirs(mypath)\n except OSError as exc:\n if exc.errno == EEXIST and path.isdir(mypath):\n pass\n else:\n raise\n\n\nstartTime = datetime.now()\nm_date = '20200903'\nm_hour = '12'\nyear = startTime.year\nif startTime.month < 10:\n month = '0' + str(startTime.month)\nelse:\n month = str(startTime.month)\nif startTime.day < 10:\n day = '0' + str(startTime.day)\nelse:\n day = str(startTime.day)\nif startTime.hour < 10:\n hour = '0' + str(startTime.hour)\nelse:\n hour = str(startTime.hour)\nmdate = str(year) + str(month) + str(day)\n\n\ndef get_init_hr(hour):\n if int(hour) < 6:\n init_hour = '00'\n elif int(hour) < 11:\n init_hour = '06'\n elif int(hour) < 17:\n init_hour = '12'\n elif int(hour) < 22:\n init_hour = '18'\n else:\n init_hour = '00'\n return init_hour\n\n\nurl = ('http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs' + mdate +\n '/gfs_0p25_1hr_' + get_init_hr(hour) + 'z')\ninit_hour = get_init_hr(hour)\n<mask token>\noutput_dir = str(year) + str(month) + str(day) + '_' + str(init_hour) + '00'\nmkdir_p(output_dir)\nmkdir_p(output_dir + '/GFS')\nds = xr.open_dataset(url)\ninit_hr = dt.datetime(int(year), int(month), int(day), int(init_hour))\ntimes = ds['tmp2m'].metpy.time\ninit_time = ds['time'][0]\nlats = np.arange(15, 70, 0.25)\nlons = np.arange(220, 330, 0.25)\nfor i in range(1, 120):\n fc_hr = init_hr + dt.timedelta(hours=1 * i)\n forecast_hour = times[0].values\n data = ds.metpy.parse_cf()\n data = data.isel(time=i)\n data = data.rename({'absvprs': 'avort', 'hgtprs': 'gph', 'rhprs': 'rh',\n 'tmpprs': 'temp', 'ugrdprs': 'u', 'vgrdprs': 'v'})\n vertical, = data['temp'].metpy.coordinates('vertical')\n time = data['temp'].metpy.time\n zH5_crs = data['temp'].metpy.cartopy_crs\n t5 = data['temp'].sel(lev=500.0, lat=lats, lon=lons)\n u5 = data['u'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 1.94384449\n v5 = data['v'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 1.94384449\n av5 = data['avort'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 100000.0\n rh5 = data['rh'].sel(lev=500.0, lat=lats, lon=lons).squeeze()\n h5 = data['gph'].sel(lev=500.0, lat=lats, lon=lons).squeeze()\n x, y = t5.metpy.coordinates('x', 'y')\n lat, lon = xr.broadcast(y, x)\n wind_slice = slice(5, -5, 5)\n fig = plt.figure(figsize=(15, 15))\n ax1 = fig.add_subplot(111, projection=zH5_crs)\n ax1.coastlines(resolution='10m')\n ax1.add_feature(cfeature.BORDERS.with_scale('10m'))\n ax1.add_feature(cfeature.STATES.with_scale('10m'))\n h5c = ax1.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200, \n 60), linewidths=1.5)\n t5c = ax1.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c = ax1.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 60, 2),\n alpha=0.8, extend='max')\n a5cb = fig.colorbar(a5c, orientation='horizontal', aspect=80, ax=ax1,\n pad=0.01, extendrect=False, ticks=range(10, 61, 5))\n a5cb.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax1.barbs(x[wind_slice], y[wind_slice], u5[wind_slice, wind_slice], v5[\n wind_slice, wind_slice], length=7)\n ax1.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax1.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax1.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax1.set_extent((265, 300, 25, 50))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vort_' + str(i) + '.png')\n plt.clf()\n plt.close()\n wind_slice_s = slice(10, -10, 10)\n fig2 = plt.figure(figsize=(15, 15))\n ax2 = fig2.add_subplot(111, projection=zH5_crs)\n ax2.coastlines(resolution='50m')\n ax2.add_feature(cfeature.BORDERS.with_scale('50m'))\n ax2.add_feature(cfeature.STATES.with_scale('50m'))\n h5c2 = ax2.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200,\n 60), linewidths=1.5)\n t5c2 = ax2.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c2 = ax2.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 65, 2),\n alpha=0.8)\n a5cb2 = fig2.colorbar(a5c2, orientation='horizontal', aspect=80, ax=ax2,\n pad=0.01, extendrect=False, ticks=range(10, 60, 5))\n a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax2.barbs(x[wind_slice_s], y[wind_slice_s], u5[wind_slice_s,\n wind_slice_s], v5[wind_slice_s, wind_slice_s], length=7)\n ax2.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax2.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax2.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax2.set_extent((225, 300, 20, 65))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vortCONUS_v2_' + str(i) + '.png')\n wind_slice_s = slice(10, -10, 10)\n fig3 = plt.figure(figsize=(15, 15))\n ax3 = fig3.add_subplot(111, projection=zH5_crs)\n ax3.coastlines(resolution='50m')\n ax3.add_feature(cfeature.BORDERS.with_scale('50m'))\n ax3.add_feature(cfeature.STATES.with_scale('50m'))\n h5c2 = ax3.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200,\n 60), linewidths=1.5)\n t5c2 = ax3.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c2 = ax3.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 65, 2),\n alpha=0.8)\n a5cb2 = fig3.colorbar(a5c2, orientation='horizontal', aspect=80, ax=ax3,\n pad=0.01, extendrect=False, ticks=range(10, 60, 5))\n a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax3.barbs(x[wind_slice_s], y[wind_slice_s], u5[wind_slice_s,\n wind_slice_s], v5[wind_slice_s, wind_slice_s], length=7)\n ax3.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax3.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax3.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax3.set_extent((260, 320, 20, 65))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vortC_ec_v1_' + str(i) + '.png')\n fcst_hr = str(0)\n print('Hour ' + str(i) + ' completed!')\n plt.close()\n timeelapsed = datetime.now() - startTime\n print(timeelapsed)\n<mask token>\n",
"step-4": "import cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport netCDF4\nimport xarray as xr\nimport metpy\nfrom datetime import datetime\nimport datetime as dt\nfrom metpy.units import units\nimport scipy.ndimage as ndimage\nfrom metpy.plots import USCOUNTIES\nimport cartopy\nfrom scipy.ndimage.filters import generic_filter as gf\n\n\ndef mkdir_p(mypath):\n \"\"\"Creates a directory. equivalent to using mkdir -p on the command line\"\"\"\n from errno import EEXIST\n from os import makedirs, path\n try:\n makedirs(mypath)\n except OSError as exc:\n if exc.errno == EEXIST and path.isdir(mypath):\n pass\n else:\n raise\n\n\nstartTime = datetime.now()\nm_date = '20200903'\nm_hour = '12'\nyear = startTime.year\nif startTime.month < 10:\n month = '0' + str(startTime.month)\nelse:\n month = str(startTime.month)\nif startTime.day < 10:\n day = '0' + str(startTime.day)\nelse:\n day = str(startTime.day)\nif startTime.hour < 10:\n hour = '0' + str(startTime.hour)\nelse:\n hour = str(startTime.hour)\nmdate = str(year) + str(month) + str(day)\n\n\ndef get_init_hr(hour):\n if int(hour) < 6:\n init_hour = '00'\n elif int(hour) < 11:\n init_hour = '06'\n elif int(hour) < 17:\n init_hour = '12'\n elif int(hour) < 22:\n init_hour = '18'\n else:\n init_hour = '00'\n return init_hour\n\n\nurl = ('http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs' + mdate +\n '/gfs_0p25_1hr_' + get_init_hr(hour) + 'z')\ninit_hour = get_init_hr(hour)\n<mask token>\noutput_dir = str(year) + str(month) + str(day) + '_' + str(init_hour) + '00'\nmkdir_p(output_dir)\nmkdir_p(output_dir + '/GFS')\nds = xr.open_dataset(url)\ninit_hr = dt.datetime(int(year), int(month), int(day), int(init_hour))\ntimes = ds['tmp2m'].metpy.time\ninit_time = ds['time'][0]\nlats = np.arange(15, 70, 0.25)\nlons = np.arange(220, 330, 0.25)\nfor i in range(1, 120):\n fc_hr = init_hr + dt.timedelta(hours=1 * i)\n forecast_hour = times[0].values\n data = ds.metpy.parse_cf()\n data = data.isel(time=i)\n data = data.rename({'absvprs': 'avort', 'hgtprs': 'gph', 'rhprs': 'rh',\n 'tmpprs': 'temp', 'ugrdprs': 'u', 'vgrdprs': 'v'})\n vertical, = data['temp'].metpy.coordinates('vertical')\n time = data['temp'].metpy.time\n zH5_crs = data['temp'].metpy.cartopy_crs\n t5 = data['temp'].sel(lev=500.0, lat=lats, lon=lons)\n u5 = data['u'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 1.94384449\n v5 = data['v'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 1.94384449\n av5 = data['avort'].sel(lev=500.0, lat=lats, lon=lons).squeeze() * 100000.0\n rh5 = data['rh'].sel(lev=500.0, lat=lats, lon=lons).squeeze()\n h5 = data['gph'].sel(lev=500.0, lat=lats, lon=lons).squeeze()\n x, y = t5.metpy.coordinates('x', 'y')\n lat, lon = xr.broadcast(y, x)\n wind_slice = slice(5, -5, 5)\n fig = plt.figure(figsize=(15, 15))\n ax1 = fig.add_subplot(111, projection=zH5_crs)\n ax1.coastlines(resolution='10m')\n ax1.add_feature(cfeature.BORDERS.with_scale('10m'))\n ax1.add_feature(cfeature.STATES.with_scale('10m'))\n h5c = ax1.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200, \n 60), linewidths=1.5)\n t5c = ax1.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c = ax1.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 60, 2),\n alpha=0.8, extend='max')\n a5cb = fig.colorbar(a5c, orientation='horizontal', aspect=80, ax=ax1,\n pad=0.01, extendrect=False, ticks=range(10, 61, 5))\n a5cb.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax1.barbs(x[wind_slice], y[wind_slice], u5[wind_slice, wind_slice], v5[\n wind_slice, wind_slice], length=7)\n ax1.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax1.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax1.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax1.set_extent((265, 300, 25, 50))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vort_' + str(i) + '.png')\n plt.clf()\n plt.close()\n wind_slice_s = slice(10, -10, 10)\n fig2 = plt.figure(figsize=(15, 15))\n ax2 = fig2.add_subplot(111, projection=zH5_crs)\n ax2.coastlines(resolution='50m')\n ax2.add_feature(cfeature.BORDERS.with_scale('50m'))\n ax2.add_feature(cfeature.STATES.with_scale('50m'))\n h5c2 = ax2.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200,\n 60), linewidths=1.5)\n t5c2 = ax2.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c2 = ax2.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 65, 2),\n alpha=0.8)\n a5cb2 = fig2.colorbar(a5c2, orientation='horizontal', aspect=80, ax=ax2,\n pad=0.01, extendrect=False, ticks=range(10, 60, 5))\n a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax2.barbs(x[wind_slice_s], y[wind_slice_s], u5[wind_slice_s,\n wind_slice_s], v5[wind_slice_s, wind_slice_s], length=7)\n ax2.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax2.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax2.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax2.set_extent((225, 300, 20, 65))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vortCONUS_v2_' + str(i) + '.png')\n wind_slice_s = slice(10, -10, 10)\n fig3 = plt.figure(figsize=(15, 15))\n ax3 = fig3.add_subplot(111, projection=zH5_crs)\n ax3.coastlines(resolution='50m')\n ax3.add_feature(cfeature.BORDERS.with_scale('50m'))\n ax3.add_feature(cfeature.STATES.with_scale('50m'))\n h5c2 = ax3.contour(x, y, h5, colors='dimgray', levels=range(4800, 6200,\n 60), linewidths=1.5)\n t5c2 = ax3.contour(x, y, t5, colors='r', levels=range(-60, 0, 5),\n linestyles='dashed', linewidths=1)\n a5c2 = ax3.contourf(x, y, av5, cmap='autumn_r', levels=range(10, 65, 2),\n alpha=0.8)\n a5cb2 = fig3.colorbar(a5c2, orientation='horizontal', aspect=80, ax=ax3,\n pad=0.01, extendrect=False, ticks=range(10, 60, 5))\n a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize=12)\n ax3.barbs(x[wind_slice_s], y[wind_slice_s], u5[wind_slice_s,\n wind_slice_s], v5[wind_slice_s, wind_slice_s], length=7)\n ax3.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',\n fontsize=16)\n ax3.set_title('\\n Valid: ' + time.dt.strftime('%Y-%m-%d %H:%MZ').item(),\n fontsize=11, loc='right')\n ax3.set_title('\\n GFS Init: ' + init_time.dt.strftime('%Y-%m-%d %H:%MZ'\n ).item(), fontsize=11, loc='left')\n ax3.set_extent((260, 320, 20, 65))\n plt.savefig(output_dir + '/GFS/gfs_hrly_h5vortC_ec_v1_' + str(i) + '.png')\n fcst_hr = str(0)\n print('Hour ' + str(i) + ' completed!')\n plt.close()\n timeelapsed = datetime.now() - startTime\n print(timeelapsed)\n<mask token>\n",
"step-5": "import cartopy.crs as ccrs\r\nimport cartopy.feature as cfeature\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport netCDF4\r\nimport xarray as xr\r\nimport metpy\r\nfrom datetime import datetime\r\nimport datetime as dt\r\nfrom metpy.units import units\r\nimport scipy.ndimage as ndimage\r\nfrom metpy.plots import USCOUNTIES\r\nimport cartopy\r\nfrom scipy.ndimage.filters import generic_filter as gf\r\n\r\n\r\ndef mkdir_p(mypath):\r\n '''Creates a directory. equivalent to using mkdir -p on the command line'''\r\n\r\n from errno import EEXIST\r\n from os import makedirs,path\r\n\r\n try:\r\n makedirs(mypath)\r\n except OSError as exc: # Python >2.5\r\n if exc.errno == EEXIST and path.isdir(mypath):\r\n pass\r\n else: raise\r\n\r\nstartTime=datetime.now()\r\n\r\nm_date='20200903'\r\nm_hour='12'\r\n\r\nyear = startTime.year\r\n\r\nif startTime.month <10:\r\n month = '0'+str(startTime.month)\r\nelse:\r\n month = str(startTime.month)\r\n\r\nif startTime.day <10:\r\n day = '0'+str(startTime.day)\r\nelse:\r\n day = str(startTime.day)\r\n\r\nif startTime.hour <10:\r\n hour = '0'+str(startTime.hour)\r\nelse:\r\n hour = str(startTime.hour)\r\n\r\nmdate = str(year)+str(month)+str(day)\r\n\r\ndef get_init_hr(hour):\r\n if int(hour) <6:\r\n init_hour = '00'\r\n elif int(hour) <11:\r\n init_hour = '06'\r\n elif int(hour) <17:\r\n init_hour = '12'\r\n elif int(hour) <22:\r\n init_hour = '18'\r\n else:\r\n init_hour = '00'\r\n return(init_hour)\r\n\r\nurl = 'http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs'+mdate+'/gfs_0p25_1hr_'+get_init_hr(hour)+'z'\r\ninit_hour = get_init_hr(hour)\r\n'''\r\nfor i in range(119):\r\n fhr = i+1\r\n'''\r\n# Create new directory\r\noutput_dir = str(year)+str(month)+str(day)+'_'+str(init_hour)+'00'\r\nmkdir_p(output_dir)\r\nmkdir_p(output_dir+'/GFS')\r\n#Parse data using MetPy\r\nds = xr.open_dataset(url)\r\ninit_hr = dt.datetime(int(year),int(month),int(day),int(init_hour))\r\ntimes = ds['tmp2m'].metpy.time\r\ninit_time = ds['time'][0]\r\n\r\nlats = np.arange(15,70,0.25)\r\nlons = np.arange(220,330,0.25)\r\n\r\nfor i in range(1,120):\r\n fc_hr = init_hr+dt.timedelta(hours=1*i)\r\n forecast_hour = times[0].values\r\n\r\n data = ds.metpy.parse_cf()\r\n data = data.isel(time=i)\r\n #Rename variables to useful things\r\n data = data.rename({\r\n 'absvprs':'avort',\r\n 'hgtprs':'gph',\r\n 'rhprs':'rh',\r\n 'tmpprs':'temp',\r\n 'ugrdprs':'u',\r\n 'vgrdprs': 'v',\r\n })\r\n\r\n vertical, = data['temp'].metpy.coordinates('vertical')\r\n time = data['temp'].metpy.time\r\n zH5_crs = data['temp'].metpy.cartopy_crs\r\n\r\n t5 = data['temp'].sel(lev=500.0,lat=lats,lon=lons)\r\n u5 = data['u'].sel(lev=500.0,lat=lats,lon=lons).squeeze()*1.94384449\r\n v5 = data['v'].sel(lev=500.0,lat=lats,lon=lons).squeeze()*1.94384449\r\n av5 = data['avort'].sel(lev=500.0,lat=lats,lon=lons).squeeze()*1e5\r\n rh5 = data['rh'].sel(lev=500.0,lat=lats,lon=lons).squeeze()\r\n h5 = data['gph'].sel(lev=500.0,lat=lats,lon=lons).squeeze()\r\n x, y = t5.metpy.coordinates('x', 'y')\r\n lat, lon = xr.broadcast(y, x)\r\n wind_slice = slice(5,-5,5)\r\n ########## SET UP FIGURE ##################################################\r\n fig = plt.figure(figsize=(15,15))\r\n ax1 = fig.add_subplot(111, projection = zH5_crs)\r\n\r\n ax1.coastlines(resolution='10m')\r\n ax1.add_feature(cfeature.BORDERS.with_scale('10m'))\r\n ax1.add_feature(cfeature.STATES.with_scale('10m'))\r\n\r\n #fig.suptitle(\"NAM Forecast valid at \" + time[0].dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=36)\r\n\r\n ########## PLOTTING #######################################################\r\n h5c = ax1.contour(x,y,h5,colors='dimgray', levels = range(4800,6200,60),linewidths=1.5)\r\n t5c = ax1.contour(x,y,t5,colors='r', levels = range(-60,0,5),linestyles='dashed',linewidths=1)\r\n a5c = ax1.contourf(x,y,av5,cmap='autumn_r',levels=range(10,60,2),alpha=0.8,extend='max')\r\n a5cb = fig.colorbar(a5c, orientation = 'horizontal', aspect = 80, ax = ax1, pad = 0.01,\r\n extendrect=False, ticks = range(10,61,5))\r\n a5cb.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize = 12)\r\n ax1.barbs(x[wind_slice],y[wind_slice],u5[wind_slice,wind_slice],v5[wind_slice,wind_slice], length=7)\r\n\r\n #h_contour = ax1.contour(x, y, mslpc, colors='dimgray', levels=range(940,1040,4),linewidths=2)\r\n #h_contour.clabel(fontsize=14, colors='dimgray', inline=1, inline_spacing=4, fmt='%i mb', rightside_up=True, use_clabeltext=True)\r\n ax1.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',fontsize=16)\r\n ax1.set_title('\\n Valid: '+time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='right')\r\n ax1.set_title('\\n GFS Init: '+init_time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='left')\r\n ax1.set_extent((265, 300, 25, 50))#, crs = zH5_crs) # Set a title and show the plot\r\n plt.savefig(output_dir+'/GFS/gfs_hrly_h5vort_'+str(i)+'.png')\r\n plt.clf()\r\n plt.close()\r\n ########## PLOT 2 #######################################################\r\n wind_slice_s = slice (10,-10,10)\r\n fig2 = plt.figure(figsize=(15,15))\r\n ax2 = fig2.add_subplot(111,projection=zH5_crs)\r\n ax2.coastlines(resolution='50m')\r\n ax2.add_feature(cfeature.BORDERS.with_scale('50m'))\r\n ax2.add_feature(cfeature.STATES.with_scale('50m'))\r\n h5c2 = ax2.contour(x,y,h5,colors='dimgray', levels = range(4800,6200,60),linewidths=1.5)\r\n t5c2 = ax2.contour(x,y,t5,colors='r', levels = range(-60,0,5),linestyles='dashed',linewidths=1)\r\n a5c2 = ax2.contourf(x,y,av5,cmap='autumn_r',levels=range(10,65,2),alpha=0.8)\r\n a5cb2 = fig2.colorbar(a5c2, orientation = 'horizontal', aspect = 80, ax = ax2, pad = 0.01,\r\n extendrect=False, ticks = range(10,60,5))\r\n a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize = 12)\r\n ax2.barbs(x[wind_slice_s],y[wind_slice_s],u5[wind_slice_s,wind_slice_s],v5[wind_slice_s,wind_slice_s], length=7)\r\n\r\n #h_contour = ax1.contour(x, y, mslpc, colors='dimgray', levels=range(940,1040,4),linewidths=2)\r\n #h_contour.clabel(fontsize=14, colors='dimgray', inline=1, inline_spacing=4, fmt='%i mb', rightside_up=True, use_clabeltext=True)\r\n ax2.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',fontsize=16)\r\n ax2.set_title('\\n Valid: '+time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='right')\r\n ax2.set_title('\\n GFS Init: '+init_time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='left')\r\n ax2.set_extent((225, 300, 20, 65))#, crs = zH5_crs) # Set a title and show the plot\r\n plt.savefig(output_dir+'/GFS/gfs_hrly_h5vortCONUS_v2_'+str(i)+'.png')\r\n\r\n ########## PLOT 3 #######################################################\r\n wind_slice_s = slice (10,-10,10)\r\n fig3 = plt.figure(figsize=(15,15))\r\n ax3 = fig3.add_subplot(111,projection=zH5_crs)\r\n ax3.coastlines(resolution='50m')\r\n ax3.add_feature(cfeature.BORDERS.with_scale('50m'))\r\n ax3.add_feature(cfeature.STATES.with_scale('50m'))\r\n h5c2 = ax3.contour(x,y,h5,colors='dimgray', levels = range(4800,6200,60),linewidths=1.5)\r\n t5c2 = ax3.contour(x,y,t5,colors='r', levels = range(-60,0,5),linestyles='dashed',linewidths=1)\r\n a5c2 = ax3.contourf(x,y,av5,cmap='autumn_r',levels=range(10,65,2),alpha=0.8)\r\n a5cb2 = fig3.colorbar(a5c2, orientation = 'horizontal', aspect = 80, ax = ax3, pad = 0.01,\r\n extendrect=False, ticks = range(10,60,5))\r\n a5cb2.set_label('500mb Absolute Vorticity ($s^{-1}$)', fontsize = 12)\r\n ax3.barbs(x[wind_slice_s],y[wind_slice_s],u5[wind_slice_s,wind_slice_s],v5[wind_slice_s,wind_slice_s], length=7)\r\n\r\n #h_contour = ax1.contour(x, y, mslpc, colors='dimgray', levels=range(940,1040,4),linewidths=2)\r\n #h_contour.clabel(fontsize=14, colors='dimgray', inline=1, inline_spacing=4, fmt='%i mb', rightside_up=True, use_clabeltext=True)\r\n ax3.set_title('500mb Heights (m) and Absolute Vorticity ($s^{-1}$)',fontsize=16)\r\n ax3.set_title('\\n Valid: '+time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='right')\r\n ax3.set_title('\\n GFS Init: '+init_time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='left')\r\n ax3.set_extent((260, 320, 20, 65))#, crs = zH5_crs) # Set a title and show the plot\r\n plt.savefig(output_dir+'/GFS/gfs_hrly_h5vortC_ec_v1_'+str(i)+'.png')\r\n\r\n fcst_hr = str(0)\r\n print('Hour '+str(i)+' completed!')\r\n plt.close()\r\n timeelapsed = datetime.now()-startTime\r\n print(timeelapsed)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n'''\r\nurl= 'http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs20200903/gfs_0p25_1hr_12z'\r\nds = xr.open_dataset(url)\r\nt2m_ds = ds['tmp2m']\r\ninit_hr = t2m_ds['time'][0].values\r\n#fc_hr = t2m.ds['time'][i].values\r\nlats = np.arange(20,50,0.25)\r\nlons = np.arange(240,300,0.25)\r\nt2m = t2m_ds.sel(time = init_hr, lat = lats, lon = lons)\r\nprint(t2m)\r\n\r\nfig = plt.figure(figsize = (12,12))\r\nfig.clf()\r\nax = plt.axes(projection=ccrs.PlateCarree())\r\nax.coastlines()\r\nax.set_extent((240,300, 20, 50), crs = ccrs.PlateCarree())\r\nt2m_c = ax.contourf(t2m, cmap='RdPu')\r\nplt.savefig('testingnomads6.png')\r\n'''\r\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
import asyncio
import logging
import os
from async_cron.job import CronJob
from async_cron.schedule import Scheduler
from sqlalchemy import asc
import spider
import squid
import verifier
from db import sess_maker
from model import Proxy, STATUS_OK, STATUS_ERROR
from server import run_api_server
from tool import logger, cron_wait
from verifier import verify_error_proxy
logging.basicConfig(
level=logging.INFO,
datefmt='%Y/%m/%d %H:%M:%S',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
VERIFY_ERROR_LIMIT = int(os.getenv("VERIFY_ERROR_LIMIT", 100))
MAX_ERROR_PROXIES = int(os.getenv("MAX_ERROR_PROXIES", 2048))
@cron_wait
async def verify_error_proxy_task():
logger.info("run verify_error_proxy_task")
s = sess_maker()
c = s.query(Proxy).filter(Proxy.status == STATUS_OK).count()
s.close()
if c < VERIFY_ERROR_LIMIT:
await verify_error_proxy()
s = sess_maker()
c = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).count()
if c > MAX_ERROR_PROXIES:
res = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).order_by(asc(Proxy.updated_at)).limit(
c - MAX_ERROR_PROXIES).from_self().all()
[s.delete(i) for i in res]
s.commit()
@cron_wait
async def update_squid_task():
logger.info("run update_squid_task")
s = sess_maker()
proxies = s.query(Proxy).filter(Proxy.status == STATUS_OK).all()
s.close()
squid.update_conf(proxies)
@cron_wait
async def verify_ok_proxy_task():
logger.info("run verify_ok_proxy_task")
await verifier.verify_ok_proxy()
await verify_error_proxy_task()
await update_squid_task()
@cron_wait
async def fetch_new_proxy_task():
logger.info("run fetch_new_proxy_task")
await spider.run_spider()
await verifier.verify_new_proxy()
# await verify_error_proxy_task()
await update_squid_task()
if __name__ == '__main__':
logger.info("start")
loop = asyncio.get_event_loop()
loop.run_until_complete(update_squid_task())
msh = Scheduler()
msh.add_job(CronJob().every(10).minute.go(verify_ok_proxy_task))
msh.add_job(CronJob().every(30).minute.go(fetch_new_proxy_task))
try:
loop.run_until_complete(asyncio.wait([
msh.start(),
run_api_server(),
]))
loop.run_forever()
except KeyboardInterrupt:
print('exit')
|
normal
|
{
"blob_id": "1d529e2ea5526ddcda0d0da30ed8ed4724002c63",
"index": 7074,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nlogging.basicConfig(level=logging.INFO, datefmt='%Y/%m/%d %H:%M:%S', format\n ='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n<mask token>\n\n\n@cron_wait\nasync def verify_error_proxy_task():\n logger.info('run verify_error_proxy_task')\n s = sess_maker()\n c = s.query(Proxy).filter(Proxy.status == STATUS_OK).count()\n s.close()\n if c < VERIFY_ERROR_LIMIT:\n await verify_error_proxy()\n s = sess_maker()\n c = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).count()\n if c > MAX_ERROR_PROXIES:\n res = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).order_by(asc\n (Proxy.updated_at)).limit(c - MAX_ERROR_PROXIES).from_self().all()\n [s.delete(i) for i in res]\n s.commit()\n\n\n@cron_wait\nasync def update_squid_task():\n logger.info('run update_squid_task')\n s = sess_maker()\n proxies = s.query(Proxy).filter(Proxy.status == STATUS_OK).all()\n s.close()\n squid.update_conf(proxies)\n\n\n@cron_wait\nasync def verify_ok_proxy_task():\n logger.info('run verify_ok_proxy_task')\n await verifier.verify_ok_proxy()\n await verify_error_proxy_task()\n await update_squid_task()\n\n\n@cron_wait\nasync def fetch_new_proxy_task():\n logger.info('run fetch_new_proxy_task')\n await spider.run_spider()\n await verifier.verify_new_proxy()\n await update_squid_task()\n\n\nif __name__ == '__main__':\n logger.info('start')\n loop = asyncio.get_event_loop()\n loop.run_until_complete(update_squid_task())\n msh = Scheduler()\n msh.add_job(CronJob().every(10).minute.go(verify_ok_proxy_task))\n msh.add_job(CronJob().every(30).minute.go(fetch_new_proxy_task))\n try:\n loop.run_until_complete(asyncio.wait([msh.start(), run_api_server()]))\n loop.run_forever()\n except KeyboardInterrupt:\n print('exit')\n",
"step-3": "<mask token>\nlogging.basicConfig(level=logging.INFO, datefmt='%Y/%m/%d %H:%M:%S', format\n ='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nVERIFY_ERROR_LIMIT = int(os.getenv('VERIFY_ERROR_LIMIT', 100))\nMAX_ERROR_PROXIES = int(os.getenv('MAX_ERROR_PROXIES', 2048))\n\n\n@cron_wait\nasync def verify_error_proxy_task():\n logger.info('run verify_error_proxy_task')\n s = sess_maker()\n c = s.query(Proxy).filter(Proxy.status == STATUS_OK).count()\n s.close()\n if c < VERIFY_ERROR_LIMIT:\n await verify_error_proxy()\n s = sess_maker()\n c = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).count()\n if c > MAX_ERROR_PROXIES:\n res = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).order_by(asc\n (Proxy.updated_at)).limit(c - MAX_ERROR_PROXIES).from_self().all()\n [s.delete(i) for i in res]\n s.commit()\n\n\n@cron_wait\nasync def update_squid_task():\n logger.info('run update_squid_task')\n s = sess_maker()\n proxies = s.query(Proxy).filter(Proxy.status == STATUS_OK).all()\n s.close()\n squid.update_conf(proxies)\n\n\n@cron_wait\nasync def verify_ok_proxy_task():\n logger.info('run verify_ok_proxy_task')\n await verifier.verify_ok_proxy()\n await verify_error_proxy_task()\n await update_squid_task()\n\n\n@cron_wait\nasync def fetch_new_proxy_task():\n logger.info('run fetch_new_proxy_task')\n await spider.run_spider()\n await verifier.verify_new_proxy()\n await update_squid_task()\n\n\nif __name__ == '__main__':\n logger.info('start')\n loop = asyncio.get_event_loop()\n loop.run_until_complete(update_squid_task())\n msh = Scheduler()\n msh.add_job(CronJob().every(10).minute.go(verify_ok_proxy_task))\n msh.add_job(CronJob().every(30).minute.go(fetch_new_proxy_task))\n try:\n loop.run_until_complete(asyncio.wait([msh.start(), run_api_server()]))\n loop.run_forever()\n except KeyboardInterrupt:\n print('exit')\n",
"step-4": "import asyncio\nimport logging\nimport os\nfrom async_cron.job import CronJob\nfrom async_cron.schedule import Scheduler\nfrom sqlalchemy import asc\nimport spider\nimport squid\nimport verifier\nfrom db import sess_maker\nfrom model import Proxy, STATUS_OK, STATUS_ERROR\nfrom server import run_api_server\nfrom tool import logger, cron_wait\nfrom verifier import verify_error_proxy\nlogging.basicConfig(level=logging.INFO, datefmt='%Y/%m/%d %H:%M:%S', format\n ='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nVERIFY_ERROR_LIMIT = int(os.getenv('VERIFY_ERROR_LIMIT', 100))\nMAX_ERROR_PROXIES = int(os.getenv('MAX_ERROR_PROXIES', 2048))\n\n\n@cron_wait\nasync def verify_error_proxy_task():\n logger.info('run verify_error_proxy_task')\n s = sess_maker()\n c = s.query(Proxy).filter(Proxy.status == STATUS_OK).count()\n s.close()\n if c < VERIFY_ERROR_LIMIT:\n await verify_error_proxy()\n s = sess_maker()\n c = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).count()\n if c > MAX_ERROR_PROXIES:\n res = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).order_by(asc\n (Proxy.updated_at)).limit(c - MAX_ERROR_PROXIES).from_self().all()\n [s.delete(i) for i in res]\n s.commit()\n\n\n@cron_wait\nasync def update_squid_task():\n logger.info('run update_squid_task')\n s = sess_maker()\n proxies = s.query(Proxy).filter(Proxy.status == STATUS_OK).all()\n s.close()\n squid.update_conf(proxies)\n\n\n@cron_wait\nasync def verify_ok_proxy_task():\n logger.info('run verify_ok_proxy_task')\n await verifier.verify_ok_proxy()\n await verify_error_proxy_task()\n await update_squid_task()\n\n\n@cron_wait\nasync def fetch_new_proxy_task():\n logger.info('run fetch_new_proxy_task')\n await spider.run_spider()\n await verifier.verify_new_proxy()\n await update_squid_task()\n\n\nif __name__ == '__main__':\n logger.info('start')\n loop = asyncio.get_event_loop()\n loop.run_until_complete(update_squid_task())\n msh = Scheduler()\n msh.add_job(CronJob().every(10).minute.go(verify_ok_proxy_task))\n msh.add_job(CronJob().every(30).minute.go(fetch_new_proxy_task))\n try:\n loop.run_until_complete(asyncio.wait([msh.start(), run_api_server()]))\n loop.run_forever()\n except KeyboardInterrupt:\n print('exit')\n",
"step-5": "import asyncio\nimport logging\nimport os\n\nfrom async_cron.job import CronJob\nfrom async_cron.schedule import Scheduler\nfrom sqlalchemy import asc\n\nimport spider\nimport squid\nimport verifier\nfrom db import sess_maker\nfrom model import Proxy, STATUS_OK, STATUS_ERROR\nfrom server import run_api_server\nfrom tool import logger, cron_wait\nfrom verifier import verify_error_proxy\n\nlogging.basicConfig(\n level=logging.INFO,\n datefmt='%Y/%m/%d %H:%M:%S',\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\n\nVERIFY_ERROR_LIMIT = int(os.getenv(\"VERIFY_ERROR_LIMIT\", 100))\nMAX_ERROR_PROXIES = int(os.getenv(\"MAX_ERROR_PROXIES\", 2048))\n\n\n@cron_wait\nasync def verify_error_proxy_task():\n logger.info(\"run verify_error_proxy_task\")\n s = sess_maker()\n c = s.query(Proxy).filter(Proxy.status == STATUS_OK).count()\n s.close()\n if c < VERIFY_ERROR_LIMIT:\n await verify_error_proxy()\n\n s = sess_maker()\n c = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).count()\n if c > MAX_ERROR_PROXIES:\n res = s.query(Proxy).filter(Proxy.status == STATUS_ERROR).order_by(asc(Proxy.updated_at)).limit(\n c - MAX_ERROR_PROXIES).from_self().all()\n [s.delete(i) for i in res]\n s.commit()\n\n\n@cron_wait\nasync def update_squid_task():\n logger.info(\"run update_squid_task\")\n s = sess_maker()\n proxies = s.query(Proxy).filter(Proxy.status == STATUS_OK).all()\n s.close()\n squid.update_conf(proxies)\n\n\n@cron_wait\nasync def verify_ok_proxy_task():\n logger.info(\"run verify_ok_proxy_task\")\n await verifier.verify_ok_proxy()\n await verify_error_proxy_task()\n await update_squid_task()\n\n\n@cron_wait\nasync def fetch_new_proxy_task():\n logger.info(\"run fetch_new_proxy_task\")\n await spider.run_spider()\n await verifier.verify_new_proxy()\n # await verify_error_proxy_task()\n await update_squid_task()\n\n\nif __name__ == '__main__':\n logger.info(\"start\")\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(update_squid_task())\n\n msh = Scheduler()\n msh.add_job(CronJob().every(10).minute.go(verify_ok_proxy_task))\n msh.add_job(CronJob().every(30).minute.go(fetch_new_proxy_task))\n try:\n loop.run_until_complete(asyncio.wait([\n msh.start(),\n run_api_server(),\n ]))\n loop.run_forever()\n except KeyboardInterrupt:\n print('exit')\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from applitools.selenium import Target, eyes
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
def test_verify_home_page(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Home Page")
eyes.check("FZ IBE Home page", Target.window())
eyes.close(False)
def test_verify_search_widget(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Search Widget")
eyes.check("FZ Search Widget", Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_manage_booking_widget(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Manage Booking Widget")
driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(2)').click()
eyes.check("FZ Manage Booking Widget", Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_checkin_widget(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Checkin Widget")
driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(3)').click()
eyes.check("FZ Manage Booking Widget", Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_flight_status_widget(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Flight Status Widget")
driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(4)').click()
eyes.check("FZ Manage Booking Widget", Target.region('div.widgetBoxWrapper'))
eyes.close(False)
def test_verify_search_ow_results_page(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Flight listing page")
driver.find_element_by_css_selector('div.widgetBoxWrapper .radio-oneway-div').click()
driver.find_element_by_css_selector('div.widgetBoxWrapper #airport-destination').click()
driver.find_element_by_css_selector('.DestinationAirlist li[data-value=\'MCT\']').click()
driver.execute_script('date = new Date();date.setDate(date.getDate()+20);document.getElementById("FormModel_DepartureDate").value=""+date')
driver.find_element_by_css_selector("div.widgetBoxWrapper input[value='Search']").click()
WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.tripSummaryBox')))
eyes.check("FZ Manage Booking Widget", Target.window())
eyes.close(False)
|
normal
|
{
"blob_id": "021efe01c21db4d3bd936ba4eb75dc03dde91cc6",
"index": 1475,
"step-1": "<mask token>\n\n\ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')\n eyes.check('FZ IBE Home page', Target.window())\n eyes.close(False)\n\n\n<mask token>\n\n\ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')\n eyes.check('FZ IBE Home page', Target.window())\n eyes.close(False)\n\n\n<mask token>\n\n\ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_search_ow_results_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper .radio-oneway-div').click()\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper #airport-destination').click()\n driver.find_element_by_css_selector(\n \".DestinationAirlist li[data-value='MCT']\").click()\n driver.execute_script(\n 'date = new Date();date.setDate(date.getDate()+20);document.getElementById(\"FormModel_DepartureDate\").value=\"\"+date'\n )\n driver.find_element_by_css_selector(\n \"div.widgetBoxWrapper input[value='Search']\").click()\n WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By\n .CSS_SELECTOR, '.tripSummaryBox')))\n eyes.check('FZ Manage Booking Widget', Target.window())\n eyes.close(False)\n",
"step-3": "<mask token>\n\n\ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')\n eyes.check('FZ IBE Home page', Target.window())\n eyes.close(False)\n\n\ndef test_verify_search_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Search Widget')\n eyes.check('FZ Search Widget', Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_search_ow_results_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper .radio-oneway-div').click()\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper #airport-destination').click()\n driver.find_element_by_css_selector(\n \".DestinationAirlist li[data-value='MCT']\").click()\n driver.execute_script(\n 'date = new Date();date.setDate(date.getDate()+20);document.getElementById(\"FormModel_DepartureDate\").value=\"\"+date'\n )\n driver.find_element_by_css_selector(\n \"div.widgetBoxWrapper input[value='Search']\").click()\n WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By\n .CSS_SELECTOR, '.tripSummaryBox')))\n eyes.check('FZ Manage Booking Widget', Target.window())\n eyes.close(False)\n",
"step-4": "from applitools.selenium import Target, eyes\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Home Page')\n eyes.check('FZ IBE Home page', Target.window())\n eyes.close(False)\n\n\ndef test_verify_search_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Search Widget')\n eyes.check('FZ Search Widget', Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Manage Booking Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Checkin Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight Status Widget')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check('FZ Manage Booking Widget', Target.region(\n 'div.widgetBoxWrapper'))\n eyes.close(False)\n\n\ndef test_verify_search_ow_results_page(eyes, driver):\n eyes.open(driver, 'FlyDubai IBE', 'Verify Flight listing page')\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper .radio-oneway-div').click()\n driver.find_element_by_css_selector(\n 'div.widgetBoxWrapper #airport-destination').click()\n driver.find_element_by_css_selector(\n \".DestinationAirlist li[data-value='MCT']\").click()\n driver.execute_script(\n 'date = new Date();date.setDate(date.getDate()+20);document.getElementById(\"FormModel_DepartureDate\").value=\"\"+date'\n )\n driver.find_element_by_css_selector(\n \"div.widgetBoxWrapper input[value='Search']\").click()\n WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By\n .CSS_SELECTOR, '.tripSummaryBox')))\n eyes.check('FZ Manage Booking Widget', Target.window())\n eyes.close(False)\n",
"step-5": "from applitools.selenium import Target, eyes\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n \ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Home Page\")\n eyes.check(\"FZ IBE Home page\", Target.window())\n eyes.close(False)\n \ndef test_verify_search_widget(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Search Widget\")\n eyes.check(\"FZ Search Widget\", Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n \ndef test_verify_manage_booking_widget(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Manage Booking Widget\")\n driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(2)').click()\n eyes.check(\"FZ Manage Booking Widget\", Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n \ndef test_verify_checkin_widget(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Checkin Widget\")\n driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(3)').click()\n eyes.check(\"FZ Manage Booking Widget\", Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n \ndef test_verify_flight_status_widget(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Flight Status Widget\")\n driver.find_element_by_css_selector('div.widgetBoxWrapper > ul li:nth-of-type(4)').click()\n eyes.check(\"FZ Manage Booking Widget\", Target.region('div.widgetBoxWrapper'))\n eyes.close(False)\n \ndef test_verify_search_ow_results_page(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Flight listing page\")\n driver.find_element_by_css_selector('div.widgetBoxWrapper .radio-oneway-div').click()\n driver.find_element_by_css_selector('div.widgetBoxWrapper #airport-destination').click()\n driver.find_element_by_css_selector('.DestinationAirlist li[data-value=\\'MCT\\']').click()\n driver.execute_script('date = new Date();date.setDate(date.getDate()+20);document.getElementById(\"FormModel_DepartureDate\").value=\"\"+date')\n driver.find_element_by_css_selector(\"div.widgetBoxWrapper input[value='Search']\").click()\n WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.tripSummaryBox')))\n eyes.check(\"FZ Manage Booking Widget\", Target.window())\n eyes.close(False)",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
#!/usr/bin/env python
number=int(input("Enter an integer"))
if number<=100:
print("Your number is smaller than equal to 100")
else:
print("Your number is greater than 100")
|
normal
|
{
"blob_id": "9666c87b4d4dc721683ea33fdbbeadefc65a0cd1",
"index": 1860,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif number <= 100:\n print('Your number is smaller than equal to 100')\nelse:\n print('Your number is greater than 100')\n",
"step-3": "number = int(input('Enter an integer'))\nif number <= 100:\n print('Your number is smaller than equal to 100')\nelse:\n print('Your number is greater than 100')\n",
"step-4": "#!/usr/bin/env python\n\nnumber=int(input(\"Enter an integer\"))\nif number<=100:\n print(\"Your number is smaller than equal to 100\")\nelse:\n print(\"Your number is greater than 100\")\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from . import preprocess
from . import utils
import random
import pickle
import feather
import time
import datetime
import sys
import os
import numpy as np
import pandas as pd
import json
from ...main import api
from flask import request
from flask_restplus import Resource, fields
import warnings
warnings.simplefilter("ignore")
predict_fields = api.model('Prediction Data', {
})
predict_accounts = api.model('Prediction Data By Employee', {
})
prediction = api.model('Prediction', {'attritionproba': fields.Float(
example=0.345), 'attritiondate': fields.String(example='2020-10-06T00:00:00.000Z')})
predictionByEmployee = api.model('Prediction By Employee', {})
model = api.model(
'Predictions', {'predictions': fields.List(fields.Nested(prediction))})
modelByEmployee = api.model(
'Predictions By Employee', {'predictions': fields.List(fields.Nested(predictionByEmployee))})
parser = api.parser()
parser.add_argument('predictdate', location='args', default=datetime.date.today().strftime("%Y-%m-%d"), help='Predict date', required=True)
@api.route("/predict")
@api.expect(parser)
class Predict(Resource):
@api.expect(predict_fields)
@api.marshal_with(model)
def post(self):
args = parser.parse_args()
return getPrediction(request.get_json(), args['predictdate'])
@api.route("/predict/<string:companyid>/<string:accountid>")
@api.expect(parser)
class PredictEmployeeByCompany(Resource):
@api.marshal_with(modelByEmployee)
def get(self, companyid, accountid):
args = parser.parse_args()
return getPredictionByEmployee(companyid, [int(accountid)], args['predictdate'])
@api.route("/predict/<string:companyid>")
@api.expect(parser)
class PredictByCompany(Resource):
@api.marshal_with(modelByEmployee)
def get(self, companyid):
args = parser.parse_args()
return getPredictionByEmployee(companyid, None, args['predictdate'])
@api.expect(predict_accounts)
@api.marshal_with(modelByEmployee)
def post(self, companyid):
args = parser.parse_args()
return getPredictionByEmployee(companyid, request.get_json()['accountids'], args['predictdate'])
package_directory = os.path.dirname(os.path.abspath(__file__))
def predict_class(local_model, df):
if os.path.isfile(local_model):
model = pickle.load(open(local_model, 'rb'))
result = pd.Series(model.predict_proba(df)[:, 1])
else:
result = pd.Series(random.sample(
range(1000), df.shape[0])).divide(10000)
return result
def predict_reg(local_model, df):
if os.path.isfile(local_model):
model = pickle.load(open(local_model, 'rb'))
result = pd.Series(model.predict(df)).apply(int).clip(lower=0)
else:
result = pd.Series(random.sample(range(100, 1000), df.shape[0]))
return result
def getPrediction(data, predictdate=np.datetime64('today')):
request_json = data
if request_json and 'instances' in request_json and 'companyid' in request_json and 'columns' in request_json:
sys.stdout = open(utils.log_dir + time.strftime("%Y%m%d-%H%M%S") + '_predict.txt', 'w')
# copy model
companyid = str(request_json['companyid'])
print(datetime.datetime.now(), 'Predict for company', companyid)
local_class_model = utils.model_dir + companyid + '/classification/model.pkl'
local_reg_model = utils.model_dir + companyid + '/regression/model.pkl'
columns = request_json['columns']
df = pd.DataFrame(request_json['instances'], columns=columns)
df_1 = preprocess.preprocessDF(df, utils.model_dir + companyid + '/', predictdate)
df_1 = df_1.drop(['CompId', 'AccountId', 'AttritionReasonId', 'AttritionDays', 'IsAttrition', 'ReasonId'], axis=1, errors='ignore')
data = {}
result_class = predict_class(local_class_model, df_1)
result_reg = predict_reg(local_reg_model, df_1)
df['HiredOrReHired'] = df['HiredOrReHired'].astype('datetime64[D]')
result_date = df['HiredOrReHired'] + pd.to_timedelta(result_reg, 'D')
data['predictions'] = json.loads(pd.DataFrame({'attritionproba': result_class, 'attritiondate': result_date}).to_json(orient='records', date_format='iso'))
sys.stdout.close()
return data
else:
return {'attritionproba': 0, 'attritiondate': ''}
def getPredictionByEmployee(companyid, accountid=None, predictdate=np.datetime64('today')):
sys.stdout = open(
utils.log_dir + time.strftime("%Y%m%d-%H%M%S") + '_predict.txt', 'w')
# copy model
print(datetime.datetime.now(), 'Predict for company', companyid)
local_class_model = utils.model_dir + companyid + '/classification/model.pkl'
local_reg_model = utils.model_dir + companyid + '/regression/model.pkl'
if np.datetime64(predictdate) >= np.datetime64('today'):
strtodate = ''
else:
strtodate = np.datetime64(predictdate).astype(datetime.datetime).strftime('%Y%m')
if os.path.isfile(utils.data_dir + companyid + '/preparedData_test' + strtodate + '.feather'):
df = feather.read_dataframe(utils.data_dir + companyid + '/preparedData_test' + strtodate + '.feather')
else:
df = pd.read_csv(utils.data_dir + companyid + '/preparedData_test' + strtodate + '.csv', low_memory=False)
feather.write_dataframe(df, utils.data_dir + companyid + '/preparedData_test' + strtodate + '.feather')
if os.path.isfile(utils.model_dir + companyid + '/preprocessedData_test' + strtodate + '.feather'):
df_1 = feather.read_dataframe(utils.model_dir + companyid + '/preprocessedData_test' + strtodate + '.feather')
else:
df_1 = pd.read_csv(utils.model_dir + companyid + '/preprocessedData_test' + strtodate + '.csv', low_memory=False)
feather.write_dataframe(df_1, utils.model_dir + companyid + '/preprocessedData_test' + strtodate + '.feather')
if accountid:
df = df.loc[(df['CompId'] == int(companyid)) & (df['AccountId'].isin(accountid))].reset_index(drop=True)
df_1 = df_1.loc[(df_1['CompId'] == int(companyid)) & (df_1['AccountId'].isin(accountid))].reset_index(drop=True)
else:
df = df.loc[(df['CompId'] == int(companyid))]
df_1 = df_1.loc[(df['CompId'] == int(companyid))]
#df_1 = preprocess.preprocessDF(df, utils.model_dir + companyid + '/', np.datetime64(predictdate))
df_1 = df_1.drop(['CompId', 'AccountId', 'AttritionReasonId', 'AttritionDays', 'IsAttrition', 'ReasonId'], axis=1, errors='ignore')
print(datetime.datetime.now(), 'Predict for data', df_1.shape)
data = {}
result_class = predict_class(local_class_model, df_1)
result_reg = predict_reg(local_reg_model, df_1)
df['HiredOrReHired'] = df['HiredOrReHired'].astype('datetime64[D]')
result_date = df['HiredOrReHired'] + pd.to_timedelta(result_reg, 'D')
data['predictions'] = json.loads(pd.DataFrame(
{'accountid': df['AccountId'], 'attritionproba': result_class, 'attritiondate': result_date}).to_json(orient='records', date_format='iso'))
sys.stdout.close()
return data
|
normal
|
{
"blob_id": "c76fd9b196b50e6fcced7e56517c0cd8ab30e24e",
"index": 7891,
"step-1": "<mask token>\n\n\n@api.route('/predict')\n@api.expect(parser)\nclass Predict(Resource):\n <mask token>\n\n\n@api.route('/predict/<string:companyid>/<string:accountid>')\n@api.expect(parser)\nclass PredictEmployeeByCompany(Resource):\n\n @api.marshal_with(modelByEmployee)\n def get(self, companyid, accountid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, [int(accountid)], args[\n 'predictdate'])\n\n\n@api.route('/predict/<string:companyid>')\n@api.expect(parser)\nclass PredictByCompany(Resource):\n\n @api.marshal_with(modelByEmployee)\n def get(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, None, args['predictdate'])\n\n @api.expect(predict_accounts)\n @api.marshal_with(modelByEmployee)\n def post(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, request.get_json()[\n 'accountids'], args['predictdate'])\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\n@api.route('/predict')\n@api.expect(parser)\nclass Predict(Resource):\n\n @api.expect(predict_fields)\n @api.marshal_with(model)\n def post(self):\n args = parser.parse_args()\n return getPrediction(request.get_json(), args['predictdate'])\n\n\n@api.route('/predict/<string:companyid>/<string:accountid>')\n@api.expect(parser)\nclass PredictEmployeeByCompany(Resource):\n\n @api.marshal_with(modelByEmployee)\n def get(self, companyid, accountid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, [int(accountid)], args[\n 'predictdate'])\n\n\n@api.route('/predict/<string:companyid>')\n@api.expect(parser)\nclass PredictByCompany(Resource):\n\n @api.marshal_with(modelByEmployee)\n def get(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, None, args['predictdate'])\n\n @api.expect(predict_accounts)\n @api.marshal_with(modelByEmployee)\n def post(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, request.get_json()[\n 'accountids'], args['predictdate'])\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\n@api.route('/predict')\n@api.expect(parser)\nclass Predict(Resource):\n\n @api.expect(predict_fields)\n @api.marshal_with(model)\n def post(self):\n args = parser.parse_args()\n return getPrediction(request.get_json(), args['predictdate'])\n\n\n@api.route('/predict/<string:companyid>/<string:accountid>')\n@api.expect(parser)\nclass PredictEmployeeByCompany(Resource):\n\n @api.marshal_with(modelByEmployee)\n def get(self, companyid, accountid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, [int(accountid)], args[\n 'predictdate'])\n\n\n@api.route('/predict/<string:companyid>')\n@api.expect(parser)\nclass PredictByCompany(Resource):\n\n @api.marshal_with(modelByEmployee)\n def get(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, None, args['predictdate'])\n\n @api.expect(predict_accounts)\n @api.marshal_with(modelByEmployee)\n def post(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, request.get_json()[\n 'accountids'], args['predictdate'])\n\n\n<mask token>\n\n\ndef predict_reg(local_model, df):\n if os.path.isfile(local_model):\n model = pickle.load(open(local_model, 'rb'))\n result = pd.Series(model.predict(df)).apply(int).clip(lower=0)\n else:\n result = pd.Series(random.sample(range(100, 1000), df.shape[0]))\n return result\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\n@api.route('/predict')\n@api.expect(parser)\nclass Predict(Resource):\n\n @api.expect(predict_fields)\n @api.marshal_with(model)\n def post(self):\n args = parser.parse_args()\n return getPrediction(request.get_json(), args['predictdate'])\n\n\n@api.route('/predict/<string:companyid>/<string:accountid>')\n@api.expect(parser)\nclass PredictEmployeeByCompany(Resource):\n\n @api.marshal_with(modelByEmployee)\n def get(self, companyid, accountid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, [int(accountid)], args[\n 'predictdate'])\n\n\n@api.route('/predict/<string:companyid>')\n@api.expect(parser)\nclass PredictByCompany(Resource):\n\n @api.marshal_with(modelByEmployee)\n def get(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, None, args['predictdate'])\n\n @api.expect(predict_accounts)\n @api.marshal_with(modelByEmployee)\n def post(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, request.get_json()[\n 'accountids'], args['predictdate'])\n\n\n<mask token>\n\n\ndef predict_class(local_model, df):\n if os.path.isfile(local_model):\n model = pickle.load(open(local_model, 'rb'))\n result = pd.Series(model.predict_proba(df)[:, 1])\n else:\n result = pd.Series(random.sample(range(1000), df.shape[0])).divide(\n 10000)\n return result\n\n\ndef predict_reg(local_model, df):\n if os.path.isfile(local_model):\n model = pickle.load(open(local_model, 'rb'))\n result = pd.Series(model.predict(df)).apply(int).clip(lower=0)\n else:\n result = pd.Series(random.sample(range(100, 1000), df.shape[0]))\n return result\n\n\n<mask token>\n\n\ndef getPredictionByEmployee(companyid, accountid=None, predictdate=np.\n datetime64('today')):\n sys.stdout = open(utils.log_dir + time.strftime('%Y%m%d-%H%M%S') +\n '_predict.txt', 'w')\n print(datetime.datetime.now(), 'Predict for company', companyid)\n local_class_model = (utils.model_dir + companyid +\n '/classification/model.pkl')\n local_reg_model = utils.model_dir + companyid + '/regression/model.pkl'\n if np.datetime64(predictdate) >= np.datetime64('today'):\n strtodate = ''\n else:\n strtodate = np.datetime64(predictdate).astype(datetime.datetime\n ).strftime('%Y%m')\n if os.path.isfile(utils.data_dir + companyid + '/preparedData_test' +\n strtodate + '.feather'):\n df = feather.read_dataframe(utils.data_dir + companyid +\n '/preparedData_test' + strtodate + '.feather')\n else:\n df = pd.read_csv(utils.data_dir + companyid + '/preparedData_test' +\n strtodate + '.csv', low_memory=False)\n feather.write_dataframe(df, utils.data_dir + companyid +\n '/preparedData_test' + strtodate + '.feather')\n if os.path.isfile(utils.model_dir + companyid +\n '/preprocessedData_test' + strtodate + '.feather'):\n df_1 = feather.read_dataframe(utils.model_dir + companyid +\n '/preprocessedData_test' + strtodate + '.feather')\n else:\n df_1 = pd.read_csv(utils.model_dir + companyid +\n '/preprocessedData_test' + strtodate + '.csv', low_memory=False)\n feather.write_dataframe(df_1, utils.model_dir + companyid +\n '/preprocessedData_test' + strtodate + '.feather')\n if accountid:\n df = df.loc[(df['CompId'] == int(companyid)) & df['AccountId'].isin\n (accountid)].reset_index(drop=True)\n df_1 = df_1.loc[(df_1['CompId'] == int(companyid)) & df_1[\n 'AccountId'].isin(accountid)].reset_index(drop=True)\n else:\n df = df.loc[df['CompId'] == int(companyid)]\n df_1 = df_1.loc[df['CompId'] == int(companyid)]\n df_1 = df_1.drop(['CompId', 'AccountId', 'AttritionReasonId',\n 'AttritionDays', 'IsAttrition', 'ReasonId'], axis=1, errors='ignore')\n print(datetime.datetime.now(), 'Predict for data', df_1.shape)\n data = {}\n result_class = predict_class(local_class_model, df_1)\n result_reg = predict_reg(local_reg_model, df_1)\n df['HiredOrReHired'] = df['HiredOrReHired'].astype('datetime64[D]')\n result_date = df['HiredOrReHired'] + pd.to_timedelta(result_reg, 'D')\n data['predictions'] = json.loads(pd.DataFrame({'accountid': df[\n 'AccountId'], 'attritionproba': result_class, 'attritiondate':\n result_date}).to_json(orient='records', date_format='iso'))\n sys.stdout.close()\n return data\n",
"step-5": "from . import preprocess\nfrom . import utils\nimport random\nimport pickle\nimport feather\nimport time\nimport datetime\nimport sys\nimport os\nimport numpy as np\nimport pandas as pd\nimport json\nfrom ...main import api\nfrom flask import request\nfrom flask_restplus import Resource, fields\n\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\n\npredict_fields = api.model('Prediction Data', {\n})\n\npredict_accounts = api.model('Prediction Data By Employee', {\n \n})\n\nprediction = api.model('Prediction', {'attritionproba': fields.Float(\n example=0.345), 'attritiondate': fields.String(example='2020-10-06T00:00:00.000Z')})\n\npredictionByEmployee = api.model('Prediction By Employee', {})\n\nmodel = api.model(\n 'Predictions', {'predictions': fields.List(fields.Nested(prediction))})\n\nmodelByEmployee = api.model(\n 'Predictions By Employee', {'predictions': fields.List(fields.Nested(predictionByEmployee))})\n\nparser = api.parser()\nparser.add_argument('predictdate', location='args', default=datetime.date.today().strftime(\"%Y-%m-%d\"), help='Predict date', required=True)\n\n\n@api.route(\"/predict\")\n@api.expect(parser)\nclass Predict(Resource):\n @api.expect(predict_fields)\n @api.marshal_with(model)\n def post(self):\n args = parser.parse_args()\n return getPrediction(request.get_json(), args['predictdate'])\n\n\n@api.route(\"/predict/<string:companyid>/<string:accountid>\")\n@api.expect(parser)\nclass PredictEmployeeByCompany(Resource):\n @api.marshal_with(modelByEmployee)\n def get(self, companyid, accountid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, [int(accountid)], args['predictdate'])\n\n\n@api.route(\"/predict/<string:companyid>\")\n@api.expect(parser)\nclass PredictByCompany(Resource):\n @api.marshal_with(modelByEmployee)\n def get(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, None, args['predictdate'])\n\n @api.expect(predict_accounts)\n @api.marshal_with(modelByEmployee)\n def post(self, companyid):\n args = parser.parse_args()\n return getPredictionByEmployee(companyid, request.get_json()['accountids'], args['predictdate'])\n\n\npackage_directory = os.path.dirname(os.path.abspath(__file__))\n\n\ndef predict_class(local_model, df):\n if os.path.isfile(local_model):\n model = pickle.load(open(local_model, 'rb'))\n result = pd.Series(model.predict_proba(df)[:, 1])\n else:\n result = pd.Series(random.sample(\n range(1000), df.shape[0])).divide(10000)\n\n return result\n\n\ndef predict_reg(local_model, df):\n if os.path.isfile(local_model):\n model = pickle.load(open(local_model, 'rb'))\n result = pd.Series(model.predict(df)).apply(int).clip(lower=0)\n else:\n result = pd.Series(random.sample(range(100, 1000), df.shape[0]))\n return result\n\n\ndef getPrediction(data, predictdate=np.datetime64('today')):\n\n request_json = data\n\n if request_json and 'instances' in request_json and 'companyid' in request_json and 'columns' in request_json:\n sys.stdout = open(utils.log_dir + time.strftime(\"%Y%m%d-%H%M%S\") + '_predict.txt', 'w')\n # copy model\n companyid = str(request_json['companyid'])\n print(datetime.datetime.now(), 'Predict for company', companyid)\n local_class_model = utils.model_dir + companyid + '/classification/model.pkl'\n local_reg_model = utils.model_dir + companyid + '/regression/model.pkl'\n columns = request_json['columns']\n df = pd.DataFrame(request_json['instances'], columns=columns)\n df_1 = preprocess.preprocessDF(df, utils.model_dir + companyid + '/', predictdate)\n df_1 = df_1.drop(['CompId', 'AccountId', 'AttritionReasonId', 'AttritionDays', 'IsAttrition', 'ReasonId'], axis=1, errors='ignore')\n data = {}\n result_class = predict_class(local_class_model, df_1)\n\n result_reg = predict_reg(local_reg_model, df_1)\n\n df['HiredOrReHired'] = df['HiredOrReHired'].astype('datetime64[D]')\n result_date = df['HiredOrReHired'] + pd.to_timedelta(result_reg, 'D')\n\n data['predictions'] = json.loads(pd.DataFrame({'attritionproba': result_class, 'attritiondate': result_date}).to_json(orient='records', date_format='iso'))\n sys.stdout.close()\n return data\n else:\n return {'attritionproba': 0, 'attritiondate': ''}\n\n\ndef getPredictionByEmployee(companyid, accountid=None, predictdate=np.datetime64('today')):\n sys.stdout = open(\n utils.log_dir + time.strftime(\"%Y%m%d-%H%M%S\") + '_predict.txt', 'w')\n # copy model\n\n print(datetime.datetime.now(), 'Predict for company', companyid)\n local_class_model = utils.model_dir + companyid + '/classification/model.pkl'\n local_reg_model = utils.model_dir + companyid + '/regression/model.pkl'\n\n if np.datetime64(predictdate) >= np.datetime64('today'):\n strtodate = ''\n else:\n strtodate = np.datetime64(predictdate).astype(datetime.datetime).strftime('%Y%m')\n \n if os.path.isfile(utils.data_dir + companyid + '/preparedData_test' + strtodate + '.feather'):\n df = feather.read_dataframe(utils.data_dir + companyid + '/preparedData_test' + strtodate + '.feather')\n else:\n df = pd.read_csv(utils.data_dir + companyid + '/preparedData_test' + strtodate + '.csv', low_memory=False)\n feather.write_dataframe(df, utils.data_dir + companyid + '/preparedData_test' + strtodate + '.feather')\n \n if os.path.isfile(utils.model_dir + companyid + '/preprocessedData_test' + strtodate + '.feather'):\n df_1 = feather.read_dataframe(utils.model_dir + companyid + '/preprocessedData_test' + strtodate + '.feather')\n else:\n df_1 = pd.read_csv(utils.model_dir + companyid + '/preprocessedData_test' + strtodate + '.csv', low_memory=False)\n feather.write_dataframe(df_1, utils.model_dir + companyid + '/preprocessedData_test' + strtodate + '.feather')\n\n if accountid:\n df = df.loc[(df['CompId'] == int(companyid)) & (df['AccountId'].isin(accountid))].reset_index(drop=True)\n df_1 = df_1.loc[(df_1['CompId'] == int(companyid)) & (df_1['AccountId'].isin(accountid))].reset_index(drop=True)\n else:\n df = df.loc[(df['CompId'] == int(companyid))]\n df_1 = df_1.loc[(df['CompId'] == int(companyid))]\n\n #df_1 = preprocess.preprocessDF(df, utils.model_dir + companyid + '/', np.datetime64(predictdate))\n\n df_1 = df_1.drop(['CompId', 'AccountId', 'AttritionReasonId', 'AttritionDays', 'IsAttrition', 'ReasonId'], axis=1, errors='ignore')\n print(datetime.datetime.now(), 'Predict for data', df_1.shape)\n\n data = {}\n result_class = predict_class(local_class_model, df_1)\n\n result_reg = predict_reg(local_reg_model, df_1)\n\n df['HiredOrReHired'] = df['HiredOrReHired'].astype('datetime64[D]')\n result_date = df['HiredOrReHired'] + pd.to_timedelta(result_reg, 'D')\n\n data['predictions'] = json.loads(pd.DataFrame(\n {'accountid': df['AccountId'], 'attritionproba': result_class, 'attritiondate': result_date}).to_json(orient='records', date_format='iso'))\n sys.stdout.close()\n return data\n",
"step-ids": [
6,
7,
8,
10,
15
]
}
|
[
6,
7,
8,
10,
15
] |
import seaborn as sns
tips = sns.load_dataset('iris')
sns.violinplot(x='species', y='sepal_length', data=tips, palette='rainbow')
|
normal
|
{
"blob_id": "274af2a0b758472ca4116f1dfa47069647babf57",
"index": 8543,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsns.violinplot(x='species', y='sepal_length', data=tips, palette='rainbow')\n",
"step-3": "<mask token>\ntips = sns.load_dataset('iris')\nsns.violinplot(x='species', y='sepal_length', data=tips, palette='rainbow')\n",
"step-4": "import seaborn as sns\ntips = sns.load_dataset('iris')\nsns.violinplot(x='species', y='sepal_length', data=tips, palette='rainbow')\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class BooksaleConfig(AppConfig):
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class BooksaleConfig(AppConfig):
name = 'booksale'
<|reserved_special_token_1|>
from django.apps import AppConfig
class BooksaleConfig(AppConfig):
name = 'booksale'
|
flexible
|
{
"blob_id": "e642054dad8a2de5b01f2994348e10e9c7574ee0",
"index": 4581,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass BooksaleConfig(AppConfig):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass BooksaleConfig(AppConfig):\n name = 'booksale'\n",
"step-4": "from django.apps import AppConfig\n\n\nclass BooksaleConfig(AppConfig):\n name = 'booksale'\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for path in sorted(contents):
files_used.append(path.name)
totalFiles += 1
print(files_used)
print(totalFiles)
<|reserved_special_token_0|>
for filename in files_used:
df = pd.read_csv(PATH + folder + filename, sep=';', skiprows=range(1, 6
), index_col=0)
li.append(df)
<|reserved_special_token_0|>
frame.to_csv('merged.csv', sep=';')
print('FINISH MERGING FILES!')
<|reserved_special_token_0|>
for file in files_used:
shutil.move(PATH + folder + file, PATH + folder_dest)
print('FINISH MOVING MERGED FILES!')
<|reserved_special_token_0|>
print('FINISH CLEAN DF!')
print(df)
df.info()
<|reserved_special_token_0|>
print('CONNECTED!')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
PATH = '/home/thomas/Documents/TER/AJOUTER_CSV_BDD/'
folder = 'test/'
files_used = []
totalFiles = 0
contents = pathlib.Path(PATH + folder).iterdir()
for path in sorted(contents):
files_used.append(path.name)
totalFiles += 1
print(files_used)
print(totalFiles)
li = []
for filename in files_used:
df = pd.read_csv(PATH + folder + filename, sep=';', skiprows=range(1, 6
), index_col=0)
li.append(df)
frame = pd.concat(li)
frame.to_csv('merged.csv', sep=';')
print('FINISH MERGING FILES!')
folder_dest = 'dest'
for file in files_used:
shutil.move(PATH + folder + file, PATH + folder_dest)
print('FINISH MOVING MERGED FILES!')
df = pd.read_csv('merged.csv', sep=';')
df['Date'] = df['Date'].str[0:10] + ' ' + df['Date'].str[11:19]
df = df.rename(columns={'Date': 'horodatage', 'Nom parking': 'nom',
'Type de parc': 'type_parking',
"Horaires d'accès au public (pour les usagers non abonnés)": 'horaires',
'Code parking': 'code_parking', 'Type de compteur': 'type_compteur',
'Places disponibles': 'places_disponibles'})
df['horodatage'] = pd.to_datetime(df['horodatage'])
df = df.loc[:, ['code_parking', 'type_compteur', 'horodatage',
'places_disponibles']]
print('FINISH CLEAN DF!')
print(df)
df.info()
host = ''
port = ''
db = ''
user = ''
psw = ''
name_table = ''
engine = sqla.create_engine('mysql://' + user + ':' + psw + '@' + host +
':' + port + '/' + db)
print('CONNECTED!')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
import pathlib
import shutil
import os
import glob
import pandas as pd
import sqlalchemy as sqla
<|reserved_special_token_0|>
PATH = '/home/thomas/Documents/TER/AJOUTER_CSV_BDD/'
folder = 'test/'
files_used = []
totalFiles = 0
contents = pathlib.Path(PATH + folder).iterdir()
for path in sorted(contents):
files_used.append(path.name)
totalFiles += 1
print(files_used)
print(totalFiles)
li = []
for filename in files_used:
df = pd.read_csv(PATH + folder + filename, sep=';', skiprows=range(1, 6
), index_col=0)
li.append(df)
frame = pd.concat(li)
frame.to_csv('merged.csv', sep=';')
print('FINISH MERGING FILES!')
folder_dest = 'dest'
for file in files_used:
shutil.move(PATH + folder + file, PATH + folder_dest)
print('FINISH MOVING MERGED FILES!')
df = pd.read_csv('merged.csv', sep=';')
df['Date'] = df['Date'].str[0:10] + ' ' + df['Date'].str[11:19]
df = df.rename(columns={'Date': 'horodatage', 'Nom parking': 'nom',
'Type de parc': 'type_parking',
"Horaires d'accès au public (pour les usagers non abonnés)": 'horaires',
'Code parking': 'code_parking', 'Type de compteur': 'type_compteur',
'Places disponibles': 'places_disponibles'})
df['horodatage'] = pd.to_datetime(df['horodatage'])
df = df.loc[:, ['code_parking', 'type_compteur', 'horodatage',
'places_disponibles']]
print('FINISH CLEAN DF!')
print(df)
df.info()
host = ''
port = ''
db = ''
user = ''
psw = ''
name_table = ''
engine = sqla.create_engine('mysql://' + user + ':' + psw + '@' + host +
':' + port + '/' + db)
print('CONNECTED!')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
import pathlib
import shutil
import os
import glob
import pandas as pd
import sqlalchemy as sqla
"""
SCRIPT TO FILL THE DATABASE FROM CSV ON MEGA IF LOSE DATA IN PARTICULAR DATE
"""
PATH = "/home/thomas/Documents/TER/AJOUTER_CSV_BDD/"
folder = "test/"
files_used = []
totalFiles = 0
contents = pathlib.Path(PATH+folder).iterdir()
for path in sorted(contents): # utiliser .stem -> nom sans extension fichier / .name -> nom fichier complet
files_used.append(path.name)
totalFiles+=1
print(files_used)
print(totalFiles)
li = []
for filename in files_used:
df = pd.read_csv(PATH+folder+filename,sep=';',skiprows=range(1,6),index_col=0)
li.append(df)
frame = pd.concat(li)
frame.to_csv("merged.csv",sep=';')
print('FINISH MERGING FILES!')
#Move all files used in folder dest
folder_dest = 'dest'
for file in files_used:
shutil.move(PATH+folder+file, PATH+folder_dest)
print('FINISH MOVING MERGED FILES!')
df = pd.read_csv('merged.csv',sep=';')
df['Date'] = df['Date'].str[0:10] +' '+df['Date'].str[11:19]
df = df.rename(columns={'Date': 'horodatage','Nom parking': 'nom','Type de parc': 'type_parking',"Horaires d'accès au public (pour les usagers non abonnés)": 'horaires','Code parking': 'code_parking','Type de compteur': 'type_compteur', 'Places disponibles': 'places_disponibles'})
df['horodatage'] = pd.to_datetime(df['horodatage'])
df = df.loc[: ,['code_parking','type_compteur','horodatage','places_disponibles']]
print('FINISH CLEAN DF!')
print(df)
df.info()
host = ''
port = ''
db = ''
user = ''
psw = ''
name_table = ''
# dialect+driver://username:password@host:port/database
engine = sqla.create_engine('mysql://'+user+':'+psw+'@'+host+':'+port+'/'+db)
print('CONNECTED!')
"""
df.to_sql(name_table,engine,if_exists='append',index=False,chunksize=1024,dtype={'id': sqla.Integer,'code_parking': sqla.String(255),'type_compteur': sqla.String(255),'horodatage': sqla.DateTime,'places_disponibles': sqla.Integer})
print('Finished export to Database!')
"""
|
flexible
|
{
"blob_id": "795936dad7a9e51edf0df66207a43ac4d97e9023",
"index": 3781,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor path in sorted(contents):\n files_used.append(path.name)\n totalFiles += 1\nprint(files_used)\nprint(totalFiles)\n<mask token>\nfor filename in files_used:\n df = pd.read_csv(PATH + folder + filename, sep=';', skiprows=range(1, 6\n ), index_col=0)\n li.append(df)\n<mask token>\nframe.to_csv('merged.csv', sep=';')\nprint('FINISH MERGING FILES!')\n<mask token>\nfor file in files_used:\n shutil.move(PATH + folder + file, PATH + folder_dest)\nprint('FINISH MOVING MERGED FILES!')\n<mask token>\nprint('FINISH CLEAN DF!')\nprint(df)\ndf.info()\n<mask token>\nprint('CONNECTED!')\n<mask token>\n",
"step-3": "<mask token>\nPATH = '/home/thomas/Documents/TER/AJOUTER_CSV_BDD/'\nfolder = 'test/'\nfiles_used = []\ntotalFiles = 0\ncontents = pathlib.Path(PATH + folder).iterdir()\nfor path in sorted(contents):\n files_used.append(path.name)\n totalFiles += 1\nprint(files_used)\nprint(totalFiles)\nli = []\nfor filename in files_used:\n df = pd.read_csv(PATH + folder + filename, sep=';', skiprows=range(1, 6\n ), index_col=0)\n li.append(df)\nframe = pd.concat(li)\nframe.to_csv('merged.csv', sep=';')\nprint('FINISH MERGING FILES!')\nfolder_dest = 'dest'\nfor file in files_used:\n shutil.move(PATH + folder + file, PATH + folder_dest)\nprint('FINISH MOVING MERGED FILES!')\ndf = pd.read_csv('merged.csv', sep=';')\ndf['Date'] = df['Date'].str[0:10] + ' ' + df['Date'].str[11:19]\ndf = df.rename(columns={'Date': 'horodatage', 'Nom parking': 'nom',\n 'Type de parc': 'type_parking',\n \"Horaires d'accès au public (pour les usagers non abonnés)\": 'horaires',\n 'Code parking': 'code_parking', 'Type de compteur': 'type_compteur',\n 'Places disponibles': 'places_disponibles'})\ndf['horodatage'] = pd.to_datetime(df['horodatage'])\ndf = df.loc[:, ['code_parking', 'type_compteur', 'horodatage',\n 'places_disponibles']]\nprint('FINISH CLEAN DF!')\nprint(df)\ndf.info()\nhost = ''\nport = ''\ndb = ''\nuser = ''\npsw = ''\nname_table = ''\nengine = sqla.create_engine('mysql://' + user + ':' + psw + '@' + host +\n ':' + port + '/' + db)\nprint('CONNECTED!')\n<mask token>\n",
"step-4": "import pathlib\nimport shutil\nimport os\nimport glob\nimport pandas as pd\nimport sqlalchemy as sqla\n<mask token>\nPATH = '/home/thomas/Documents/TER/AJOUTER_CSV_BDD/'\nfolder = 'test/'\nfiles_used = []\ntotalFiles = 0\ncontents = pathlib.Path(PATH + folder).iterdir()\nfor path in sorted(contents):\n files_used.append(path.name)\n totalFiles += 1\nprint(files_used)\nprint(totalFiles)\nli = []\nfor filename in files_used:\n df = pd.read_csv(PATH + folder + filename, sep=';', skiprows=range(1, 6\n ), index_col=0)\n li.append(df)\nframe = pd.concat(li)\nframe.to_csv('merged.csv', sep=';')\nprint('FINISH MERGING FILES!')\nfolder_dest = 'dest'\nfor file in files_used:\n shutil.move(PATH + folder + file, PATH + folder_dest)\nprint('FINISH MOVING MERGED FILES!')\ndf = pd.read_csv('merged.csv', sep=';')\ndf['Date'] = df['Date'].str[0:10] + ' ' + df['Date'].str[11:19]\ndf = df.rename(columns={'Date': 'horodatage', 'Nom parking': 'nom',\n 'Type de parc': 'type_parking',\n \"Horaires d'accès au public (pour les usagers non abonnés)\": 'horaires',\n 'Code parking': 'code_parking', 'Type de compteur': 'type_compteur',\n 'Places disponibles': 'places_disponibles'})\ndf['horodatage'] = pd.to_datetime(df['horodatage'])\ndf = df.loc[:, ['code_parking', 'type_compteur', 'horodatage',\n 'places_disponibles']]\nprint('FINISH CLEAN DF!')\nprint(df)\ndf.info()\nhost = ''\nport = ''\ndb = ''\nuser = ''\npsw = ''\nname_table = ''\nengine = sqla.create_engine('mysql://' + user + ':' + psw + '@' + host +\n ':' + port + '/' + db)\nprint('CONNECTED!')\n<mask token>\n",
"step-5": "import pathlib\nimport shutil\nimport os\nimport glob\nimport pandas as pd\nimport sqlalchemy as sqla\n\n\"\"\"\nSCRIPT TO FILL THE DATABASE FROM CSV ON MEGA IF LOSE DATA IN PARTICULAR DATE\n\"\"\"\n\nPATH = \"/home/thomas/Documents/TER/AJOUTER_CSV_BDD/\"\nfolder = \"test/\"\nfiles_used = []\ntotalFiles = 0\ncontents = pathlib.Path(PATH+folder).iterdir()\nfor path in sorted(contents): # utiliser .stem -> nom sans extension fichier / .name -> nom fichier complet\n files_used.append(path.name)\n totalFiles+=1\n\nprint(files_used)\nprint(totalFiles)\n\nli = []\n\nfor filename in files_used:\n\tdf = pd.read_csv(PATH+folder+filename,sep=';',skiprows=range(1,6),index_col=0)\n\tli.append(df)\n\nframe = pd.concat(li)\n\n\nframe.to_csv(\"merged.csv\",sep=';')\nprint('FINISH MERGING FILES!')\n\n#Move all files used in folder dest\nfolder_dest = 'dest'\nfor file in files_used:\n shutil.move(PATH+folder+file, PATH+folder_dest)\nprint('FINISH MOVING MERGED FILES!')\n\n\ndf = pd.read_csv('merged.csv',sep=';') \n\n\ndf['Date'] = df['Date'].str[0:10] +' '+df['Date'].str[11:19]\ndf = df.rename(columns={'Date': 'horodatage','Nom parking': 'nom','Type de parc': 'type_parking',\"Horaires d'accès au public (pour les usagers non abonnés)\": 'horaires','Code parking': 'code_parking','Type de compteur': 'type_compteur', 'Places disponibles': 'places_disponibles'})\ndf['horodatage'] = pd.to_datetime(df['horodatage'])\ndf = df.loc[: ,['code_parking','type_compteur','horodatage','places_disponibles']]\nprint('FINISH CLEAN DF!')\nprint(df)\ndf.info()\n\nhost = ''\nport = ''\ndb = ''\nuser = ''\npsw = ''\nname_table = ''\n\n\n# dialect+driver://username:password@host:port/database\nengine = sqla.create_engine('mysql://'+user+':'+psw+'@'+host+':'+port+'/'+db)\nprint('CONNECTED!')\n\n\"\"\"\n\ndf.to_sql(name_table,engine,if_exists='append',index=False,chunksize=1024,dtype={'id': sqla.Integer,'code_parking': sqla.String(255),'type_compteur': sqla.String(255),'horodatage': sqla.DateTime,'places_disponibles': sqla.Integer})\nprint('Finished export to Database!')\n\"\"\"\n\n\n\n\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def test_resource_not_found(petstore_client):
with pytest.raises(AttributeError) as excinfo:
petstore_client.foo
assert 'foo not found' in str(excinfo.value)
@pytest.fixture
def client_tags_with_spaces():
return SwaggerClient.from_spec({'swagger': '2.0', 'info': {'version':
'', 'title': 'API'}, 'paths': {'/ping': {'get': {'operationId':
'ping', 'responses': {'200': {'description': 'ping'}}, 'tags': [
'my tag']}}}})
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_resource_exists(petstore_client):
assert type(petstore_client.pet) == ResourceDecorator
def test_resource_not_found(petstore_client):
with pytest.raises(AttributeError) as excinfo:
petstore_client.foo
assert 'foo not found' in str(excinfo.value)
@pytest.fixture
def client_tags_with_spaces():
return SwaggerClient.from_spec({'swagger': '2.0', 'info': {'version':
'', 'title': 'API'}, 'paths': {'/ping': {'get': {'operationId':
'ping', 'responses': {'200': {'description': 'ping'}}, 'tags': [
'my tag']}}}})
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_resource_exists(petstore_client):
assert type(petstore_client.pet) == ResourceDecorator
def test_resource_not_found(petstore_client):
with pytest.raises(AttributeError) as excinfo:
petstore_client.foo
assert 'foo not found' in str(excinfo.value)
@pytest.fixture
def client_tags_with_spaces():
return SwaggerClient.from_spec({'swagger': '2.0', 'info': {'version':
'', 'title': 'API'}, 'paths': {'/ping': {'get': {'operationId':
'ping', 'responses': {'200': {'description': 'ping'}}, 'tags': [
'my tag']}}}})
def test_get_resource(client_tags_with_spaces):
assert type(client_tags_with_spaces._get_resource('my tag')
) == ResourceDecorator
<|reserved_special_token_1|>
import pytest
from bravado.client import ResourceDecorator
from bravado.client import SwaggerClient
def test_resource_exists(petstore_client):
assert type(petstore_client.pet) == ResourceDecorator
def test_resource_not_found(petstore_client):
with pytest.raises(AttributeError) as excinfo:
petstore_client.foo
assert 'foo not found' in str(excinfo.value)
@pytest.fixture
def client_tags_with_spaces():
return SwaggerClient.from_spec({'swagger': '2.0', 'info': {'version':
'', 'title': 'API'}, 'paths': {'/ping': {'get': {'operationId':
'ping', 'responses': {'200': {'description': 'ping'}}, 'tags': [
'my tag']}}}})
def test_get_resource(client_tags_with_spaces):
assert type(client_tags_with_spaces._get_resource('my tag')
) == ResourceDecorator
<|reserved_special_token_1|>
# -*- coding: utf-8 -*-
import pytest
from bravado.client import ResourceDecorator
from bravado.client import SwaggerClient
def test_resource_exists(petstore_client):
assert type(petstore_client.pet) == ResourceDecorator
def test_resource_not_found(petstore_client):
with pytest.raises(AttributeError) as excinfo:
petstore_client.foo
assert 'foo not found' in str(excinfo.value)
@pytest.fixture
def client_tags_with_spaces():
return SwaggerClient.from_spec({
'swagger': '2.0',
'info': {
'version': '',
'title': 'API'
},
'paths': {
'/ping': {
'get': {
'operationId': 'ping',
'responses': {
'200': {
'description': 'ping'
}
},
'tags': [
'my tag'
]
}
}
}
})
def test_get_resource(client_tags_with_spaces):
assert type(client_tags_with_spaces._get_resource('my tag')) == ResourceDecorator
|
flexible
|
{
"blob_id": "5ee1d8ef7ec4b191e0789ceb9c6dd2d58af526a0",
"index": 7875,
"step-1": "<mask token>\n\n\ndef test_resource_not_found(petstore_client):\n with pytest.raises(AttributeError) as excinfo:\n petstore_client.foo\n assert 'foo not found' in str(excinfo.value)\n\n\n@pytest.fixture\ndef client_tags_with_spaces():\n return SwaggerClient.from_spec({'swagger': '2.0', 'info': {'version':\n '', 'title': 'API'}, 'paths': {'/ping': {'get': {'operationId':\n 'ping', 'responses': {'200': {'description': 'ping'}}, 'tags': [\n 'my tag']}}}})\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_resource_exists(petstore_client):\n assert type(petstore_client.pet) == ResourceDecorator\n\n\ndef test_resource_not_found(petstore_client):\n with pytest.raises(AttributeError) as excinfo:\n petstore_client.foo\n assert 'foo not found' in str(excinfo.value)\n\n\n@pytest.fixture\ndef client_tags_with_spaces():\n return SwaggerClient.from_spec({'swagger': '2.0', 'info': {'version':\n '', 'title': 'API'}, 'paths': {'/ping': {'get': {'operationId':\n 'ping', 'responses': {'200': {'description': 'ping'}}, 'tags': [\n 'my tag']}}}})\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef test_resource_exists(petstore_client):\n assert type(petstore_client.pet) == ResourceDecorator\n\n\ndef test_resource_not_found(petstore_client):\n with pytest.raises(AttributeError) as excinfo:\n petstore_client.foo\n assert 'foo not found' in str(excinfo.value)\n\n\n@pytest.fixture\ndef client_tags_with_spaces():\n return SwaggerClient.from_spec({'swagger': '2.0', 'info': {'version':\n '', 'title': 'API'}, 'paths': {'/ping': {'get': {'operationId':\n 'ping', 'responses': {'200': {'description': 'ping'}}, 'tags': [\n 'my tag']}}}})\n\n\ndef test_get_resource(client_tags_with_spaces):\n assert type(client_tags_with_spaces._get_resource('my tag')\n ) == ResourceDecorator\n",
"step-4": "import pytest\nfrom bravado.client import ResourceDecorator\nfrom bravado.client import SwaggerClient\n\n\ndef test_resource_exists(petstore_client):\n assert type(petstore_client.pet) == ResourceDecorator\n\n\ndef test_resource_not_found(petstore_client):\n with pytest.raises(AttributeError) as excinfo:\n petstore_client.foo\n assert 'foo not found' in str(excinfo.value)\n\n\n@pytest.fixture\ndef client_tags_with_spaces():\n return SwaggerClient.from_spec({'swagger': '2.0', 'info': {'version':\n '', 'title': 'API'}, 'paths': {'/ping': {'get': {'operationId':\n 'ping', 'responses': {'200': {'description': 'ping'}}, 'tags': [\n 'my tag']}}}})\n\n\ndef test_get_resource(client_tags_with_spaces):\n assert type(client_tags_with_spaces._get_resource('my tag')\n ) == ResourceDecorator\n",
"step-5": "# -*- coding: utf-8 -*-\nimport pytest\n\nfrom bravado.client import ResourceDecorator\nfrom bravado.client import SwaggerClient\n\n\ndef test_resource_exists(petstore_client):\n assert type(petstore_client.pet) == ResourceDecorator\n\n\ndef test_resource_not_found(petstore_client):\n with pytest.raises(AttributeError) as excinfo:\n petstore_client.foo\n assert 'foo not found' in str(excinfo.value)\n\n\n@pytest.fixture\ndef client_tags_with_spaces():\n return SwaggerClient.from_spec({\n 'swagger': '2.0',\n 'info': {\n 'version': '',\n 'title': 'API'\n },\n 'paths': {\n '/ping': {\n 'get': {\n 'operationId': 'ping',\n 'responses': {\n '200': {\n 'description': 'ping'\n }\n },\n 'tags': [\n 'my tag'\n ]\n }\n }\n }\n })\n\n\ndef test_get_resource(client_tags_with_spaces):\n assert type(client_tags_with_spaces._get_resource('my tag')) == ResourceDecorator\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def printBoard(board, pref):
border = '+----+----+----+----+----+----+----+----+'
for row in board:
print(pref, border)
cells = '|'
for cell in row:
if cell == 0:
cell = ' '
elif cell in range(1, 10):
cell = '0{}'.format(cell)
cells += ' {} '.format(cell)
cells += '|'
print(pref, cells)
print(pref, border)
<|reserved_special_token_1|>
def printBoard(board,pref):
border = "+----+----+----+----+----+----+----+----+"
for row in board:
print(pref,border)
cells ="|"
for cell in row:
if cell == 0:
cell = " "
elif cell in range(1,10):
cell = "0{}".format(cell)
cells +=" {} ".format(cell)
cells +="|"
print(pref,cells )
print(pref,border)
|
flexible
|
{
"blob_id": "07e875a24d0e63ef596db57c4ec402f768225eec",
"index": 5103,
"step-1": "<mask token>\n",
"step-2": "def printBoard(board, pref):\n border = '+----+----+----+----+----+----+----+----+'\n for row in board:\n print(pref, border)\n cells = '|'\n for cell in row:\n if cell == 0:\n cell = ' '\n elif cell in range(1, 10):\n cell = '0{}'.format(cell)\n cells += ' {} '.format(cell)\n cells += '|'\n print(pref, cells)\n print(pref, border)\n",
"step-3": "def printBoard(board,pref):\n border = \"+----+----+----+----+----+----+----+----+\"\n for row in board:\n print(pref,border)\n cells =\"|\"\n for cell in row:\n if cell == 0:\n cell = \" \"\n elif cell in range(1,10):\n cell = \"0{}\".format(cell)\n cells +=\" {} \".format(cell)\n cells +=\"|\"\n \n print(pref,cells )\n print(pref,border)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Voucher(Base):
__tablename__ = 't_juju_voucher'
code = Column(String(100), index=True, unique=True)
serial_no = Column(String(120), index=True, unique=True)
amount = Column(Float, default=0, nullable=False)
vtime = Column(DateTime(), nullable=False)
vtype = Column(String(50), ForeignKey('t_juju_code.vtype'))
comment = Column(String(150), nullable=True)
create_time = Column(DateTime(), default=datetime.now)
update_time = Column(DateTime(), default=datetime.now, onupdate=
datetime.now)
owner_id = Column(Integer, ForeignKey('t_juju_account.id'))
modifier_id = Column(Integer, ForeignKey('t_juju_account.id'))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
if TYPE_CHECKING:
from .account import Account
from .code import Code
class Voucher(Base):
__tablename__ = 't_juju_voucher'
code = Column(String(100), index=True, unique=True)
serial_no = Column(String(120), index=True, unique=True)
amount = Column(Float, default=0, nullable=False)
vtime = Column(DateTime(), nullable=False)
vtype = Column(String(50), ForeignKey('t_juju_code.vtype'))
comment = Column(String(150), nullable=True)
create_time = Column(DateTime(), default=datetime.now)
update_time = Column(DateTime(), default=datetime.now, onupdate=
datetime.now)
owner_id = Column(Integer, ForeignKey('t_juju_account.id'))
modifier_id = Column(Integer, ForeignKey('t_juju_account.id'))
<|reserved_special_token_1|>
from __future__ import annotations
from typing import TYPE_CHECKING
from datetime import datetime
from sqlalchemy import Column, ForeignKey, String, DateTime, Float, Integer
from sqlalchemy.orm import relationship
from app.db.base_class import Base
if TYPE_CHECKING:
from .account import Account
from .code import Code
class Voucher(Base):
__tablename__ = 't_juju_voucher'
code = Column(String(100), index=True, unique=True)
serial_no = Column(String(120), index=True, unique=True)
amount = Column(Float, default=0, nullable=False)
vtime = Column(DateTime(), nullable=False)
vtype = Column(String(50), ForeignKey('t_juju_code.vtype'))
comment = Column(String(150), nullable=True)
create_time = Column(DateTime(), default=datetime.now)
update_time = Column(DateTime(), default=datetime.now, onupdate=
datetime.now)
owner_id = Column(Integer, ForeignKey('t_juju_account.id'))
modifier_id = Column(Integer, ForeignKey('t_juju_account.id'))
<|reserved_special_token_1|>
from __future__ import annotations
from typing import TYPE_CHECKING
from datetime import datetime
from sqlalchemy import Column, ForeignKey, String, DateTime, Float, Integer
from sqlalchemy.orm import relationship
from app.db.base_class import Base
if TYPE_CHECKING:
from .account import Account # noqa: F401
from .code import Code # noqa: F401
class Voucher(Base):
__tablename__ = 't_juju_voucher'
code = Column(String(100), index=True, unique=True)
serial_no = Column(String(120), index=True, unique=True)
amount = Column(Float, default=0, nullable=False)
vtime = Column(DateTime(), nullable=False)
vtype = Column(String(50), ForeignKey("t_juju_code.vtype"))
comment = Column(String(150), nullable=True)
create_time = Column(DateTime(), default=datetime.now)
update_time = Column(DateTime(), default=datetime.now,
onupdate=datetime.now)
owner_id = Column(Integer, ForeignKey("t_juju_account.id"))
modifier_id = Column(Integer, ForeignKey("t_juju_account.id"))
|
flexible
|
{
"blob_id": "60d8276a5715899823b12ffdf132925c6f2693bd",
"index": 8675,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Voucher(Base):\n __tablename__ = 't_juju_voucher'\n code = Column(String(100), index=True, unique=True)\n serial_no = Column(String(120), index=True, unique=True)\n amount = Column(Float, default=0, nullable=False)\n vtime = Column(DateTime(), nullable=False)\n vtype = Column(String(50), ForeignKey('t_juju_code.vtype'))\n comment = Column(String(150), nullable=True)\n create_time = Column(DateTime(), default=datetime.now)\n update_time = Column(DateTime(), default=datetime.now, onupdate=\n datetime.now)\n owner_id = Column(Integer, ForeignKey('t_juju_account.id'))\n modifier_id = Column(Integer, ForeignKey('t_juju_account.id'))\n",
"step-3": "<mask token>\nif TYPE_CHECKING:\n from .account import Account\n from .code import Code\n\n\nclass Voucher(Base):\n __tablename__ = 't_juju_voucher'\n code = Column(String(100), index=True, unique=True)\n serial_no = Column(String(120), index=True, unique=True)\n amount = Column(Float, default=0, nullable=False)\n vtime = Column(DateTime(), nullable=False)\n vtype = Column(String(50), ForeignKey('t_juju_code.vtype'))\n comment = Column(String(150), nullable=True)\n create_time = Column(DateTime(), default=datetime.now)\n update_time = Column(DateTime(), default=datetime.now, onupdate=\n datetime.now)\n owner_id = Column(Integer, ForeignKey('t_juju_account.id'))\n modifier_id = Column(Integer, ForeignKey('t_juju_account.id'))\n",
"step-4": "from __future__ import annotations\nfrom typing import TYPE_CHECKING\nfrom datetime import datetime\nfrom sqlalchemy import Column, ForeignKey, String, DateTime, Float, Integer\nfrom sqlalchemy.orm import relationship\nfrom app.db.base_class import Base\nif TYPE_CHECKING:\n from .account import Account\n from .code import Code\n\n\nclass Voucher(Base):\n __tablename__ = 't_juju_voucher'\n code = Column(String(100), index=True, unique=True)\n serial_no = Column(String(120), index=True, unique=True)\n amount = Column(Float, default=0, nullable=False)\n vtime = Column(DateTime(), nullable=False)\n vtype = Column(String(50), ForeignKey('t_juju_code.vtype'))\n comment = Column(String(150), nullable=True)\n create_time = Column(DateTime(), default=datetime.now)\n update_time = Column(DateTime(), default=datetime.now, onupdate=\n datetime.now)\n owner_id = Column(Integer, ForeignKey('t_juju_account.id'))\n modifier_id = Column(Integer, ForeignKey('t_juju_account.id'))\n",
"step-5": "from __future__ import annotations\n\n\nfrom typing import TYPE_CHECKING\nfrom datetime import datetime\n\nfrom sqlalchemy import Column, ForeignKey, String, DateTime, Float, Integer\nfrom sqlalchemy.orm import relationship\n\nfrom app.db.base_class import Base\n\nif TYPE_CHECKING:\n from .account import Account # noqa: F401\n from .code import Code # noqa: F401\n\n\nclass Voucher(Base):\n __tablename__ = 't_juju_voucher'\n code = Column(String(100), index=True, unique=True)\n serial_no = Column(String(120), index=True, unique=True)\n amount = Column(Float, default=0, nullable=False)\n vtime = Column(DateTime(), nullable=False)\n\n vtype = Column(String(50), ForeignKey(\"t_juju_code.vtype\"))\n\n comment = Column(String(150), nullable=True)\n create_time = Column(DateTime(), default=datetime.now)\n update_time = Column(DateTime(), default=datetime.now,\n onupdate=datetime.now)\n\n owner_id = Column(Integer, ForeignKey(\"t_juju_account.id\"))\n modifier_id = Column(Integer, ForeignKey(\"t_juju_account.id\"))\n",
"step-ids": [
0,
2,
3,
4,
5
]
}
|
[
0,
2,
3,
4,
5
] |
"""
# System of national accounts (SNA)
This is an end-to-end example of national accounts sequence,
from output to net lending. It is based on Russian Federation data
for 2014-2018.
Below is a python session transcript with comments.
You can fork [a github repo](https://github.com/epogrebnyak/sna-ru)
to replicate calculations.
"""
"""
## Chart
A short mnemonic chart to accompaign the calculations:
```
[controlling for factor income and transfers]
| |
V V
X -> GDP -> GNI -> GNDI = C + S (+ net capital transfers)
| |
Ch + I + Cg + NX S = I + Net lending
|
W + t' + P Always a mystery:
| S - I = NX = Net lending
X - AX (See Open Economy identitites below)
```
"""
"""
## Preparations
"""
import pandas as pd
import handout
doc = handout.Handout("handout") # handout: exclude
"""
`eq` function will check identities considering some rounding error.
"""
def eq(df1, df2, precision=0.5) -> bool:
"""Compare two dataframes by element with precision margin."""
return ((df1 - df2).abs() < precision).all()
"""
Read dataset from file.
"""
df = pd.read_csv("data/sna.csv", index_col=0)
"""
## 1. Output at market prices
Output at market prices is output at basic prices
plus tax on products less subsidy on products.
"""
df["X"] = df.Xb + df.Tp - df.Sp
"""
## 2. Production of goods and services account
Output and import are resources,
consumption, investment (I) and export are uses.
Consumption is intermediate (AX) and final (C).
"""
resources = df.X + df.IM
uses = df.AX + df.C + df.I + df.EX
doc.add_image("res_use.png", "png", width=1) # handout: exclude
doc.show() # handout: exclude
"""
Resources and uses are equal, controlling for
[statistical discrepancy](https://www.stat.fi/meta/kas/tilastollinen_e_en.html).
"""
assert eq(resources, uses + df.desc)
"""
## 3. Gross domestic product (GDP)
There are three ways to calculate a GDP.
With some luck they yield to similar values.
"""
gdp1 = df.X - df.AX
gdp2 = (df.C + df.I - df.IM) + df.EX + df.desc
gdp3 = df.W + df.Tf - df.Sf + df.GP
assert eq(gdp1, gdp2)
assert eq(gdp2, df.GDP)
assert eq(gdp3, df.GDP)
"""```
>> gdp1.divide(10**6).round(1)
2014 79.1
2015 83.1
2016 86.0
2017 92.1
2018 103.9
```"""
"""
## 4. Controlling for income and current transfers from abroad
Gross national income (GNI) is GDP and
net property and labor ("factor") income
form rest of the world (ROW).
"""
gni = (
df.GDP
+ df.ROW_property_income_recieved
- df.ROW_property_income_paid
+ df.ROW_wage_net
)
assert eq(gni.iloc[1:,], df.GNI.iloc[1:,])
"""
Gross national disposable income (GNDI)
is GNI and net current transfers from abroad
"""
gndi = gni + df.CT_recieved - df.CT_paid
assert eq(gndi, df.GNDI)
"""
## 5. Savings
Savings is gross domestic income
less household and government consumption.
"""
S = gndi - (df.HH + df.G)
assert eq(df.C, df.HH + df.G)
assert eq(S, df.S)
"""
Investment is gross fixed capital formation
and change in inventories.
"""
I = df.GFCF + df.inv
assert eq(I, df.I)
"""
## 6. Net lending
Net lending is S-I, and a balance of capital transfers
and a non-produced non-material asset aquisition (K.2).
"""
NL = S + df.d9_recieved - df.d9_paid - I - df.k2
assert eq(NL, df.NL0)
"""
Net lending is an entry value into financial account (flow of funds).
Is usually contains a statistical error, later netted in flow of funds.
"""
"""
## Links
- [SNA 2008 manual](https://unstats.un.org/unsd/nationalaccount/docs/SNA2008.pdf)
- [Russian national accounts data](https://www.gks.ru/folder/210/document/13221)
- [Open economy identitites](https://github.com/hisamsabouni/macroLectures/blob/master/lecture_6.pdf)
"""
doc.show() # handout: exclude
|
normal
|
{
"blob_id": "2d4187ab5d178efa4920110ccef61c608fdb14c0",
"index": 8780,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef eq(df1, df2, precision=0.5) ->bool:\n \"\"\"Compare two dataframes by element with precision margin.\"\"\"\n return ((df1 - df2).abs() < precision).all()\n\n\n<mask token>\ndoc.add_image('res_use.png', 'png', width=1)\ndoc.show()\n<mask token>\nassert eq(resources, uses + df.desc)\n<mask token>\nassert eq(gdp1, gdp2)\nassert eq(gdp2, df.GDP)\nassert eq(gdp3, df.GDP)\n<mask token>\nassert eq(gni.iloc[1:,], df.GNI.iloc[1:,])\n<mask token>\nassert eq(gndi, df.GNDI)\n<mask token>\nassert eq(df.C, df.HH + df.G)\nassert eq(S, df.S)\n<mask token>\nassert eq(I, df.I)\n<mask token>\nassert eq(NL, df.NL0)\n<mask token>\ndoc.show()\n",
"step-3": "<mask token>\ndoc = handout.Handout('handout')\n<mask token>\n\n\ndef eq(df1, df2, precision=0.5) ->bool:\n \"\"\"Compare two dataframes by element with precision margin.\"\"\"\n return ((df1 - df2).abs() < precision).all()\n\n\n<mask token>\ndf = pd.read_csv('data/sna.csv', index_col=0)\n<mask token>\ndf['X'] = df.Xb + df.Tp - df.Sp\n<mask token>\nresources = df.X + df.IM\nuses = df.AX + df.C + df.I + df.EX\ndoc.add_image('res_use.png', 'png', width=1)\ndoc.show()\n<mask token>\nassert eq(resources, uses + df.desc)\n<mask token>\ngdp1 = df.X - df.AX\ngdp2 = df.C + df.I - df.IM + df.EX + df.desc\ngdp3 = df.W + df.Tf - df.Sf + df.GP\nassert eq(gdp1, gdp2)\nassert eq(gdp2, df.GDP)\nassert eq(gdp3, df.GDP)\n<mask token>\ngni = (df.GDP + df.ROW_property_income_recieved - df.\n ROW_property_income_paid + df.ROW_wage_net)\nassert eq(gni.iloc[1:,], df.GNI.iloc[1:,])\n<mask token>\ngndi = gni + df.CT_recieved - df.CT_paid\nassert eq(gndi, df.GNDI)\n<mask token>\nS = gndi - (df.HH + df.G)\nassert eq(df.C, df.HH + df.G)\nassert eq(S, df.S)\n<mask token>\nI = df.GFCF + df.inv\nassert eq(I, df.I)\n<mask token>\nNL = S + df.d9_recieved - df.d9_paid - I - df.k2\nassert eq(NL, df.NL0)\n<mask token>\ndoc.show()\n",
"step-4": "<mask token>\nimport pandas as pd\nimport handout\ndoc = handout.Handout('handout')\n<mask token>\n\n\ndef eq(df1, df2, precision=0.5) ->bool:\n \"\"\"Compare two dataframes by element with precision margin.\"\"\"\n return ((df1 - df2).abs() < precision).all()\n\n\n<mask token>\ndf = pd.read_csv('data/sna.csv', index_col=0)\n<mask token>\ndf['X'] = df.Xb + df.Tp - df.Sp\n<mask token>\nresources = df.X + df.IM\nuses = df.AX + df.C + df.I + df.EX\ndoc.add_image('res_use.png', 'png', width=1)\ndoc.show()\n<mask token>\nassert eq(resources, uses + df.desc)\n<mask token>\ngdp1 = df.X - df.AX\ngdp2 = df.C + df.I - df.IM + df.EX + df.desc\ngdp3 = df.W + df.Tf - df.Sf + df.GP\nassert eq(gdp1, gdp2)\nassert eq(gdp2, df.GDP)\nassert eq(gdp3, df.GDP)\n<mask token>\ngni = (df.GDP + df.ROW_property_income_recieved - df.\n ROW_property_income_paid + df.ROW_wage_net)\nassert eq(gni.iloc[1:,], df.GNI.iloc[1:,])\n<mask token>\ngndi = gni + df.CT_recieved - df.CT_paid\nassert eq(gndi, df.GNDI)\n<mask token>\nS = gndi - (df.HH + df.G)\nassert eq(df.C, df.HH + df.G)\nassert eq(S, df.S)\n<mask token>\nI = df.GFCF + df.inv\nassert eq(I, df.I)\n<mask token>\nNL = S + df.d9_recieved - df.d9_paid - I - df.k2\nassert eq(NL, df.NL0)\n<mask token>\ndoc.show()\n",
"step-5": "\"\"\"\n# System of national accounts (SNA)\n\nThis is an end-to-end example of national accounts sequence, \nfrom output to net lending. It is based on Russian Federation data \nfor 2014-2018. \n\nBelow is a python session transcript with comments. \nYou can fork [a github repo](https://github.com/epogrebnyak/sna-ru) \nto replicate calculations.\n\"\"\"\n\n\"\"\"\n## Chart \n\nA short mnemonic chart to accompaign the calculations:\n \n```\n [controlling for factor income and transfers] \n | |\n V V\nX -> GDP -> GNI -> GNDI = C + S (+ net capital transfers)\n | | \n Ch + I + Cg + NX S = I + Net lending \n |\n W + t' + P Always a mystery:\n | S - I = NX = Net lending \n X - AX (See Open Economy identitites below) \n\n```\n\"\"\"\n\n\"\"\"\n## Preparations\n\"\"\"\n\nimport pandas as pd\nimport handout\n\ndoc = handout.Handout(\"handout\") # handout: exclude\n\n\"\"\"\n`eq` function will check identities considering some rounding error.\n\"\"\"\n\n\ndef eq(df1, df2, precision=0.5) -> bool:\n \"\"\"Compare two dataframes by element with precision margin.\"\"\"\n return ((df1 - df2).abs() < precision).all()\n\n\n\"\"\"\nRead dataset from file. \n\"\"\"\n\ndf = pd.read_csv(\"data/sna.csv\", index_col=0)\n\n\"\"\"\n## 1. Output at market prices\n\nOutput at market prices is output at basic prices \nplus tax on products less subsidy on products.\n\"\"\"\n\ndf[\"X\"] = df.Xb + df.Tp - df.Sp\n\n\n\"\"\"\n## 2. Production of goods and services account\n\nOutput and import are resources,\nconsumption, investment (I) and export are uses.\nConsumption is intermediate (AX) and final (C).\n\"\"\"\n\nresources = df.X + df.IM\nuses = df.AX + df.C + df.I + df.EX\n\ndoc.add_image(\"res_use.png\", \"png\", width=1) # handout: exclude\ndoc.show() # handout: exclude\n\n\"\"\"\nResources and uses are equal, controlling for \n[statistical discrepancy](https://www.stat.fi/meta/kas/tilastollinen_e_en.html).\n\"\"\"\nassert eq(resources, uses + df.desc)\n\n\n\"\"\"\n## 3. Gross domestic product (GDP)\n\nThere are three ways to calculate a GDP. \n\nWith some luck they yield to similar values.\n\n\"\"\"\n\ngdp1 = df.X - df.AX\ngdp2 = (df.C + df.I - df.IM) + df.EX + df.desc\ngdp3 = df.W + df.Tf - df.Sf + df.GP\n\nassert eq(gdp1, gdp2)\nassert eq(gdp2, df.GDP)\nassert eq(gdp3, df.GDP)\n\n\"\"\"```\n>> gdp1.divide(10**6).round(1)\n\n2014 79.1\n2015 83.1\n2016 86.0\n2017 92.1\n2018 103.9\n\n```\"\"\"\n\n\n\"\"\"\n## 4. Controlling for income and current transfers from abroad\n\nGross national income (GNI) is GDP and \nnet property and labor (\"factor\") income \nform rest of the world (ROW).\n\"\"\"\n\n\ngni = (\n df.GDP\n + df.ROW_property_income_recieved\n - df.ROW_property_income_paid\n + df.ROW_wage_net\n)\nassert eq(gni.iloc[1:,], df.GNI.iloc[1:,])\n\n\"\"\"\n\nGross national disposable income (GNDI) \nis GNI and net current transfers from abroad\n\"\"\"\n\ngndi = gni + df.CT_recieved - df.CT_paid\nassert eq(gndi, df.GNDI)\n\n\"\"\"\n## 5. Savings\n\nSavings is gross domestic income \nless household and government consumption. \n\"\"\"\n\nS = gndi - (df.HH + df.G)\nassert eq(df.C, df.HH + df.G)\nassert eq(S, df.S)\n\n\"\"\"\nInvestment is gross fixed capital formation \nand change in inventories.\n\"\"\"\n\nI = df.GFCF + df.inv\nassert eq(I, df.I)\n\n\"\"\"\n## 6. Net lending\n\nNet lending is S-I, and a balance of capital transfers\nand a non-produced non-material asset aquisition (K.2).\n\"\"\"\n\nNL = S + df.d9_recieved - df.d9_paid - I - df.k2\nassert eq(NL, df.NL0)\n\n\"\"\"\nNet lending is an entry value into financial account (flow of funds).\nIs usually contains a statistical error, later netted in flow of funds.\n\"\"\"\n\n\n\"\"\"\n## Links\n\n- [SNA 2008 manual](https://unstats.un.org/unsd/nationalaccount/docs/SNA2008.pdf)\n- [Russian national accounts data](https://www.gks.ru/folder/210/document/13221)\n- [Open economy identitites](https://github.com/hisamsabouni/macroLectures/blob/master/lecture_6.pdf)\n\"\"\"\n\ndoc.show() # handout: exclude\n",
"step-ids": [
0,
2,
3,
4,
5
]
}
|
[
0,
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 18 16:11:44 2021
@author: ignacio
"""
import matplotlib.pyplot as plt
from numpy.linalg import inv as invertir
from time import perf_counter
import numpy as np
def matriz_laplaciana(N, t=np.single): # funcion obtenida de clase
e=np.eye(N)-np.eye(N,N,1)
return t(e+e.T)
Ns = [2, 5, 10,12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200, 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000]
corridas = 10
for corrida in range(corridas):
tiempo = []
memoria = []
name = (f"single{corrida}.txt")
fid = open(name,"w")
for i in Ns:
print(f"i = {i}")
A = matriz_laplaciana(i)
t1 = perf_counter()
invertir(A)
t2 = perf_counter()
dt = t2 - t1
size = 3 * (i**2) * 32
tiempo.append(dt)
memoria.append(size)
fid.write(f"{i} {dt} {size}\n")
print(f"Tiempo transcurrido = {dt} s")
print(f"Mmoria usada = {size} bytes")
fid.flush()
fid.close()
dim = []
tim = []
mem = []
for n in range(10):
dimension = []
time = []
memory = []
with open(f"single{n}.txt", "r") as f:
lineas = [linea.split() for linea in f]
for i in lineas:
dimension.append(int(i[0]))
time.append(float(i[1]))
memory.append(int(i[2]))
dim.append(dimension)
tim.append(time)
mem.append(memory)
#Grafico superior
plt.subplot(2, 1, 1)
plt.plot(dim[0],tim[0],"-o")
plt.plot(dim[0],tim[1],"-o")
plt.plot(dim[0],tim[2],"-o")
plt.plot(dim[0],tim[3],"-o")
plt.plot(dim[0],tim[4],"-o")
plt.plot(dim[0],tim[5],"-o")
plt.plot(dim[0],tim[6],"-o")
plt.plot(dim[0],tim[7],"-o")
plt.plot(dim[0],tim[8],"-o")
plt.plot(dim[0],tim[9],"-o")
plt.yscale('log')
plt.xscale('log')
xticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]
xtext = ["", "", "", "", "", "", "", "", "", "", ""]
yticks = [0.1/1000, 1/1000, 10/1000, 0.1, 1, 10, 60, 600]
ytext = ["0.1 ms", "1 ms", "10 ms", "0.1 s", "1 s", "10 s", "1 min", "10 min"]
plt.yticks(yticks, ytext)
plt.xticks(xticks, xtext)
plt.title("Rendimiento caso1_single")
plt.ylabel("Tiempo transcurrido (s)")
plt.grid(True)
#Grafico inferior
plt.subplot(2, 1, 2)
plt.plot(Ns,memoria,'-ob')
plt.yscale('log')
plt.xscale('log')
xticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]
xtext = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]
yticks = [1000,10000, 100000, 1000000, 10000000, 100000000, 1000000000, 100000000000]
ytext = ["1 KB ", "10 KB", "100 KB", "1 MB", "10 MB", "100 MB", "1 GB", "10 GB"]
plt.axhline(y=4000000000, linestyle="--",color="black") # RAM 4 GB
plt.yticks(yticks, ytext)
plt.xticks(xticks, xtext, rotation=45)
plt.xlabel("Tamaño matriz N")
plt.ylabel("Uso memoria (bytes)")
plt.grid(True)
plt.savefig("Rendimiento caso1_single.png")
|
normal
|
{
"blob_id": "86345702bcd423bc31e29b1d28aa9c438629297d",
"index": 7331,
"step-1": "<mask token>\n\n\ndef matriz_laplaciana(N, t=np.single):\n e = np.eye(N) - np.eye(N, N, 1)\n return t(e + e.T)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef matriz_laplaciana(N, t=np.single):\n e = np.eye(N) - np.eye(N, N, 1)\n return t(e + e.T)\n\n\n<mask token>\nfor corrida in range(corridas):\n tiempo = []\n memoria = []\n name = f'single{corrida}.txt'\n fid = open(name, 'w')\n for i in Ns:\n print(f'i = {i}')\n A = matriz_laplaciana(i)\n t1 = perf_counter()\n invertir(A)\n t2 = perf_counter()\n dt = t2 - t1\n size = 3 * i ** 2 * 32\n tiempo.append(dt)\n memoria.append(size)\n fid.write(f'{i} {dt} {size}\\n')\n print(f'Tiempo transcurrido = {dt} s')\n print(f'Mmoria usada = {size} bytes')\n fid.flush()\nfid.close()\n<mask token>\nfor n in range(10):\n dimension = []\n time = []\n memory = []\n with open(f'single{n}.txt', 'r') as f:\n lineas = [linea.split() for linea in f]\n for i in lineas:\n dimension.append(int(i[0]))\n time.append(float(i[1]))\n memory.append(int(i[2]))\n dim.append(dimension)\n tim.append(time)\n mem.append(memory)\nplt.subplot(2, 1, 1)\nplt.plot(dim[0], tim[0], '-o')\nplt.plot(dim[0], tim[1], '-o')\nplt.plot(dim[0], tim[2], '-o')\nplt.plot(dim[0], tim[3], '-o')\nplt.plot(dim[0], tim[4], '-o')\nplt.plot(dim[0], tim[5], '-o')\nplt.plot(dim[0], tim[6], '-o')\nplt.plot(dim[0], tim[7], '-o')\nplt.plot(dim[0], tim[8], '-o')\nplt.plot(dim[0], tim[9], '-o')\nplt.yscale('log')\nplt.xscale('log')\n<mask token>\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext)\nplt.title('Rendimiento caso1_single')\nplt.ylabel('Tiempo transcurrido (s)')\nplt.grid(True)\nplt.subplot(2, 1, 2)\nplt.plot(Ns, memoria, '-ob')\nplt.yscale('log')\nplt.xscale('log')\n<mask token>\nplt.axhline(y=4000000000, linestyle='--', color='black')\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext, rotation=45)\nplt.xlabel('Tamaño matriz N')\nplt.ylabel('Uso memoria (bytes)')\nplt.grid(True)\nplt.savefig('Rendimiento caso1_single.png')\n",
"step-3": "<mask token>\n\n\ndef matriz_laplaciana(N, t=np.single):\n e = np.eye(N) - np.eye(N, N, 1)\n return t(e + e.T)\n\n\nNs = [2, 5, 10, 12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200,\n 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000]\ncorridas = 10\nfor corrida in range(corridas):\n tiempo = []\n memoria = []\n name = f'single{corrida}.txt'\n fid = open(name, 'w')\n for i in Ns:\n print(f'i = {i}')\n A = matriz_laplaciana(i)\n t1 = perf_counter()\n invertir(A)\n t2 = perf_counter()\n dt = t2 - t1\n size = 3 * i ** 2 * 32\n tiempo.append(dt)\n memoria.append(size)\n fid.write(f'{i} {dt} {size}\\n')\n print(f'Tiempo transcurrido = {dt} s')\n print(f'Mmoria usada = {size} bytes')\n fid.flush()\nfid.close()\ndim = []\ntim = []\nmem = []\nfor n in range(10):\n dimension = []\n time = []\n memory = []\n with open(f'single{n}.txt', 'r') as f:\n lineas = [linea.split() for linea in f]\n for i in lineas:\n dimension.append(int(i[0]))\n time.append(float(i[1]))\n memory.append(int(i[2]))\n dim.append(dimension)\n tim.append(time)\n mem.append(memory)\nplt.subplot(2, 1, 1)\nplt.plot(dim[0], tim[0], '-o')\nplt.plot(dim[0], tim[1], '-o')\nplt.plot(dim[0], tim[2], '-o')\nplt.plot(dim[0], tim[3], '-o')\nplt.plot(dim[0], tim[4], '-o')\nplt.plot(dim[0], tim[5], '-o')\nplt.plot(dim[0], tim[6], '-o')\nplt.plot(dim[0], tim[7], '-o')\nplt.plot(dim[0], tim[8], '-o')\nplt.plot(dim[0], tim[9], '-o')\nplt.yscale('log')\nplt.xscale('log')\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nxtext = ['', '', '', '', '', '', '', '', '', '', '']\nyticks = [0.1 / 1000, 1 / 1000, 10 / 1000, 0.1, 1, 10, 60, 600]\nytext = ['0.1 ms', '1 ms', '10 ms', '0.1 s', '1 s', '10 s', '1 min', '10 min']\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext)\nplt.title('Rendimiento caso1_single')\nplt.ylabel('Tiempo transcurrido (s)')\nplt.grid(True)\nplt.subplot(2, 1, 2)\nplt.plot(Ns, memoria, '-ob')\nplt.yscale('log')\nplt.xscale('log')\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nxtext = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nyticks = [1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, \n 100000000000]\nytext = ['1 KB ', '10 KB', '100 KB', '1 MB', '10 MB', '100 MB', '1 GB', '10 GB'\n ]\nplt.axhline(y=4000000000, linestyle='--', color='black')\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext, rotation=45)\nplt.xlabel('Tamaño matriz N')\nplt.ylabel('Uso memoria (bytes)')\nplt.grid(True)\nplt.savefig('Rendimiento caso1_single.png')\n",
"step-4": "<mask token>\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import inv as invertir\nfrom time import perf_counter\nimport numpy as np\n\n\ndef matriz_laplaciana(N, t=np.single):\n e = np.eye(N) - np.eye(N, N, 1)\n return t(e + e.T)\n\n\nNs = [2, 5, 10, 12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200,\n 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000]\ncorridas = 10\nfor corrida in range(corridas):\n tiempo = []\n memoria = []\n name = f'single{corrida}.txt'\n fid = open(name, 'w')\n for i in Ns:\n print(f'i = {i}')\n A = matriz_laplaciana(i)\n t1 = perf_counter()\n invertir(A)\n t2 = perf_counter()\n dt = t2 - t1\n size = 3 * i ** 2 * 32\n tiempo.append(dt)\n memoria.append(size)\n fid.write(f'{i} {dt} {size}\\n')\n print(f'Tiempo transcurrido = {dt} s')\n print(f'Mmoria usada = {size} bytes')\n fid.flush()\nfid.close()\ndim = []\ntim = []\nmem = []\nfor n in range(10):\n dimension = []\n time = []\n memory = []\n with open(f'single{n}.txt', 'r') as f:\n lineas = [linea.split() for linea in f]\n for i in lineas:\n dimension.append(int(i[0]))\n time.append(float(i[1]))\n memory.append(int(i[2]))\n dim.append(dimension)\n tim.append(time)\n mem.append(memory)\nplt.subplot(2, 1, 1)\nplt.plot(dim[0], tim[0], '-o')\nplt.plot(dim[0], tim[1], '-o')\nplt.plot(dim[0], tim[2], '-o')\nplt.plot(dim[0], tim[3], '-o')\nplt.plot(dim[0], tim[4], '-o')\nplt.plot(dim[0], tim[5], '-o')\nplt.plot(dim[0], tim[6], '-o')\nplt.plot(dim[0], tim[7], '-o')\nplt.plot(dim[0], tim[8], '-o')\nplt.plot(dim[0], tim[9], '-o')\nplt.yscale('log')\nplt.xscale('log')\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nxtext = ['', '', '', '', '', '', '', '', '', '', '']\nyticks = [0.1 / 1000, 1 / 1000, 10 / 1000, 0.1, 1, 10, 60, 600]\nytext = ['0.1 ms', '1 ms', '10 ms', '0.1 s', '1 s', '10 s', '1 min', '10 min']\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext)\nplt.title('Rendimiento caso1_single')\nplt.ylabel('Tiempo transcurrido (s)')\nplt.grid(True)\nplt.subplot(2, 1, 2)\nplt.plot(Ns, memoria, '-ob')\nplt.yscale('log')\nplt.xscale('log')\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nxtext = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nyticks = [1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, \n 100000000000]\nytext = ['1 KB ', '10 KB', '100 KB', '1 MB', '10 MB', '100 MB', '1 GB', '10 GB'\n ]\nplt.axhline(y=4000000000, linestyle='--', color='black')\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext, rotation=45)\nplt.xlabel('Tamaño matriz N')\nplt.ylabel('Uso memoria (bytes)')\nplt.grid(True)\nplt.savefig('Rendimiento caso1_single.png')\n",
"step-5": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 18 16:11:44 2021\r\n\r\n@author: ignacio\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom numpy.linalg import inv as invertir\r\nfrom time import perf_counter\r\nimport numpy as np\r\n\r\ndef matriz_laplaciana(N, t=np.single): # funcion obtenida de clase\r\n e=np.eye(N)-np.eye(N,N,1)\r\n return t(e+e.T)\r\n\r\n\r\nNs = [2, 5, 10,12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200, 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000]\r\n\r\ncorridas = 10\r\n\r\nfor corrida in range(corridas):\r\n \r\n tiempo = []\r\n memoria = []\r\n \r\n name = (f\"single{corrida}.txt\")\r\n\r\n fid = open(name,\"w\")\r\n \r\n for i in Ns:\r\n\r\n print(f\"i = {i}\") \r\n \r\n A = matriz_laplaciana(i)\r\n \r\n t1 = perf_counter()\r\n\r\n invertir(A)\r\n \r\n t2 = perf_counter()\r\n\r\n dt = t2 - t1\r\n \r\n size = 3 * (i**2) * 32\r\n\r\n tiempo.append(dt) \r\n memoria.append(size)\r\n \r\n fid.write(f\"{i} {dt} {size}\\n\")\r\n \r\n print(f\"Tiempo transcurrido = {dt} s\")\r\n print(f\"Mmoria usada = {size} bytes\")\r\n\r\n fid.flush()\r\n \r\n \r\nfid.close()\r\n\r\n\r\n\r\ndim = []\r\ntim = []\r\nmem = []\r\n\r\nfor n in range(10):\r\n dimension = []\r\n time = []\r\n memory = []\r\n with open(f\"single{n}.txt\", \"r\") as f:\r\n lineas = [linea.split() for linea in f]\r\n \r\n for i in lineas:\r\n dimension.append(int(i[0]))\r\n time.append(float(i[1]))\r\n memory.append(int(i[2]))\r\n \r\n dim.append(dimension)\r\n tim.append(time)\r\n mem.append(memory)\r\n\r\n#Grafico superior\r\n\r\nplt.subplot(2, 1, 1)\r\nplt.plot(dim[0],tim[0],\"-o\")\r\nplt.plot(dim[0],tim[1],\"-o\")\r\nplt.plot(dim[0],tim[2],\"-o\")\r\nplt.plot(dim[0],tim[3],\"-o\")\r\nplt.plot(dim[0],tim[4],\"-o\")\r\nplt.plot(dim[0],tim[5],\"-o\")\r\nplt.plot(dim[0],tim[6],\"-o\")\r\nplt.plot(dim[0],tim[7],\"-o\")\r\nplt.plot(dim[0],tim[8],\"-o\")\r\nplt.plot(dim[0],tim[9],\"-o\")\r\n \r\nplt.yscale('log')\r\nplt.xscale('log')\r\n\r\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\r\nxtext = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]\r\n\r\nyticks = [0.1/1000, 1/1000, 10/1000, 0.1, 1, 10, 60, 600]\r\nytext = [\"0.1 ms\", \"1 ms\", \"10 ms\", \"0.1 s\", \"1 s\", \"10 s\", \"1 min\", \"10 min\"]\r\n\r\nplt.yticks(yticks, ytext)\r\nplt.xticks(xticks, xtext)\r\n\r\nplt.title(\"Rendimiento caso1_single\")\r\nplt.ylabel(\"Tiempo transcurrido (s)\")\r\nplt.grid(True)\r\n\r\n#Grafico inferior \r\n\r\nplt.subplot(2, 1, 2)\r\n\r\nplt.plot(Ns,memoria,'-ob')\r\n\r\nplt.yscale('log')\r\nplt.xscale('log')\r\n\r\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\r\nxtext = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\r\n\r\nyticks = [1000,10000, 100000, 1000000, 10000000, 100000000, 1000000000, 100000000000]\r\nytext = [\"1 KB \", \"10 KB\", \"100 KB\", \"1 MB\", \"10 MB\", \"100 MB\", \"1 GB\", \"10 GB\"]\r\n\r\nplt.axhline(y=4000000000, linestyle=\"--\",color=\"black\") # RAM 4 GB\r\n\r\nplt.yticks(yticks, ytext)\r\nplt.xticks(xticks, xtext, rotation=45)\r\n\r\nplt.xlabel(\"Tamaño matriz N\")\r\nplt.ylabel(\"Uso memoria (bytes)\")\r\nplt.grid(True)\r\nplt.savefig(\"Rendimiento caso1_single.png\")",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def chessKnight(cell):
pivot = 'abcdefgh'
count = 8
for i in range(len(pivot)):
if cell[0] == pivot[i]:
vertical_4, vertical_2 = False, False
if int(cell[1]) == 8 or int(cell[1]) == 1:
vertical_4 = True
count -= 4
elif int(cell[1]) == 7 or int(cell[1]) == 2:
vertical_2 = True
count -= 2
if i == 0 or i == 7:
if vertical_4:
count -= 2
elif vertical_2:
count -= 3
else:
count -= 4
elif i == 1 or i == 6:
if vertical_4:
count -= 1
else:
count -= 2
return count
<|reserved_special_token_1|>
def chessKnight(cell):
pivot = "abcdefgh"
count = 8
for i in range(len(pivot)):
if cell[0] == pivot[i]:
vertical_4 , vertical_2 = False , False
if int(cell[1]) == 8 or int(cell[1]) == 1:
vertical_4 = True
count -= 4
elif int(cell[1]) == 7 or int(cell[1]) == 2:
vertical_2 = True
count -= 2
if i == 0 or i == 7:
if vertical_4:
count -= 2
elif vertical_2:
count -= 3
else:
count -= 4
elif i == 1 or i == 6:
if vertical_4:
count -= 1
else:
count -= 2
return count
|
flexible
|
{
"blob_id": "c1335a8128ad4ba6ce6942e80f3c8b68a4210902",
"index": 6355,
"step-1": "<mask token>\n",
"step-2": "def chessKnight(cell):\n pivot = 'abcdefgh'\n count = 8\n for i in range(len(pivot)):\n if cell[0] == pivot[i]:\n vertical_4, vertical_2 = False, False\n if int(cell[1]) == 8 or int(cell[1]) == 1:\n vertical_4 = True\n count -= 4\n elif int(cell[1]) == 7 or int(cell[1]) == 2:\n vertical_2 = True\n count -= 2\n if i == 0 or i == 7:\n if vertical_4:\n count -= 2\n elif vertical_2:\n count -= 3\n else:\n count -= 4\n elif i == 1 or i == 6:\n if vertical_4:\n count -= 1\n else:\n count -= 2\n return count\n",
"step-3": "def chessKnight(cell):\n pivot = \"abcdefgh\"\n count = 8\n for i in range(len(pivot)):\n if cell[0] == pivot[i]:\n vertical_4 , vertical_2 = False , False\n if int(cell[1]) == 8 or int(cell[1]) == 1:\n vertical_4 = True\n count -= 4\n elif int(cell[1]) == 7 or int(cell[1]) == 2:\n vertical_2 = True\n count -= 2\n if i == 0 or i == 7:\n if vertical_4:\n count -= 2\n elif vertical_2:\n count -= 3\n else:\n count -= 4\n elif i == 1 or i == 6:\n if vertical_4:\n count -= 1\n else:\n count -= 2\n return count\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
# -*- coding: utf-8 -*-
# @Author : William
# @Project : TextGAN-william
# @FileName : gan_loss.py
# @Time : Created at 2019-07-11
# @Blog : http://zhiweil.ml/
# @Description :
# Copyrights (C) 2018. All Rights Reserved.
import torch
import torch.nn as nn
import config as cfg
class GANLoss(nn.Module):
"""Define different GAN Discriminator's objectives.
The GANLoss class abstracts away the need to create the target label tensor
that has the same size as the input.
"""
def __init__(self, loss_mode, which_net, which_D, target_real_label=1.0, target_fake_label=0.0, CUDA=False):
""" Initialize the GAN's Discriminator Loss class.
Parameters:
loss_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.
target_real_label (bool) - - label for a real image
target_fake_label (bool) - - label of a fake image
Note: Do not use sigmoid as the last layer of Discriminator.
LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.
"""
super(GANLoss, self).__init__()
self.register_buffer('real_label', torch.tensor(target_real_label))
self.register_buffer('fake_label', torch.tensor(target_fake_label))
self.loss_mode = loss_mode
self.which_net = which_net
self.which_D = which_D
self.gpu = CUDA
if loss_mode == 'lsgan':
self.loss = nn.MSELoss()
elif loss_mode in ['vanilla', 'ragan', 'rsgan']:
self.loss = nn.BCEWithLogitsLoss()
elif loss_mode in ['wgan', 'hinge']:
self.loss = None
else:
raise NotImplementedError('gan mode %s not implemented' % loss_mode)
def get_target_tensor(self, prediction, target_is_real):
"""Create label tensors with the same size as the input.
Parameters:
prediction (tensor) - - tpyically the prediction from a discriminator
target_is_real (bool) - - if the ground truth label is for real images or fake images
Returns:
A label tensor filled with ground truth label, and with the size of the input
"""
if target_is_real:
target_tensor = self.real_label
else:
target_tensor = self.fake_label
if self.gpu:
target_tensor = target_tensor.cuda()
return target_tensor.expand_as(prediction)
def G_loss(self, Dreal, Dfake):
if self.loss_mode != 'rsgan' and cfg.d_out_mean:
Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)
Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)
real_tensor = self.get_target_tensor(Dreal, True)
fake_tensor = self.get_target_tensor(Dreal, False)
if self.which_D == 'S':
prediction_fake = Dfake
prediction_real = real_tensor if self.loss_mode in ['vanilla'] else fake_tensor
elif self.which_D == 'Ra':
prediction_fake = Dfake - torch.mean(Dreal)
prediction_real = Dreal - torch.mean(Dfake)
else:
raise NotImplementedError('which_D name [%s] is not recognized' % self.which_D)
if self.loss_mode in ['lsgan', 'ragan']:
loss_fake = self.loss(prediction_fake, real_tensor)
loss_real = self.loss(prediction_real, fake_tensor)
g_loss = loss_fake + loss_real
elif self.loss_mode == 'vanilla':
loss_fake = -self.loss(prediction_fake, fake_tensor)
g_loss = loss_fake
elif self.loss_mode in ['wgan', 'hinge'] and self.which_D == 'S':
loss_fake = -prediction_fake.mean()
loss_real = prediction_real.mean()
g_loss = loss_fake + loss_real
elif self.loss_mode == 'hinge' and self.which_D == 'Ra':
loss_fake = nn.ReLU()(1.0 - prediction_fake).mean()
loss_real = nn.ReLU()(1.0 + prediction_real).mean()
g_loss = loss_fake + loss_real
elif self.loss_mode == 'rsgan':
loss_fake = self.loss(Dfake - Dreal, real_tensor)
g_loss = loss_fake
else:
raise NotImplementedError('loss_mode name [%s] is not recognized' % self.loss_mode)
return g_loss
def D_loss(self, Dreal, Dfake):
if self.loss_mode != 'rsgan' and cfg.d_out_mean:
Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)
Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)
real_tensor = self.get_target_tensor(Dreal, True)
fake_tensor = self.get_target_tensor(Dreal, False)
if self.which_D == 'S':
prediction_fake = Dfake
prediction_real = Dreal
elif self.which_D == 'Ra':
prediction_fake = Dfake - torch.mean(Dreal)
prediction_real = Dreal - torch.mean(Dfake)
else:
raise NotImplementedError('which_D name [%s] is not recognized' % self.which_D)
if self.loss_mode in ['lsgan', 'ragan', 'vanilla']:
loss_fake = self.loss(prediction_fake, fake_tensor)
loss_real = self.loss(prediction_real, real_tensor)
elif self.loss_mode == 'wgan':
loss_fake = prediction_fake.mean()
loss_real = -prediction_real.mean()
elif self.loss_mode == 'hinge':
loss_fake = nn.ReLU()(1.0 + prediction_fake).mean()
loss_real = nn.ReLU()(1.0 - prediction_real).mean()
elif self.loss_mode == 'rsgan':
loss_fake = 0.
loss_real = self.loss(Dreal - Dfake, real_tensor)
else:
raise NotImplementedError('loss_mode name [%s] is not recognized' % self.loss_mode)
return loss_fake + loss_real
def __call__(self, Dreal, Dfake):
"""Calculate loss given Discriminator's output and grount truth labels."""
if self.which_net == 'G':
return self.G_loss(Dreal, Dfake)
elif self.which_net == 'D':
return self.D_loss(Dreal, Dfake)
else:
raise NotImplementedError('which_net name [%s] is not recognized' % self.which_net)
|
normal
|
{
"blob_id": "9cea998d7d5cad3ddc00f667ca06151a938d48a1",
"index": 9424,
"step-1": "<mask token>\n\n\nclass GANLoss(nn.Module):\n <mask token>\n\n def __init__(self, loss_mode, which_net, which_D, target_real_label=1.0,\n target_fake_label=0.0, CUDA=False):\n \"\"\" Initialize the GAN's Discriminator Loss class.\n\n Parameters:\n loss_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n target_real_label (bool) - - label for a real image\n target_fake_label (bool) - - label of a fake image\n\n Note: Do not use sigmoid as the last layer of Discriminator.\n LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n \"\"\"\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n self.loss_mode = loss_mode\n self.which_net = which_net\n self.which_D = which_D\n self.gpu = CUDA\n if loss_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif loss_mode in ['vanilla', 'ragan', 'rsgan']:\n self.loss = nn.BCEWithLogitsLoss()\n elif loss_mode in ['wgan', 'hinge']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % loss_mode\n )\n\n def get_target_tensor(self, prediction, target_is_real):\n \"\"\"Create label tensors with the same size as the input.\n Parameters:\n prediction (tensor) - - tpyically the prediction from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n Returns:\n A label tensor filled with ground truth label, and with the size of the input\n \"\"\"\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n if self.gpu:\n target_tensor = target_tensor.cuda()\n return target_tensor.expand_as(prediction)\n\n def G_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = real_tensor if self.loss_mode in ['vanilla'\n ] else fake_tensor\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' %\n self.which_D)\n if self.loss_mode in ['lsgan', 'ragan']:\n loss_fake = self.loss(prediction_fake, real_tensor)\n loss_real = self.loss(prediction_real, fake_tensor)\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'vanilla':\n loss_fake = -self.loss(prediction_fake, fake_tensor)\n g_loss = loss_fake\n elif self.loss_mode in ['wgan', 'hinge'] and self.which_D == 'S':\n loss_fake = -prediction_fake.mean()\n loss_real = prediction_real.mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'hinge' and self.which_D == 'Ra':\n loss_fake = nn.ReLU()(1.0 - prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 + prediction_real).mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'rsgan':\n loss_fake = self.loss(Dfake - Dreal, real_tensor)\n g_loss = loss_fake\n else:\n raise NotImplementedError(\n 'loss_mode name [%s] is not recognized' % self.loss_mode)\n return g_loss\n\n def D_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = Dreal\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' %\n self.which_D)\n if self.loss_mode in ['lsgan', 'ragan', 'vanilla']:\n loss_fake = self.loss(prediction_fake, fake_tensor)\n loss_real = self.loss(prediction_real, real_tensor)\n elif self.loss_mode == 'wgan':\n loss_fake = prediction_fake.mean()\n loss_real = -prediction_real.mean()\n elif self.loss_mode == 'hinge':\n loss_fake = nn.ReLU()(1.0 + prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 - prediction_real).mean()\n elif self.loss_mode == 'rsgan':\n loss_fake = 0.0\n loss_real = self.loss(Dreal - Dfake, real_tensor)\n else:\n raise NotImplementedError(\n 'loss_mode name [%s] is not recognized' % self.loss_mode)\n return loss_fake + loss_real\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass GANLoss(nn.Module):\n <mask token>\n\n def __init__(self, loss_mode, which_net, which_D, target_real_label=1.0,\n target_fake_label=0.0, CUDA=False):\n \"\"\" Initialize the GAN's Discriminator Loss class.\n\n Parameters:\n loss_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n target_real_label (bool) - - label for a real image\n target_fake_label (bool) - - label of a fake image\n\n Note: Do not use sigmoid as the last layer of Discriminator.\n LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n \"\"\"\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n self.loss_mode = loss_mode\n self.which_net = which_net\n self.which_D = which_D\n self.gpu = CUDA\n if loss_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif loss_mode in ['vanilla', 'ragan', 'rsgan']:\n self.loss = nn.BCEWithLogitsLoss()\n elif loss_mode in ['wgan', 'hinge']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % loss_mode\n )\n\n def get_target_tensor(self, prediction, target_is_real):\n \"\"\"Create label tensors with the same size as the input.\n Parameters:\n prediction (tensor) - - tpyically the prediction from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n Returns:\n A label tensor filled with ground truth label, and with the size of the input\n \"\"\"\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n if self.gpu:\n target_tensor = target_tensor.cuda()\n return target_tensor.expand_as(prediction)\n\n def G_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = real_tensor if self.loss_mode in ['vanilla'\n ] else fake_tensor\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' %\n self.which_D)\n if self.loss_mode in ['lsgan', 'ragan']:\n loss_fake = self.loss(prediction_fake, real_tensor)\n loss_real = self.loss(prediction_real, fake_tensor)\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'vanilla':\n loss_fake = -self.loss(prediction_fake, fake_tensor)\n g_loss = loss_fake\n elif self.loss_mode in ['wgan', 'hinge'] and self.which_D == 'S':\n loss_fake = -prediction_fake.mean()\n loss_real = prediction_real.mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'hinge' and self.which_D == 'Ra':\n loss_fake = nn.ReLU()(1.0 - prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 + prediction_real).mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'rsgan':\n loss_fake = self.loss(Dfake - Dreal, real_tensor)\n g_loss = loss_fake\n else:\n raise NotImplementedError(\n 'loss_mode name [%s] is not recognized' % self.loss_mode)\n return g_loss\n\n def D_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = Dreal\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' %\n self.which_D)\n if self.loss_mode in ['lsgan', 'ragan', 'vanilla']:\n loss_fake = self.loss(prediction_fake, fake_tensor)\n loss_real = self.loss(prediction_real, real_tensor)\n elif self.loss_mode == 'wgan':\n loss_fake = prediction_fake.mean()\n loss_real = -prediction_real.mean()\n elif self.loss_mode == 'hinge':\n loss_fake = nn.ReLU()(1.0 + prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 - prediction_real).mean()\n elif self.loss_mode == 'rsgan':\n loss_fake = 0.0\n loss_real = self.loss(Dreal - Dfake, real_tensor)\n else:\n raise NotImplementedError(\n 'loss_mode name [%s] is not recognized' % self.loss_mode)\n return loss_fake + loss_real\n\n def __call__(self, Dreal, Dfake):\n \"\"\"Calculate loss given Discriminator's output and grount truth labels.\"\"\"\n if self.which_net == 'G':\n return self.G_loss(Dreal, Dfake)\n elif self.which_net == 'D':\n return self.D_loss(Dreal, Dfake)\n else:\n raise NotImplementedError(\n 'which_net name [%s] is not recognized' % self.which_net)\n",
"step-3": "<mask token>\n\n\nclass GANLoss(nn.Module):\n \"\"\"Define different GAN Discriminator's objectives.\n\n The GANLoss class abstracts away the need to create the target label tensor\n that has the same size as the input.\n \"\"\"\n\n def __init__(self, loss_mode, which_net, which_D, target_real_label=1.0,\n target_fake_label=0.0, CUDA=False):\n \"\"\" Initialize the GAN's Discriminator Loss class.\n\n Parameters:\n loss_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n target_real_label (bool) - - label for a real image\n target_fake_label (bool) - - label of a fake image\n\n Note: Do not use sigmoid as the last layer of Discriminator.\n LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n \"\"\"\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n self.loss_mode = loss_mode\n self.which_net = which_net\n self.which_D = which_D\n self.gpu = CUDA\n if loss_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif loss_mode in ['vanilla', 'ragan', 'rsgan']:\n self.loss = nn.BCEWithLogitsLoss()\n elif loss_mode in ['wgan', 'hinge']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % loss_mode\n )\n\n def get_target_tensor(self, prediction, target_is_real):\n \"\"\"Create label tensors with the same size as the input.\n Parameters:\n prediction (tensor) - - tpyically the prediction from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n Returns:\n A label tensor filled with ground truth label, and with the size of the input\n \"\"\"\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n if self.gpu:\n target_tensor = target_tensor.cuda()\n return target_tensor.expand_as(prediction)\n\n def G_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = real_tensor if self.loss_mode in ['vanilla'\n ] else fake_tensor\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' %\n self.which_D)\n if self.loss_mode in ['lsgan', 'ragan']:\n loss_fake = self.loss(prediction_fake, real_tensor)\n loss_real = self.loss(prediction_real, fake_tensor)\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'vanilla':\n loss_fake = -self.loss(prediction_fake, fake_tensor)\n g_loss = loss_fake\n elif self.loss_mode in ['wgan', 'hinge'] and self.which_D == 'S':\n loss_fake = -prediction_fake.mean()\n loss_real = prediction_real.mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'hinge' and self.which_D == 'Ra':\n loss_fake = nn.ReLU()(1.0 - prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 + prediction_real).mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'rsgan':\n loss_fake = self.loss(Dfake - Dreal, real_tensor)\n g_loss = loss_fake\n else:\n raise NotImplementedError(\n 'loss_mode name [%s] is not recognized' % self.loss_mode)\n return g_loss\n\n def D_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = Dreal\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' %\n self.which_D)\n if self.loss_mode in ['lsgan', 'ragan', 'vanilla']:\n loss_fake = self.loss(prediction_fake, fake_tensor)\n loss_real = self.loss(prediction_real, real_tensor)\n elif self.loss_mode == 'wgan':\n loss_fake = prediction_fake.mean()\n loss_real = -prediction_real.mean()\n elif self.loss_mode == 'hinge':\n loss_fake = nn.ReLU()(1.0 + prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 - prediction_real).mean()\n elif self.loss_mode == 'rsgan':\n loss_fake = 0.0\n loss_real = self.loss(Dreal - Dfake, real_tensor)\n else:\n raise NotImplementedError(\n 'loss_mode name [%s] is not recognized' % self.loss_mode)\n return loss_fake + loss_real\n\n def __call__(self, Dreal, Dfake):\n \"\"\"Calculate loss given Discriminator's output and grount truth labels.\"\"\"\n if self.which_net == 'G':\n return self.G_loss(Dreal, Dfake)\n elif self.which_net == 'D':\n return self.D_loss(Dreal, Dfake)\n else:\n raise NotImplementedError(\n 'which_net name [%s] is not recognized' % self.which_net)\n",
"step-4": "import torch\nimport torch.nn as nn\nimport config as cfg\n\n\nclass GANLoss(nn.Module):\n \"\"\"Define different GAN Discriminator's objectives.\n\n The GANLoss class abstracts away the need to create the target label tensor\n that has the same size as the input.\n \"\"\"\n\n def __init__(self, loss_mode, which_net, which_D, target_real_label=1.0,\n target_fake_label=0.0, CUDA=False):\n \"\"\" Initialize the GAN's Discriminator Loss class.\n\n Parameters:\n loss_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n target_real_label (bool) - - label for a real image\n target_fake_label (bool) - - label of a fake image\n\n Note: Do not use sigmoid as the last layer of Discriminator.\n LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n \"\"\"\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n self.loss_mode = loss_mode\n self.which_net = which_net\n self.which_D = which_D\n self.gpu = CUDA\n if loss_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif loss_mode in ['vanilla', 'ragan', 'rsgan']:\n self.loss = nn.BCEWithLogitsLoss()\n elif loss_mode in ['wgan', 'hinge']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % loss_mode\n )\n\n def get_target_tensor(self, prediction, target_is_real):\n \"\"\"Create label tensors with the same size as the input.\n Parameters:\n prediction (tensor) - - tpyically the prediction from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n Returns:\n A label tensor filled with ground truth label, and with the size of the input\n \"\"\"\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n if self.gpu:\n target_tensor = target_tensor.cuda()\n return target_tensor.expand_as(prediction)\n\n def G_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = real_tensor if self.loss_mode in ['vanilla'\n ] else fake_tensor\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' %\n self.which_D)\n if self.loss_mode in ['lsgan', 'ragan']:\n loss_fake = self.loss(prediction_fake, real_tensor)\n loss_real = self.loss(prediction_real, fake_tensor)\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'vanilla':\n loss_fake = -self.loss(prediction_fake, fake_tensor)\n g_loss = loss_fake\n elif self.loss_mode in ['wgan', 'hinge'] and self.which_D == 'S':\n loss_fake = -prediction_fake.mean()\n loss_real = prediction_real.mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'hinge' and self.which_D == 'Ra':\n loss_fake = nn.ReLU()(1.0 - prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 + prediction_real).mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'rsgan':\n loss_fake = self.loss(Dfake - Dreal, real_tensor)\n g_loss = loss_fake\n else:\n raise NotImplementedError(\n 'loss_mode name [%s] is not recognized' % self.loss_mode)\n return g_loss\n\n def D_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = Dreal\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' %\n self.which_D)\n if self.loss_mode in ['lsgan', 'ragan', 'vanilla']:\n loss_fake = self.loss(prediction_fake, fake_tensor)\n loss_real = self.loss(prediction_real, real_tensor)\n elif self.loss_mode == 'wgan':\n loss_fake = prediction_fake.mean()\n loss_real = -prediction_real.mean()\n elif self.loss_mode == 'hinge':\n loss_fake = nn.ReLU()(1.0 + prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 - prediction_real).mean()\n elif self.loss_mode == 'rsgan':\n loss_fake = 0.0\n loss_real = self.loss(Dreal - Dfake, real_tensor)\n else:\n raise NotImplementedError(\n 'loss_mode name [%s] is not recognized' % self.loss_mode)\n return loss_fake + loss_real\n\n def __call__(self, Dreal, Dfake):\n \"\"\"Calculate loss given Discriminator's output and grount truth labels.\"\"\"\n if self.which_net == 'G':\n return self.G_loss(Dreal, Dfake)\n elif self.which_net == 'D':\n return self.D_loss(Dreal, Dfake)\n else:\n raise NotImplementedError(\n 'which_net name [%s] is not recognized' % self.which_net)\n",
"step-5": "# -*- coding: utf-8 -*-\n# @Author : William\n# @Project : TextGAN-william\n# @FileName : gan_loss.py\n# @Time : Created at 2019-07-11\n# @Blog : http://zhiweil.ml/\n# @Description : \n# Copyrights (C) 2018. All Rights Reserved.\n\nimport torch\nimport torch.nn as nn\n\nimport config as cfg\n\n\nclass GANLoss(nn.Module):\n \"\"\"Define different GAN Discriminator's objectives.\n\n The GANLoss class abstracts away the need to create the target label tensor\n that has the same size as the input.\n \"\"\"\n\n def __init__(self, loss_mode, which_net, which_D, target_real_label=1.0, target_fake_label=0.0, CUDA=False):\n \"\"\" Initialize the GAN's Discriminator Loss class.\n\n Parameters:\n loss_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n target_real_label (bool) - - label for a real image\n target_fake_label (bool) - - label of a fake image\n\n Note: Do not use sigmoid as the last layer of Discriminator.\n LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n \"\"\"\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n self.loss_mode = loss_mode\n self.which_net = which_net\n self.which_D = which_D\n self.gpu = CUDA\n\n if loss_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif loss_mode in ['vanilla', 'ragan', 'rsgan']:\n self.loss = nn.BCEWithLogitsLoss()\n elif loss_mode in ['wgan', 'hinge']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % loss_mode)\n\n def get_target_tensor(self, prediction, target_is_real):\n \"\"\"Create label tensors with the same size as the input.\n Parameters:\n prediction (tensor) - - tpyically the prediction from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n Returns:\n A label tensor filled with ground truth label, and with the size of the input\n \"\"\"\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n if self.gpu:\n target_tensor = target_tensor.cuda()\n return target_tensor.expand_as(prediction)\n\n def G_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = real_tensor if self.loss_mode in ['vanilla'] else fake_tensor\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' % self.which_D)\n\n if self.loss_mode in ['lsgan', 'ragan']:\n loss_fake = self.loss(prediction_fake, real_tensor)\n loss_real = self.loss(prediction_real, fake_tensor)\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'vanilla':\n loss_fake = -self.loss(prediction_fake, fake_tensor)\n g_loss = loss_fake\n elif self.loss_mode in ['wgan', 'hinge'] and self.which_D == 'S':\n loss_fake = -prediction_fake.mean()\n loss_real = prediction_real.mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'hinge' and self.which_D == 'Ra':\n loss_fake = nn.ReLU()(1.0 - prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 + prediction_real).mean()\n g_loss = loss_fake + loss_real\n elif self.loss_mode == 'rsgan':\n loss_fake = self.loss(Dfake - Dreal, real_tensor)\n g_loss = loss_fake\n else:\n raise NotImplementedError('loss_mode name [%s] is not recognized' % self.loss_mode)\n\n return g_loss\n\n def D_loss(self, Dreal, Dfake):\n if self.loss_mode != 'rsgan' and cfg.d_out_mean:\n Dfake = torch.mean(Dfake.view(cfg.batch_size, -1), dim=-1)\n Dreal = torch.mean(Dreal.view(cfg.batch_size, -1), dim=-1)\n\n real_tensor = self.get_target_tensor(Dreal, True)\n fake_tensor = self.get_target_tensor(Dreal, False)\n\n if self.which_D == 'S':\n prediction_fake = Dfake\n prediction_real = Dreal\n elif self.which_D == 'Ra':\n prediction_fake = Dfake - torch.mean(Dreal)\n prediction_real = Dreal - torch.mean(Dfake)\n else:\n raise NotImplementedError('which_D name [%s] is not recognized' % self.which_D)\n\n if self.loss_mode in ['lsgan', 'ragan', 'vanilla']:\n loss_fake = self.loss(prediction_fake, fake_tensor)\n loss_real = self.loss(prediction_real, real_tensor)\n elif self.loss_mode == 'wgan':\n loss_fake = prediction_fake.mean()\n loss_real = -prediction_real.mean()\n elif self.loss_mode == 'hinge':\n loss_fake = nn.ReLU()(1.0 + prediction_fake).mean()\n loss_real = nn.ReLU()(1.0 - prediction_real).mean()\n elif self.loss_mode == 'rsgan':\n loss_fake = 0.\n loss_real = self.loss(Dreal - Dfake, real_tensor)\n else:\n raise NotImplementedError('loss_mode name [%s] is not recognized' % self.loss_mode)\n\n return loss_fake + loss_real\n\n def __call__(self, Dreal, Dfake):\n \"\"\"Calculate loss given Discriminator's output and grount truth labels.\"\"\"\n if self.which_net == 'G':\n return self.G_loss(Dreal, Dfake)\n elif self.which_net == 'D':\n return self.D_loss(Dreal, Dfake)\n else:\n raise NotImplementedError('which_net name [%s] is not recognized' % self.which_net)\n",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def renew_commodity_future(year_month: str, contract_kind: str,
main_code_path: str, rar_data_file_path: str, clean_data_path: str,
time_range_path: str, end_date: str, commodity_bool=True):
"""
用于更新月度的商品期货数据
year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911
contract_kind:放对应品种的list 类似['A','B']
main_code_path:对应存放主力合约的地方
rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名
clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处
time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv
end_date :'20200103' 今日的日期,用来请求tushare中的交易日历,数据的读取合并都是以交易日历的时间驱动
commodity_bool:商品期货对应True,金融期货False,默认商品期货
"""
month = year_month
if commodity_bool:
file_name = rar_data_file_path + 'FutAC_Min1_Std_' + month + '.rar'
else:
file_name = rar_data_file_path + 'FutSF_Min1_Std_' + month + '.rar'
orignial_path = main_code_path
specifi_path = orignial_path + contract_kind + '_1day_main.npy'
rar = rarfile.RarFile(file_name, pwd='www.jinshuyuan.net')
orignal_clean_csv_path = clean_data_path
pwd = 'www.jinshuyuan.net'
data = np.load(specifi_path)
time_0931_15 = pd.read_csv(time_range_path)['date'].values.tolist()
rar.extractall(path=file_name.split('.')[0])
pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6'
)
ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
date_df = pro.trade_cal(exchange='DCE', start_date='20100101', end_date
=end_date)
date_df = date_df.loc[date_df['is_open'] == 1]
date_list = date_df['cal_date'].tolist()
date_df = pd.DataFrame({'date': date_list})
date_df['month'] = date_df['date'].str[:6]
target_date = date_df.loc[date_df['month'] == month]
target_date_index = target_date.index.values
target_date = target_date['date'].values
data = data.reshape(-1)
contract_main_pool = data[target_date_index]
contract_main_pool = (pd.Series(contract_main_pool).str.split('.').str[
0] + '.csv').values
file_pools = os.listdir(file_name.split('.')[0])
if contract_main_pool[0] not in file_pools:
contract_main_pool = [contract_file.lower() for contract_file in
contract_main_pool]
if contract_main_pool[0] not in file_pools:
print(f'找不到{contract_main_pool[0]}')
contract_main_pool = (file_name.split('.')[0] + '/' + pd.Series(
contract_main_pool)).values
row_1 = ['市场代码', '合约代码', '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量']
orignal_data = []
orignal_data.append(row_1)
for index in range(len(target_date)):
date = target_date[index]
one_file_path = contract_main_pool[index]
df = pd.read_csv(one_file_path, encoding='gbk')
df['date'] = df['时间'].str[:10]
df['date2'] = df['date'].str.replace('-', '')
result = df.loc[df['date2'] == date]
if result.shape[0] > 0:
for row_index in range(len(result)):
target_row = result.iloc[row_index].tolist()
clean_row = target_row[:-2]
orignal_data.append(clean_row)
print(f'{contract_kind} {date} finished!')
else:
print(f'没找到合约品种{contract_kind}在{date}')
print(f'{contract_kind}在{month}月的主力合约数据读取完成')
final_df = pd.DataFrame(orignal_data[1:], columns=orignal_data[0])
final_df['date'] = final_df['时间'].str[:10]
final_df_date = final_df['date'].unique()
final_df['date'] = final_df['时间'].str[:10]
final_df['time'] = final_df['时间'].str[10:].str.strip()
final_df['时间'] = final_df['date'] + ' ' + final_df['time']
final_df = final_df.sort_values('时间')
final_df['合约代码'] = final_df['合约代码'].str.upper()
final_df = final_df.sort_values('时间')
final_df['transf_date'] = pd.to_datetime(final_df['date'])
final_df.set_index('transf_date', inplace=True)
combine_all_df = pd.DataFrame()
final_df['date2'] = final_df['date'].str.replace('-', '')
for date_index in range(len(target_date)):
target_df = final_df.loc[final_df['date2'] == target_date[date_index]]
target_num = len(target_df)
theory_num = len(time_0931_15)
if target_num > 0:
have_time = target_df['time'].values.tolist()
lack_time = [x for x in time_0931_15 if x not in have_time]
if lack_time:
print(f'{target_date[date_index]} 不连续')
insert_array = np.empty(shape=(len(lack_time), 12))
insert_array.fill(np.nan)
insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',
'时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])
insert_df['date'] = target_date[date_index]
insert_df['time'] = lack_time
if len(lack_time) < len(time_0931_15):
insert_df['合约代码'] = target_df['合约代码'].unique()[-1]
combine_insert_df = pd.concat([target_df, insert_df])
combine_all_df = pd.concat([combine_all_df, combine_insert_df])
else:
print(f'{target_date[date_index]}empty ')
lack_time = [x for x in time_0931_15]
insert_array = np.empty(shape=(len(lack_time), 12))
insert_array.fill(np.nan)
insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',
'时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])
insert_df['date'] = target_date[date_index]
insert_df['time'] = lack_time
combine_all_df = pd.concat([combine_all_df, insert_df])
combine_all_df['时间'] = combine_all_df['date'] + ' ' + combine_all_df['time'
]
combine_all_df = combine_all_df.sort_values('时间')
combine_all_df.reset_index(inplace=True)
combine_all_df = combine_all_df[['市场代码', '合约代码', '时间', '开', '高', '低',
'收', '成交量', '成交额', '持仓量', 'date', 'time']]
combine_all_df['时间'] = combine_all_df['时间'].str.replace('-', '')
combine_all_df['date'] = combine_all_df['date'].str.replace('-', '')
combine_df = combine_all_df.copy()
contract_type = contract_kind
combine_df = combine_df.sort_values('时间')
end_time = '15:15:00'
end_index = np.where(combine_df['time'] == end_time)[0] + 1
end_index = np.hstack(([0], end_index))
start = end_index[:-1]
end = end_index[1:]
last_day = date_df['date'].iloc[target_date_index[0] - 1]
last_day = last_day[:4] + '-' + last_day[4:6] + '-' + last_day[6:]
first_day_have = combine_df[start[0]:end[0]]['time'].values
full_time = combine_df['time'].unique()
full_time.sort()
first_day_lack = [x for x in full_time[-179:]]
first_day_lack.sort()
lack_array = np.empty(shape=(len(first_day_lack), 12))
lack_array.fill(np.nan)
first_day_lack_df = pd.DataFrame(lack_array, columns=combine_df.columns)
first_day_lack_df['time'] = first_day_lack
first_day_lack_df['date'] = last_day
first_day_lack_df['时间'] = first_day_lack_df['date'
] + ' ' + first_day_lack_df['time']
last_df = pd.read_csv(contract_main_pool[0], encoding='gbk')
last_df['date'] = last_df['时间'].str[:10]
last_df['time'] = last_df['时间'].str[11:]
last_time_pool = last_df.loc[last_df['date'] == last_day]['time'].values
last_day_have_date = []
if last_time_pool.shape[0] > 0:
print(f'期货品种{contract_kind}在前一个交易日{last_day}有夜盘数据,需要读取覆盖')
last_day_have_date = [x for x in last_time_pool]
if last_day_have_date:
for index in range(len(last_day_have_date)):
origanl_index = last_df.loc[(last_df['date'] == last_day) & (
last_df['time'] == last_day_have_date[index])].index[0]
target_index = first_day_lack_df.loc[first_day_lack_df['time'] ==
last_day_have_date[index]].index[0]
first_day_lack_df.iloc[target_index] = last_df.iloc[origanl_index]
else:
print(f'期货品种{contract_kind}在前一个交易日{last_day}没有夜盘数据,不需要读取覆盖')
print('直接使用np.nan填充上一个交易日的夜盘数据')
for index in range(first_day_lack_df.shape[0]):
combine_df = combine_df.append(first_day_lack_df.iloc[index])
combine_df['时间'] = combine_df['时间'].str.replace('-', '')
combine_df['date'] = combine_df['date'].str.replace('-', '')
combine_df.sort_values('时间', inplace=True)
end_index = np.where(combine_df['time'] == end_time)[0] + 1
end_index = np.hstack(([0], end_index))
start = end_index[:-1]
end = end_index[1:]
col_type_list = ['开', '高', '低', '收', '成交量', '成交额', '持仓量']
dir_name_list = ['open', 'high', 'low', 'close', 'volume', 'amount',
'position']
merge_df = pd.DataFrame({'time': time_0931_15})
combine_df['date'] = combine_df['时间'].str[:8]
for index in range(len(col_type_list)):
col_type = col_type_list[index]
csv_df = pd.DataFrame()
for s_index, e_index in zip(start, end):
res = combine_df.iloc[s_index:e_index, :]
one_date_df = pd.DataFrame(res[col_type].values.reshape(1, -1),
columns=res['time'].values.tolist())
one_date_df['main_contract_code'] = res.iloc[-1]['合约代码']
one_date_df['date'] = res.iloc[-1]['date']
col_layout = ['date']
col_layout = np.hstack((col_layout, res['time'].values.tolist()))
col_layout = np.hstack((col_layout, ['main_contract_code']))
one_date_df = one_date_df[col_layout]
csv_df = pd.concat([csv_df, one_date_df])
orignal_csv_df = pd.read_csv(orignal_clean_csv_path + contract_kind +
'_1min_' + dir_name_list[index] + '.csv')
column_ouput_form = orignal_csv_df.columns.values
orignal_date_pool = pd.to_datetime(orignal_csv_df['date'], format=
'%Y-%m-%d').values
current_date_pool = pd.to_datetime(csv_df['date'], format='%Y-%m-%d'
).values
orignal_csv_df['date'] = pd.to_datetime(orignal_csv_df['date'],
format='%Y-%m-%d').dt.strftime('%Y-%m-%d')
csv_df['date'] = pd.to_datetime(csv_df['date'], format='%Y%m%d'
).dt.strftime('%Y-%m-%d')
main_code = csv_df['main_contract_code'].iloc[0]
main_code_num = csv_df['main_contract_code'].str.findall('[0-9]+'
).iloc[0][0]
if len(main_code_num) == 3:
print(f'合约代码{main_code}缺少一位数字,将被替换')
csv_df['main_contract_code'] = csv_df['main_contract_code'].str[:2
] + month[0] + csv_df['main_contract_code'].str[2:]
main_code = csv_df['main_contract_code'].iloc[0]
print(f'合约代码{main_code}')
intersection_pool = [date for date in orignal_date_pool if date in
current_date_pool]
if not intersection_pool:
print(
f'新旧数据没有时间交集,{contract_kind} {dir_name_list[index]} 将被添加到先前数据中'
)
orignal_csv_df = pd.concat([orignal_csv_df, csv_df])
orignal_csv_df.sort_values('date', inplace=True)
orignal_csv_df = orignal_csv_df[column_ouput_form]
orignal_csv_df.to_csv(orignal_clean_csv_path + contract_kind +
'_1min_' + dir_name_list[index] + '.csv', index=False)
print(f'期货品种{contract_kind} {dir_name_list[index]} 完成')
else:
print(
f'新旧数据的时间出现交集!!{contract_kind} {dir_name_list[index]} 将不会被添加到先前数据中'
)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
year_month = '201911'
contract_kind = 'NI'
rar_data_file_path = (
'C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'
)
main_code_path = (
'C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/main/main_/'
)
clean_data_path = 'D:/1_min补充统一/'
end_date = '20200107'
time_range_path = 'D:/统一所有品种时间范围.csv'
def renew_commodity_future(year_month: str, contract_kind: str,
main_code_path: str, rar_data_file_path: str, clean_data_path: str,
time_range_path: str, end_date: str, commodity_bool=True):
"""
用于更新月度的商品期货数据
year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911
contract_kind:放对应品种的list 类似['A','B']
main_code_path:对应存放主力合约的地方
rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名
clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处
time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv
end_date :'20200103' 今日的日期,用来请求tushare中的交易日历,数据的读取合并都是以交易日历的时间驱动
commodity_bool:商品期货对应True,金融期货False,默认商品期货
"""
month = year_month
if commodity_bool:
file_name = rar_data_file_path + 'FutAC_Min1_Std_' + month + '.rar'
else:
file_name = rar_data_file_path + 'FutSF_Min1_Std_' + month + '.rar'
orignial_path = main_code_path
specifi_path = orignial_path + contract_kind + '_1day_main.npy'
rar = rarfile.RarFile(file_name, pwd='www.jinshuyuan.net')
orignal_clean_csv_path = clean_data_path
pwd = 'www.jinshuyuan.net'
data = np.load(specifi_path)
time_0931_15 = pd.read_csv(time_range_path)['date'].values.tolist()
rar.extractall(path=file_name.split('.')[0])
pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6'
)
ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
date_df = pro.trade_cal(exchange='DCE', start_date='20100101', end_date
=end_date)
date_df = date_df.loc[date_df['is_open'] == 1]
date_list = date_df['cal_date'].tolist()
date_df = pd.DataFrame({'date': date_list})
date_df['month'] = date_df['date'].str[:6]
target_date = date_df.loc[date_df['month'] == month]
target_date_index = target_date.index.values
target_date = target_date['date'].values
data = data.reshape(-1)
contract_main_pool = data[target_date_index]
contract_main_pool = (pd.Series(contract_main_pool).str.split('.').str[
0] + '.csv').values
file_pools = os.listdir(file_name.split('.')[0])
if contract_main_pool[0] not in file_pools:
contract_main_pool = [contract_file.lower() for contract_file in
contract_main_pool]
if contract_main_pool[0] not in file_pools:
print(f'找不到{contract_main_pool[0]}')
contract_main_pool = (file_name.split('.')[0] + '/' + pd.Series(
contract_main_pool)).values
row_1 = ['市场代码', '合约代码', '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量']
orignal_data = []
orignal_data.append(row_1)
for index in range(len(target_date)):
date = target_date[index]
one_file_path = contract_main_pool[index]
df = pd.read_csv(one_file_path, encoding='gbk')
df['date'] = df['时间'].str[:10]
df['date2'] = df['date'].str.replace('-', '')
result = df.loc[df['date2'] == date]
if result.shape[0] > 0:
for row_index in range(len(result)):
target_row = result.iloc[row_index].tolist()
clean_row = target_row[:-2]
orignal_data.append(clean_row)
print(f'{contract_kind} {date} finished!')
else:
print(f'没找到合约品种{contract_kind}在{date}')
print(f'{contract_kind}在{month}月的主力合约数据读取完成')
final_df = pd.DataFrame(orignal_data[1:], columns=orignal_data[0])
final_df['date'] = final_df['时间'].str[:10]
final_df_date = final_df['date'].unique()
final_df['date'] = final_df['时间'].str[:10]
final_df['time'] = final_df['时间'].str[10:].str.strip()
final_df['时间'] = final_df['date'] + ' ' + final_df['time']
final_df = final_df.sort_values('时间')
final_df['合约代码'] = final_df['合约代码'].str.upper()
final_df = final_df.sort_values('时间')
final_df['transf_date'] = pd.to_datetime(final_df['date'])
final_df.set_index('transf_date', inplace=True)
combine_all_df = pd.DataFrame()
final_df['date2'] = final_df['date'].str.replace('-', '')
for date_index in range(len(target_date)):
target_df = final_df.loc[final_df['date2'] == target_date[date_index]]
target_num = len(target_df)
theory_num = len(time_0931_15)
if target_num > 0:
have_time = target_df['time'].values.tolist()
lack_time = [x for x in time_0931_15 if x not in have_time]
if lack_time:
print(f'{target_date[date_index]} 不连续')
insert_array = np.empty(shape=(len(lack_time), 12))
insert_array.fill(np.nan)
insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',
'时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])
insert_df['date'] = target_date[date_index]
insert_df['time'] = lack_time
if len(lack_time) < len(time_0931_15):
insert_df['合约代码'] = target_df['合约代码'].unique()[-1]
combine_insert_df = pd.concat([target_df, insert_df])
combine_all_df = pd.concat([combine_all_df, combine_insert_df])
else:
print(f'{target_date[date_index]}empty ')
lack_time = [x for x in time_0931_15]
insert_array = np.empty(shape=(len(lack_time), 12))
insert_array.fill(np.nan)
insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',
'时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])
insert_df['date'] = target_date[date_index]
insert_df['time'] = lack_time
combine_all_df = pd.concat([combine_all_df, insert_df])
combine_all_df['时间'] = combine_all_df['date'] + ' ' + combine_all_df['time'
]
combine_all_df = combine_all_df.sort_values('时间')
combine_all_df.reset_index(inplace=True)
combine_all_df = combine_all_df[['市场代码', '合约代码', '时间', '开', '高', '低',
'收', '成交量', '成交额', '持仓量', 'date', 'time']]
combine_all_df['时间'] = combine_all_df['时间'].str.replace('-', '')
combine_all_df['date'] = combine_all_df['date'].str.replace('-', '')
combine_df = combine_all_df.copy()
contract_type = contract_kind
combine_df = combine_df.sort_values('时间')
end_time = '15:15:00'
end_index = np.where(combine_df['time'] == end_time)[0] + 1
end_index = np.hstack(([0], end_index))
start = end_index[:-1]
end = end_index[1:]
last_day = date_df['date'].iloc[target_date_index[0] - 1]
last_day = last_day[:4] + '-' + last_day[4:6] + '-' + last_day[6:]
first_day_have = combine_df[start[0]:end[0]]['time'].values
full_time = combine_df['time'].unique()
full_time.sort()
first_day_lack = [x for x in full_time[-179:]]
first_day_lack.sort()
lack_array = np.empty(shape=(len(first_day_lack), 12))
lack_array.fill(np.nan)
first_day_lack_df = pd.DataFrame(lack_array, columns=combine_df.columns)
first_day_lack_df['time'] = first_day_lack
first_day_lack_df['date'] = last_day
first_day_lack_df['时间'] = first_day_lack_df['date'
] + ' ' + first_day_lack_df['time']
last_df = pd.read_csv(contract_main_pool[0], encoding='gbk')
last_df['date'] = last_df['时间'].str[:10]
last_df['time'] = last_df['时间'].str[11:]
last_time_pool = last_df.loc[last_df['date'] == last_day]['time'].values
last_day_have_date = []
if last_time_pool.shape[0] > 0:
print(f'期货品种{contract_kind}在前一个交易日{last_day}有夜盘数据,需要读取覆盖')
last_day_have_date = [x for x in last_time_pool]
if last_day_have_date:
for index in range(len(last_day_have_date)):
origanl_index = last_df.loc[(last_df['date'] == last_day) & (
last_df['time'] == last_day_have_date[index])].index[0]
target_index = first_day_lack_df.loc[first_day_lack_df['time'] ==
last_day_have_date[index]].index[0]
first_day_lack_df.iloc[target_index] = last_df.iloc[origanl_index]
else:
print(f'期货品种{contract_kind}在前一个交易日{last_day}没有夜盘数据,不需要读取覆盖')
print('直接使用np.nan填充上一个交易日的夜盘数据')
for index in range(first_day_lack_df.shape[0]):
combine_df = combine_df.append(first_day_lack_df.iloc[index])
combine_df['时间'] = combine_df['时间'].str.replace('-', '')
combine_df['date'] = combine_df['date'].str.replace('-', '')
combine_df.sort_values('时间', inplace=True)
end_index = np.where(combine_df['time'] == end_time)[0] + 1
end_index = np.hstack(([0], end_index))
start = end_index[:-1]
end = end_index[1:]
col_type_list = ['开', '高', '低', '收', '成交量', '成交额', '持仓量']
dir_name_list = ['open', 'high', 'low', 'close', 'volume', 'amount',
'position']
merge_df = pd.DataFrame({'time': time_0931_15})
combine_df['date'] = combine_df['时间'].str[:8]
for index in range(len(col_type_list)):
col_type = col_type_list[index]
csv_df = pd.DataFrame()
for s_index, e_index in zip(start, end):
res = combine_df.iloc[s_index:e_index, :]
one_date_df = pd.DataFrame(res[col_type].values.reshape(1, -1),
columns=res['time'].values.tolist())
one_date_df['main_contract_code'] = res.iloc[-1]['合约代码']
one_date_df['date'] = res.iloc[-1]['date']
col_layout = ['date']
col_layout = np.hstack((col_layout, res['time'].values.tolist()))
col_layout = np.hstack((col_layout, ['main_contract_code']))
one_date_df = one_date_df[col_layout]
csv_df = pd.concat([csv_df, one_date_df])
orignal_csv_df = pd.read_csv(orignal_clean_csv_path + contract_kind +
'_1min_' + dir_name_list[index] + '.csv')
column_ouput_form = orignal_csv_df.columns.values
orignal_date_pool = pd.to_datetime(orignal_csv_df['date'], format=
'%Y-%m-%d').values
current_date_pool = pd.to_datetime(csv_df['date'], format='%Y-%m-%d'
).values
orignal_csv_df['date'] = pd.to_datetime(orignal_csv_df['date'],
format='%Y-%m-%d').dt.strftime('%Y-%m-%d')
csv_df['date'] = pd.to_datetime(csv_df['date'], format='%Y%m%d'
).dt.strftime('%Y-%m-%d')
main_code = csv_df['main_contract_code'].iloc[0]
main_code_num = csv_df['main_contract_code'].str.findall('[0-9]+'
).iloc[0][0]
if len(main_code_num) == 3:
print(f'合约代码{main_code}缺少一位数字,将被替换')
csv_df['main_contract_code'] = csv_df['main_contract_code'].str[:2
] + month[0] + csv_df['main_contract_code'].str[2:]
main_code = csv_df['main_contract_code'].iloc[0]
print(f'合约代码{main_code}')
intersection_pool = [date for date in orignal_date_pool if date in
current_date_pool]
if not intersection_pool:
print(
f'新旧数据没有时间交集,{contract_kind} {dir_name_list[index]} 将被添加到先前数据中'
)
orignal_csv_df = pd.concat([orignal_csv_df, csv_df])
orignal_csv_df.sort_values('date', inplace=True)
orignal_csv_df = orignal_csv_df[column_ouput_form]
orignal_csv_df.to_csv(orignal_clean_csv_path + contract_kind +
'_1min_' + dir_name_list[index] + '.csv', index=False)
print(f'期货品种{contract_kind} {dir_name_list[index]} 完成')
else:
print(
f'新旧数据的时间出现交集!!{contract_kind} {dir_name_list[index]} 将不会被添加到先前数据中'
)
<|reserved_special_token_1|>
import numpy as np
import pandas as pd
from unrar import rarfile
import numpy as np
import pandas as pd
import tushare as ts
import os
year_month = '201911'
contract_kind = 'NI'
rar_data_file_path = (
'C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'
)
main_code_path = (
'C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/main/main_/'
)
clean_data_path = 'D:/1_min补充统一/'
end_date = '20200107'
time_range_path = 'D:/统一所有品种时间范围.csv'
def renew_commodity_future(year_month: str, contract_kind: str,
main_code_path: str, rar_data_file_path: str, clean_data_path: str,
time_range_path: str, end_date: str, commodity_bool=True):
"""
用于更新月度的商品期货数据
year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911
contract_kind:放对应品种的list 类似['A','B']
main_code_path:对应存放主力合约的地方
rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名
clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处
time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv
end_date :'20200103' 今日的日期,用来请求tushare中的交易日历,数据的读取合并都是以交易日历的时间驱动
commodity_bool:商品期货对应True,金融期货False,默认商品期货
"""
month = year_month
if commodity_bool:
file_name = rar_data_file_path + 'FutAC_Min1_Std_' + month + '.rar'
else:
file_name = rar_data_file_path + 'FutSF_Min1_Std_' + month + '.rar'
orignial_path = main_code_path
specifi_path = orignial_path + contract_kind + '_1day_main.npy'
rar = rarfile.RarFile(file_name, pwd='www.jinshuyuan.net')
orignal_clean_csv_path = clean_data_path
pwd = 'www.jinshuyuan.net'
data = np.load(specifi_path)
time_0931_15 = pd.read_csv(time_range_path)['date'].values.tolist()
rar.extractall(path=file_name.split('.')[0])
pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6'
)
ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
date_df = pro.trade_cal(exchange='DCE', start_date='20100101', end_date
=end_date)
date_df = date_df.loc[date_df['is_open'] == 1]
date_list = date_df['cal_date'].tolist()
date_df = pd.DataFrame({'date': date_list})
date_df['month'] = date_df['date'].str[:6]
target_date = date_df.loc[date_df['month'] == month]
target_date_index = target_date.index.values
target_date = target_date['date'].values
data = data.reshape(-1)
contract_main_pool = data[target_date_index]
contract_main_pool = (pd.Series(contract_main_pool).str.split('.').str[
0] + '.csv').values
file_pools = os.listdir(file_name.split('.')[0])
if contract_main_pool[0] not in file_pools:
contract_main_pool = [contract_file.lower() for contract_file in
contract_main_pool]
if contract_main_pool[0] not in file_pools:
print(f'找不到{contract_main_pool[0]}')
contract_main_pool = (file_name.split('.')[0] + '/' + pd.Series(
contract_main_pool)).values
row_1 = ['市场代码', '合约代码', '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量']
orignal_data = []
orignal_data.append(row_1)
for index in range(len(target_date)):
date = target_date[index]
one_file_path = contract_main_pool[index]
df = pd.read_csv(one_file_path, encoding='gbk')
df['date'] = df['时间'].str[:10]
df['date2'] = df['date'].str.replace('-', '')
result = df.loc[df['date2'] == date]
if result.shape[0] > 0:
for row_index in range(len(result)):
target_row = result.iloc[row_index].tolist()
clean_row = target_row[:-2]
orignal_data.append(clean_row)
print(f'{contract_kind} {date} finished!')
else:
print(f'没找到合约品种{contract_kind}在{date}')
print(f'{contract_kind}在{month}月的主力合约数据读取完成')
final_df = pd.DataFrame(orignal_data[1:], columns=orignal_data[0])
final_df['date'] = final_df['时间'].str[:10]
final_df_date = final_df['date'].unique()
final_df['date'] = final_df['时间'].str[:10]
final_df['time'] = final_df['时间'].str[10:].str.strip()
final_df['时间'] = final_df['date'] + ' ' + final_df['time']
final_df = final_df.sort_values('时间')
final_df['合约代码'] = final_df['合约代码'].str.upper()
final_df = final_df.sort_values('时间')
final_df['transf_date'] = pd.to_datetime(final_df['date'])
final_df.set_index('transf_date', inplace=True)
combine_all_df = pd.DataFrame()
final_df['date2'] = final_df['date'].str.replace('-', '')
for date_index in range(len(target_date)):
target_df = final_df.loc[final_df['date2'] == target_date[date_index]]
target_num = len(target_df)
theory_num = len(time_0931_15)
if target_num > 0:
have_time = target_df['time'].values.tolist()
lack_time = [x for x in time_0931_15 if x not in have_time]
if lack_time:
print(f'{target_date[date_index]} 不连续')
insert_array = np.empty(shape=(len(lack_time), 12))
insert_array.fill(np.nan)
insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',
'时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])
insert_df['date'] = target_date[date_index]
insert_df['time'] = lack_time
if len(lack_time) < len(time_0931_15):
insert_df['合约代码'] = target_df['合约代码'].unique()[-1]
combine_insert_df = pd.concat([target_df, insert_df])
combine_all_df = pd.concat([combine_all_df, combine_insert_df])
else:
print(f'{target_date[date_index]}empty ')
lack_time = [x for x in time_0931_15]
insert_array = np.empty(shape=(len(lack_time), 12))
insert_array.fill(np.nan)
insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',
'时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])
insert_df['date'] = target_date[date_index]
insert_df['time'] = lack_time
combine_all_df = pd.concat([combine_all_df, insert_df])
combine_all_df['时间'] = combine_all_df['date'] + ' ' + combine_all_df['time'
]
combine_all_df = combine_all_df.sort_values('时间')
combine_all_df.reset_index(inplace=True)
combine_all_df = combine_all_df[['市场代码', '合约代码', '时间', '开', '高', '低',
'收', '成交量', '成交额', '持仓量', 'date', 'time']]
combine_all_df['时间'] = combine_all_df['时间'].str.replace('-', '')
combine_all_df['date'] = combine_all_df['date'].str.replace('-', '')
combine_df = combine_all_df.copy()
contract_type = contract_kind
combine_df = combine_df.sort_values('时间')
end_time = '15:15:00'
end_index = np.where(combine_df['time'] == end_time)[0] + 1
end_index = np.hstack(([0], end_index))
start = end_index[:-1]
end = end_index[1:]
last_day = date_df['date'].iloc[target_date_index[0] - 1]
last_day = last_day[:4] + '-' + last_day[4:6] + '-' + last_day[6:]
first_day_have = combine_df[start[0]:end[0]]['time'].values
full_time = combine_df['time'].unique()
full_time.sort()
first_day_lack = [x for x in full_time[-179:]]
first_day_lack.sort()
lack_array = np.empty(shape=(len(first_day_lack), 12))
lack_array.fill(np.nan)
first_day_lack_df = pd.DataFrame(lack_array, columns=combine_df.columns)
first_day_lack_df['time'] = first_day_lack
first_day_lack_df['date'] = last_day
first_day_lack_df['时间'] = first_day_lack_df['date'
] + ' ' + first_day_lack_df['time']
last_df = pd.read_csv(contract_main_pool[0], encoding='gbk')
last_df['date'] = last_df['时间'].str[:10]
last_df['time'] = last_df['时间'].str[11:]
last_time_pool = last_df.loc[last_df['date'] == last_day]['time'].values
last_day_have_date = []
if last_time_pool.shape[0] > 0:
print(f'期货品种{contract_kind}在前一个交易日{last_day}有夜盘数据,需要读取覆盖')
last_day_have_date = [x for x in last_time_pool]
if last_day_have_date:
for index in range(len(last_day_have_date)):
origanl_index = last_df.loc[(last_df['date'] == last_day) & (
last_df['time'] == last_day_have_date[index])].index[0]
target_index = first_day_lack_df.loc[first_day_lack_df['time'] ==
last_day_have_date[index]].index[0]
first_day_lack_df.iloc[target_index] = last_df.iloc[origanl_index]
else:
print(f'期货品种{contract_kind}在前一个交易日{last_day}没有夜盘数据,不需要读取覆盖')
print('直接使用np.nan填充上一个交易日的夜盘数据')
for index in range(first_day_lack_df.shape[0]):
combine_df = combine_df.append(first_day_lack_df.iloc[index])
combine_df['时间'] = combine_df['时间'].str.replace('-', '')
combine_df['date'] = combine_df['date'].str.replace('-', '')
combine_df.sort_values('时间', inplace=True)
end_index = np.where(combine_df['time'] == end_time)[0] + 1
end_index = np.hstack(([0], end_index))
start = end_index[:-1]
end = end_index[1:]
col_type_list = ['开', '高', '低', '收', '成交量', '成交额', '持仓量']
dir_name_list = ['open', 'high', 'low', 'close', 'volume', 'amount',
'position']
merge_df = pd.DataFrame({'time': time_0931_15})
combine_df['date'] = combine_df['时间'].str[:8]
for index in range(len(col_type_list)):
col_type = col_type_list[index]
csv_df = pd.DataFrame()
for s_index, e_index in zip(start, end):
res = combine_df.iloc[s_index:e_index, :]
one_date_df = pd.DataFrame(res[col_type].values.reshape(1, -1),
columns=res['time'].values.tolist())
one_date_df['main_contract_code'] = res.iloc[-1]['合约代码']
one_date_df['date'] = res.iloc[-1]['date']
col_layout = ['date']
col_layout = np.hstack((col_layout, res['time'].values.tolist()))
col_layout = np.hstack((col_layout, ['main_contract_code']))
one_date_df = one_date_df[col_layout]
csv_df = pd.concat([csv_df, one_date_df])
orignal_csv_df = pd.read_csv(orignal_clean_csv_path + contract_kind +
'_1min_' + dir_name_list[index] + '.csv')
column_ouput_form = orignal_csv_df.columns.values
orignal_date_pool = pd.to_datetime(orignal_csv_df['date'], format=
'%Y-%m-%d').values
current_date_pool = pd.to_datetime(csv_df['date'], format='%Y-%m-%d'
).values
orignal_csv_df['date'] = pd.to_datetime(orignal_csv_df['date'],
format='%Y-%m-%d').dt.strftime('%Y-%m-%d')
csv_df['date'] = pd.to_datetime(csv_df['date'], format='%Y%m%d'
).dt.strftime('%Y-%m-%d')
main_code = csv_df['main_contract_code'].iloc[0]
main_code_num = csv_df['main_contract_code'].str.findall('[0-9]+'
).iloc[0][0]
if len(main_code_num) == 3:
print(f'合约代码{main_code}缺少一位数字,将被替换')
csv_df['main_contract_code'] = csv_df['main_contract_code'].str[:2
] + month[0] + csv_df['main_contract_code'].str[2:]
main_code = csv_df['main_contract_code'].iloc[0]
print(f'合约代码{main_code}')
intersection_pool = [date for date in orignal_date_pool if date in
current_date_pool]
if not intersection_pool:
print(
f'新旧数据没有时间交集,{contract_kind} {dir_name_list[index]} 将被添加到先前数据中'
)
orignal_csv_df = pd.concat([orignal_csv_df, csv_df])
orignal_csv_df.sort_values('date', inplace=True)
orignal_csv_df = orignal_csv_df[column_ouput_form]
orignal_csv_df.to_csv(orignal_clean_csv_path + contract_kind +
'_1min_' + dir_name_list[index] + '.csv', index=False)
print(f'期货品种{contract_kind} {dir_name_list[index]} 完成')
else:
print(
f'新旧数据的时间出现交集!!{contract_kind} {dir_name_list[index]} 将不会被添加到先前数据中'
)
<|reserved_special_token_1|>
import numpy as np
import pandas as pd
from unrar import rarfile
import numpy as np
import pandas as pd
import tushare as ts
import os
year_month='201911'
contract_kind='NI'
rar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'
main_code_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/main/main_/'
clean_data_path='D:/1_min补充统一/'
end_date='20200107'
time_range_path='D:/统一所有品种时间范围.csv'
# save_month_fill_data_path='D:/1_min补充统一/'+contract_kind+'主力连续'+'_'+month+'.csv'
def renew_commodity_future(year_month:str,contract_kind:str,main_code_path:str,rar_data_file_path:str,clean_data_path:str,time_range_path:str,end_date:str,commodity_bool=True):
'''
用于更新月度的商品期货数据
year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911
contract_kind:放对应品种的list 类似['A','B']
main_code_path:对应存放主力合约的地方
rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名
clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处
time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv
end_date :'20200103' 今日的日期,用来请求tushare中的交易日历,数据的读取合并都是以交易日历的时间驱动
commodity_bool:商品期货对应True,金融期货False,默认商品期货
'''
month=year_month
if commodity_bool:
file_name=rar_data_file_path+'FutAC_Min1_Std_'+month+'.rar'
else:
file_name=rar_data_file_path+'FutSF_Min1_Std_'+month+'.rar'
orignial_path=main_code_path
specifi_path=orignial_path+contract_kind+'_1day_main.npy'
rar = rarfile.RarFile(file_name,pwd='www.jinshuyuan.net')
# 原始的处理好的数据
orignal_clean_csv_path=clean_data_path
pwd='www.jinshuyuan.net'
data=np.load(specifi_path)
time_0931_15=pd.read_csv(time_range_path)['date'].values.tolist()
rar.extractall(path=file_name.split('.')[0])
# 首先需要输入end_date 确保截取的时间长度和main主力合约的时间对齐
# 按照月份确定位置
pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
date_df=pro.trade_cal(exchange='DCE', start_date='20100101', end_date=end_date)
date_df=date_df.loc[date_df['is_open']==1]
date_list=date_df['cal_date'].tolist()
# ==========================================================================
# 针对的是201911月数据,对应的合约index 放在 target_date_index中
date_df=pd.DataFrame({'date':date_list})
date_df['month']=date_df['date'].str[:6]
target_date=date_df.loc[date_df['month']==month]
target_date_index=target_date.index.values
target_date=target_date['date'].values
# 获取对应目标
data=data.reshape(-1)
contract_main_pool=data[target_date_index]
# 去掉交易所的代码编号
contract_main_pool=(pd.Series(contract_main_pool).str.split('.').str[0]+'.csv').values
file_pools=os.listdir(file_name.split('.')[0])
# 郑州期货交易所是大写,其它都是小写,这里需要逻辑判断
if contract_main_pool[0] not in file_pools:
contract_main_pool=[contract_file.lower() for contract_file in contract_main_pool]
if contract_main_pool[0] not in file_pools:
print(f'找不到{contract_main_pool[0]}')
# 读取好所有的路径
contract_main_pool=(file_name.split('.')[0]+'/'+pd.Series(contract_main_pool)).values
# (len(target_date),contract_main_pool.shape[0])
row_1=['市场代码','合约代码', '时间', '开','高', '低', '收', '成交量', '成交额', '持仓量']
orignal_data=[]
orignal_data.append(row_1)
for index in range(len(target_date)):
date=target_date[index]
one_file_path=contract_main_pool[index]
df=pd.read_csv(one_file_path,encoding='gbk')
df['date']=df['时间'].str[:10]
df['date2']=df['date'].str.replace('-','')
result=df.loc[df['date2']==date]
if result.shape[0]>0:
for row_index in range(len(result)):
target_row=result.iloc[row_index].tolist()
clean_row=target_row[:-2]
orignal_data.append(clean_row)
print(f'{contract_kind} {date} finished!')
else:
print(f'没找到合约品种{contract_kind}在{date}')
print(f'{contract_kind}在{month}月的主力合约数据读取完成')
final_df=pd.DataFrame(orignal_data[1:],columns=orignal_data[0])
final_df['date']=final_df['时间'].str[:10]
final_df_date=final_df['date'].unique()
final_df['date']=final_df['时间'].str[:10]
final_df['time']=final_df['时间'].str[10:].str.strip()
final_df['时间']=final_df['date']+' '+final_df['time']
final_df=final_df.sort_values('时间')
final_df['合约代码']=final_df['合约代码'].str.upper()
final_df=final_df.sort_values('时间')
# ===============================增加了从constant_time进行截取================================
final_df['transf_date']=pd.to_datetime(final_df['date'])
final_df.set_index('transf_date',inplace=True)
combine_all_df=pd.DataFrame()
final_df['date2']=final_df['date'].str.replace('-','')
# 按月进行填充
# 设置了存放按月填充的路径
for date_index in range(len(target_date)):
#按日期进行分割
target_df=final_df.loc[final_df['date2']==target_date[date_index]]
#分割到的长度放入容器中
target_num=len(target_df)
#理论长度
theory_num=len(time_0931_15)
#实际上两种情况:1.是交易日但完全没有数据2.是交易日,只有部分数据 3.是交易日,数据也是完整的
if target_num>0:
#开始区分2,3情况
have_time=target_df['time'].values.tolist()
lack_time=[x for x in time_0931_15 if x not in have_time]
#检查是不是情况2
if lack_time:
print(f'{target_date[date_index]} 不连续')
#一共12列,先全部填充nan的时候,最后再把已知填入
insert_array=np.empty(shape=(len(lack_time),12))
insert_array.fill(np.nan)
insert_df=pd.DataFrame(insert_array,columns=['市场代码','合约代码','时间','开','高','低','收','成交量','成交额','持仓量','date','time'])
insert_df['date']=target_date[date_index]
insert_df['time']=lack_time
#缺少时间的个数小于time_0931_15则说明,当天并不是完全没数据,只是部分数据缺失,因此要对合约代码进行填充
if len(lack_time)<len(time_0931_15):
insert_df['合约代码']=target_df['合约代码'].unique()[-1]
#生成一天完整的数据
combine_insert_df=pd.concat([target_df,insert_df])
#将数据添加到容器中
combine_all_df=pd.concat([combine_all_df,combine_insert_df])
#完全没有数据,直接填充
else:
print(f'{target_date[date_index]}empty ')
lack_time=[x for x in time_0931_15]
#一共12列,先全部填充nan的时候,最后再把已知填入
insert_array=np.empty(shape=(len(lack_time),12))
insert_array.fill(np.nan)
insert_df=pd.DataFrame(insert_array,columns=['市场代码','合约代码','时间','开','高','低','收','成交量','成交额','持仓量','date','time'])
insert_df['date']=target_date[date_index]
insert_df['time']=lack_time
#将数据添加到容器
combine_all_df=pd.concat([combine_all_df,insert_df])
combine_all_df['时间']=combine_all_df['date']+' '+combine_all_df['time']
#调整时间
combine_all_df=combine_all_df.sort_values('时间')
combine_all_df.reset_index(inplace=True)
#数据输出,按设定的顺序
combine_all_df=combine_all_df[['市场代码', '合约代码', '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量','date','time']]
combine_all_df['时间']=combine_all_df['时间'].str.replace('-','')
combine_all_df['date']=combine_all_df['date'].str.replace('-','')
# combine_all_df.to_csv(save_month_fill_data_path,index=False,encoding='utf-8-sig')
# ==========================储存数据=================================================
combine_df=combine_all_df.copy()
contract_type=contract_kind
combine_df=combine_df.sort_values('时间')
# ====================================================================开始截取============================================================
# end_time+1其实是可以作为每次截取的起点,终点下一个就是起点,不过要加上0,而终点的位置也可以是end_time+1,因为end_time+1只能取end_time
# 按照下午15:15统一截取
end_time='15:15:00'
end_index=np.where(combine_df['time']==end_time)[0]+1
end_index=np.hstack(([0],end_index))
start=end_index[:-1]
end=end_index[1:]
# ================================================================缺失第一个交易日前一天的夜盘数据==========================================
# 这里的选择构造一个虚拟的时间戳,来满足缺失的夜盘数据
# 按照上一步的截取方法,第一个交易日缺少前一天的夜盘数据
last_day=date_df['date'].iloc[target_date_index[0]-1]
last_day=last_day[:4]+'-'+last_day[4:6]+'-'+last_day[6:]
first_day_have=combine_df[start[0]:end[0]]['time'].values
full_time=combine_df['time'].unique()
full_time.sort()
first_day_lack=[x for x in full_time[-179:]]
first_day_lack.sort()
lack_array=np.empty(shape=(len(first_day_lack),12))
lack_array.fill(np.nan)
# ===============================准备缺失部分df==========================================================================================
first_day_lack_df=pd.DataFrame(lack_array,columns=combine_df.columns)
first_day_lack_df['time']=first_day_lack
first_day_lack_df['date']=last_day
first_day_lack_df['时间']=first_day_lack_df['date']+' '+first_day_lack_df['time']
last_df=pd.read_csv(contract_main_pool[0],encoding='gbk')
# 确定之前的有没有夜盘
last_df['date']=last_df['时间'].str[:10]
last_df['time']=last_df['时间'].str[11:]
# 补夜盘数据
last_time_pool=last_df.loc[last_df['date']==last_day]['time'].values
last_day_have_date=[]
# 说明在上个交易日有数据
if last_time_pool.shape[0]>0:
print(f'期货品种{contract_kind}在前一个交易日{last_day}有夜盘数据,需要读取覆盖')
last_day_have_date=[x for x in last_time_pool]
if last_day_have_date:
for index in range(len(last_day_have_date)):
origanl_index=last_df.loc[(last_df['date']==last_day)&(last_df['time']==last_day_have_date[index])].index[0]
target_index=first_day_lack_df.loc[first_day_lack_df['time']==last_day_have_date[index]].index[0]
first_day_lack_df.iloc[target_index]=last_df.iloc[origanl_index]
else:
print(f'期货品种{contract_kind}在前一个交易日{last_day}没有夜盘数据,不需要读取覆盖')
print('直接使用np.nan填充上一个交易日的夜盘数据')
for index in range(first_day_lack_df.shape[0]):
combine_df=combine_df.append(first_day_lack_df.iloc[index])
combine_df['时间']=combine_df['时间'].str.replace('-','')
combine_df['date']=combine_df['date'].str.replace('-','')
combine_df.sort_values('时间',inplace=True)
# =================================缺失部分填充=========================================================================================
# combine_df=pd.concat([first_day_lack_df,combine_df])
# # ================================重新按时间排序========================================================================================
# combine_df=combine_df.sort_values('时间')
# ============================重新进行切割===============================================================================================
end_index=np.where(combine_df['time']==end_time)[0]+1
end_index=np.hstack(([0],end_index))
start=end_index[:-1]
end=end_index[1:]
# ==============================进行分割按照特定时间,明确col===============================================================================
col_type_list=['开','高','低','收','成交量','成交额','持仓量']
dir_name_list=['open','high','low','close','volume','amount','position']
#这个变量现在没有用
#交易到凌晨01
#merge_df=pd.DataFrame({'time':with_night_01})
#交易到凌晨0230,version中没有集合竞价时间,time_0931_15去掉9:00,21:00
merge_df=pd.DataFrame({'time':time_0931_15})
combine_df['date']=combine_df['时间'].str[:8]
for index in range(len(col_type_list)):
col_type=col_type_list[index]
# 用来接收分col数据的容器
csv_df=pd.DataFrame()
for s_index,e_index in zip(start,end):
# =========================================截取每个交易日数据==============================================================================
res=combine_df.iloc[s_index:e_index,:]
one_date_df=pd.DataFrame(res[col_type].values.reshape(1,-1),columns=res['time'].values.tolist())
one_date_df['main_contract_code']=res.iloc[-1]['合约代码']
one_date_df['date']=res.iloc[-1]['date']
# =======================================设置输出格式====================================================================================
col_layout=['date']
col_layout=np.hstack((col_layout,res['time'].values.tolist()))
col_layout=np.hstack((col_layout,['main_contract_code']))
one_date_df=one_date_df[col_layout]
# =======================================合并数据========================================================================================
csv_df=pd.concat([csv_df,one_date_df])
# ========================追加原始数据=======================================
# 时间问题需要处理,不然对不齐
# 在测试文件中测试,所以修改了路径
orignal_csv_df=pd.read_csv(orignal_clean_csv_path+contract_kind+'_1min_'+dir_name_list[index]+'.csv')
column_ouput_form=orignal_csv_df.columns.values
orignal_date_pool=pd.to_datetime(orignal_csv_df['date'],format='%Y-%m-%d').values
current_date_pool=pd.to_datetime(csv_df['date'],format='%Y-%m-%d').values
orignal_csv_df['date']=pd.to_datetime(orignal_csv_df['date'],format='%Y-%m-%d').dt.strftime('%Y-%m-%d')
csv_df['date']=pd.to_datetime(csv_df['date'],format='%Y%m%d').dt.strftime('%Y-%m-%d')
# check代码中的数字个数等于四个
main_code=csv_df['main_contract_code'].iloc[0]
main_code_num=csv_df['main_contract_code'].str.findall(r'[0-9]+').iloc[0][0]
if len(main_code_num)==3:
print(f'合约代码{main_code}缺少一位数字,将被替换')
csv_df['main_contract_code']=csv_df['main_contract_code'].str[:2]+month[0]+csv_df['main_contract_code'].str[2:]
main_code=csv_df['main_contract_code'].iloc[0]
print(f'合约代码{main_code}')
# 查看有没有交集,如果有交集会停止,说明进行了重复操作
intersection_pool=[date for date in orignal_date_pool if date in current_date_pool]
if not intersection_pool:
print(f'新旧数据没有时间交集,{contract_kind} {dir_name_list[index]} 将被添加到先前数据中')
orignal_csv_df=pd.concat([orignal_csv_df,csv_df])
orignal_csv_df.sort_values('date',inplace=True)
orignal_csv_df=orignal_csv_df[column_ouput_form]
orignal_csv_df.to_csv(orignal_clean_csv_path+contract_kind+'_1min_'+dir_name_list[index]+'.csv',index=False)
print(f'期货品种{contract_kind} {dir_name_list[index]} 完成')
else:
print(f'新旧数据的时间出现交集!!{contract_kind} {dir_name_list[index]} 将不会被添加到先前数据中')
|
flexible
|
{
"blob_id": "1c2967c26c845281ceb46cc1d8c06768298ef6b6",
"index": 9407,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef renew_commodity_future(year_month: str, contract_kind: str,\n main_code_path: str, rar_data_file_path: str, clean_data_path: str,\n time_range_path: str, end_date: str, commodity_bool=True):\n \"\"\"\n 用于更新月度的商品期货数据\n year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911\n contract_kind:放对应品种的list 类似['A','B']\n main_code_path:对应存放主力合约的地方\n rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名\n clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处\n time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv\n end_date :'20200103' 今日的日期,用来请求tushare中的交易日历,数据的读取合并都是以交易日历的时间驱动\n commodity_bool:商品期货对应True,金融期货False,默认商品期货\n \"\"\"\n month = year_month\n if commodity_bool:\n file_name = rar_data_file_path + 'FutAC_Min1_Std_' + month + '.rar'\n else:\n file_name = rar_data_file_path + 'FutSF_Min1_Std_' + month + '.rar'\n orignial_path = main_code_path\n specifi_path = orignial_path + contract_kind + '_1day_main.npy'\n rar = rarfile.RarFile(file_name, pwd='www.jinshuyuan.net')\n orignal_clean_csv_path = clean_data_path\n pwd = 'www.jinshuyuan.net'\n data = np.load(specifi_path)\n time_0931_15 = pd.read_csv(time_range_path)['date'].values.tolist()\n rar.extractall(path=file_name.split('.')[0])\n pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6'\n )\n ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')\n date_df = pro.trade_cal(exchange='DCE', start_date='20100101', end_date\n =end_date)\n date_df = date_df.loc[date_df['is_open'] == 1]\n date_list = date_df['cal_date'].tolist()\n date_df = pd.DataFrame({'date': date_list})\n date_df['month'] = date_df['date'].str[:6]\n target_date = date_df.loc[date_df['month'] == month]\n target_date_index = target_date.index.values\n target_date = target_date['date'].values\n data = data.reshape(-1)\n contract_main_pool = data[target_date_index]\n contract_main_pool = (pd.Series(contract_main_pool).str.split('.').str[\n 0] + '.csv').values\n file_pools = os.listdir(file_name.split('.')[0])\n if contract_main_pool[0] not in file_pools:\n contract_main_pool = [contract_file.lower() for contract_file in\n contract_main_pool]\n if contract_main_pool[0] not in file_pools:\n print(f'找不到{contract_main_pool[0]}')\n contract_main_pool = (file_name.split('.')[0] + '/' + pd.Series(\n contract_main_pool)).values\n row_1 = ['市场代码', '合约代码', '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量']\n orignal_data = []\n orignal_data.append(row_1)\n for index in range(len(target_date)):\n date = target_date[index]\n one_file_path = contract_main_pool[index]\n df = pd.read_csv(one_file_path, encoding='gbk')\n df['date'] = df['时间'].str[:10]\n df['date2'] = df['date'].str.replace('-', '')\n result = df.loc[df['date2'] == date]\n if result.shape[0] > 0:\n for row_index in range(len(result)):\n target_row = result.iloc[row_index].tolist()\n clean_row = target_row[:-2]\n orignal_data.append(clean_row)\n print(f'{contract_kind} {date} finished!')\n else:\n print(f'没找到合约品种{contract_kind}在{date}')\n print(f'{contract_kind}在{month}月的主力合约数据读取完成')\n final_df = pd.DataFrame(orignal_data[1:], columns=orignal_data[0])\n final_df['date'] = final_df['时间'].str[:10]\n final_df_date = final_df['date'].unique()\n final_df['date'] = final_df['时间'].str[:10]\n final_df['time'] = final_df['时间'].str[10:].str.strip()\n final_df['时间'] = final_df['date'] + ' ' + final_df['time']\n final_df = final_df.sort_values('时间')\n final_df['合约代码'] = final_df['合约代码'].str.upper()\n final_df = final_df.sort_values('时间')\n final_df['transf_date'] = pd.to_datetime(final_df['date'])\n final_df.set_index('transf_date', inplace=True)\n combine_all_df = pd.DataFrame()\n final_df['date2'] = final_df['date'].str.replace('-', '')\n for date_index in range(len(target_date)):\n target_df = final_df.loc[final_df['date2'] == target_date[date_index]]\n target_num = len(target_df)\n theory_num = len(time_0931_15)\n if target_num > 0:\n have_time = target_df['time'].values.tolist()\n lack_time = [x for x in time_0931_15 if x not in have_time]\n if lack_time:\n print(f'{target_date[date_index]} 不连续')\n insert_array = np.empty(shape=(len(lack_time), 12))\n insert_array.fill(np.nan)\n insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',\n '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])\n insert_df['date'] = target_date[date_index]\n insert_df['time'] = lack_time\n if len(lack_time) < len(time_0931_15):\n insert_df['合约代码'] = target_df['合约代码'].unique()[-1]\n combine_insert_df = pd.concat([target_df, insert_df])\n combine_all_df = pd.concat([combine_all_df, combine_insert_df])\n else:\n print(f'{target_date[date_index]}empty ')\n lack_time = [x for x in time_0931_15]\n insert_array = np.empty(shape=(len(lack_time), 12))\n insert_array.fill(np.nan)\n insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',\n '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])\n insert_df['date'] = target_date[date_index]\n insert_df['time'] = lack_time\n combine_all_df = pd.concat([combine_all_df, insert_df])\n combine_all_df['时间'] = combine_all_df['date'] + ' ' + combine_all_df['time'\n ]\n combine_all_df = combine_all_df.sort_values('时间')\n combine_all_df.reset_index(inplace=True)\n combine_all_df = combine_all_df[['市场代码', '合约代码', '时间', '开', '高', '低',\n '收', '成交量', '成交额', '持仓量', 'date', 'time']]\n combine_all_df['时间'] = combine_all_df['时间'].str.replace('-', '')\n combine_all_df['date'] = combine_all_df['date'].str.replace('-', '')\n combine_df = combine_all_df.copy()\n contract_type = contract_kind\n combine_df = combine_df.sort_values('时间')\n end_time = '15:15:00'\n end_index = np.where(combine_df['time'] == end_time)[0] + 1\n end_index = np.hstack(([0], end_index))\n start = end_index[:-1]\n end = end_index[1:]\n last_day = date_df['date'].iloc[target_date_index[0] - 1]\n last_day = last_day[:4] + '-' + last_day[4:6] + '-' + last_day[6:]\n first_day_have = combine_df[start[0]:end[0]]['time'].values\n full_time = combine_df['time'].unique()\n full_time.sort()\n first_day_lack = [x for x in full_time[-179:]]\n first_day_lack.sort()\n lack_array = np.empty(shape=(len(first_day_lack), 12))\n lack_array.fill(np.nan)\n first_day_lack_df = pd.DataFrame(lack_array, columns=combine_df.columns)\n first_day_lack_df['time'] = first_day_lack\n first_day_lack_df['date'] = last_day\n first_day_lack_df['时间'] = first_day_lack_df['date'\n ] + ' ' + first_day_lack_df['time']\n last_df = pd.read_csv(contract_main_pool[0], encoding='gbk')\n last_df['date'] = last_df['时间'].str[:10]\n last_df['time'] = last_df['时间'].str[11:]\n last_time_pool = last_df.loc[last_df['date'] == last_day]['time'].values\n last_day_have_date = []\n if last_time_pool.shape[0] > 0:\n print(f'期货品种{contract_kind}在前一个交易日{last_day}有夜盘数据,需要读取覆盖')\n last_day_have_date = [x for x in last_time_pool]\n if last_day_have_date:\n for index in range(len(last_day_have_date)):\n origanl_index = last_df.loc[(last_df['date'] == last_day) & (\n last_df['time'] == last_day_have_date[index])].index[0]\n target_index = first_day_lack_df.loc[first_day_lack_df['time'] ==\n last_day_have_date[index]].index[0]\n first_day_lack_df.iloc[target_index] = last_df.iloc[origanl_index]\n else:\n print(f'期货品种{contract_kind}在前一个交易日{last_day}没有夜盘数据,不需要读取覆盖')\n print('直接使用np.nan填充上一个交易日的夜盘数据')\n for index in range(first_day_lack_df.shape[0]):\n combine_df = combine_df.append(first_day_lack_df.iloc[index])\n combine_df['时间'] = combine_df['时间'].str.replace('-', '')\n combine_df['date'] = combine_df['date'].str.replace('-', '')\n combine_df.sort_values('时间', inplace=True)\n end_index = np.where(combine_df['time'] == end_time)[0] + 1\n end_index = np.hstack(([0], end_index))\n start = end_index[:-1]\n end = end_index[1:]\n col_type_list = ['开', '高', '低', '收', '成交量', '成交额', '持仓量']\n dir_name_list = ['open', 'high', 'low', 'close', 'volume', 'amount',\n 'position']\n merge_df = pd.DataFrame({'time': time_0931_15})\n combine_df['date'] = combine_df['时间'].str[:8]\n for index in range(len(col_type_list)):\n col_type = col_type_list[index]\n csv_df = pd.DataFrame()\n for s_index, e_index in zip(start, end):\n res = combine_df.iloc[s_index:e_index, :]\n one_date_df = pd.DataFrame(res[col_type].values.reshape(1, -1),\n columns=res['time'].values.tolist())\n one_date_df['main_contract_code'] = res.iloc[-1]['合约代码']\n one_date_df['date'] = res.iloc[-1]['date']\n col_layout = ['date']\n col_layout = np.hstack((col_layout, res['time'].values.tolist()))\n col_layout = np.hstack((col_layout, ['main_contract_code']))\n one_date_df = one_date_df[col_layout]\n csv_df = pd.concat([csv_df, one_date_df])\n orignal_csv_df = pd.read_csv(orignal_clean_csv_path + contract_kind +\n '_1min_' + dir_name_list[index] + '.csv')\n column_ouput_form = orignal_csv_df.columns.values\n orignal_date_pool = pd.to_datetime(orignal_csv_df['date'], format=\n '%Y-%m-%d').values\n current_date_pool = pd.to_datetime(csv_df['date'], format='%Y-%m-%d'\n ).values\n orignal_csv_df['date'] = pd.to_datetime(orignal_csv_df['date'],\n format='%Y-%m-%d').dt.strftime('%Y-%m-%d')\n csv_df['date'] = pd.to_datetime(csv_df['date'], format='%Y%m%d'\n ).dt.strftime('%Y-%m-%d')\n main_code = csv_df['main_contract_code'].iloc[0]\n main_code_num = csv_df['main_contract_code'].str.findall('[0-9]+'\n ).iloc[0][0]\n if len(main_code_num) == 3:\n print(f'合约代码{main_code}缺少一位数字,将被替换')\n csv_df['main_contract_code'] = csv_df['main_contract_code'].str[:2\n ] + month[0] + csv_df['main_contract_code'].str[2:]\n main_code = csv_df['main_contract_code'].iloc[0]\n print(f'合约代码{main_code}')\n intersection_pool = [date for date in orignal_date_pool if date in\n current_date_pool]\n if not intersection_pool:\n print(\n f'新旧数据没有时间交集,{contract_kind} {dir_name_list[index]} 将被添加到先前数据中'\n )\n orignal_csv_df = pd.concat([orignal_csv_df, csv_df])\n orignal_csv_df.sort_values('date', inplace=True)\n orignal_csv_df = orignal_csv_df[column_ouput_form]\n orignal_csv_df.to_csv(orignal_clean_csv_path + contract_kind +\n '_1min_' + dir_name_list[index] + '.csv', index=False)\n print(f'期货品种{contract_kind} {dir_name_list[index]} 完成')\n else:\n print(\n f'新旧数据的时间出现交集!!{contract_kind} {dir_name_list[index]} 将不会被添加到先前数据中'\n )\n",
"step-3": "<mask token>\nyear_month = '201911'\ncontract_kind = 'NI'\nrar_data_file_path = (\n 'C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'\n )\nmain_code_path = (\n 'C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/main/main_/'\n )\nclean_data_path = 'D:/1_min补充统一/'\nend_date = '20200107'\ntime_range_path = 'D:/统一所有品种时间范围.csv'\n\n\ndef renew_commodity_future(year_month: str, contract_kind: str,\n main_code_path: str, rar_data_file_path: str, clean_data_path: str,\n time_range_path: str, end_date: str, commodity_bool=True):\n \"\"\"\n 用于更新月度的商品期货数据\n year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911\n contract_kind:放对应品种的list 类似['A','B']\n main_code_path:对应存放主力合约的地方\n rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名\n clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处\n time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv\n end_date :'20200103' 今日的日期,用来请求tushare中的交易日历,数据的读取合并都是以交易日历的时间驱动\n commodity_bool:商品期货对应True,金融期货False,默认商品期货\n \"\"\"\n month = year_month\n if commodity_bool:\n file_name = rar_data_file_path + 'FutAC_Min1_Std_' + month + '.rar'\n else:\n file_name = rar_data_file_path + 'FutSF_Min1_Std_' + month + '.rar'\n orignial_path = main_code_path\n specifi_path = orignial_path + contract_kind + '_1day_main.npy'\n rar = rarfile.RarFile(file_name, pwd='www.jinshuyuan.net')\n orignal_clean_csv_path = clean_data_path\n pwd = 'www.jinshuyuan.net'\n data = np.load(specifi_path)\n time_0931_15 = pd.read_csv(time_range_path)['date'].values.tolist()\n rar.extractall(path=file_name.split('.')[0])\n pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6'\n )\n ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')\n date_df = pro.trade_cal(exchange='DCE', start_date='20100101', end_date\n =end_date)\n date_df = date_df.loc[date_df['is_open'] == 1]\n date_list = date_df['cal_date'].tolist()\n date_df = pd.DataFrame({'date': date_list})\n date_df['month'] = date_df['date'].str[:6]\n target_date = date_df.loc[date_df['month'] == month]\n target_date_index = target_date.index.values\n target_date = target_date['date'].values\n data = data.reshape(-1)\n contract_main_pool = data[target_date_index]\n contract_main_pool = (pd.Series(contract_main_pool).str.split('.').str[\n 0] + '.csv').values\n file_pools = os.listdir(file_name.split('.')[0])\n if contract_main_pool[0] not in file_pools:\n contract_main_pool = [contract_file.lower() for contract_file in\n contract_main_pool]\n if contract_main_pool[0] not in file_pools:\n print(f'找不到{contract_main_pool[0]}')\n contract_main_pool = (file_name.split('.')[0] + '/' + pd.Series(\n contract_main_pool)).values\n row_1 = ['市场代码', '合约代码', '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量']\n orignal_data = []\n orignal_data.append(row_1)\n for index in range(len(target_date)):\n date = target_date[index]\n one_file_path = contract_main_pool[index]\n df = pd.read_csv(one_file_path, encoding='gbk')\n df['date'] = df['时间'].str[:10]\n df['date2'] = df['date'].str.replace('-', '')\n result = df.loc[df['date2'] == date]\n if result.shape[0] > 0:\n for row_index in range(len(result)):\n target_row = result.iloc[row_index].tolist()\n clean_row = target_row[:-2]\n orignal_data.append(clean_row)\n print(f'{contract_kind} {date} finished!')\n else:\n print(f'没找到合约品种{contract_kind}在{date}')\n print(f'{contract_kind}在{month}月的主力合约数据读取完成')\n final_df = pd.DataFrame(orignal_data[1:], columns=orignal_data[0])\n final_df['date'] = final_df['时间'].str[:10]\n final_df_date = final_df['date'].unique()\n final_df['date'] = final_df['时间'].str[:10]\n final_df['time'] = final_df['时间'].str[10:].str.strip()\n final_df['时间'] = final_df['date'] + ' ' + final_df['time']\n final_df = final_df.sort_values('时间')\n final_df['合约代码'] = final_df['合约代码'].str.upper()\n final_df = final_df.sort_values('时间')\n final_df['transf_date'] = pd.to_datetime(final_df['date'])\n final_df.set_index('transf_date', inplace=True)\n combine_all_df = pd.DataFrame()\n final_df['date2'] = final_df['date'].str.replace('-', '')\n for date_index in range(len(target_date)):\n target_df = final_df.loc[final_df['date2'] == target_date[date_index]]\n target_num = len(target_df)\n theory_num = len(time_0931_15)\n if target_num > 0:\n have_time = target_df['time'].values.tolist()\n lack_time = [x for x in time_0931_15 if x not in have_time]\n if lack_time:\n print(f'{target_date[date_index]} 不连续')\n insert_array = np.empty(shape=(len(lack_time), 12))\n insert_array.fill(np.nan)\n insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',\n '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])\n insert_df['date'] = target_date[date_index]\n insert_df['time'] = lack_time\n if len(lack_time) < len(time_0931_15):\n insert_df['合约代码'] = target_df['合约代码'].unique()[-1]\n combine_insert_df = pd.concat([target_df, insert_df])\n combine_all_df = pd.concat([combine_all_df, combine_insert_df])\n else:\n print(f'{target_date[date_index]}empty ')\n lack_time = [x for x in time_0931_15]\n insert_array = np.empty(shape=(len(lack_time), 12))\n insert_array.fill(np.nan)\n insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',\n '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])\n insert_df['date'] = target_date[date_index]\n insert_df['time'] = lack_time\n combine_all_df = pd.concat([combine_all_df, insert_df])\n combine_all_df['时间'] = combine_all_df['date'] + ' ' + combine_all_df['time'\n ]\n combine_all_df = combine_all_df.sort_values('时间')\n combine_all_df.reset_index(inplace=True)\n combine_all_df = combine_all_df[['市场代码', '合约代码', '时间', '开', '高', '低',\n '收', '成交量', '成交额', '持仓量', 'date', 'time']]\n combine_all_df['时间'] = combine_all_df['时间'].str.replace('-', '')\n combine_all_df['date'] = combine_all_df['date'].str.replace('-', '')\n combine_df = combine_all_df.copy()\n contract_type = contract_kind\n combine_df = combine_df.sort_values('时间')\n end_time = '15:15:00'\n end_index = np.where(combine_df['time'] == end_time)[0] + 1\n end_index = np.hstack(([0], end_index))\n start = end_index[:-1]\n end = end_index[1:]\n last_day = date_df['date'].iloc[target_date_index[0] - 1]\n last_day = last_day[:4] + '-' + last_day[4:6] + '-' + last_day[6:]\n first_day_have = combine_df[start[0]:end[0]]['time'].values\n full_time = combine_df['time'].unique()\n full_time.sort()\n first_day_lack = [x for x in full_time[-179:]]\n first_day_lack.sort()\n lack_array = np.empty(shape=(len(first_day_lack), 12))\n lack_array.fill(np.nan)\n first_day_lack_df = pd.DataFrame(lack_array, columns=combine_df.columns)\n first_day_lack_df['time'] = first_day_lack\n first_day_lack_df['date'] = last_day\n first_day_lack_df['时间'] = first_day_lack_df['date'\n ] + ' ' + first_day_lack_df['time']\n last_df = pd.read_csv(contract_main_pool[0], encoding='gbk')\n last_df['date'] = last_df['时间'].str[:10]\n last_df['time'] = last_df['时间'].str[11:]\n last_time_pool = last_df.loc[last_df['date'] == last_day]['time'].values\n last_day_have_date = []\n if last_time_pool.shape[0] > 0:\n print(f'期货品种{contract_kind}在前一个交易日{last_day}有夜盘数据,需要读取覆盖')\n last_day_have_date = [x for x in last_time_pool]\n if last_day_have_date:\n for index in range(len(last_day_have_date)):\n origanl_index = last_df.loc[(last_df['date'] == last_day) & (\n last_df['time'] == last_day_have_date[index])].index[0]\n target_index = first_day_lack_df.loc[first_day_lack_df['time'] ==\n last_day_have_date[index]].index[0]\n first_day_lack_df.iloc[target_index] = last_df.iloc[origanl_index]\n else:\n print(f'期货品种{contract_kind}在前一个交易日{last_day}没有夜盘数据,不需要读取覆盖')\n print('直接使用np.nan填充上一个交易日的夜盘数据')\n for index in range(first_day_lack_df.shape[0]):\n combine_df = combine_df.append(first_day_lack_df.iloc[index])\n combine_df['时间'] = combine_df['时间'].str.replace('-', '')\n combine_df['date'] = combine_df['date'].str.replace('-', '')\n combine_df.sort_values('时间', inplace=True)\n end_index = np.where(combine_df['time'] == end_time)[0] + 1\n end_index = np.hstack(([0], end_index))\n start = end_index[:-1]\n end = end_index[1:]\n col_type_list = ['开', '高', '低', '收', '成交量', '成交额', '持仓量']\n dir_name_list = ['open', 'high', 'low', 'close', 'volume', 'amount',\n 'position']\n merge_df = pd.DataFrame({'time': time_0931_15})\n combine_df['date'] = combine_df['时间'].str[:8]\n for index in range(len(col_type_list)):\n col_type = col_type_list[index]\n csv_df = pd.DataFrame()\n for s_index, e_index in zip(start, end):\n res = combine_df.iloc[s_index:e_index, :]\n one_date_df = pd.DataFrame(res[col_type].values.reshape(1, -1),\n columns=res['time'].values.tolist())\n one_date_df['main_contract_code'] = res.iloc[-1]['合约代码']\n one_date_df['date'] = res.iloc[-1]['date']\n col_layout = ['date']\n col_layout = np.hstack((col_layout, res['time'].values.tolist()))\n col_layout = np.hstack((col_layout, ['main_contract_code']))\n one_date_df = one_date_df[col_layout]\n csv_df = pd.concat([csv_df, one_date_df])\n orignal_csv_df = pd.read_csv(orignal_clean_csv_path + contract_kind +\n '_1min_' + dir_name_list[index] + '.csv')\n column_ouput_form = orignal_csv_df.columns.values\n orignal_date_pool = pd.to_datetime(orignal_csv_df['date'], format=\n '%Y-%m-%d').values\n current_date_pool = pd.to_datetime(csv_df['date'], format='%Y-%m-%d'\n ).values\n orignal_csv_df['date'] = pd.to_datetime(orignal_csv_df['date'],\n format='%Y-%m-%d').dt.strftime('%Y-%m-%d')\n csv_df['date'] = pd.to_datetime(csv_df['date'], format='%Y%m%d'\n ).dt.strftime('%Y-%m-%d')\n main_code = csv_df['main_contract_code'].iloc[0]\n main_code_num = csv_df['main_contract_code'].str.findall('[0-9]+'\n ).iloc[0][0]\n if len(main_code_num) == 3:\n print(f'合约代码{main_code}缺少一位数字,将被替换')\n csv_df['main_contract_code'] = csv_df['main_contract_code'].str[:2\n ] + month[0] + csv_df['main_contract_code'].str[2:]\n main_code = csv_df['main_contract_code'].iloc[0]\n print(f'合约代码{main_code}')\n intersection_pool = [date for date in orignal_date_pool if date in\n current_date_pool]\n if not intersection_pool:\n print(\n f'新旧数据没有时间交集,{contract_kind} {dir_name_list[index]} 将被添加到先前数据中'\n )\n orignal_csv_df = pd.concat([orignal_csv_df, csv_df])\n orignal_csv_df.sort_values('date', inplace=True)\n orignal_csv_df = orignal_csv_df[column_ouput_form]\n orignal_csv_df.to_csv(orignal_clean_csv_path + contract_kind +\n '_1min_' + dir_name_list[index] + '.csv', index=False)\n print(f'期货品种{contract_kind} {dir_name_list[index]} 完成')\n else:\n print(\n f'新旧数据的时间出现交集!!{contract_kind} {dir_name_list[index]} 将不会被添加到先前数据中'\n )\n",
"step-4": "import numpy as np\nimport pandas as pd\nfrom unrar import rarfile\nimport numpy as np\nimport pandas as pd\nimport tushare as ts\nimport os\nyear_month = '201911'\ncontract_kind = 'NI'\nrar_data_file_path = (\n 'C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'\n )\nmain_code_path = (\n 'C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/main/main_/'\n )\nclean_data_path = 'D:/1_min补充统一/'\nend_date = '20200107'\ntime_range_path = 'D:/统一所有品种时间范围.csv'\n\n\ndef renew_commodity_future(year_month: str, contract_kind: str,\n main_code_path: str, rar_data_file_path: str, clean_data_path: str,\n time_range_path: str, end_date: str, commodity_bool=True):\n \"\"\"\n 用于更新月度的商品期货数据\n year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911\n contract_kind:放对应品种的list 类似['A','B']\n main_code_path:对应存放主力合约的地方\n rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名\n clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处\n time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv\n end_date :'20200103' 今日的日期,用来请求tushare中的交易日历,数据的读取合并都是以交易日历的时间驱动\n commodity_bool:商品期货对应True,金融期货False,默认商品期货\n \"\"\"\n month = year_month\n if commodity_bool:\n file_name = rar_data_file_path + 'FutAC_Min1_Std_' + month + '.rar'\n else:\n file_name = rar_data_file_path + 'FutSF_Min1_Std_' + month + '.rar'\n orignial_path = main_code_path\n specifi_path = orignial_path + contract_kind + '_1day_main.npy'\n rar = rarfile.RarFile(file_name, pwd='www.jinshuyuan.net')\n orignal_clean_csv_path = clean_data_path\n pwd = 'www.jinshuyuan.net'\n data = np.load(specifi_path)\n time_0931_15 = pd.read_csv(time_range_path)['date'].values.tolist()\n rar.extractall(path=file_name.split('.')[0])\n pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6'\n )\n ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')\n date_df = pro.trade_cal(exchange='DCE', start_date='20100101', end_date\n =end_date)\n date_df = date_df.loc[date_df['is_open'] == 1]\n date_list = date_df['cal_date'].tolist()\n date_df = pd.DataFrame({'date': date_list})\n date_df['month'] = date_df['date'].str[:6]\n target_date = date_df.loc[date_df['month'] == month]\n target_date_index = target_date.index.values\n target_date = target_date['date'].values\n data = data.reshape(-1)\n contract_main_pool = data[target_date_index]\n contract_main_pool = (pd.Series(contract_main_pool).str.split('.').str[\n 0] + '.csv').values\n file_pools = os.listdir(file_name.split('.')[0])\n if contract_main_pool[0] not in file_pools:\n contract_main_pool = [contract_file.lower() for contract_file in\n contract_main_pool]\n if contract_main_pool[0] not in file_pools:\n print(f'找不到{contract_main_pool[0]}')\n contract_main_pool = (file_name.split('.')[0] + '/' + pd.Series(\n contract_main_pool)).values\n row_1 = ['市场代码', '合约代码', '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量']\n orignal_data = []\n orignal_data.append(row_1)\n for index in range(len(target_date)):\n date = target_date[index]\n one_file_path = contract_main_pool[index]\n df = pd.read_csv(one_file_path, encoding='gbk')\n df['date'] = df['时间'].str[:10]\n df['date2'] = df['date'].str.replace('-', '')\n result = df.loc[df['date2'] == date]\n if result.shape[0] > 0:\n for row_index in range(len(result)):\n target_row = result.iloc[row_index].tolist()\n clean_row = target_row[:-2]\n orignal_data.append(clean_row)\n print(f'{contract_kind} {date} finished!')\n else:\n print(f'没找到合约品种{contract_kind}在{date}')\n print(f'{contract_kind}在{month}月的主力合约数据读取完成')\n final_df = pd.DataFrame(orignal_data[1:], columns=orignal_data[0])\n final_df['date'] = final_df['时间'].str[:10]\n final_df_date = final_df['date'].unique()\n final_df['date'] = final_df['时间'].str[:10]\n final_df['time'] = final_df['时间'].str[10:].str.strip()\n final_df['时间'] = final_df['date'] + ' ' + final_df['time']\n final_df = final_df.sort_values('时间')\n final_df['合约代码'] = final_df['合约代码'].str.upper()\n final_df = final_df.sort_values('时间')\n final_df['transf_date'] = pd.to_datetime(final_df['date'])\n final_df.set_index('transf_date', inplace=True)\n combine_all_df = pd.DataFrame()\n final_df['date2'] = final_df['date'].str.replace('-', '')\n for date_index in range(len(target_date)):\n target_df = final_df.loc[final_df['date2'] == target_date[date_index]]\n target_num = len(target_df)\n theory_num = len(time_0931_15)\n if target_num > 0:\n have_time = target_df['time'].values.tolist()\n lack_time = [x for x in time_0931_15 if x not in have_time]\n if lack_time:\n print(f'{target_date[date_index]} 不连续')\n insert_array = np.empty(shape=(len(lack_time), 12))\n insert_array.fill(np.nan)\n insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',\n '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])\n insert_df['date'] = target_date[date_index]\n insert_df['time'] = lack_time\n if len(lack_time) < len(time_0931_15):\n insert_df['合约代码'] = target_df['合约代码'].unique()[-1]\n combine_insert_df = pd.concat([target_df, insert_df])\n combine_all_df = pd.concat([combine_all_df, combine_insert_df])\n else:\n print(f'{target_date[date_index]}empty ')\n lack_time = [x for x in time_0931_15]\n insert_array = np.empty(shape=(len(lack_time), 12))\n insert_array.fill(np.nan)\n insert_df = pd.DataFrame(insert_array, columns=['市场代码', '合约代码',\n '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量', 'date', 'time'])\n insert_df['date'] = target_date[date_index]\n insert_df['time'] = lack_time\n combine_all_df = pd.concat([combine_all_df, insert_df])\n combine_all_df['时间'] = combine_all_df['date'] + ' ' + combine_all_df['time'\n ]\n combine_all_df = combine_all_df.sort_values('时间')\n combine_all_df.reset_index(inplace=True)\n combine_all_df = combine_all_df[['市场代码', '合约代码', '时间', '开', '高', '低',\n '收', '成交量', '成交额', '持仓量', 'date', 'time']]\n combine_all_df['时间'] = combine_all_df['时间'].str.replace('-', '')\n combine_all_df['date'] = combine_all_df['date'].str.replace('-', '')\n combine_df = combine_all_df.copy()\n contract_type = contract_kind\n combine_df = combine_df.sort_values('时间')\n end_time = '15:15:00'\n end_index = np.where(combine_df['time'] == end_time)[0] + 1\n end_index = np.hstack(([0], end_index))\n start = end_index[:-1]\n end = end_index[1:]\n last_day = date_df['date'].iloc[target_date_index[0] - 1]\n last_day = last_day[:4] + '-' + last_day[4:6] + '-' + last_day[6:]\n first_day_have = combine_df[start[0]:end[0]]['time'].values\n full_time = combine_df['time'].unique()\n full_time.sort()\n first_day_lack = [x for x in full_time[-179:]]\n first_day_lack.sort()\n lack_array = np.empty(shape=(len(first_day_lack), 12))\n lack_array.fill(np.nan)\n first_day_lack_df = pd.DataFrame(lack_array, columns=combine_df.columns)\n first_day_lack_df['time'] = first_day_lack\n first_day_lack_df['date'] = last_day\n first_day_lack_df['时间'] = first_day_lack_df['date'\n ] + ' ' + first_day_lack_df['time']\n last_df = pd.read_csv(contract_main_pool[0], encoding='gbk')\n last_df['date'] = last_df['时间'].str[:10]\n last_df['time'] = last_df['时间'].str[11:]\n last_time_pool = last_df.loc[last_df['date'] == last_day]['time'].values\n last_day_have_date = []\n if last_time_pool.shape[0] > 0:\n print(f'期货品种{contract_kind}在前一个交易日{last_day}有夜盘数据,需要读取覆盖')\n last_day_have_date = [x for x in last_time_pool]\n if last_day_have_date:\n for index in range(len(last_day_have_date)):\n origanl_index = last_df.loc[(last_df['date'] == last_day) & (\n last_df['time'] == last_day_have_date[index])].index[0]\n target_index = first_day_lack_df.loc[first_day_lack_df['time'] ==\n last_day_have_date[index]].index[0]\n first_day_lack_df.iloc[target_index] = last_df.iloc[origanl_index]\n else:\n print(f'期货品种{contract_kind}在前一个交易日{last_day}没有夜盘数据,不需要读取覆盖')\n print('直接使用np.nan填充上一个交易日的夜盘数据')\n for index in range(first_day_lack_df.shape[0]):\n combine_df = combine_df.append(first_day_lack_df.iloc[index])\n combine_df['时间'] = combine_df['时间'].str.replace('-', '')\n combine_df['date'] = combine_df['date'].str.replace('-', '')\n combine_df.sort_values('时间', inplace=True)\n end_index = np.where(combine_df['time'] == end_time)[0] + 1\n end_index = np.hstack(([0], end_index))\n start = end_index[:-1]\n end = end_index[1:]\n col_type_list = ['开', '高', '低', '收', '成交量', '成交额', '持仓量']\n dir_name_list = ['open', 'high', 'low', 'close', 'volume', 'amount',\n 'position']\n merge_df = pd.DataFrame({'time': time_0931_15})\n combine_df['date'] = combine_df['时间'].str[:8]\n for index in range(len(col_type_list)):\n col_type = col_type_list[index]\n csv_df = pd.DataFrame()\n for s_index, e_index in zip(start, end):\n res = combine_df.iloc[s_index:e_index, :]\n one_date_df = pd.DataFrame(res[col_type].values.reshape(1, -1),\n columns=res['time'].values.tolist())\n one_date_df['main_contract_code'] = res.iloc[-1]['合约代码']\n one_date_df['date'] = res.iloc[-1]['date']\n col_layout = ['date']\n col_layout = np.hstack((col_layout, res['time'].values.tolist()))\n col_layout = np.hstack((col_layout, ['main_contract_code']))\n one_date_df = one_date_df[col_layout]\n csv_df = pd.concat([csv_df, one_date_df])\n orignal_csv_df = pd.read_csv(orignal_clean_csv_path + contract_kind +\n '_1min_' + dir_name_list[index] + '.csv')\n column_ouput_form = orignal_csv_df.columns.values\n orignal_date_pool = pd.to_datetime(orignal_csv_df['date'], format=\n '%Y-%m-%d').values\n current_date_pool = pd.to_datetime(csv_df['date'], format='%Y-%m-%d'\n ).values\n orignal_csv_df['date'] = pd.to_datetime(orignal_csv_df['date'],\n format='%Y-%m-%d').dt.strftime('%Y-%m-%d')\n csv_df['date'] = pd.to_datetime(csv_df['date'], format='%Y%m%d'\n ).dt.strftime('%Y-%m-%d')\n main_code = csv_df['main_contract_code'].iloc[0]\n main_code_num = csv_df['main_contract_code'].str.findall('[0-9]+'\n ).iloc[0][0]\n if len(main_code_num) == 3:\n print(f'合约代码{main_code}缺少一位数字,将被替换')\n csv_df['main_contract_code'] = csv_df['main_contract_code'].str[:2\n ] + month[0] + csv_df['main_contract_code'].str[2:]\n main_code = csv_df['main_contract_code'].iloc[0]\n print(f'合约代码{main_code}')\n intersection_pool = [date for date in orignal_date_pool if date in\n current_date_pool]\n if not intersection_pool:\n print(\n f'新旧数据没有时间交集,{contract_kind} {dir_name_list[index]} 将被添加到先前数据中'\n )\n orignal_csv_df = pd.concat([orignal_csv_df, csv_df])\n orignal_csv_df.sort_values('date', inplace=True)\n orignal_csv_df = orignal_csv_df[column_ouput_form]\n orignal_csv_df.to_csv(orignal_clean_csv_path + contract_kind +\n '_1min_' + dir_name_list[index] + '.csv', index=False)\n print(f'期货品种{contract_kind} {dir_name_list[index]} 完成')\n else:\n print(\n f'新旧数据的时间出现交集!!{contract_kind} {dir_name_list[index]} 将不会被添加到先前数据中'\n )\n",
"step-5": "import numpy as np \nimport pandas as pd\nfrom unrar import rarfile\nimport numpy as np \nimport pandas as pd\nimport tushare as ts\nimport os\n\nyear_month='201911'\ncontract_kind='NI'\nrar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'\nmain_code_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/main/main_/'\nclean_data_path='D:/1_min补充统一/'\nend_date='20200107'\ntime_range_path='D:/统一所有品种时间范围.csv'\n# save_month_fill_data_path='D:/1_min补充统一/'+contract_kind+'主力连续'+'_'+month+'.csv'\ndef renew_commodity_future(year_month:str,contract_kind:str,main_code_path:str,rar_data_file_path:str,clean_data_path:str,time_range_path:str,end_date:str,commodity_bool=True):\n '''\n 用于更新月度的商品期货数据\n year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911\n contract_kind:放对应品种的list 类似['A','B']\n main_code_path:对应存放主力合约的地方\n rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名\n clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处\n time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv\n end_date :'20200103' 今日的日期,用来请求tushare中的交易日历,数据的读取合并都是以交易日历的时间驱动\n commodity_bool:商品期货对应True,金融期货False,默认商品期货\n '''\n month=year_month\n if commodity_bool: \n file_name=rar_data_file_path+'FutAC_Min1_Std_'+month+'.rar'\n else:\n file_name=rar_data_file_path+'FutSF_Min1_Std_'+month+'.rar'\n orignial_path=main_code_path\n specifi_path=orignial_path+contract_kind+'_1day_main.npy'\n rar = rarfile.RarFile(file_name,pwd='www.jinshuyuan.net')\n # 原始的处理好的数据\n orignal_clean_csv_path=clean_data_path\n pwd='www.jinshuyuan.net'\n data=np.load(specifi_path)\n time_0931_15=pd.read_csv(time_range_path)['date'].values.tolist()\n rar.extractall(path=file_name.split('.')[0])\n # 首先需要输入end_date 确保截取的时间长度和main主力合约的时间对齐\n # 按照月份确定位置\n pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')\n ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')\n date_df=pro.trade_cal(exchange='DCE', start_date='20100101', end_date=end_date)\n date_df=date_df.loc[date_df['is_open']==1]\n date_list=date_df['cal_date'].tolist()\n # ==========================================================================\n # 针对的是201911月数据,对应的合约index 放在 target_date_index中\n date_df=pd.DataFrame({'date':date_list})\n date_df['month']=date_df['date'].str[:6]\n target_date=date_df.loc[date_df['month']==month]\n target_date_index=target_date.index.values\n target_date=target_date['date'].values\n # 获取对应目标\n data=data.reshape(-1)\n contract_main_pool=data[target_date_index]\n # 去掉交易所的代码编号\n contract_main_pool=(pd.Series(contract_main_pool).str.split('.').str[0]+'.csv').values\n file_pools=os.listdir(file_name.split('.')[0])\n # 郑州期货交易所是大写,其它都是小写,这里需要逻辑判断\n if contract_main_pool[0] not in file_pools:\n contract_main_pool=[contract_file.lower() for contract_file in contract_main_pool]\n if contract_main_pool[0] not in file_pools:\n print(f'找不到{contract_main_pool[0]}')\n # 读取好所有的路径\n contract_main_pool=(file_name.split('.')[0]+'/'+pd.Series(contract_main_pool)).values\n # (len(target_date),contract_main_pool.shape[0])\n row_1=['市场代码','合约代码',\t'时间',\t'开','高',\t'低',\t'收',\t'成交量',\t'成交额',\t'持仓量']\n orignal_data=[]\n orignal_data.append(row_1)\n for index in range(len(target_date)):\n date=target_date[index]\n one_file_path=contract_main_pool[index]\n df=pd.read_csv(one_file_path,encoding='gbk')\n df['date']=df['时间'].str[:10]\n df['date2']=df['date'].str.replace('-','')\n result=df.loc[df['date2']==date]\n if result.shape[0]>0:\n for row_index in range(len(result)):\n target_row=result.iloc[row_index].tolist()\n clean_row=target_row[:-2]\n orignal_data.append(clean_row)\n print(f'{contract_kind} {date} finished!')\n else:\n print(f'没找到合约品种{contract_kind}在{date}')\n print(f'{contract_kind}在{month}月的主力合约数据读取完成')\n final_df=pd.DataFrame(orignal_data[1:],columns=orignal_data[0])\n\n final_df['date']=final_df['时间'].str[:10]\n final_df_date=final_df['date'].unique()\n\n final_df['date']=final_df['时间'].str[:10]\n final_df['time']=final_df['时间'].str[10:].str.strip()\n final_df['时间']=final_df['date']+' '+final_df['time']\n final_df=final_df.sort_values('时间')\n final_df['合约代码']=final_df['合约代码'].str.upper()\n final_df=final_df.sort_values('时间')\n # ===============================增加了从constant_time进行截取================================\n final_df['transf_date']=pd.to_datetime(final_df['date'])\n final_df.set_index('transf_date',inplace=True)\n combine_all_df=pd.DataFrame()\n final_df['date2']=final_df['date'].str.replace('-','')\n # 按月进行填充\n # 设置了存放按月填充的路径\n for date_index in range(len(target_date)):\n\n #按日期进行分割\n target_df=final_df.loc[final_df['date2']==target_date[date_index]]\n #分割到的长度放入容器中\n target_num=len(target_df)\n #理论长度\n theory_num=len(time_0931_15)\n #实际上两种情况:1.是交易日但完全没有数据2.是交易日,只有部分数据 3.是交易日,数据也是完整的\n if target_num>0:\n #开始区分2,3情况\n have_time=target_df['time'].values.tolist()\n lack_time=[x for x in time_0931_15 if x not in have_time]\n #检查是不是情况2\n if lack_time:\n print(f'{target_date[date_index]} 不连续')\n #一共12列,先全部填充nan的时候,最后再把已知填入\n insert_array=np.empty(shape=(len(lack_time),12))\n insert_array.fill(np.nan)\n insert_df=pd.DataFrame(insert_array,columns=['市场代码','合约代码','时间','开','高','低','收','成交量','成交额','持仓量','date','time'])\n insert_df['date']=target_date[date_index]\n insert_df['time']=lack_time\n #缺少时间的个数小于time_0931_15则说明,当天并不是完全没数据,只是部分数据缺失,因此要对合约代码进行填充\n if len(lack_time)<len(time_0931_15):\n \n insert_df['合约代码']=target_df['合约代码'].unique()[-1]\n #生成一天完整的数据\n combine_insert_df=pd.concat([target_df,insert_df])\n #将数据添加到容器中\n combine_all_df=pd.concat([combine_all_df,combine_insert_df]) \n \n #完全没有数据,直接填充 \n else:\n print(f'{target_date[date_index]}empty ')\n lack_time=[x for x in time_0931_15]\n #一共12列,先全部填充nan的时候,最后再把已知填入\n insert_array=np.empty(shape=(len(lack_time),12))\n insert_array.fill(np.nan)\n insert_df=pd.DataFrame(insert_array,columns=['市场代码','合约代码','时间','开','高','低','收','成交量','成交额','持仓量','date','time'])\n insert_df['date']=target_date[date_index]\n insert_df['time']=lack_time\n #将数据添加到容器\n combine_all_df=pd.concat([combine_all_df,insert_df])\n combine_all_df['时间']=combine_all_df['date']+' '+combine_all_df['time']\n #调整时间\n combine_all_df=combine_all_df.sort_values('时间')\n\n combine_all_df.reset_index(inplace=True)\n #数据输出,按设定的顺序\n combine_all_df=combine_all_df[['市场代码', '合约代码', '时间', '开', '高', '低', '收', '成交量', '成交额', '持仓量','date','time']]\n combine_all_df['时间']=combine_all_df['时间'].str.replace('-','')\n combine_all_df['date']=combine_all_df['date'].str.replace('-','')\n # combine_all_df.to_csv(save_month_fill_data_path,index=False,encoding='utf-8-sig')\n # ==========================储存数据=================================================\n combine_df=combine_all_df.copy()\n contract_type=contract_kind\n combine_df=combine_df.sort_values('时间')\n # ====================================================================开始截取============================================================\n # end_time+1其实是可以作为每次截取的起点,终点下一个就是起点,不过要加上0,而终点的位置也可以是end_time+1,因为end_time+1只能取end_time\n # 按照下午15:15统一截取\n end_time='15:15:00'\n end_index=np.where(combine_df['time']==end_time)[0]+1\n end_index=np.hstack(([0],end_index))\n start=end_index[:-1]\n end=end_index[1:]\n # ================================================================缺失第一个交易日前一天的夜盘数据==========================================\n # 这里的选择构造一个虚拟的时间戳,来满足缺失的夜盘数据\n # 按照上一步的截取方法,第一个交易日缺少前一天的夜盘数据\n last_day=date_df['date'].iloc[target_date_index[0]-1]\n last_day=last_day[:4]+'-'+last_day[4:6]+'-'+last_day[6:]\n first_day_have=combine_df[start[0]:end[0]]['time'].values\n full_time=combine_df['time'].unique()\n full_time.sort()\n first_day_lack=[x for x in full_time[-179:]]\n first_day_lack.sort()\n lack_array=np.empty(shape=(len(first_day_lack),12))\n lack_array.fill(np.nan)\n # ===============================准备缺失部分df==========================================================================================\n first_day_lack_df=pd.DataFrame(lack_array,columns=combine_df.columns)\n first_day_lack_df['time']=first_day_lack\n first_day_lack_df['date']=last_day\n first_day_lack_df['时间']=first_day_lack_df['date']+' '+first_day_lack_df['time']\n\n last_df=pd.read_csv(contract_main_pool[0],encoding='gbk')\n # 确定之前的有没有夜盘\n last_df['date']=last_df['时间'].str[:10]\n last_df['time']=last_df['时间'].str[11:]\n # 补夜盘数据\n last_time_pool=last_df.loc[last_df['date']==last_day]['time'].values\n\n last_day_have_date=[]\n # 说明在上个交易日有数据\n if last_time_pool.shape[0]>0:\n \n print(f'期货品种{contract_kind}在前一个交易日{last_day}有夜盘数据,需要读取覆盖')\n last_day_have_date=[x for x in last_time_pool]\n if last_day_have_date:\n for index in range(len(last_day_have_date)):\n origanl_index=last_df.loc[(last_df['date']==last_day)&(last_df['time']==last_day_have_date[index])].index[0]\n target_index=first_day_lack_df.loc[first_day_lack_df['time']==last_day_have_date[index]].index[0]\n first_day_lack_df.iloc[target_index]=last_df.iloc[origanl_index]\n else:\n print(f'期货品种{contract_kind}在前一个交易日{last_day}没有夜盘数据,不需要读取覆盖')\n print('直接使用np.nan填充上一个交易日的夜盘数据')\n for index in range(first_day_lack_df.shape[0]):\n combine_df=combine_df.append(first_day_lack_df.iloc[index])\n combine_df['时间']=combine_df['时间'].str.replace('-','')\n combine_df['date']=combine_df['date'].str.replace('-','')\n combine_df.sort_values('时间',inplace=True)\n # =================================缺失部分填充=========================================================================================\n # combine_df=pd.concat([first_day_lack_df,combine_df])\n # # ================================重新按时间排序========================================================================================\n # combine_df=combine_df.sort_values('时间')\n # ============================重新进行切割===============================================================================================\n end_index=np.where(combine_df['time']==end_time)[0]+1\n end_index=np.hstack(([0],end_index))\n start=end_index[:-1]\n end=end_index[1:]\n\n # ==============================进行分割按照特定时间,明确col===============================================================================\n\n col_type_list=['开','高','低','收','成交量','成交额','持仓量']\n dir_name_list=['open','high','low','close','volume','amount','position']\n #这个变量现在没有用\n #交易到凌晨01\n #merge_df=pd.DataFrame({'time':with_night_01})\n #交易到凌晨0230,version中没有集合竞价时间,time_0931_15去掉9:00,21:00\n merge_df=pd.DataFrame({'time':time_0931_15})\n\n combine_df['date']=combine_df['时间'].str[:8]\n for index in range(len(col_type_list)):\n\n col_type=col_type_list[index]\n # 用来接收分col数据的容器\n csv_df=pd.DataFrame()\n for s_index,e_index in zip(start,end):\n\n # =========================================截取每个交易日数据==============================================================================\n res=combine_df.iloc[s_index:e_index,:]\n one_date_df=pd.DataFrame(res[col_type].values.reshape(1,-1),columns=res['time'].values.tolist())\n one_date_df['main_contract_code']=res.iloc[-1]['合约代码']\n one_date_df['date']=res.iloc[-1]['date']\n # =======================================设置输出格式====================================================================================\n\n col_layout=['date']\n col_layout=np.hstack((col_layout,res['time'].values.tolist()))\n col_layout=np.hstack((col_layout,['main_contract_code']))\n one_date_df=one_date_df[col_layout]\n # =======================================合并数据========================================================================================\n csv_df=pd.concat([csv_df,one_date_df])\n # ========================追加原始数据=======================================\n # 时间问题需要处理,不然对不齐\n # 在测试文件中测试,所以修改了路径\n orignal_csv_df=pd.read_csv(orignal_clean_csv_path+contract_kind+'_1min_'+dir_name_list[index]+'.csv')\n column_ouput_form=orignal_csv_df.columns.values\n orignal_date_pool=pd.to_datetime(orignal_csv_df['date'],format='%Y-%m-%d').values\n current_date_pool=pd.to_datetime(csv_df['date'],format='%Y-%m-%d').values\n orignal_csv_df['date']=pd.to_datetime(orignal_csv_df['date'],format='%Y-%m-%d').dt.strftime('%Y-%m-%d')\n csv_df['date']=pd.to_datetime(csv_df['date'],format='%Y%m%d').dt.strftime('%Y-%m-%d')\n # check代码中的数字个数等于四个\n main_code=csv_df['main_contract_code'].iloc[0]\n main_code_num=csv_df['main_contract_code'].str.findall(r'[0-9]+').iloc[0][0]\n if len(main_code_num)==3:\n print(f'合约代码{main_code}缺少一位数字,将被替换')\n csv_df['main_contract_code']=csv_df['main_contract_code'].str[:2]+month[0]+csv_df['main_contract_code'].str[2:]\n main_code=csv_df['main_contract_code'].iloc[0]\n print(f'合约代码{main_code}')\n # 查看有没有交集,如果有交集会停止,说明进行了重复操作\n \n intersection_pool=[date for date in orignal_date_pool if date in current_date_pool]\n if not intersection_pool:\n print(f'新旧数据没有时间交集,{contract_kind} {dir_name_list[index]} 将被添加到先前数据中')\n orignal_csv_df=pd.concat([orignal_csv_df,csv_df]) \n orignal_csv_df.sort_values('date',inplace=True)\n orignal_csv_df=orignal_csv_df[column_ouput_form]\n orignal_csv_df.to_csv(orignal_clean_csv_path+contract_kind+'_1min_'+dir_name_list[index]+'.csv',index=False)\n print(f'期货品种{contract_kind} {dir_name_list[index]} 完成')\n else:\n print(f'新旧数据的时间出现交集!!{contract_kind} {dir_name_list[index]} 将不会被添加到先前数据中')\n \n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import logging
from random import randint
import pygame
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
from playsound import playsound
app = Flask(__name__)
ask = Ask(app, "/")
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
@ask.launch
def new_game():
pygame.mixer.init()
pygame.mixer.music.load("haha2.mp3")
pygame.mixer.music.play()
welcome_msg = render_template('welcome')
return question(welcome_msg)
@ask.intent("ChooseIntent", convert={'first': int})
def ask_choose(first):
session.attributes['first'] = first
ask = render_template('ask')
return question(ask)
@ask.intent("StopIntent")
def stop():
pygame.mixer.music.stop()
return question('')
@ask.intent("AgainIntent")
def again():
pygame.mixer.music.load("britney.mp3")
pygame.mixer.music.play()
return question('')
@ask.intent("AMAZON.YesIntent")
def yes_ans():
first = session.attributes['first']
if first % 3 == 0:
msg = render_template('win')
else:
msg = render_template('lose')
return statement(msg)
@ask.intent("AMAZON.NoIntent")
def no_ans():
first = session.attributes['first']
if first % 3 != 0:
msg = render_template('win')
else:
msg = render_template('lose')
return statement(msg)
if __name__ == '__main__':
app.run(debug=True)
|
normal
|
{
"blob_id": "e4b6304be10ee5a741c8a193dcf65950299ef11a",
"index": 1477,
"step-1": "<mask token>\n\n\n@ask.launch\ndef new_game():\n pygame.mixer.init()\n pygame.mixer.music.load('haha2.mp3')\n pygame.mixer.music.play()\n welcome_msg = render_template('welcome')\n return question(welcome_msg)\n\n\n@ask.intent('ChooseIntent', convert={'first': int})\ndef ask_choose(first):\n session.attributes['first'] = first\n ask = render_template('ask')\n return question(ask)\n\n\n@ask.intent('StopIntent')\ndef stop():\n pygame.mixer.music.stop()\n return question('')\n\n\n@ask.intent('AgainIntent')\ndef again():\n pygame.mixer.music.load('britney.mp3')\n pygame.mixer.music.play()\n return question('')\n\n\n@ask.intent('AMAZON.YesIntent')\ndef yes_ans():\n first = session.attributes['first']\n if first % 3 == 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n return statement(msg)\n\n\n@ask.intent('AMAZON.NoIntent')\ndef no_ans():\n first = session.attributes['first']\n if first % 3 != 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n return statement(msg)\n\n\n<mask token>\n",
"step-2": "<mask token>\nlogging.getLogger('flask_ask').setLevel(logging.DEBUG)\n\n\n@ask.launch\ndef new_game():\n pygame.mixer.init()\n pygame.mixer.music.load('haha2.mp3')\n pygame.mixer.music.play()\n welcome_msg = render_template('welcome')\n return question(welcome_msg)\n\n\n@ask.intent('ChooseIntent', convert={'first': int})\ndef ask_choose(first):\n session.attributes['first'] = first\n ask = render_template('ask')\n return question(ask)\n\n\n@ask.intent('StopIntent')\ndef stop():\n pygame.mixer.music.stop()\n return question('')\n\n\n@ask.intent('AgainIntent')\ndef again():\n pygame.mixer.music.load('britney.mp3')\n pygame.mixer.music.play()\n return question('')\n\n\n@ask.intent('AMAZON.YesIntent')\ndef yes_ans():\n first = session.attributes['first']\n if first % 3 == 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n return statement(msg)\n\n\n@ask.intent('AMAZON.NoIntent')\ndef no_ans():\n first = session.attributes['first']\n if first % 3 != 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n return statement(msg)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n",
"step-3": "<mask token>\napp = Flask(__name__)\nask = Ask(app, '/')\nlogging.getLogger('flask_ask').setLevel(logging.DEBUG)\n\n\n@ask.launch\ndef new_game():\n pygame.mixer.init()\n pygame.mixer.music.load('haha2.mp3')\n pygame.mixer.music.play()\n welcome_msg = render_template('welcome')\n return question(welcome_msg)\n\n\n@ask.intent('ChooseIntent', convert={'first': int})\ndef ask_choose(first):\n session.attributes['first'] = first\n ask = render_template('ask')\n return question(ask)\n\n\n@ask.intent('StopIntent')\ndef stop():\n pygame.mixer.music.stop()\n return question('')\n\n\n@ask.intent('AgainIntent')\ndef again():\n pygame.mixer.music.load('britney.mp3')\n pygame.mixer.music.play()\n return question('')\n\n\n@ask.intent('AMAZON.YesIntent')\ndef yes_ans():\n first = session.attributes['first']\n if first % 3 == 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n return statement(msg)\n\n\n@ask.intent('AMAZON.NoIntent')\ndef no_ans():\n first = session.attributes['first']\n if first % 3 != 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n return statement(msg)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n",
"step-4": "import logging\nfrom random import randint\nimport pygame\nfrom flask import Flask, render_template\nfrom flask_ask import Ask, statement, question, session\nfrom playsound import playsound\napp = Flask(__name__)\nask = Ask(app, '/')\nlogging.getLogger('flask_ask').setLevel(logging.DEBUG)\n\n\n@ask.launch\ndef new_game():\n pygame.mixer.init()\n pygame.mixer.music.load('haha2.mp3')\n pygame.mixer.music.play()\n welcome_msg = render_template('welcome')\n return question(welcome_msg)\n\n\n@ask.intent('ChooseIntent', convert={'first': int})\ndef ask_choose(first):\n session.attributes['first'] = first\n ask = render_template('ask')\n return question(ask)\n\n\n@ask.intent('StopIntent')\ndef stop():\n pygame.mixer.music.stop()\n return question('')\n\n\n@ask.intent('AgainIntent')\ndef again():\n pygame.mixer.music.load('britney.mp3')\n pygame.mixer.music.play()\n return question('')\n\n\n@ask.intent('AMAZON.YesIntent')\ndef yes_ans():\n first = session.attributes['first']\n if first % 3 == 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n return statement(msg)\n\n\n@ask.intent('AMAZON.NoIntent')\ndef no_ans():\n first = session.attributes['first']\n if first % 3 != 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n return statement(msg)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n",
"step-5": "import logging\n\nfrom random import randint\nimport pygame\n\nfrom flask import Flask, render_template\nfrom flask_ask import Ask, statement, question, session\nfrom playsound import playsound\n\napp = Flask(__name__)\nask = Ask(app, \"/\")\nlogging.getLogger(\"flask_ask\").setLevel(logging.DEBUG)\n\n\n@ask.launch\ndef new_game():\n pygame.mixer.init()\n pygame.mixer.music.load(\"haha2.mp3\")\n pygame.mixer.music.play()\n welcome_msg = render_template('welcome')\n return question(welcome_msg)\n\n\n@ask.intent(\"ChooseIntent\", convert={'first': int})\ndef ask_choose(first):\n session.attributes['first'] = first\n ask = render_template('ask')\n return question(ask)\n\n\n@ask.intent(\"StopIntent\")\ndef stop():\n pygame.mixer.music.stop()\n return question('')\n\n\n@ask.intent(\"AgainIntent\")\ndef again():\n pygame.mixer.music.load(\"britney.mp3\")\n pygame.mixer.music.play()\n return question('')\n\n\n@ask.intent(\"AMAZON.YesIntent\")\ndef yes_ans():\n first = session.attributes['first']\n if first % 3 == 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n\n return statement(msg)\n\n\n@ask.intent(\"AMAZON.NoIntent\")\ndef no_ans():\n first = session.attributes['first']\n if first % 3 != 0:\n msg = render_template('win')\n else:\n msg = render_template('lose')\n\n return statement(msg)\n\n\nif __name__ == '__main__':\n\n app.run(debug=True)\n",
"step-ids": [
6,
7,
8,
9,
10
]
}
|
[
6,
7,
8,
9,
10
] |
import stock as stk
import portfolio as portf
import plot
import sys
import cmd
import os
import decision as des
class CLI(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = '$> '
self.stk_data_coll = stk.StockDataCollection()
self.add_to_plot_lst = []
self.paralel_count = 10
def do_set_paralel_count(self, arg):
self.paralel_count = arg
def do_get_paralel_count(self, arg):
print self.paralel_count
def help_set_paralel_count(self):
print "syntax: set_paralel_count [NUMBER]",
print "-- update self.paralel_count for load command"
def do_load_collection(self, arg):
self.stk_data_coll.load(conf_file=arg, paralel_count=self.paralel_count)
print "---------------------------------------"
print "Data downloaded for ", arg
def help_load_collection(self):
print "syntax: load [portfolio file]",
print "-- load/updates the tickers from portfolio file"
def do_set_collection(self, arg):
self.stk_data_coll.set_colection(arg)
def help_set_collection(self):
print "syntax: set_collection [portfolio file]",
print "-- set the tickers from portfolio file"
def do_get_collection(self, arg):
print "-----------------------------"
print " Collection from ", self.stk_data_coll.conf_file
print "-----------------------------"
for c in self.stk_data_coll.stk_data_coll:
print c
def do_cleanup(self, arg):
filelist = [ f for f in os.listdir("./data") if f.endswith(".dat") ]
for f in filelist:
os.remove("./data/" + f)
def help_cleanup(self):
print "syntax: cleanup",
print "-- removes all data files"
def do_plot_indexes(self, arg):
indexes = arg.split(',',1)
a_plot = plot.Plot(plot.PlotCellIndex(indexes[0]))
try:
for index in indexes[1:]:
p = plot.PlotCellIndex(index)
a_plot.addSimple(plot.PlotCell((p.data,p.dates)))
finally: a_plot.plot()
def help_plot_indexes(self):
print "syntax: plot_index [index_name1,index_name2,....]",
print "-- plot slimple index from csv"
def do_plot_ticker_indexes(self,arg):
calc = stk.StockCalcIndex(self.stk_data_coll)
sd = stk.StockData()
ticker, indexes, startdate = arg.split()
indexes = indexes.split(',',1)
sd.load(ticker, startdate)
a_plot = plot.Plot(plot.PlotCell((sd.Cs,sd.dates)))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 200),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 50),overlay=True))
for index in indexes:
p = plot.PlotCellIndex(index)
p.truncate(startdate)
a_plot.addSimple(plot.PlotCell((p.data,p.dates)))
a_plot.addSimple(plot.PlotCell(calc.sma((p.data,p.dates),20)))
a_plot.addSimple(plot.PlotCell(calc.sma((p.data,p.dates),50),overlay=True))
a_plot.plot()
def do_plot_collection(self, arg):
calc = stk.StockCalcIndex(self.stk_data_coll)
sd = stk.StockData()
ticker, startdate = arg.split()
sd.load(ticker, startdate)
a_plot = plot.Plot(plot.PlotCell((sd.Cs,sd.dates)))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 200),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 50),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.llv((sd.Cs, sd.dates), 100),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Vs,sd.dates),20 )))
a_plot.addSimple(plot.PlotCell( calc.obv((sd.Cs,sd.Vs,sd.dates) )))
a_plot.addSimple(plot.PlotCell( calc.correlation_adj((sd.Cs,sd.dates))))
a_plot.plot()
def do_plot(self, arg):
calc = stk.StockCalcIndex(self.stk_data_coll)
sd = stk.StockData()
ticker, startdate = arg.split()
sd.load(ticker, startdate)
a_plot = plot.Plot(plot.PlotCell((sd.Cs,sd.dates)))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 200),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 50),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.llv((sd.Cs, sd.dates), 100),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Vs,sd.dates),20 )))
arr_obv = calc.obv((sd.Cs,sd.Vs,sd.dates) )
a_plot.addSimple(plot.PlotCell( arr_obv))
a_plot.addSimple(plot.PlotCell( calc.sma(arr_obv, 20),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.sma(arr_obv, 60),overlay=True))
a_plot.plot()
def help_plot(self):
print "syntax: plot [ticker] []|[start date YYYYMMDD]",
print "-- plots the ticker"
def do_simulation(self, arg):
ticker, startdate = arg.split()
calc = stk.StockCalcIndex(self.stk_data_coll)
sd = stk.StockData()
sd.load(ticker, startdate)
port = des.DecisionCollection(ticker, 50000)
decision = des.DecisionSimpleSMA(ticker, (sd.Cs, sd.dates), port)
decision.looper()
print ticker, ":", str(port)
port2 = des.DecisionCollection(ticker, 50000)
decision2 = des.DecisionSimpleStopSMA(ticker, (sd.Cs, sd.dates), port2, risk_factor=0.01, )
decision2.looper()
print ticker, ":", str(port2)
port2.print_all()
a_plot = plot.Plot(plot.PlotCell((sd.Cs,sd.dates)))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 200),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 50),overlay=True))
a_plot.addSimple(plot.PlotCell( calc.llv((sd.Cs, sd.dates), 100),overlay=True))
a_plot.addSimple(plot.PlotCell( port2.get_enter_plot_cell(), overlay=True, color='go' ))
a_plot.addSimple(plot.PlotCell( port2.get_leave_plot_cell(), overlay=True, color='ro' ))
a_plot.addSimple(plot.PlotCell( port2.get_value_plot_cell()))
a_plot.plot()
def help_simulation(self):
print "syntax: simulation [ticker] []|[start date YYYYMMDD]",
print "-- runs a simulation on a single ticker"
def do_simulation_collection(self, arg ):
for ticker in self.stk_data_coll.stk_data_coll:
sd = stk.StockData()
sd.load(ticker, arg)
port = des.DecisionCollection(ticker, 50000)
decision = des.DecisionSimpleStopSMA(ticker, (sd.Cs, sd.dates), port, risk_factor=0.02, sma_fast=10, sma_slow=50, stop_per=5)
decision.looper()
port4 = des.DecisionCollection(ticker, 50000)
decision4 = des.DecisionSimpleSMA(ticker, (sd.Cs, sd.dates), port4, sma_fast=10, sma_slow=50, stop_per=5)
decision4.looper()
port2 = des.DecisionCollection(ticker, 50000)
decision2 = des.DecisionSimpleSMA(ticker, (sd.Cs, sd.dates), port2)
decision2.looper()
port3 = des.DecisionCollection(ticker, 50000)
decision3 = des.DecisionSimpleStopSMA(ticker, (sd.Cs, sd.dates), port3, risk_factor=0.02, sma_fast=50, sma_slow=200, stop_per=40)
decision3.looper()
print "STOP_FAST - ", ticker, " ", str(port)
print "SIMPLE_FAST - ", ticker, " ", str(port4)
print "STOP_SLOW - ", ticker, " ", str(port3)
print "SIMPLE_SLOW - ", ticker, " ", str(port2)
def emptyline(self):
pass
def do_quit(self, arg):
sys.exit(1)
if __name__ == "__main__":
cli = CLI()
cli.cmdloop()
|
normal
|
{
"blob_id": "d386047c087155b1809d47349339eb6882cf8e26",
"index": 5013,
"step-1": "import stock as stk\nimport portfolio as portf\nimport plot\nimport sys\nimport cmd\nimport os\nimport decision as des\n \n \nclass CLI(cmd.Cmd):\n\n def __init__(self):\n cmd.Cmd.__init__(self)\n self.prompt = '$> '\n self.stk_data_coll = stk.StockDataCollection()\n self.add_to_plot_lst = []\n self.paralel_count = 10\n \n def do_set_paralel_count(self, arg):\n self.paralel_count = arg\n \n def do_get_paralel_count(self, arg):\n print self.paralel_count\n \n def help_set_paralel_count(self):\n print \"syntax: set_paralel_count [NUMBER]\",\n print \"-- update self.paralel_count for load command\"\n \n \n def do_load_collection(self, arg):\n self.stk_data_coll.load(conf_file=arg, paralel_count=self.paralel_count)\n print \"---------------------------------------\"\n print \"Data downloaded for \", arg \n \n def help_load_collection(self):\n print \"syntax: load [portfolio file]\",\n print \"-- load/updates the tickers from portfolio file\"\n\n def do_set_collection(self, arg):\n self.stk_data_coll.set_colection(arg)\n \n def help_set_collection(self):\n print \"syntax: set_collection [portfolio file]\",\n print \"-- set the tickers from portfolio file\"\n\n \n def do_get_collection(self, arg):\n print \"-----------------------------\"\n print \" Collection from \", self.stk_data_coll.conf_file\n print \"-----------------------------\"\n for c in self.stk_data_coll.stk_data_coll:\n print c\n \n \n def do_cleanup(self, arg):\n filelist = [ f for f in os.listdir(\"./data\") if f.endswith(\".dat\") ]\n for f in filelist:\n os.remove(\"./data/\" + f)\n \n def help_cleanup(self):\n print \"syntax: cleanup\",\n print \"-- removes all data files\"\n \n\n def do_plot_indexes(self, arg): \n indexes = arg.split(',',1)\n a_plot = plot.Plot(plot.PlotCellIndex(indexes[0]))\n try:\n for index in indexes[1:]:\n p = plot.PlotCellIndex(index)\n a_plot.addSimple(plot.PlotCell((p.data,p.dates)))\n finally: a_plot.plot()\n \n def help_plot_indexes(self):\n print \"syntax: plot_index [index_name1,index_name2,....]\",\n print \"-- plot slimple index from csv\"\n \n def do_plot_ticker_indexes(self,arg):\n calc = stk.StockCalcIndex(self.stk_data_coll)\n sd = stk.StockData()\n ticker, indexes, startdate = arg.split()\n indexes = indexes.split(',',1)\n \n sd.load(ticker, startdate)\n a_plot = plot.Plot(plot.PlotCell((sd.Cs,sd.dates)))\n \n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 200),overlay=True))\n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 50),overlay=True))\n \n for index in indexes:\n p = plot.PlotCellIndex(index)\n p.truncate(startdate)\n a_plot.addSimple(plot.PlotCell((p.data,p.dates))) \n a_plot.addSimple(plot.PlotCell(calc.sma((p.data,p.dates),20)))\n a_plot.addSimple(plot.PlotCell(calc.sma((p.data,p.dates),50),overlay=True))\n \n a_plot.plot()\n \n def do_plot_collection(self, arg):\n calc = stk.StockCalcIndex(self.stk_data_coll)\n sd = stk.StockData()\n ticker, startdate = arg.split()\n \n sd.load(ticker, startdate)\n a_plot = plot.Plot(plot.PlotCell((sd.Cs,sd.dates)))\n \n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 200),overlay=True))\n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 50),overlay=True))\n a_plot.addSimple(plot.PlotCell( calc.llv((sd.Cs, sd.dates), 100),overlay=True))\n\n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Vs,sd.dates),20 )))\n a_plot.addSimple(plot.PlotCell( calc.obv((sd.Cs,sd.Vs,sd.dates) )))\n \n a_plot.addSimple(plot.PlotCell( calc.correlation_adj((sd.Cs,sd.dates))))\n \n a_plot.plot()\n\n\n def do_plot(self, arg):\n calc = stk.StockCalcIndex(self.stk_data_coll)\n sd = stk.StockData()\n ticker, startdate = arg.split()\n \n sd.load(ticker, startdate)\n a_plot = plot.Plot(plot.PlotCell((sd.Cs,sd.dates)))\n \n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 200),overlay=True))\n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 50),overlay=True))\n a_plot.addSimple(plot.PlotCell( calc.llv((sd.Cs, sd.dates), 100),overlay=True))\n\n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Vs,sd.dates),20 )))\n \n arr_obv = calc.obv((sd.Cs,sd.Vs,sd.dates) )\n a_plot.addSimple(plot.PlotCell( arr_obv)) \n \n a_plot.addSimple(plot.PlotCell( calc.sma(arr_obv, 20),overlay=True))\n a_plot.addSimple(plot.PlotCell( calc.sma(arr_obv, 60),overlay=True))\n \n \n a_plot.plot()\n\n \n def help_plot(self):\n print \"syntax: plot [ticker] []|[start date YYYYMMDD]\",\n print \"-- plots the ticker\"\n \n \n def do_simulation(self, arg):\n ticker, startdate = arg.split()\n calc = stk.StockCalcIndex(self.stk_data_coll)\n sd = stk.StockData()\n sd.load(ticker, startdate)\n\n port = des.DecisionCollection(ticker, 50000)\n decision = des.DecisionSimpleSMA(ticker, (sd.Cs, sd.dates), port)\n decision.looper()\n print ticker, \":\", str(port)\n \n port2 = des.DecisionCollection(ticker, 50000)\n decision2 = des.DecisionSimpleStopSMA(ticker, (sd.Cs, sd.dates), port2, risk_factor=0.01, )\n decision2.looper()\n print ticker, \":\", str(port2)\n port2.print_all()\n \n a_plot = plot.Plot(plot.PlotCell((sd.Cs,sd.dates)))\n \n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 200),overlay=True))\n a_plot.addSimple(plot.PlotCell( calc.sma((sd.Cs, sd.dates), 50),overlay=True))\n a_plot.addSimple(plot.PlotCell( calc.llv((sd.Cs, sd.dates), 100),overlay=True))\n\n a_plot.addSimple(plot.PlotCell( port2.get_enter_plot_cell(), overlay=True, color='go' ))\n a_plot.addSimple(plot.PlotCell( port2.get_leave_plot_cell(), overlay=True, color='ro' ))\n \n a_plot.addSimple(plot.PlotCell( port2.get_value_plot_cell()))\n a_plot.plot()\n \n def help_simulation(self):\n print \"syntax: simulation [ticker] []|[start date YYYYMMDD]\",\n print \"-- runs a simulation on a single ticker\"\n \n \n def do_simulation_collection(self, arg ):\n for ticker in self.stk_data_coll.stk_data_coll:\n sd = stk.StockData()\n sd.load(ticker, arg)\n\n port = des.DecisionCollection(ticker, 50000)\n decision = des.DecisionSimpleStopSMA(ticker, (sd.Cs, sd.dates), port, risk_factor=0.02, sma_fast=10, sma_slow=50, stop_per=5)\n decision.looper()\n \n port4 = des.DecisionCollection(ticker, 50000)\n decision4 = des.DecisionSimpleSMA(ticker, (sd.Cs, sd.dates), port4, sma_fast=10, sma_slow=50, stop_per=5)\n decision4.looper() \n \n port2 = des.DecisionCollection(ticker, 50000)\n decision2 = des.DecisionSimpleSMA(ticker, (sd.Cs, sd.dates), port2)\n decision2.looper()\n \n port3 = des.DecisionCollection(ticker, 50000)\n decision3 = des.DecisionSimpleStopSMA(ticker, (sd.Cs, sd.dates), port3, risk_factor=0.02, sma_fast=50, sma_slow=200, stop_per=40)\n decision3.looper() \n \n print \"STOP_FAST - \", ticker, \" \", str(port)\n print \"SIMPLE_FAST - \", ticker, \" \", str(port4)\n print \"STOP_SLOW - \", ticker, \" \", str(port3)\n print \"SIMPLE_SLOW - \", ticker, \" \", str(port2)\n \n \n \n def emptyline(self):\n pass\n \n def do_quit(self, arg):\n sys.exit(1)\n \nif __name__ == \"__main__\": \n \n cli = CLI()\n cli.cmdloop()\n ",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
#!/usr/bin/env python3
import sys, os
import random
import numpy as np
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import shapely.geometry as geometry
from shapely.ops import cascaded_union, polygonize
import math
from matplotlib.pyplot import arrow
import dubins
this_script_path = os.path.dirname(__file__)
path_to_utils = os.path.join(this_script_path, "utils")
sys.path.append(path_to_utils)
import figure_utils
import orienteering_utils
from orienteering_utils import ProblemType
legend_font_size = 24
tick_font_size = 20
NUM_POINTS_TO_GEN = 16
SCATTER_SIZE = 80
FIG_HEIGHT = 7.5
SHOW_FIGURE = True
RESULT_FILE = "../sources/results/results.log"
RESULT_FILE = os.path.join(this_script_path, RESULT_FILE)
#use nice latex fonts if latex is installed
#figure_utils.configure_latex_fonts_latex()
data_vns_sop = orienteering_utils.parse_op_log(RESULT_FILE)
print("using the last results")
record = data_vns_sop[-1]
print("record", record)
problem_type = ProblemType.UNKNOWN
PROBLEM_FILE = record['PROBLEM_FILE']
PROBLEM_FILE = os.path.join(this_script_path, PROBLEM_FILE)
if "datasets/sop/" in PROBLEM_FILE:
print("showing SOP")
problem_type = ProblemType.SOP
SAVE_TO_FIGURE = "solution_sop.png"
elif "datasets/dop_sop_dataset/" in PROBLEM_FILE:
print("showing DOP")
problem_type = ProblemType.DOP
SAVE_TO_FIGURE = "solution_dop.png"
elif "datasets/opn_sop_dataset/" in PROBLEM_FILE:
print("showing OPN")
problem_type = ProblemType.OPN
SAVE_TO_FIGURE = "solution_opn.png"
else:
error("can not decide problem type based on problem file location")
problem_type = ProblemType.UNKNOWN
op = orienteering_utils.SetOrienteeringProblemDefinition()
op.load_problem_file(PROBLEM_FILE)
nodes = op.nodes
sets_prices = op.get_sets_prices()
sets = op.get_sets()
original_nodes = op.get_set_centers()
result_target_ids = record['RESULT_TARGET_IDS']
result_cluster_ids = record['RESULT_CLUSTER_IDS']
result_rewards = record['REWARDS']
print("problem loaded")
print("result_target_ids:", result_target_ids)
print("result_cluster_ids:", result_cluster_ids)
print("result_rewards", result_rewards)
print("sets_prices", sets_prices)
print("sets", sets)
print("nodes", nodes)
# for the DOP only
result_head_angs = []
sampling_heading = len(sets[0])
calc_reward = 0
for clust_idx in range(len(result_cluster_ids)):
clust = result_cluster_ids[clust_idx]
node = result_target_ids[clust_idx]
if problem_type == ProblemType.DOP:
node_inside_cluster = node - sets[clust][0]
# result_node_inside_cluster.append(node_inside_cluster)
head_ang = math.pi + (2 * math.pi * node_inside_cluster) / sampling_heading
result_head_angs.append(head_ang)
calc_reward += sets_prices[clust]
if node not in sets[clust]:
print("what the hell, it is not good")
print("calc_reward", calc_reward)
mycmap = plt.cm.get_cmap('RdYlBu_r')
maxx, maxy = -sys.float_info.max,-sys.float_info.max
minx, miny = sys.float_info.max,sys.float_info.max
circle_radiuses = np.ones([len(nodes), 1])
circle_radiuses1 = np.multiply(2.0, circle_radiuses)
nodes_w_rewards = np.zeros((len(nodes), 3))
if problem_type == ProblemType.DOP:
xses = [i[0] for i in original_nodes]
yses = [i[1] for i in original_nodes]
maxx = max(xses)
minx = min(xses)
maxy = max(yses)
miny = min(yses)
nodes_w_rewards = np.zeros((len(original_nodes), 3))
for nidx in range(len(original_nodes)):
nodes_w_rewards[nidx, 0] = original_nodes[nidx][0]
nodes_w_rewards[nidx, 1] = original_nodes[nidx][1]
nodes_w_rewards[nidx, 2] = sets_prices[nidx]
elif problem_type == ProblemType.OPN :
xses = [nodes[i][0] for i in nodes]
yses = [nodes[i][1] for i in nodes]
maxx = max(xses)
minx = min(xses)
maxy = max(yses)
miny = min(yses)
nodes_w_rewards = np.zeros((len(nodes), 3))
for nidx in nodes:
nodes_w_rewards[nidx, 0] = nodes[nidx][0]
nodes_w_rewards[nidx, 1] = nodes[nidx][1]
for set_idx in sets:
if nidx in sets[set_idx]:
nodes_w_rewards[nidx, 2] = sets_prices[set_idx]
break
else:
xses = [nodes[i][0] for i in nodes]
yses = [nodes[i][1] for i in nodes]
maxx = max(xses)
minx = min(xses)
maxy = max(yses)
miny = min(yses)
nodes_w_rewards = np.zeros((len(nodes), 3))
for nidx in nodes:
nodes_w_rewards[nidx, 0] = nodes[nidx][0]
nodes_w_rewards[nidx, 1] = nodes[nidx][1]
for set_idx in sets:
if nidx in sets[set_idx]:
nodes_w_rewards[nidx, 2] = sets_prices[set_idx]
break
minrew = min(nodes_w_rewards[:, 2])
maxrew = max(nodes_w_rewards[:, 2])
cNorm = mpl.colors.Normalize(vmin=minrew, vmax=maxrew + 0.1 * (maxrew - minrew))
mycmapScalarMap = mpl.cm.ScalarMappable(norm=cNorm, cmap=mycmap)
fig_width = FIG_HEIGHT*(maxx-minx)/(maxy-miny)
figsize = (fig_width*0.9,FIG_HEIGHT)
print(figsize)
fig = plt.figure(num=None, figsize=figsize, dpi=80, facecolor='w', edgecolor='k')
circles = figure_utils.circles(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], circle_radiuses1, c=nodes_w_rewards[:, 2] , alpha=0.05, edgecolor='black', linewidth=0.9, linestyle=':')
sc = plt.scatter(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], c=nodes_w_rewards[:, 2], cmap=mycmap , alpha=1.0, s=1, facecolor='black', lw=0.5)
plt.plot(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], 'ok', ms=4.0)
# print(nodes_w_rewards[:, 2])
if problem_type == ProblemType.DOP:
for nidx1 in range(len(nodes_w_rewards)):
points = []
node1 = nodes_w_rewards[nidx1, :]
points.append([node1[0], node1[1]])
for hind in range(sampling_heading):
head_ang = math.pi + (2 * math.pi * hind) / sampling_heading
arrow_len = 30
arrow(node1[0], node1[1], arrow_len * math.cos(head_ang), arrow_len * math.sin(head_ang))
set_rew = nodes_w_rewards[nidx1, 2]
alpha = 0.0
concave_hull = figure_utils.alpha_shape(points, alpha=alpha)
color = mycmapScalarMap.to_rgba(set_rew)
figure_utils.plot_polygon(concave_hull.buffer(40), fc=color)
elif problem_type == ProblemType.OPN:
for set_idx in reversed(sorted(sets.keys())):
points = []
set_rew = sets_prices[set_idx]
for nidx1 in sets[set_idx]:
node1 = nodes_w_rewards[nidx1, :]
points.append([node1[0], node1[1]])
for nidx2 in sets[set_idx]:
if(nidx1 != nidx2):
node2 = nodes_w_rewards[nidx2, :]
# plt.plot([node1[0], node2[0] ], [node1[1], node2[1] ], '-k', lw=0.2)
alpha = 0.0
concave_hull = figure_utils.alpha_shape(points, alpha=alpha)
color = mycmapScalarMap.to_rgba(set_rew)
figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)
else:
for set_idx in reversed(sorted(sets.keys())):
points = []
set_rew = sets_prices[set_idx]
for nidx1 in sets[set_idx]:
node1 = nodes_w_rewards[nidx1, :]
points.append([node1[0], node1[1]])
for nidx2 in sets[set_idx]:
if(nidx1 != nidx2):
node2 = nodes_w_rewards[nidx2, :]
# plt.plot([node1[0], node2[0] ], [node1[1], node2[1] ], '-k', lw=0.2)
alpha = 0.0
concave_hull = figure_utils.alpha_shape(points, alpha=alpha)
color = mycmapScalarMap.to_rgba(set_rew)
figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)
for node_idx in range(1, len(result_target_ids)):
if problem_type == ProblemType.DOP:
step_size = 20
turning_radius = op.dubins_radius
node = result_cluster_ids[node_idx]
node_prew = result_cluster_ids[node_idx - 1]
q_start = [nodes_w_rewards[node, 0], nodes_w_rewards[node, 1], result_head_angs[node_idx]]
q_end = [nodes_w_rewards[node_prew][0], nodes_w_rewards[node_prew][1], result_head_angs[node_idx - 1]]
path = dubins.shortest_path(q_start, q_end, turning_radius)
qs, _ = path.sample_many(step_size)
# length_dub += math.ceil(path.path_length())
xses = [item[0] for item in qs]
yses = [item[1] for item in qs]
print(node_prew, '->', node, ",", q_start, '->', q_end)
plt.plot(xses, yses, '-g', lw=1.6)
elif problem_type == ProblemType.OPN:
node = result_target_ids[node_idx]
node_prew = result_target_ids[node_idx - 1]
node_pos = [nodes[node][0], nodes[node][1]]
node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]
print(node_prew, '->', node, ",", node_pos_prew, '->', node_pos)
plt.plot([node_pos_prew[0], node_pos[0] ], [node_pos_prew[1], node_pos[1] ], '-g', lw=1.6)
else:
node = result_target_ids[node_idx]
node_prew = result_target_ids[node_idx - 1]
node_pos = [nodes[node][0], nodes[node][1]]
node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]
print(node_prew, '->', node, ",", node_pos_prew, '->', node_pos)
plt.plot([node_pos_prew[0], node_pos[0] ], [node_pos_prew[1], node_pos[1] ], '-g', lw=1.6)
ax = plt.gca()
ax.axis('equal')
figure_utils.no_axis(ax)
cbar_position = [0.20, 0.05, 0.6, 0.03]
cbar_ax = fig.add_axes(cbar_position)
cb = plt.colorbar(sc, cax=cbar_ax, orientation='horizontal')
cb.ax.tick_params(labelsize=tick_font_size)
cb.set_label('profit', labelpad=-65.0, y=0.8, fontsize=legend_font_size)
# offset = 0.08
fig.subplots_adjust(left=-0.035, right=1.035 , top=1.07 , bottom=0.0)
plt.savefig(SAVE_TO_FIGURE, dpi=300)
if SHOW_FIGURE:
plt.show()
|
normal
|
{
"blob_id": "b4454d92ab8380e0eded2f7aed737378e1710c72",
"index": 9413,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif os.environ.get('DISPLAY', '') == '':\n print('no display found. Using non-interactive Agg backend')\n mpl.use('Agg')\n<mask token>\nsys.path.append(path_to_utils)\n<mask token>\nprint('using the last results')\n<mask token>\nprint('record', record)\n<mask token>\nif 'datasets/sop/' in PROBLEM_FILE:\n print('showing SOP')\n problem_type = ProblemType.SOP\n SAVE_TO_FIGURE = 'solution_sop.png'\nelif 'datasets/dop_sop_dataset/' in PROBLEM_FILE:\n print('showing DOP')\n problem_type = ProblemType.DOP\n SAVE_TO_FIGURE = 'solution_dop.png'\nelif 'datasets/opn_sop_dataset/' in PROBLEM_FILE:\n print('showing OPN')\n problem_type = ProblemType.OPN\n SAVE_TO_FIGURE = 'solution_opn.png'\nelse:\n error('can not decide problem type based on problem file location')\n problem_type = ProblemType.UNKNOWN\n<mask token>\nop.load_problem_file(PROBLEM_FILE)\n<mask token>\nprint('problem loaded')\nprint('result_target_ids:', result_target_ids)\nprint('result_cluster_ids:', result_cluster_ids)\nprint('result_rewards', result_rewards)\nprint('sets_prices', sets_prices)\nprint('sets', sets)\nprint('nodes', nodes)\n<mask token>\nfor clust_idx in range(len(result_cluster_ids)):\n clust = result_cluster_ids[clust_idx]\n node = result_target_ids[clust_idx]\n if problem_type == ProblemType.DOP:\n node_inside_cluster = node - sets[clust][0]\n head_ang = (math.pi + 2 * math.pi * node_inside_cluster /\n sampling_heading)\n result_head_angs.append(head_ang)\n calc_reward += sets_prices[clust]\n if node not in sets[clust]:\n print('what the hell, it is not good')\nprint('calc_reward', calc_reward)\n<mask token>\nif problem_type == ProblemType.DOP:\n xses = [i[0] for i in original_nodes]\n yses = [i[1] for i in original_nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(original_nodes), 3))\n for nidx in range(len(original_nodes)):\n nodes_w_rewards[nidx, 0] = original_nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = original_nodes[nidx][1]\n nodes_w_rewards[nidx, 2] = sets_prices[nidx]\nelif problem_type == ProblemType.OPN:\n xses = [nodes[i][0] for i in nodes]\n yses = [nodes[i][1] for i in nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(nodes), 3))\n for nidx in nodes:\n nodes_w_rewards[nidx, 0] = nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = nodes[nidx][1]\n for set_idx in sets:\n if nidx in sets[set_idx]:\n nodes_w_rewards[nidx, 2] = sets_prices[set_idx]\n break\nelse:\n xses = [nodes[i][0] for i in nodes]\n yses = [nodes[i][1] for i in nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(nodes), 3))\n for nidx in nodes:\n nodes_w_rewards[nidx, 0] = nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = nodes[nidx][1]\n for set_idx in sets:\n if nidx in sets[set_idx]:\n nodes_w_rewards[nidx, 2] = sets_prices[set_idx]\n break\n<mask token>\nprint(figsize)\n<mask token>\nplt.plot(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], 'ok', ms=4.0)\nif problem_type == ProblemType.DOP:\n for nidx1 in range(len(nodes_w_rewards)):\n points = []\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for hind in range(sampling_heading):\n head_ang = math.pi + 2 * math.pi * hind / sampling_heading\n arrow_len = 30\n arrow(node1[0], node1[1], arrow_len * math.cos(head_ang), \n arrow_len * math.sin(head_ang))\n set_rew = nodes_w_rewards[nidx1, 2]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(40), fc=color)\nelif problem_type == ProblemType.OPN:\n for set_idx in reversed(sorted(sets.keys())):\n points = []\n set_rew = sets_prices[set_idx]\n for nidx1 in sets[set_idx]:\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for nidx2 in sets[set_idx]:\n if nidx1 != nidx2:\n node2 = nodes_w_rewards[nidx2, :]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)\nelse:\n for set_idx in reversed(sorted(sets.keys())):\n points = []\n set_rew = sets_prices[set_idx]\n for nidx1 in sets[set_idx]:\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for nidx2 in sets[set_idx]:\n if nidx1 != nidx2:\n node2 = nodes_w_rewards[nidx2, :]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)\nfor node_idx in range(1, len(result_target_ids)):\n if problem_type == ProblemType.DOP:\n step_size = 20\n turning_radius = op.dubins_radius\n node = result_cluster_ids[node_idx]\n node_prew = result_cluster_ids[node_idx - 1]\n q_start = [nodes_w_rewards[node, 0], nodes_w_rewards[node, 1],\n result_head_angs[node_idx]]\n q_end = [nodes_w_rewards[node_prew][0], nodes_w_rewards[node_prew][\n 1], result_head_angs[node_idx - 1]]\n path = dubins.shortest_path(q_start, q_end, turning_radius)\n qs, _ = path.sample_many(step_size)\n xses = [item[0] for item in qs]\n yses = [item[1] for item in qs]\n print(node_prew, '->', node, ',', q_start, '->', q_end)\n plt.plot(xses, yses, '-g', lw=1.6)\n elif problem_type == ProblemType.OPN:\n node = result_target_ids[node_idx]\n node_prew = result_target_ids[node_idx - 1]\n node_pos = [nodes[node][0], nodes[node][1]]\n node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]\n print(node_prew, '->', node, ',', node_pos_prew, '->', node_pos)\n plt.plot([node_pos_prew[0], node_pos[0]], [node_pos_prew[1],\n node_pos[1]], '-g', lw=1.6)\n else:\n node = result_target_ids[node_idx]\n node_prew = result_target_ids[node_idx - 1]\n node_pos = [nodes[node][0], nodes[node][1]]\n node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]\n print(node_prew, '->', node, ',', node_pos_prew, '->', node_pos)\n plt.plot([node_pos_prew[0], node_pos[0]], [node_pos_prew[1],\n node_pos[1]], '-g', lw=1.6)\n<mask token>\nax.axis('equal')\nfigure_utils.no_axis(ax)\n<mask token>\ncb.ax.tick_params(labelsize=tick_font_size)\ncb.set_label('profit', labelpad=-65.0, y=0.8, fontsize=legend_font_size)\nfig.subplots_adjust(left=-0.035, right=1.035, top=1.07, bottom=0.0)\nplt.savefig(SAVE_TO_FIGURE, dpi=300)\nif SHOW_FIGURE:\n plt.show()\n",
"step-3": "<mask token>\nif os.environ.get('DISPLAY', '') == '':\n print('no display found. Using non-interactive Agg backend')\n mpl.use('Agg')\n<mask token>\nthis_script_path = os.path.dirname(__file__)\npath_to_utils = os.path.join(this_script_path, 'utils')\nsys.path.append(path_to_utils)\n<mask token>\nlegend_font_size = 24\ntick_font_size = 20\nNUM_POINTS_TO_GEN = 16\nSCATTER_SIZE = 80\nFIG_HEIGHT = 7.5\nSHOW_FIGURE = True\nRESULT_FILE = '../sources/results/results.log'\nRESULT_FILE = os.path.join(this_script_path, RESULT_FILE)\ndata_vns_sop = orienteering_utils.parse_op_log(RESULT_FILE)\nprint('using the last results')\nrecord = data_vns_sop[-1]\nprint('record', record)\nproblem_type = ProblemType.UNKNOWN\nPROBLEM_FILE = record['PROBLEM_FILE']\nPROBLEM_FILE = os.path.join(this_script_path, PROBLEM_FILE)\nif 'datasets/sop/' in PROBLEM_FILE:\n print('showing SOP')\n problem_type = ProblemType.SOP\n SAVE_TO_FIGURE = 'solution_sop.png'\nelif 'datasets/dop_sop_dataset/' in PROBLEM_FILE:\n print('showing DOP')\n problem_type = ProblemType.DOP\n SAVE_TO_FIGURE = 'solution_dop.png'\nelif 'datasets/opn_sop_dataset/' in PROBLEM_FILE:\n print('showing OPN')\n problem_type = ProblemType.OPN\n SAVE_TO_FIGURE = 'solution_opn.png'\nelse:\n error('can not decide problem type based on problem file location')\n problem_type = ProblemType.UNKNOWN\nop = orienteering_utils.SetOrienteeringProblemDefinition()\nop.load_problem_file(PROBLEM_FILE)\nnodes = op.nodes\nsets_prices = op.get_sets_prices()\nsets = op.get_sets()\noriginal_nodes = op.get_set_centers()\nresult_target_ids = record['RESULT_TARGET_IDS']\nresult_cluster_ids = record['RESULT_CLUSTER_IDS']\nresult_rewards = record['REWARDS']\nprint('problem loaded')\nprint('result_target_ids:', result_target_ids)\nprint('result_cluster_ids:', result_cluster_ids)\nprint('result_rewards', result_rewards)\nprint('sets_prices', sets_prices)\nprint('sets', sets)\nprint('nodes', nodes)\nresult_head_angs = []\nsampling_heading = len(sets[0])\ncalc_reward = 0\nfor clust_idx in range(len(result_cluster_ids)):\n clust = result_cluster_ids[clust_idx]\n node = result_target_ids[clust_idx]\n if problem_type == ProblemType.DOP:\n node_inside_cluster = node - sets[clust][0]\n head_ang = (math.pi + 2 * math.pi * node_inside_cluster /\n sampling_heading)\n result_head_angs.append(head_ang)\n calc_reward += sets_prices[clust]\n if node not in sets[clust]:\n print('what the hell, it is not good')\nprint('calc_reward', calc_reward)\nmycmap = plt.cm.get_cmap('RdYlBu_r')\nmaxx, maxy = -sys.float_info.max, -sys.float_info.max\nminx, miny = sys.float_info.max, sys.float_info.max\ncircle_radiuses = np.ones([len(nodes), 1])\ncircle_radiuses1 = np.multiply(2.0, circle_radiuses)\nnodes_w_rewards = np.zeros((len(nodes), 3))\nif problem_type == ProblemType.DOP:\n xses = [i[0] for i in original_nodes]\n yses = [i[1] for i in original_nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(original_nodes), 3))\n for nidx in range(len(original_nodes)):\n nodes_w_rewards[nidx, 0] = original_nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = original_nodes[nidx][1]\n nodes_w_rewards[nidx, 2] = sets_prices[nidx]\nelif problem_type == ProblemType.OPN:\n xses = [nodes[i][0] for i in nodes]\n yses = [nodes[i][1] for i in nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(nodes), 3))\n for nidx in nodes:\n nodes_w_rewards[nidx, 0] = nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = nodes[nidx][1]\n for set_idx in sets:\n if nidx in sets[set_idx]:\n nodes_w_rewards[nidx, 2] = sets_prices[set_idx]\n break\nelse:\n xses = [nodes[i][0] for i in nodes]\n yses = [nodes[i][1] for i in nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(nodes), 3))\n for nidx in nodes:\n nodes_w_rewards[nidx, 0] = nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = nodes[nidx][1]\n for set_idx in sets:\n if nidx in sets[set_idx]:\n nodes_w_rewards[nidx, 2] = sets_prices[set_idx]\n break\nminrew = min(nodes_w_rewards[:, 2])\nmaxrew = max(nodes_w_rewards[:, 2])\ncNorm = mpl.colors.Normalize(vmin=minrew, vmax=maxrew + 0.1 * (maxrew - minrew)\n )\nmycmapScalarMap = mpl.cm.ScalarMappable(norm=cNorm, cmap=mycmap)\nfig_width = FIG_HEIGHT * (maxx - minx) / (maxy - miny)\nfigsize = fig_width * 0.9, FIG_HEIGHT\nprint(figsize)\nfig = plt.figure(num=None, figsize=figsize, dpi=80, facecolor='w',\n edgecolor='k')\ncircles = figure_utils.circles(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1],\n circle_radiuses1, c=nodes_w_rewards[:, 2], alpha=0.05, edgecolor=\n 'black', linewidth=0.9, linestyle=':')\nsc = plt.scatter(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], c=\n nodes_w_rewards[:, 2], cmap=mycmap, alpha=1.0, s=1, facecolor='black',\n lw=0.5)\nplt.plot(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], 'ok', ms=4.0)\nif problem_type == ProblemType.DOP:\n for nidx1 in range(len(nodes_w_rewards)):\n points = []\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for hind in range(sampling_heading):\n head_ang = math.pi + 2 * math.pi * hind / sampling_heading\n arrow_len = 30\n arrow(node1[0], node1[1], arrow_len * math.cos(head_ang), \n arrow_len * math.sin(head_ang))\n set_rew = nodes_w_rewards[nidx1, 2]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(40), fc=color)\nelif problem_type == ProblemType.OPN:\n for set_idx in reversed(sorted(sets.keys())):\n points = []\n set_rew = sets_prices[set_idx]\n for nidx1 in sets[set_idx]:\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for nidx2 in sets[set_idx]:\n if nidx1 != nidx2:\n node2 = nodes_w_rewards[nidx2, :]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)\nelse:\n for set_idx in reversed(sorted(sets.keys())):\n points = []\n set_rew = sets_prices[set_idx]\n for nidx1 in sets[set_idx]:\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for nidx2 in sets[set_idx]:\n if nidx1 != nidx2:\n node2 = nodes_w_rewards[nidx2, :]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)\nfor node_idx in range(1, len(result_target_ids)):\n if problem_type == ProblemType.DOP:\n step_size = 20\n turning_radius = op.dubins_radius\n node = result_cluster_ids[node_idx]\n node_prew = result_cluster_ids[node_idx - 1]\n q_start = [nodes_w_rewards[node, 0], nodes_w_rewards[node, 1],\n result_head_angs[node_idx]]\n q_end = [nodes_w_rewards[node_prew][0], nodes_w_rewards[node_prew][\n 1], result_head_angs[node_idx - 1]]\n path = dubins.shortest_path(q_start, q_end, turning_radius)\n qs, _ = path.sample_many(step_size)\n xses = [item[0] for item in qs]\n yses = [item[1] for item in qs]\n print(node_prew, '->', node, ',', q_start, '->', q_end)\n plt.plot(xses, yses, '-g', lw=1.6)\n elif problem_type == ProblemType.OPN:\n node = result_target_ids[node_idx]\n node_prew = result_target_ids[node_idx - 1]\n node_pos = [nodes[node][0], nodes[node][1]]\n node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]\n print(node_prew, '->', node, ',', node_pos_prew, '->', node_pos)\n plt.plot([node_pos_prew[0], node_pos[0]], [node_pos_prew[1],\n node_pos[1]], '-g', lw=1.6)\n else:\n node = result_target_ids[node_idx]\n node_prew = result_target_ids[node_idx - 1]\n node_pos = [nodes[node][0], nodes[node][1]]\n node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]\n print(node_prew, '->', node, ',', node_pos_prew, '->', node_pos)\n plt.plot([node_pos_prew[0], node_pos[0]], [node_pos_prew[1],\n node_pos[1]], '-g', lw=1.6)\nax = plt.gca()\nax.axis('equal')\nfigure_utils.no_axis(ax)\ncbar_position = [0.2, 0.05, 0.6, 0.03]\ncbar_ax = fig.add_axes(cbar_position)\ncb = plt.colorbar(sc, cax=cbar_ax, orientation='horizontal')\ncb.ax.tick_params(labelsize=tick_font_size)\ncb.set_label('profit', labelpad=-65.0, y=0.8, fontsize=legend_font_size)\nfig.subplots_adjust(left=-0.035, right=1.035, top=1.07, bottom=0.0)\nplt.savefig(SAVE_TO_FIGURE, dpi=300)\nif SHOW_FIGURE:\n plt.show()\n",
"step-4": "import sys, os\nimport random\nimport numpy as np\nimport matplotlib as mpl\nif os.environ.get('DISPLAY', '') == '':\n print('no display found. Using non-interactive Agg backend')\n mpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport shapely.geometry as geometry\nfrom shapely.ops import cascaded_union, polygonize\nimport math\nfrom matplotlib.pyplot import arrow\nimport dubins\nthis_script_path = os.path.dirname(__file__)\npath_to_utils = os.path.join(this_script_path, 'utils')\nsys.path.append(path_to_utils)\nimport figure_utils\nimport orienteering_utils\nfrom orienteering_utils import ProblemType\nlegend_font_size = 24\ntick_font_size = 20\nNUM_POINTS_TO_GEN = 16\nSCATTER_SIZE = 80\nFIG_HEIGHT = 7.5\nSHOW_FIGURE = True\nRESULT_FILE = '../sources/results/results.log'\nRESULT_FILE = os.path.join(this_script_path, RESULT_FILE)\ndata_vns_sop = orienteering_utils.parse_op_log(RESULT_FILE)\nprint('using the last results')\nrecord = data_vns_sop[-1]\nprint('record', record)\nproblem_type = ProblemType.UNKNOWN\nPROBLEM_FILE = record['PROBLEM_FILE']\nPROBLEM_FILE = os.path.join(this_script_path, PROBLEM_FILE)\nif 'datasets/sop/' in PROBLEM_FILE:\n print('showing SOP')\n problem_type = ProblemType.SOP\n SAVE_TO_FIGURE = 'solution_sop.png'\nelif 'datasets/dop_sop_dataset/' in PROBLEM_FILE:\n print('showing DOP')\n problem_type = ProblemType.DOP\n SAVE_TO_FIGURE = 'solution_dop.png'\nelif 'datasets/opn_sop_dataset/' in PROBLEM_FILE:\n print('showing OPN')\n problem_type = ProblemType.OPN\n SAVE_TO_FIGURE = 'solution_opn.png'\nelse:\n error('can not decide problem type based on problem file location')\n problem_type = ProblemType.UNKNOWN\nop = orienteering_utils.SetOrienteeringProblemDefinition()\nop.load_problem_file(PROBLEM_FILE)\nnodes = op.nodes\nsets_prices = op.get_sets_prices()\nsets = op.get_sets()\noriginal_nodes = op.get_set_centers()\nresult_target_ids = record['RESULT_TARGET_IDS']\nresult_cluster_ids = record['RESULT_CLUSTER_IDS']\nresult_rewards = record['REWARDS']\nprint('problem loaded')\nprint('result_target_ids:', result_target_ids)\nprint('result_cluster_ids:', result_cluster_ids)\nprint('result_rewards', result_rewards)\nprint('sets_prices', sets_prices)\nprint('sets', sets)\nprint('nodes', nodes)\nresult_head_angs = []\nsampling_heading = len(sets[0])\ncalc_reward = 0\nfor clust_idx in range(len(result_cluster_ids)):\n clust = result_cluster_ids[clust_idx]\n node = result_target_ids[clust_idx]\n if problem_type == ProblemType.DOP:\n node_inside_cluster = node - sets[clust][0]\n head_ang = (math.pi + 2 * math.pi * node_inside_cluster /\n sampling_heading)\n result_head_angs.append(head_ang)\n calc_reward += sets_prices[clust]\n if node not in sets[clust]:\n print('what the hell, it is not good')\nprint('calc_reward', calc_reward)\nmycmap = plt.cm.get_cmap('RdYlBu_r')\nmaxx, maxy = -sys.float_info.max, -sys.float_info.max\nminx, miny = sys.float_info.max, sys.float_info.max\ncircle_radiuses = np.ones([len(nodes), 1])\ncircle_radiuses1 = np.multiply(2.0, circle_radiuses)\nnodes_w_rewards = np.zeros((len(nodes), 3))\nif problem_type == ProblemType.DOP:\n xses = [i[0] for i in original_nodes]\n yses = [i[1] for i in original_nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(original_nodes), 3))\n for nidx in range(len(original_nodes)):\n nodes_w_rewards[nidx, 0] = original_nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = original_nodes[nidx][1]\n nodes_w_rewards[nidx, 2] = sets_prices[nidx]\nelif problem_type == ProblemType.OPN:\n xses = [nodes[i][0] for i in nodes]\n yses = [nodes[i][1] for i in nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(nodes), 3))\n for nidx in nodes:\n nodes_w_rewards[nidx, 0] = nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = nodes[nidx][1]\n for set_idx in sets:\n if nidx in sets[set_idx]:\n nodes_w_rewards[nidx, 2] = sets_prices[set_idx]\n break\nelse:\n xses = [nodes[i][0] for i in nodes]\n yses = [nodes[i][1] for i in nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n nodes_w_rewards = np.zeros((len(nodes), 3))\n for nidx in nodes:\n nodes_w_rewards[nidx, 0] = nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = nodes[nidx][1]\n for set_idx in sets:\n if nidx in sets[set_idx]:\n nodes_w_rewards[nidx, 2] = sets_prices[set_idx]\n break\nminrew = min(nodes_w_rewards[:, 2])\nmaxrew = max(nodes_w_rewards[:, 2])\ncNorm = mpl.colors.Normalize(vmin=minrew, vmax=maxrew + 0.1 * (maxrew - minrew)\n )\nmycmapScalarMap = mpl.cm.ScalarMappable(norm=cNorm, cmap=mycmap)\nfig_width = FIG_HEIGHT * (maxx - minx) / (maxy - miny)\nfigsize = fig_width * 0.9, FIG_HEIGHT\nprint(figsize)\nfig = plt.figure(num=None, figsize=figsize, dpi=80, facecolor='w',\n edgecolor='k')\ncircles = figure_utils.circles(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1],\n circle_radiuses1, c=nodes_w_rewards[:, 2], alpha=0.05, edgecolor=\n 'black', linewidth=0.9, linestyle=':')\nsc = plt.scatter(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], c=\n nodes_w_rewards[:, 2], cmap=mycmap, alpha=1.0, s=1, facecolor='black',\n lw=0.5)\nplt.plot(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], 'ok', ms=4.0)\nif problem_type == ProblemType.DOP:\n for nidx1 in range(len(nodes_w_rewards)):\n points = []\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for hind in range(sampling_heading):\n head_ang = math.pi + 2 * math.pi * hind / sampling_heading\n arrow_len = 30\n arrow(node1[0], node1[1], arrow_len * math.cos(head_ang), \n arrow_len * math.sin(head_ang))\n set_rew = nodes_w_rewards[nidx1, 2]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(40), fc=color)\nelif problem_type == ProblemType.OPN:\n for set_idx in reversed(sorted(sets.keys())):\n points = []\n set_rew = sets_prices[set_idx]\n for nidx1 in sets[set_idx]:\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for nidx2 in sets[set_idx]:\n if nidx1 != nidx2:\n node2 = nodes_w_rewards[nidx2, :]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)\nelse:\n for set_idx in reversed(sorted(sets.keys())):\n points = []\n set_rew = sets_prices[set_idx]\n for nidx1 in sets[set_idx]:\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for nidx2 in sets[set_idx]:\n if nidx1 != nidx2:\n node2 = nodes_w_rewards[nidx2, :]\n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)\nfor node_idx in range(1, len(result_target_ids)):\n if problem_type == ProblemType.DOP:\n step_size = 20\n turning_radius = op.dubins_radius\n node = result_cluster_ids[node_idx]\n node_prew = result_cluster_ids[node_idx - 1]\n q_start = [nodes_w_rewards[node, 0], nodes_w_rewards[node, 1],\n result_head_angs[node_idx]]\n q_end = [nodes_w_rewards[node_prew][0], nodes_w_rewards[node_prew][\n 1], result_head_angs[node_idx - 1]]\n path = dubins.shortest_path(q_start, q_end, turning_radius)\n qs, _ = path.sample_many(step_size)\n xses = [item[0] for item in qs]\n yses = [item[1] for item in qs]\n print(node_prew, '->', node, ',', q_start, '->', q_end)\n plt.plot(xses, yses, '-g', lw=1.6)\n elif problem_type == ProblemType.OPN:\n node = result_target_ids[node_idx]\n node_prew = result_target_ids[node_idx - 1]\n node_pos = [nodes[node][0], nodes[node][1]]\n node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]\n print(node_prew, '->', node, ',', node_pos_prew, '->', node_pos)\n plt.plot([node_pos_prew[0], node_pos[0]], [node_pos_prew[1],\n node_pos[1]], '-g', lw=1.6)\n else:\n node = result_target_ids[node_idx]\n node_prew = result_target_ids[node_idx - 1]\n node_pos = [nodes[node][0], nodes[node][1]]\n node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]\n print(node_prew, '->', node, ',', node_pos_prew, '->', node_pos)\n plt.plot([node_pos_prew[0], node_pos[0]], [node_pos_prew[1],\n node_pos[1]], '-g', lw=1.6)\nax = plt.gca()\nax.axis('equal')\nfigure_utils.no_axis(ax)\ncbar_position = [0.2, 0.05, 0.6, 0.03]\ncbar_ax = fig.add_axes(cbar_position)\ncb = plt.colorbar(sc, cax=cbar_ax, orientation='horizontal')\ncb.ax.tick_params(labelsize=tick_font_size)\ncb.set_label('profit', labelpad=-65.0, y=0.8, fontsize=legend_font_size)\nfig.subplots_adjust(left=-0.035, right=1.035, top=1.07, bottom=0.0)\nplt.savefig(SAVE_TO_FIGURE, dpi=300)\nif SHOW_FIGURE:\n plt.show()\n",
"step-5": "#!/usr/bin/env python3\n\nimport sys, os\nimport random\nimport numpy as np\n\nimport matplotlib as mpl\nif os.environ.get('DISPLAY','') == '':\n print('no display found. Using non-interactive Agg backend')\n mpl.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport shapely.geometry as geometry\nfrom shapely.ops import cascaded_union, polygonize\nimport math\nfrom matplotlib.pyplot import arrow\nimport dubins\nthis_script_path = os.path.dirname(__file__) \npath_to_utils = os.path.join(this_script_path, \"utils\") \nsys.path.append(path_to_utils)\nimport figure_utils\nimport orienteering_utils\nfrom orienteering_utils import ProblemType\n\n\nlegend_font_size = 24\ntick_font_size = 20\nNUM_POINTS_TO_GEN = 16\nSCATTER_SIZE = 80\nFIG_HEIGHT = 7.5\nSHOW_FIGURE = True\n\nRESULT_FILE = \"../sources/results/results.log\"\nRESULT_FILE = os.path.join(this_script_path, RESULT_FILE)\n \n#use nice latex fonts if latex is installed\n#figure_utils.configure_latex_fonts_latex()\n\ndata_vns_sop = orienteering_utils.parse_op_log(RESULT_FILE)\n\nprint(\"using the last results\")\nrecord = data_vns_sop[-1]\nprint(\"record\", record)\n\nproblem_type = ProblemType.UNKNOWN\n\nPROBLEM_FILE = record['PROBLEM_FILE']\nPROBLEM_FILE = os.path.join(this_script_path, PROBLEM_FILE)\n\nif \"datasets/sop/\" in PROBLEM_FILE:\n print(\"showing SOP\")\n problem_type = ProblemType.SOP\n SAVE_TO_FIGURE = \"solution_sop.png\"\n\nelif \"datasets/dop_sop_dataset/\" in PROBLEM_FILE:\n print(\"showing DOP\")\n problem_type = ProblemType.DOP\n SAVE_TO_FIGURE = \"solution_dop.png\"\n\nelif \"datasets/opn_sop_dataset/\" in PROBLEM_FILE:\n print(\"showing OPN\")\n problem_type = ProblemType.OPN\n SAVE_TO_FIGURE = \"solution_opn.png\"\n \nelse:\n error(\"can not decide problem type based on problem file location\")\n problem_type = ProblemType.UNKNOWN\n\nop = orienteering_utils.SetOrienteeringProblemDefinition()\nop.load_problem_file(PROBLEM_FILE)\nnodes = op.nodes\nsets_prices = op.get_sets_prices()\nsets = op.get_sets()\noriginal_nodes = op.get_set_centers()\n\nresult_target_ids = record['RESULT_TARGET_IDS']\nresult_cluster_ids = record['RESULT_CLUSTER_IDS']\nresult_rewards = record['REWARDS']\nprint(\"problem loaded\")\nprint(\"result_target_ids:\", result_target_ids)\nprint(\"result_cluster_ids:\", result_cluster_ids)\nprint(\"result_rewards\", result_rewards)\nprint(\"sets_prices\", sets_prices)\nprint(\"sets\", sets)\nprint(\"nodes\", nodes)\n\n# for the DOP only\nresult_head_angs = []\nsampling_heading = len(sets[0])\n\ncalc_reward = 0\nfor clust_idx in range(len(result_cluster_ids)):\n clust = result_cluster_ids[clust_idx]\n node = result_target_ids[clust_idx]\n\n if problem_type == ProblemType.DOP:\n node_inside_cluster = node - sets[clust][0]\n # result_node_inside_cluster.append(node_inside_cluster)\n head_ang = math.pi + (2 * math.pi * node_inside_cluster) / sampling_heading\n result_head_angs.append(head_ang)\n\n calc_reward += sets_prices[clust]\n if node not in sets[clust]:\n print(\"what the hell, it is not good\")\n\nprint(\"calc_reward\", calc_reward)\n\nmycmap = plt.cm.get_cmap('RdYlBu_r')\n\nmaxx, maxy = -sys.float_info.max,-sys.float_info.max\nminx, miny = sys.float_info.max,sys.float_info.max\n\ncircle_radiuses = np.ones([len(nodes), 1])\ncircle_radiuses1 = np.multiply(2.0, circle_radiuses)\n\nnodes_w_rewards = np.zeros((len(nodes), 3))\nif problem_type == ProblemType.DOP:\n xses = [i[0] for i in original_nodes]\n yses = [i[1] for i in original_nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n \n nodes_w_rewards = np.zeros((len(original_nodes), 3))\n for nidx in range(len(original_nodes)):\n nodes_w_rewards[nidx, 0] = original_nodes[nidx][0] \n nodes_w_rewards[nidx, 1] = original_nodes[nidx][1] \n nodes_w_rewards[nidx, 2] = sets_prices[nidx]\nelif problem_type == ProblemType.OPN :\n xses = [nodes[i][0] for i in nodes]\n yses = [nodes[i][1] for i in nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n \n nodes_w_rewards = np.zeros((len(nodes), 3))\n for nidx in nodes:\n nodes_w_rewards[nidx, 0] = nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = nodes[nidx][1]\n \n for set_idx in sets:\n if nidx in sets[set_idx]:\n nodes_w_rewards[nidx, 2] = sets_prices[set_idx]\n break\nelse:\n xses = [nodes[i][0] for i in nodes]\n yses = [nodes[i][1] for i in nodes]\n maxx = max(xses)\n minx = min(xses)\n maxy = max(yses)\n miny = min(yses)\n \n nodes_w_rewards = np.zeros((len(nodes), 3))\n for nidx in nodes:\n nodes_w_rewards[nidx, 0] = nodes[nidx][0]\n nodes_w_rewards[nidx, 1] = nodes[nidx][1]\n\n for set_idx in sets:\n if nidx in sets[set_idx]:\n nodes_w_rewards[nidx, 2] = sets_prices[set_idx]\n break\n\nminrew = min(nodes_w_rewards[:, 2])\nmaxrew = max(nodes_w_rewards[:, 2])\n\n\ncNorm = mpl.colors.Normalize(vmin=minrew, vmax=maxrew + 0.1 * (maxrew - minrew)) \nmycmapScalarMap = mpl.cm.ScalarMappable(norm=cNorm, cmap=mycmap)\n\nfig_width = FIG_HEIGHT*(maxx-minx)/(maxy-miny)\nfigsize = (fig_width*0.9,FIG_HEIGHT)\nprint(figsize)\n\nfig = plt.figure(num=None, figsize=figsize, dpi=80, facecolor='w', edgecolor='k')\ncircles = figure_utils.circles(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], circle_radiuses1, c=nodes_w_rewards[:, 2] , alpha=0.05, edgecolor='black', linewidth=0.9, linestyle=':')\nsc = plt.scatter(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], c=nodes_w_rewards[:, 2], cmap=mycmap , alpha=1.0, s=1, facecolor='black', lw=0.5)\nplt.plot(nodes_w_rewards[:, 0], nodes_w_rewards[:, 1], 'ok', ms=4.0)\n\n# print(nodes_w_rewards[:, 2])\n\nif problem_type == ProblemType.DOP:\n for nidx1 in range(len(nodes_w_rewards)): \n points = []\n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n \n for hind in range(sampling_heading):\n head_ang = math.pi + (2 * math.pi * hind) / sampling_heading\n arrow_len = 30\n arrow(node1[0], node1[1], arrow_len * math.cos(head_ang), arrow_len * math.sin(head_ang))\n \n set_rew = nodes_w_rewards[nidx1, 2] \n \n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha) \n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(40), fc=color)\nelif problem_type == ProblemType.OPN:\n for set_idx in reversed(sorted(sets.keys())):\n points = []\n set_rew = sets_prices[set_idx]\n for nidx1 in sets[set_idx]: \n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for nidx2 in sets[set_idx]: \n if(nidx1 != nidx2):\n node2 = nodes_w_rewards[nidx2, :]\n # plt.plot([node1[0], node2[0] ], [node1[1], node2[1] ], '-k', lw=0.2)\n \n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n \n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)\n\nelse: \n for set_idx in reversed(sorted(sets.keys())):\n points = []\n set_rew = sets_prices[set_idx]\n for nidx1 in sets[set_idx]: \n node1 = nodes_w_rewards[nidx1, :]\n points.append([node1[0], node1[1]])\n for nidx2 in sets[set_idx]: \n if(nidx1 != nidx2):\n node2 = nodes_w_rewards[nidx2, :]\n # plt.plot([node1[0], node2[0] ], [node1[1], node2[1] ], '-k', lw=0.2)\n \n alpha = 0.0\n concave_hull = figure_utils.alpha_shape(points, alpha=alpha)\n \n color = mycmapScalarMap.to_rgba(set_rew)\n figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)\n \n\nfor node_idx in range(1, len(result_target_ids)):\n \n if problem_type == ProblemType.DOP:\n step_size = 20\n turning_radius = op.dubins_radius\n node = result_cluster_ids[node_idx]\n node_prew = result_cluster_ids[node_idx - 1]\n q_start = [nodes_w_rewards[node, 0], nodes_w_rewards[node, 1], result_head_angs[node_idx]]\n q_end = [nodes_w_rewards[node_prew][0], nodes_w_rewards[node_prew][1], result_head_angs[node_idx - 1]]\n path = dubins.shortest_path(q_start, q_end, turning_radius)\n qs, _ = path.sample_many(step_size)\n # length_dub += math.ceil(path.path_length())\n xses = [item[0] for item in qs]\n yses = [item[1] for item in qs]\n print(node_prew, '->', node, \",\", q_start, '->', q_end)\n plt.plot(xses, yses, '-g', lw=1.6)\n \n elif problem_type == ProblemType.OPN:\n node = result_target_ids[node_idx]\n node_prew = result_target_ids[node_idx - 1]\n node_pos = [nodes[node][0], nodes[node][1]]\n node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]\n print(node_prew, '->', node, \",\", node_pos_prew, '->', node_pos)\n plt.plot([node_pos_prew[0], node_pos[0] ], [node_pos_prew[1], node_pos[1] ], '-g', lw=1.6)\n\n else:\n node = result_target_ids[node_idx]\n node_prew = result_target_ids[node_idx - 1]\n node_pos = [nodes[node][0], nodes[node][1]]\n node_pos_prew = [nodes[node_prew][0], nodes[node_prew][1]]\n print(node_prew, '->', node, \",\", node_pos_prew, '->', node_pos)\n plt.plot([node_pos_prew[0], node_pos[0] ], [node_pos_prew[1], node_pos[1] ], '-g', lw=1.6)\n\nax = plt.gca()\nax.axis('equal')\nfigure_utils.no_axis(ax)\n\ncbar_position = [0.20, 0.05, 0.6, 0.03]\ncbar_ax = fig.add_axes(cbar_position)\ncb = plt.colorbar(sc, cax=cbar_ax, orientation='horizontal')\ncb.ax.tick_params(labelsize=tick_font_size)\ncb.set_label('profit', labelpad=-65.0, y=0.8, fontsize=legend_font_size)\n\n# offset = 0.08\nfig.subplots_adjust(left=-0.035, right=1.035 , top=1.07 , bottom=0.0)\n\nplt.savefig(SAVE_TO_FIGURE, dpi=300)\nif SHOW_FIGURE:\n plt.show() \n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for pessoas in range(1, 8):
nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: '))
idade = atual - nasc
if idade >= 21:
totmaior += 1
else:
totmenor += 1
print(f'Ao todo tivemos {totmaior} pessoas maiores de idade!')
print(f'E tambem tivemos {totmenor} pessoas menores de idade!')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
atual = date.today().year
totmaior = 0
totmenor = 0
for pessoas in range(1, 8):
nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: '))
idade = atual - nasc
if idade >= 21:
totmaior += 1
else:
totmenor += 1
print(f'Ao todo tivemos {totmaior} pessoas maiores de idade!')
print(f'E tambem tivemos {totmenor} pessoas menores de idade!')
<|reserved_special_token_1|>
from datetime import date
atual = date.today().year
totmaior = 0
totmenor = 0
for pessoas in range(1, 8):
nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: '))
idade = atual - nasc
if idade >= 21:
totmaior += 1
else:
totmenor += 1
print(f'Ao todo tivemos {totmaior} pessoas maiores de idade!')
print(f'E tambem tivemos {totmenor} pessoas menores de idade!')
|
flexible
|
{
"blob_id": "f6d7ce2d020d11086640a34aac656098ab0b0f33",
"index": 9495,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor pessoas in range(1, 8):\n nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: '))\n idade = atual - nasc\n if idade >= 21:\n totmaior += 1\n else:\n totmenor += 1\nprint(f'Ao todo tivemos {totmaior} pessoas maiores de idade!')\nprint(f'E tambem tivemos {totmenor} pessoas menores de idade!')\n",
"step-3": "<mask token>\natual = date.today().year\ntotmaior = 0\ntotmenor = 0\nfor pessoas in range(1, 8):\n nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: '))\n idade = atual - nasc\n if idade >= 21:\n totmaior += 1\n else:\n totmenor += 1\nprint(f'Ao todo tivemos {totmaior} pessoas maiores de idade!')\nprint(f'E tambem tivemos {totmenor} pessoas menores de idade!')\n",
"step-4": "from datetime import date\natual = date.today().year\ntotmaior = 0\ntotmenor = 0\nfor pessoas in range(1, 8):\n nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: '))\n idade = atual - nasc\n if idade >= 21:\n totmaior += 1\n else:\n totmenor += 1\nprint(f'Ao todo tivemos {totmaior} pessoas maiores de idade!')\nprint(f'E tambem tivemos {totmenor} pessoas menores de idade!')\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from django.conf.urls import url
from .import views
app_name='user'
# user子路由
urlpatterns = [
# user首页
url(r'^$',views.index,name='index'),
# 用户登录
url('login/', views.login, name='login'),
# 用户注册
url('regist/', views.regist, name='regist'),
# 根据id判断用户是否存在
url(r'^getuser\w*/(?P<id>\d*)', views.getUserById, name='getuser'),
# 获取短信验证接口
url(r'^sendmessage\w*/(?P<user_telephone>\d*)',views.sendMessage,name='sendmessage'),
# 根据token查询一定的用户信息 postRight
url(r'gettoken', views.getUserbyToken, name='getUserbyToken'),
]
|
normal
|
{
"blob_id": "de7b5e44c5c213e4ab70b0f8c0c402edaf4926e0",
"index": 211,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napp_name = 'user'\nurlpatterns = [url('^$', views.index, name='index'), url('login/', views.\n login, name='login'), url('regist/', views.regist, name='regist'), url(\n '^getuser\\\\w*/(?P<id>\\\\d*)', views.getUserById, name='getuser'), url(\n '^sendmessage\\\\w*/(?P<user_telephone>\\\\d*)', views.sendMessage, name=\n 'sendmessage'), url('gettoken', views.getUserbyToken, name=\n 'getUserbyToken')]\n",
"step-3": "from django.conf.urls import url\nfrom . import views\napp_name = 'user'\nurlpatterns = [url('^$', views.index, name='index'), url('login/', views.\n login, name='login'), url('regist/', views.regist, name='regist'), url(\n '^getuser\\\\w*/(?P<id>\\\\d*)', views.getUserById, name='getuser'), url(\n '^sendmessage\\\\w*/(?P<user_telephone>\\\\d*)', views.sendMessage, name=\n 'sendmessage'), url('gettoken', views.getUserbyToken, name=\n 'getUserbyToken')]\n",
"step-4": "\nfrom django.conf.urls import url\nfrom .import views\n\napp_name='user'\n# user子路由\nurlpatterns = [\n\n # user首页\n url(r'^$',views.index,name='index'),\n\n # 用户登录\n url('login/', views.login, name='login'),\n\n # 用户注册\n url('regist/', views.regist, name='regist'),\n\n # 根据id判断用户是否存在\n url(r'^getuser\\w*/(?P<id>\\d*)', views.getUserById, name='getuser'),\n\n # 获取短信验证接口\n url(r'^sendmessage\\w*/(?P<user_telephone>\\d*)',views.sendMessage,name='sendmessage'),\n\n # 根据token查询一定的用户信息 postRight\n url(r'gettoken', views.getUserbyToken, name='getUserbyToken'),\n\n\n\n]\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
with Session() as ps:
ps.app.runMenuItem(ps.app.stringIDToTypeID('toggleProofColors'))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from photoshop import Session
with Session() as ps:
ps.app.runMenuItem(ps.app.stringIDToTypeID('toggleProofColors'))
<|reserved_special_token_1|>
"""Toggle the proof color.
Like operating in the menu:
**View** > **Proof Colors** (Ctrl + Y)
"""
# Import local modules
from photoshop import Session
with Session() as ps:
ps.app.runMenuItem(ps.app.stringIDToTypeID("toggleProofColors"))
|
flexible
|
{
"blob_id": "1db866ca73bc264d474d5e5086c4a047d7e46546",
"index": 2299,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith Session() as ps:\n ps.app.runMenuItem(ps.app.stringIDToTypeID('toggleProofColors'))\n",
"step-3": "<mask token>\nfrom photoshop import Session\nwith Session() as ps:\n ps.app.runMenuItem(ps.app.stringIDToTypeID('toggleProofColors'))\n",
"step-4": "\"\"\"Toggle the proof color.\n\nLike operating in the menu:\n**View** > **Proof Colors** (Ctrl + Y)\n\n\"\"\"\n# Import local modules\nfrom photoshop import Session\n\n\nwith Session() as ps:\n ps.app.runMenuItem(ps.app.stringIDToTypeID(\"toggleProofColors\"))\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#-*- coding: UTF-8 -*-
#Author Motuii
'''
* ┏┓ ┏┓
* ┏┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ ┳┛ ┗┳ ┃
* ┃ ┃
* ┃ ┻ ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ 神兽保佑
* ┃ ┃ 代码无BUG!
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*
'''
n = 10
# arr = [[1]*i for i in range(1,n+1)]
# for i in range(len(arr)):
# for j in range(len(arr[i])):
# if (j!=0 and j!=len(arr[i-1])):
# arr[i][j] = arr[i-1][j-1] + arr[i-1][j]
# print ' '.join(map(lambda x:str(x),arr[i]))
an = [1]*n
for i in range(n):
for j in range(i-1,0,-1):
an[j] = an[j]+an[j-1]
print an[0:i+1]
#print "\t".join(map(lambda x:str(x),an[0:i+1]))
|
normal
|
{
"blob_id": "131caf50cc8682cf180168a1b136b1dcdd70fa76",
"index": 6837,
"step-1": "#-*- coding: UTF-8 -*-\n#Author Motuii\n'''\n * ┏┓ ┏┓ \n * ┏┛┻━━━┛┻┓ \n * ┃ ┃ \n * ┃ ━ ┃ \n * ┃ ┳┛ ┗┳ ┃ \n * ┃ ┃ \n * ┃ ┻ ┃ \n * ┃ ┃ \n * ┗━┓ ┏━┛ \n * ┃ ┃ 神兽保佑 \n * ┃ ┃ 代码无BUG! \n * ┃ ┗━━━┓ \n * ┃ ┣┓ \n * ┃ ┏┛ \n * ┗┓┓┏━┳┓┏┛ \n * ┃┫┫ ┃┫┫ \n * ┗┻┛ ┗┻┛ \n * \n '''\n\nn = 10\n# arr = [[1]*i for i in range(1,n+1)]\n# for i in range(len(arr)):\n# \tfor j in range(len(arr[i])):\n# \t\tif (j!=0 and j!=len(arr[i-1])):\n# \t\t\tarr[i][j] = arr[i-1][j-1] + arr[i-1][j]\n# \tprint ' '.join(map(lambda x:str(x),arr[i]))\n\nan = [1]*n\nfor i in range(n):\n\tfor j in range(i-1,0,-1):\n\t\tan[j] = an[j]+an[j-1]\n\n\tprint an[0:i+1]\n\t#print \"\\t\".join(map(lambda x:str(x),an[0:i+1]))\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
def is_printing():
try:
status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',
timeout=1)
if status.json() == 'printing':
state = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/state', timeout=1).json()
if (state == 'none' or state == 'wait_cleanup' or state ==
'wait_user_action'):
return False
else:
return True
else:
return False
except Exception as e:
return False
def is_pre_printing():
state = http.get('http://' + PRINTER_IP + '/api/v1/print_job/state',
timeout=1).json()
return state == 'pre_print'
def register_pre_printing():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
title = http.get('http://' + PRINTER_IP + '/api/v1/print_job/name',
timeout=1).json()
duration = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/time_total', timeout=1).json()
status = 'pre-printing'
db_cur.execute("INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)",
(title, status, duration, date.today()))
db.commit()
db.close()
return db_cur.lastrowid
def store_preview(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
f = open('tmp/preview.jpg', 'rb')
db_cur.execute('UPDATE timelapses SET preview = ? WHERE id = ?', (
sqlite3.Binary(f.read()), id))
f.close()
db.commit()
db.close()
def update_timelapse_status(id, status):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute('\n\t\tUPDATE timelapses SET status = ? WHERE id = ?\n\t',
(status, id))
db.commit()
db.close()
def check_timelapses():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute(
"""
CREATE TABLE IF NOT EXISTS timelapses(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT,
status TEXT,
duration INTEGER,
date DATE,
preview BLOB)
"""
)
db_cur.execute('SELECT * from timelapses')
timelapses = db_cur.fetchall()
for timelapse in timelapses:
filepath = get_filepath(timelapse[0])
if timelapse[2] == 'pre-printing' and not is_printing():
update_timelapse_status(timelapse[0], 'failed')
elif timelapse[2] == 'printing' and not is_printing():
update_timelapse_status(timelapse[0], 'failed')
elif timelapse[2] == 'missing':
if os.path.isfile(filepath):
update_timelapse_status(timelapse[0], 'finished')
elif timelapse[2] == 'finished':
if not os.path.isfile(filepath):
update_timelapse_status(timelapse[0], 'missing')
for timelapse in timelapses:
timelapseDate = timelapse[4].split('-')
timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]),
int(timelapseDate[2]))
currentDate = date.today()
if (currentDate - timelapseDate).days > 31:
filepath = get_filepath(timelapse[0])
if os.path.isfile(filepath):
os.remove(filepath)
db_cur.execute('DELETE FROM timelapses WHERE id = ?', (
timelapse[0],))
db.commit()
db.close()
def get_filepath(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute('SELECT title FROM timelapses WHERE id = ?', (id,))
title = db_cur.fetchone()[0]
db.commit()
db.close()
return os.path.join(TIMELAPSE_PATH, title + str(id) + '.mp4')
def start_timelapse_daemon():
while True:
check_timelapses()
print('Waiting for print to start...')
while not is_printing():
time.sleep(5)
print('Waiting for printer calibration...')
current_print_id = register_pre_printing()
while is_pre_printing():
time.sleep(1)
if not is_printing():
continue
print('Printing...')
update_timelapse_status(current_print_id, 'printing')
if os.path.isdir('tmp'):
for file in os.listdir('tmp'):
file_path = os.path.join('tmp', file)
if os.path.isfile(file_path):
os.remove(file_path)
else:
os.mkdir('tmp')
duration = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/time_total').json()
frame = 0
while is_printing():
frame += 1
res = http.get('http://' + PRINTER_IP + ':8080/?action=snapshot')
filepath = 'tmp/' + str(frame) + '.jpg'
f = open(filepath, 'bw')
f.write(res.content)
f.close()
time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))
update_timelapse_status(current_print_id, 'finished')
filepath = get_filepath(current_print_id)
if not os.path.isdir(TIMELAPSE_PATH):
os.mkdir(TIMELAPSE_PATH)
os.system('ffmpeg -r ' + str(FRAMERATE) +
" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 " + filepath)
os.system('ffmpeg -i ' + filepath + ' -vf "select=\'eq(n,' + str(5 *
frame // 6) + ')\'" -vframes 1 tmp/preview.jpg')
store_preview(current_print_id)
for file in os.listdir('tmp'):
file_path = os.path.join('tmp', file)
if os.path.isfile(file_path):
os.remove(file_path)
os.rmdir('tmp')
print('Print done!')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def is_printing():
try:
status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',
timeout=1)
if status.json() == 'printing':
state = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/state', timeout=1).json()
if (state == 'none' or state == 'wait_cleanup' or state ==
'wait_user_action'):
return False
else:
return True
else:
return False
except Exception as e:
return False
def is_pre_printing():
state = http.get('http://' + PRINTER_IP + '/api/v1/print_job/state',
timeout=1).json()
return state == 'pre_print'
def register_pre_printing():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
title = http.get('http://' + PRINTER_IP + '/api/v1/print_job/name',
timeout=1).json()
duration = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/time_total', timeout=1).json()
status = 'pre-printing'
db_cur.execute("INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)",
(title, status, duration, date.today()))
db.commit()
db.close()
return db_cur.lastrowid
def store_preview(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
f = open('tmp/preview.jpg', 'rb')
db_cur.execute('UPDATE timelapses SET preview = ? WHERE id = ?', (
sqlite3.Binary(f.read()), id))
f.close()
db.commit()
db.close()
def update_timelapse_status(id, status):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute('\n\t\tUPDATE timelapses SET status = ? WHERE id = ?\n\t',
(status, id))
db.commit()
db.close()
def check_timelapses():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute(
"""
CREATE TABLE IF NOT EXISTS timelapses(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT,
status TEXT,
duration INTEGER,
date DATE,
preview BLOB)
"""
)
db_cur.execute('SELECT * from timelapses')
timelapses = db_cur.fetchall()
for timelapse in timelapses:
filepath = get_filepath(timelapse[0])
if timelapse[2] == 'pre-printing' and not is_printing():
update_timelapse_status(timelapse[0], 'failed')
elif timelapse[2] == 'printing' and not is_printing():
update_timelapse_status(timelapse[0], 'failed')
elif timelapse[2] == 'missing':
if os.path.isfile(filepath):
update_timelapse_status(timelapse[0], 'finished')
elif timelapse[2] == 'finished':
if not os.path.isfile(filepath):
update_timelapse_status(timelapse[0], 'missing')
for timelapse in timelapses:
timelapseDate = timelapse[4].split('-')
timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]),
int(timelapseDate[2]))
currentDate = date.today()
if (currentDate - timelapseDate).days > 31:
filepath = get_filepath(timelapse[0])
if os.path.isfile(filepath):
os.remove(filepath)
db_cur.execute('DELETE FROM timelapses WHERE id = ?', (
timelapse[0],))
db.commit()
db.close()
def get_filepath(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute('SELECT title FROM timelapses WHERE id = ?', (id,))
title = db_cur.fetchone()[0]
db.commit()
db.close()
return os.path.join(TIMELAPSE_PATH, title + str(id) + '.mp4')
def start_timelapse_daemon():
while True:
check_timelapses()
print('Waiting for print to start...')
while not is_printing():
time.sleep(5)
print('Waiting for printer calibration...')
current_print_id = register_pre_printing()
while is_pre_printing():
time.sleep(1)
if not is_printing():
continue
print('Printing...')
update_timelapse_status(current_print_id, 'printing')
if os.path.isdir('tmp'):
for file in os.listdir('tmp'):
file_path = os.path.join('tmp', file)
if os.path.isfile(file_path):
os.remove(file_path)
else:
os.mkdir('tmp')
duration = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/time_total').json()
frame = 0
while is_printing():
frame += 1
res = http.get('http://' + PRINTER_IP + ':8080/?action=snapshot')
filepath = 'tmp/' + str(frame) + '.jpg'
f = open(filepath, 'bw')
f.write(res.content)
f.close()
time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))
update_timelapse_status(current_print_id, 'finished')
filepath = get_filepath(current_print_id)
if not os.path.isdir(TIMELAPSE_PATH):
os.mkdir(TIMELAPSE_PATH)
os.system('ffmpeg -r ' + str(FRAMERATE) +
" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 " + filepath)
os.system('ffmpeg -i ' + filepath + ' -vf "select=\'eq(n,' + str(5 *
frame // 6) + ')\'" -vframes 1 tmp/preview.jpg')
store_preview(current_print_id)
for file in os.listdir('tmp'):
file_path = os.path.join('tmp', file)
if os.path.isfile(file_path):
os.remove(file_path)
os.rmdir('tmp')
print('Print done!')
<|reserved_special_token_0|>
parser.add_argument('-ip', help='specifies the ip of the printer', required
=True)
<|reserved_special_token_0|>
start_timelapse_daemon()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
PRINTER_IP = ''
FRAMERATE = 30
TIMELAPSE_DURATION = 60
TIMELAPSE_PATH = 'timelapses'
DATABASE_PATH = 'timelapses.db'
def is_printing():
try:
status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',
timeout=1)
if status.json() == 'printing':
state = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/state', timeout=1).json()
if (state == 'none' or state == 'wait_cleanup' or state ==
'wait_user_action'):
return False
else:
return True
else:
return False
except Exception as e:
return False
def is_pre_printing():
state = http.get('http://' + PRINTER_IP + '/api/v1/print_job/state',
timeout=1).json()
return state == 'pre_print'
def register_pre_printing():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
title = http.get('http://' + PRINTER_IP + '/api/v1/print_job/name',
timeout=1).json()
duration = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/time_total', timeout=1).json()
status = 'pre-printing'
db_cur.execute("INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)",
(title, status, duration, date.today()))
db.commit()
db.close()
return db_cur.lastrowid
def store_preview(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
f = open('tmp/preview.jpg', 'rb')
db_cur.execute('UPDATE timelapses SET preview = ? WHERE id = ?', (
sqlite3.Binary(f.read()), id))
f.close()
db.commit()
db.close()
def update_timelapse_status(id, status):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute('\n\t\tUPDATE timelapses SET status = ? WHERE id = ?\n\t',
(status, id))
db.commit()
db.close()
def check_timelapses():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute(
"""
CREATE TABLE IF NOT EXISTS timelapses(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT,
status TEXT,
duration INTEGER,
date DATE,
preview BLOB)
"""
)
db_cur.execute('SELECT * from timelapses')
timelapses = db_cur.fetchall()
for timelapse in timelapses:
filepath = get_filepath(timelapse[0])
if timelapse[2] == 'pre-printing' and not is_printing():
update_timelapse_status(timelapse[0], 'failed')
elif timelapse[2] == 'printing' and not is_printing():
update_timelapse_status(timelapse[0], 'failed')
elif timelapse[2] == 'missing':
if os.path.isfile(filepath):
update_timelapse_status(timelapse[0], 'finished')
elif timelapse[2] == 'finished':
if not os.path.isfile(filepath):
update_timelapse_status(timelapse[0], 'missing')
for timelapse in timelapses:
timelapseDate = timelapse[4].split('-')
timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]),
int(timelapseDate[2]))
currentDate = date.today()
if (currentDate - timelapseDate).days > 31:
filepath = get_filepath(timelapse[0])
if os.path.isfile(filepath):
os.remove(filepath)
db_cur.execute('DELETE FROM timelapses WHERE id = ?', (
timelapse[0],))
db.commit()
db.close()
def get_filepath(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute('SELECT title FROM timelapses WHERE id = ?', (id,))
title = db_cur.fetchone()[0]
db.commit()
db.close()
return os.path.join(TIMELAPSE_PATH, title + str(id) + '.mp4')
def start_timelapse_daemon():
while True:
check_timelapses()
print('Waiting for print to start...')
while not is_printing():
time.sleep(5)
print('Waiting for printer calibration...')
current_print_id = register_pre_printing()
while is_pre_printing():
time.sleep(1)
if not is_printing():
continue
print('Printing...')
update_timelapse_status(current_print_id, 'printing')
if os.path.isdir('tmp'):
for file in os.listdir('tmp'):
file_path = os.path.join('tmp', file)
if os.path.isfile(file_path):
os.remove(file_path)
else:
os.mkdir('tmp')
duration = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/time_total').json()
frame = 0
while is_printing():
frame += 1
res = http.get('http://' + PRINTER_IP + ':8080/?action=snapshot')
filepath = 'tmp/' + str(frame) + '.jpg'
f = open(filepath, 'bw')
f.write(res.content)
f.close()
time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))
update_timelapse_status(current_print_id, 'finished')
filepath = get_filepath(current_print_id)
if not os.path.isdir(TIMELAPSE_PATH):
os.mkdir(TIMELAPSE_PATH)
os.system('ffmpeg -r ' + str(FRAMERATE) +
" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 " + filepath)
os.system('ffmpeg -i ' + filepath + ' -vf "select=\'eq(n,' + str(5 *
frame // 6) + ')\'" -vframes 1 tmp/preview.jpg')
store_preview(current_print_id)
for file in os.listdir('tmp'):
file_path = os.path.join('tmp', file)
if os.path.isfile(file_path):
os.remove(file_path)
os.rmdir('tmp')
print('Print done!')
parser = ArgumentParser(description=
'Recover timelapses from the ultimaker s5 printer')
parser.add_argument('-ip', help='specifies the ip of the printer', required
=True)
args = parser.parse_args()
PRINTER_IP = args.ip
start_timelapse_daemon()
<|reserved_special_token_1|>
import time, json, os, sqlite3, uuid, json, base64, sys
import requests as http
import numpy as np
from os.path import isfile, join
from datetime import date, datetime
from argparse import ArgumentParser
PRINTER_IP = ''
FRAMERATE = 30
TIMELAPSE_DURATION = 60
TIMELAPSE_PATH = 'timelapses'
DATABASE_PATH = 'timelapses.db'
def is_printing():
try:
status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',
timeout=1)
if status.json() == 'printing':
state = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/state', timeout=1).json()
if (state == 'none' or state == 'wait_cleanup' or state ==
'wait_user_action'):
return False
else:
return True
else:
return False
except Exception as e:
return False
def is_pre_printing():
state = http.get('http://' + PRINTER_IP + '/api/v1/print_job/state',
timeout=1).json()
return state == 'pre_print'
def register_pre_printing():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
title = http.get('http://' + PRINTER_IP + '/api/v1/print_job/name',
timeout=1).json()
duration = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/time_total', timeout=1).json()
status = 'pre-printing'
db_cur.execute("INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)",
(title, status, duration, date.today()))
db.commit()
db.close()
return db_cur.lastrowid
def store_preview(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
f = open('tmp/preview.jpg', 'rb')
db_cur.execute('UPDATE timelapses SET preview = ? WHERE id = ?', (
sqlite3.Binary(f.read()), id))
f.close()
db.commit()
db.close()
def update_timelapse_status(id, status):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute('\n\t\tUPDATE timelapses SET status = ? WHERE id = ?\n\t',
(status, id))
db.commit()
db.close()
def check_timelapses():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute(
"""
CREATE TABLE IF NOT EXISTS timelapses(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT,
status TEXT,
duration INTEGER,
date DATE,
preview BLOB)
"""
)
db_cur.execute('SELECT * from timelapses')
timelapses = db_cur.fetchall()
for timelapse in timelapses:
filepath = get_filepath(timelapse[0])
if timelapse[2] == 'pre-printing' and not is_printing():
update_timelapse_status(timelapse[0], 'failed')
elif timelapse[2] == 'printing' and not is_printing():
update_timelapse_status(timelapse[0], 'failed')
elif timelapse[2] == 'missing':
if os.path.isfile(filepath):
update_timelapse_status(timelapse[0], 'finished')
elif timelapse[2] == 'finished':
if not os.path.isfile(filepath):
update_timelapse_status(timelapse[0], 'missing')
for timelapse in timelapses:
timelapseDate = timelapse[4].split('-')
timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]),
int(timelapseDate[2]))
currentDate = date.today()
if (currentDate - timelapseDate).days > 31:
filepath = get_filepath(timelapse[0])
if os.path.isfile(filepath):
os.remove(filepath)
db_cur.execute('DELETE FROM timelapses WHERE id = ?', (
timelapse[0],))
db.commit()
db.close()
def get_filepath(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute('SELECT title FROM timelapses WHERE id = ?', (id,))
title = db_cur.fetchone()[0]
db.commit()
db.close()
return os.path.join(TIMELAPSE_PATH, title + str(id) + '.mp4')
def start_timelapse_daemon():
while True:
check_timelapses()
print('Waiting for print to start...')
while not is_printing():
time.sleep(5)
print('Waiting for printer calibration...')
current_print_id = register_pre_printing()
while is_pre_printing():
time.sleep(1)
if not is_printing():
continue
print('Printing...')
update_timelapse_status(current_print_id, 'printing')
if os.path.isdir('tmp'):
for file in os.listdir('tmp'):
file_path = os.path.join('tmp', file)
if os.path.isfile(file_path):
os.remove(file_path)
else:
os.mkdir('tmp')
duration = http.get('http://' + PRINTER_IP +
'/api/v1/print_job/time_total').json()
frame = 0
while is_printing():
frame += 1
res = http.get('http://' + PRINTER_IP + ':8080/?action=snapshot')
filepath = 'tmp/' + str(frame) + '.jpg'
f = open(filepath, 'bw')
f.write(res.content)
f.close()
time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))
update_timelapse_status(current_print_id, 'finished')
filepath = get_filepath(current_print_id)
if not os.path.isdir(TIMELAPSE_PATH):
os.mkdir(TIMELAPSE_PATH)
os.system('ffmpeg -r ' + str(FRAMERATE) +
" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 " + filepath)
os.system('ffmpeg -i ' + filepath + ' -vf "select=\'eq(n,' + str(5 *
frame // 6) + ')\'" -vframes 1 tmp/preview.jpg')
store_preview(current_print_id)
for file in os.listdir('tmp'):
file_path = os.path.join('tmp', file)
if os.path.isfile(file_path):
os.remove(file_path)
os.rmdir('tmp')
print('Print done!')
parser = ArgumentParser(description=
'Recover timelapses from the ultimaker s5 printer')
parser.add_argument('-ip', help='specifies the ip of the printer', required
=True)
args = parser.parse_args()
PRINTER_IP = args.ip
start_timelapse_daemon()
<|reserved_special_token_1|>
#!/usr/local/bin/python3
import time, json, os, sqlite3, uuid, json, base64, sys
import requests as http
import numpy as np
from os.path import isfile, join
from datetime import date, datetime
from argparse import ArgumentParser
PRINTER_IP = ""
FRAMERATE = 30
TIMELAPSE_DURATION = 60
TIMELAPSE_PATH = "timelapses"
DATABASE_PATH = "timelapses.db"
# Checks if a print is running
#
# @return boolean the status of the printer
def is_printing():
try:
status = http.get("http://" + PRINTER_IP + "/api/v1/printer/status", timeout=1)
if status.json() == "printing":
state = http.get("http://" + PRINTER_IP + "/api/v1/print_job/state", timeout=1).json()
if state == 'none' or state == 'wait_cleanup' or state == "wait_user_action":
return False
else:
return True
else:
return False;
except Exception as e:
return False
# Checks if a print is starting
#
# @return boolean the status of the calibration
def is_pre_printing():
state = http.get("http://" + PRINTER_IP + "/api/v1/print_job/state", timeout=1).json()
return state == 'pre_print'
# Adds a pre-printing print in the database
#
# @returns int the id of the timelapse
def register_pre_printing():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
title = http.get("http://" + PRINTER_IP + "/api/v1/print_job/name", timeout=1).json()
duration = http.get("http://" + PRINTER_IP + "/api/v1/print_job/time_total", timeout=1).json()
status = "pre-printing"
db_cur.execute("INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)", (title, status, duration, date.today()))
db.commit()
db.close()
return db_cur.lastrowid
# Saves a preview image of the timelapse in the database
def store_preview(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
f = open("tmp/preview.jpg", "rb")
db_cur.execute("UPDATE timelapses SET preview = ? WHERE id = ?", (sqlite3.Binary(f.read()), id, ))
f.close()
db.commit()
db.close()
# Updates a timelapse status
#
# @param id the id of the timelapse in the db
# @param status the status to be updated
def update_timelapse_status(id, status):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute("""
UPDATE timelapses SET status = ? WHERE id = ?
""", (status, id, ))
db.commit()
db.close()
# Checks if timelapses are not too old or if files are not missing
def check_timelapses():
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute("""
CREATE TABLE IF NOT EXISTS timelapses(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT,
status TEXT,
duration INTEGER,
date DATE,
preview BLOB)
""");
db_cur.execute("SELECT * from timelapses")
timelapses = db_cur.fetchall()
# checks if timelapse files are not missing
for timelapse in timelapses:
filepath = get_filepath(timelapse[0])
if timelapse[2] == "pre-printing" and not is_printing():
update_timelapse_status(timelapse[0], "failed")
elif timelapse[2] == "printing" and not is_printing():
update_timelapse_status(timelapse[0], "failed")
elif timelapse[2] == "missing":
if os.path.isfile(filepath):
update_timelapse_status(timelapse[0], "finished")
elif timelapse[2] == "finished":
if not os.path.isfile(filepath):
update_timelapse_status(timelapse[0], "missing")
# deletes a timelapse and its file if too old
for timelapse in timelapses:
timelapseDate = timelapse[4].split("-")
timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]), int(timelapseDate[2]))
currentDate = date.today()
if (currentDate - timelapseDate).days > 31:
filepath = get_filepath(timelapse[0])
if os.path.isfile(filepath):
os.remove(filepath)
db_cur.execute("DELETE FROM timelapses WHERE id = ?", (timelapse[0], ))
db.commit()
db.close()
# Gets the filepath of a specific timelapse
#
# @param id the id of the timelapse
def get_filepath(id):
db = sqlite3.connect(DATABASE_PATH)
db_cur = db.cursor()
db_cur.execute("SELECT title FROM timelapses WHERE id = ?", (id, ))
title = db_cur.fetchone()[0]
db.commit()
db.close()
return os.path.join(TIMELAPSE_PATH, title + str(id) + ".mp4")
def start_timelapse_daemon():
while True:
check_timelapses()
print("Waiting for print to start...")
while not is_printing():
time.sleep(5)
print("Waiting for printer calibration...")
current_print_id = register_pre_printing()
while is_pre_printing():
time.sleep(1)
if not is_printing():
continue
print("Printing...")
update_timelapse_status(current_print_id, "printing")
# removes existing tmp folder
if os.path.isdir("tmp"):
for file in os.listdir("tmp"):
file_path = os.path.join("tmp", file)
if os.path.isfile(file_path):
os.remove(file_path)
else:
os.mkdir("tmp")
duration = http.get("http://" + PRINTER_IP + "/api/v1/print_job/time_total").json();
frame = 0
while is_printing():
frame += 1
res = http.get("http://" + PRINTER_IP + ":8080/?action=snapshot")
filepath = "tmp/" + str(frame) + ".jpg"
f = open(filepath, 'bw')
f.write(res.content)
f.close()
time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))
update_timelapse_status(current_print_id, "finished")
# generates the video
filepath = get_filepath(current_print_id)
if not os.path.isdir(TIMELAPSE_PATH):
os.mkdir(TIMELAPSE_PATH)
os.system("ffmpeg -r " + str(FRAMERATE) + " -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 " + filepath)
# extracts a preview image
os.system("ffmpeg -i " + filepath + " -vf \"select='eq(n," + str(5 * frame // 6) + ")'\" -vframes 1 tmp/preview.jpg")
store_preview(current_print_id)
# removes the tmp folder
for file in os.listdir("tmp"):
file_path = os.path.join("tmp", file)
if os.path.isfile(file_path):
os.remove(file_path)
os.rmdir("tmp")
print("Print done!")
parser = ArgumentParser(description='Recover timelapses from the ultimaker s5 printer')
parser.add_argument('-ip', help='specifies the ip of the printer', required=True)
args = parser.parse_args()
PRINTER_IP = args.ip
start_timelapse_daemon()
|
flexible
|
{
"blob_id": "d443e9054481984d5372343170254268dca8a3b1",
"index": 3235,
"step-1": "<mask token>\n\n\ndef is_printing():\n try:\n status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',\n timeout=1)\n if status.json() == 'printing':\n state = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/state', timeout=1).json()\n if (state == 'none' or state == 'wait_cleanup' or state ==\n 'wait_user_action'):\n return False\n else:\n return True\n else:\n return False\n except Exception as e:\n return False\n\n\ndef is_pre_printing():\n state = http.get('http://' + PRINTER_IP + '/api/v1/print_job/state',\n timeout=1).json()\n return state == 'pre_print'\n\n\ndef register_pre_printing():\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n title = http.get('http://' + PRINTER_IP + '/api/v1/print_job/name',\n timeout=1).json()\n duration = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/time_total', timeout=1).json()\n status = 'pre-printing'\n db_cur.execute(\"INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)\",\n (title, status, duration, date.today()))\n db.commit()\n db.close()\n return db_cur.lastrowid\n\n\ndef store_preview(id):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n f = open('tmp/preview.jpg', 'rb')\n db_cur.execute('UPDATE timelapses SET preview = ? WHERE id = ?', (\n sqlite3.Binary(f.read()), id))\n f.close()\n db.commit()\n db.close()\n\n\ndef update_timelapse_status(id, status):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute('\\n\\t\\tUPDATE timelapses SET status = ? WHERE id = ?\\n\\t',\n (status, id))\n db.commit()\n db.close()\n\n\ndef check_timelapses():\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute(\n \"\"\"\n\tCREATE TABLE IF NOT EXISTS timelapses(\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\t\ttitle TEXT,\n\t\tstatus TEXT,\n\t\tduration INTEGER,\n\t\tdate DATE,\n\t\tpreview BLOB)\n\t\"\"\"\n )\n db_cur.execute('SELECT * from timelapses')\n timelapses = db_cur.fetchall()\n for timelapse in timelapses:\n filepath = get_filepath(timelapse[0])\n if timelapse[2] == 'pre-printing' and not is_printing():\n update_timelapse_status(timelapse[0], 'failed')\n elif timelapse[2] == 'printing' and not is_printing():\n update_timelapse_status(timelapse[0], 'failed')\n elif timelapse[2] == 'missing':\n if os.path.isfile(filepath):\n update_timelapse_status(timelapse[0], 'finished')\n elif timelapse[2] == 'finished':\n if not os.path.isfile(filepath):\n update_timelapse_status(timelapse[0], 'missing')\n for timelapse in timelapses:\n timelapseDate = timelapse[4].split('-')\n timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]),\n int(timelapseDate[2]))\n currentDate = date.today()\n if (currentDate - timelapseDate).days > 31:\n filepath = get_filepath(timelapse[0])\n if os.path.isfile(filepath):\n os.remove(filepath)\n db_cur.execute('DELETE FROM timelapses WHERE id = ?', (\n timelapse[0],))\n db.commit()\n db.close()\n\n\ndef get_filepath(id):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute('SELECT title FROM timelapses WHERE id = ?', (id,))\n title = db_cur.fetchone()[0]\n db.commit()\n db.close()\n return os.path.join(TIMELAPSE_PATH, title + str(id) + '.mp4')\n\n\ndef start_timelapse_daemon():\n while True:\n check_timelapses()\n print('Waiting for print to start...')\n while not is_printing():\n time.sleep(5)\n print('Waiting for printer calibration...')\n current_print_id = register_pre_printing()\n while is_pre_printing():\n time.sleep(1)\n if not is_printing():\n continue\n print('Printing...')\n update_timelapse_status(current_print_id, 'printing')\n if os.path.isdir('tmp'):\n for file in os.listdir('tmp'):\n file_path = os.path.join('tmp', file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n else:\n os.mkdir('tmp')\n duration = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/time_total').json()\n frame = 0\n while is_printing():\n frame += 1\n res = http.get('http://' + PRINTER_IP + ':8080/?action=snapshot')\n filepath = 'tmp/' + str(frame) + '.jpg'\n f = open(filepath, 'bw')\n f.write(res.content)\n f.close()\n time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))\n update_timelapse_status(current_print_id, 'finished')\n filepath = get_filepath(current_print_id)\n if not os.path.isdir(TIMELAPSE_PATH):\n os.mkdir(TIMELAPSE_PATH)\n os.system('ffmpeg -r ' + str(FRAMERATE) +\n \" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 \" + filepath)\n os.system('ffmpeg -i ' + filepath + ' -vf \"select=\\'eq(n,' + str(5 *\n frame // 6) + ')\\'\" -vframes 1 tmp/preview.jpg')\n store_preview(current_print_id)\n for file in os.listdir('tmp'):\n file_path = os.path.join('tmp', file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n os.rmdir('tmp')\n print('Print done!')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef is_printing():\n try:\n status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',\n timeout=1)\n if status.json() == 'printing':\n state = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/state', timeout=1).json()\n if (state == 'none' or state == 'wait_cleanup' or state ==\n 'wait_user_action'):\n return False\n else:\n return True\n else:\n return False\n except Exception as e:\n return False\n\n\ndef is_pre_printing():\n state = http.get('http://' + PRINTER_IP + '/api/v1/print_job/state',\n timeout=1).json()\n return state == 'pre_print'\n\n\ndef register_pre_printing():\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n title = http.get('http://' + PRINTER_IP + '/api/v1/print_job/name',\n timeout=1).json()\n duration = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/time_total', timeout=1).json()\n status = 'pre-printing'\n db_cur.execute(\"INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)\",\n (title, status, duration, date.today()))\n db.commit()\n db.close()\n return db_cur.lastrowid\n\n\ndef store_preview(id):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n f = open('tmp/preview.jpg', 'rb')\n db_cur.execute('UPDATE timelapses SET preview = ? WHERE id = ?', (\n sqlite3.Binary(f.read()), id))\n f.close()\n db.commit()\n db.close()\n\n\ndef update_timelapse_status(id, status):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute('\\n\\t\\tUPDATE timelapses SET status = ? WHERE id = ?\\n\\t',\n (status, id))\n db.commit()\n db.close()\n\n\ndef check_timelapses():\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute(\n \"\"\"\n\tCREATE TABLE IF NOT EXISTS timelapses(\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\t\ttitle TEXT,\n\t\tstatus TEXT,\n\t\tduration INTEGER,\n\t\tdate DATE,\n\t\tpreview BLOB)\n\t\"\"\"\n )\n db_cur.execute('SELECT * from timelapses')\n timelapses = db_cur.fetchall()\n for timelapse in timelapses:\n filepath = get_filepath(timelapse[0])\n if timelapse[2] == 'pre-printing' and not is_printing():\n update_timelapse_status(timelapse[0], 'failed')\n elif timelapse[2] == 'printing' and not is_printing():\n update_timelapse_status(timelapse[0], 'failed')\n elif timelapse[2] == 'missing':\n if os.path.isfile(filepath):\n update_timelapse_status(timelapse[0], 'finished')\n elif timelapse[2] == 'finished':\n if not os.path.isfile(filepath):\n update_timelapse_status(timelapse[0], 'missing')\n for timelapse in timelapses:\n timelapseDate = timelapse[4].split('-')\n timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]),\n int(timelapseDate[2]))\n currentDate = date.today()\n if (currentDate - timelapseDate).days > 31:\n filepath = get_filepath(timelapse[0])\n if os.path.isfile(filepath):\n os.remove(filepath)\n db_cur.execute('DELETE FROM timelapses WHERE id = ?', (\n timelapse[0],))\n db.commit()\n db.close()\n\n\ndef get_filepath(id):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute('SELECT title FROM timelapses WHERE id = ?', (id,))\n title = db_cur.fetchone()[0]\n db.commit()\n db.close()\n return os.path.join(TIMELAPSE_PATH, title + str(id) + '.mp4')\n\n\ndef start_timelapse_daemon():\n while True:\n check_timelapses()\n print('Waiting for print to start...')\n while not is_printing():\n time.sleep(5)\n print('Waiting for printer calibration...')\n current_print_id = register_pre_printing()\n while is_pre_printing():\n time.sleep(1)\n if not is_printing():\n continue\n print('Printing...')\n update_timelapse_status(current_print_id, 'printing')\n if os.path.isdir('tmp'):\n for file in os.listdir('tmp'):\n file_path = os.path.join('tmp', file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n else:\n os.mkdir('tmp')\n duration = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/time_total').json()\n frame = 0\n while is_printing():\n frame += 1\n res = http.get('http://' + PRINTER_IP + ':8080/?action=snapshot')\n filepath = 'tmp/' + str(frame) + '.jpg'\n f = open(filepath, 'bw')\n f.write(res.content)\n f.close()\n time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))\n update_timelapse_status(current_print_id, 'finished')\n filepath = get_filepath(current_print_id)\n if not os.path.isdir(TIMELAPSE_PATH):\n os.mkdir(TIMELAPSE_PATH)\n os.system('ffmpeg -r ' + str(FRAMERATE) +\n \" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 \" + filepath)\n os.system('ffmpeg -i ' + filepath + ' -vf \"select=\\'eq(n,' + str(5 *\n frame // 6) + ')\\'\" -vframes 1 tmp/preview.jpg')\n store_preview(current_print_id)\n for file in os.listdir('tmp'):\n file_path = os.path.join('tmp', file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n os.rmdir('tmp')\n print('Print done!')\n\n\n<mask token>\nparser.add_argument('-ip', help='specifies the ip of the printer', required\n =True)\n<mask token>\nstart_timelapse_daemon()\n",
"step-3": "<mask token>\nPRINTER_IP = ''\nFRAMERATE = 30\nTIMELAPSE_DURATION = 60\nTIMELAPSE_PATH = 'timelapses'\nDATABASE_PATH = 'timelapses.db'\n\n\ndef is_printing():\n try:\n status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',\n timeout=1)\n if status.json() == 'printing':\n state = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/state', timeout=1).json()\n if (state == 'none' or state == 'wait_cleanup' or state ==\n 'wait_user_action'):\n return False\n else:\n return True\n else:\n return False\n except Exception as e:\n return False\n\n\ndef is_pre_printing():\n state = http.get('http://' + PRINTER_IP + '/api/v1/print_job/state',\n timeout=1).json()\n return state == 'pre_print'\n\n\ndef register_pre_printing():\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n title = http.get('http://' + PRINTER_IP + '/api/v1/print_job/name',\n timeout=1).json()\n duration = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/time_total', timeout=1).json()\n status = 'pre-printing'\n db_cur.execute(\"INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)\",\n (title, status, duration, date.today()))\n db.commit()\n db.close()\n return db_cur.lastrowid\n\n\ndef store_preview(id):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n f = open('tmp/preview.jpg', 'rb')\n db_cur.execute('UPDATE timelapses SET preview = ? WHERE id = ?', (\n sqlite3.Binary(f.read()), id))\n f.close()\n db.commit()\n db.close()\n\n\ndef update_timelapse_status(id, status):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute('\\n\\t\\tUPDATE timelapses SET status = ? WHERE id = ?\\n\\t',\n (status, id))\n db.commit()\n db.close()\n\n\ndef check_timelapses():\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute(\n \"\"\"\n\tCREATE TABLE IF NOT EXISTS timelapses(\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\t\ttitle TEXT,\n\t\tstatus TEXT,\n\t\tduration INTEGER,\n\t\tdate DATE,\n\t\tpreview BLOB)\n\t\"\"\"\n )\n db_cur.execute('SELECT * from timelapses')\n timelapses = db_cur.fetchall()\n for timelapse in timelapses:\n filepath = get_filepath(timelapse[0])\n if timelapse[2] == 'pre-printing' and not is_printing():\n update_timelapse_status(timelapse[0], 'failed')\n elif timelapse[2] == 'printing' and not is_printing():\n update_timelapse_status(timelapse[0], 'failed')\n elif timelapse[2] == 'missing':\n if os.path.isfile(filepath):\n update_timelapse_status(timelapse[0], 'finished')\n elif timelapse[2] == 'finished':\n if not os.path.isfile(filepath):\n update_timelapse_status(timelapse[0], 'missing')\n for timelapse in timelapses:\n timelapseDate = timelapse[4].split('-')\n timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]),\n int(timelapseDate[2]))\n currentDate = date.today()\n if (currentDate - timelapseDate).days > 31:\n filepath = get_filepath(timelapse[0])\n if os.path.isfile(filepath):\n os.remove(filepath)\n db_cur.execute('DELETE FROM timelapses WHERE id = ?', (\n timelapse[0],))\n db.commit()\n db.close()\n\n\ndef get_filepath(id):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute('SELECT title FROM timelapses WHERE id = ?', (id,))\n title = db_cur.fetchone()[0]\n db.commit()\n db.close()\n return os.path.join(TIMELAPSE_PATH, title + str(id) + '.mp4')\n\n\ndef start_timelapse_daemon():\n while True:\n check_timelapses()\n print('Waiting for print to start...')\n while not is_printing():\n time.sleep(5)\n print('Waiting for printer calibration...')\n current_print_id = register_pre_printing()\n while is_pre_printing():\n time.sleep(1)\n if not is_printing():\n continue\n print('Printing...')\n update_timelapse_status(current_print_id, 'printing')\n if os.path.isdir('tmp'):\n for file in os.listdir('tmp'):\n file_path = os.path.join('tmp', file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n else:\n os.mkdir('tmp')\n duration = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/time_total').json()\n frame = 0\n while is_printing():\n frame += 1\n res = http.get('http://' + PRINTER_IP + ':8080/?action=snapshot')\n filepath = 'tmp/' + str(frame) + '.jpg'\n f = open(filepath, 'bw')\n f.write(res.content)\n f.close()\n time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))\n update_timelapse_status(current_print_id, 'finished')\n filepath = get_filepath(current_print_id)\n if not os.path.isdir(TIMELAPSE_PATH):\n os.mkdir(TIMELAPSE_PATH)\n os.system('ffmpeg -r ' + str(FRAMERATE) +\n \" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 \" + filepath)\n os.system('ffmpeg -i ' + filepath + ' -vf \"select=\\'eq(n,' + str(5 *\n frame // 6) + ')\\'\" -vframes 1 tmp/preview.jpg')\n store_preview(current_print_id)\n for file in os.listdir('tmp'):\n file_path = os.path.join('tmp', file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n os.rmdir('tmp')\n print('Print done!')\n\n\nparser = ArgumentParser(description=\n 'Recover timelapses from the ultimaker s5 printer')\nparser.add_argument('-ip', help='specifies the ip of the printer', required\n =True)\nargs = parser.parse_args()\nPRINTER_IP = args.ip\nstart_timelapse_daemon()\n",
"step-4": "import time, json, os, sqlite3, uuid, json, base64, sys\nimport requests as http\nimport numpy as np\nfrom os.path import isfile, join\nfrom datetime import date, datetime\nfrom argparse import ArgumentParser\nPRINTER_IP = ''\nFRAMERATE = 30\nTIMELAPSE_DURATION = 60\nTIMELAPSE_PATH = 'timelapses'\nDATABASE_PATH = 'timelapses.db'\n\n\ndef is_printing():\n try:\n status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',\n timeout=1)\n if status.json() == 'printing':\n state = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/state', timeout=1).json()\n if (state == 'none' or state == 'wait_cleanup' or state ==\n 'wait_user_action'):\n return False\n else:\n return True\n else:\n return False\n except Exception as e:\n return False\n\n\ndef is_pre_printing():\n state = http.get('http://' + PRINTER_IP + '/api/v1/print_job/state',\n timeout=1).json()\n return state == 'pre_print'\n\n\ndef register_pre_printing():\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n title = http.get('http://' + PRINTER_IP + '/api/v1/print_job/name',\n timeout=1).json()\n duration = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/time_total', timeout=1).json()\n status = 'pre-printing'\n db_cur.execute(\"INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)\",\n (title, status, duration, date.today()))\n db.commit()\n db.close()\n return db_cur.lastrowid\n\n\ndef store_preview(id):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n f = open('tmp/preview.jpg', 'rb')\n db_cur.execute('UPDATE timelapses SET preview = ? WHERE id = ?', (\n sqlite3.Binary(f.read()), id))\n f.close()\n db.commit()\n db.close()\n\n\ndef update_timelapse_status(id, status):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute('\\n\\t\\tUPDATE timelapses SET status = ? WHERE id = ?\\n\\t',\n (status, id))\n db.commit()\n db.close()\n\n\ndef check_timelapses():\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute(\n \"\"\"\n\tCREATE TABLE IF NOT EXISTS timelapses(\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\t\ttitle TEXT,\n\t\tstatus TEXT,\n\t\tduration INTEGER,\n\t\tdate DATE,\n\t\tpreview BLOB)\n\t\"\"\"\n )\n db_cur.execute('SELECT * from timelapses')\n timelapses = db_cur.fetchall()\n for timelapse in timelapses:\n filepath = get_filepath(timelapse[0])\n if timelapse[2] == 'pre-printing' and not is_printing():\n update_timelapse_status(timelapse[0], 'failed')\n elif timelapse[2] == 'printing' and not is_printing():\n update_timelapse_status(timelapse[0], 'failed')\n elif timelapse[2] == 'missing':\n if os.path.isfile(filepath):\n update_timelapse_status(timelapse[0], 'finished')\n elif timelapse[2] == 'finished':\n if not os.path.isfile(filepath):\n update_timelapse_status(timelapse[0], 'missing')\n for timelapse in timelapses:\n timelapseDate = timelapse[4].split('-')\n timelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]),\n int(timelapseDate[2]))\n currentDate = date.today()\n if (currentDate - timelapseDate).days > 31:\n filepath = get_filepath(timelapse[0])\n if os.path.isfile(filepath):\n os.remove(filepath)\n db_cur.execute('DELETE FROM timelapses WHERE id = ?', (\n timelapse[0],))\n db.commit()\n db.close()\n\n\ndef get_filepath(id):\n db = sqlite3.connect(DATABASE_PATH)\n db_cur = db.cursor()\n db_cur.execute('SELECT title FROM timelapses WHERE id = ?', (id,))\n title = db_cur.fetchone()[0]\n db.commit()\n db.close()\n return os.path.join(TIMELAPSE_PATH, title + str(id) + '.mp4')\n\n\ndef start_timelapse_daemon():\n while True:\n check_timelapses()\n print('Waiting for print to start...')\n while not is_printing():\n time.sleep(5)\n print('Waiting for printer calibration...')\n current_print_id = register_pre_printing()\n while is_pre_printing():\n time.sleep(1)\n if not is_printing():\n continue\n print('Printing...')\n update_timelapse_status(current_print_id, 'printing')\n if os.path.isdir('tmp'):\n for file in os.listdir('tmp'):\n file_path = os.path.join('tmp', file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n else:\n os.mkdir('tmp')\n duration = http.get('http://' + PRINTER_IP +\n '/api/v1/print_job/time_total').json()\n frame = 0\n while is_printing():\n frame += 1\n res = http.get('http://' + PRINTER_IP + ':8080/?action=snapshot')\n filepath = 'tmp/' + str(frame) + '.jpg'\n f = open(filepath, 'bw')\n f.write(res.content)\n f.close()\n time.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))\n update_timelapse_status(current_print_id, 'finished')\n filepath = get_filepath(current_print_id)\n if not os.path.isdir(TIMELAPSE_PATH):\n os.mkdir(TIMELAPSE_PATH)\n os.system('ffmpeg -r ' + str(FRAMERATE) +\n \" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 \" + filepath)\n os.system('ffmpeg -i ' + filepath + ' -vf \"select=\\'eq(n,' + str(5 *\n frame // 6) + ')\\'\" -vframes 1 tmp/preview.jpg')\n store_preview(current_print_id)\n for file in os.listdir('tmp'):\n file_path = os.path.join('tmp', file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n os.rmdir('tmp')\n print('Print done!')\n\n\nparser = ArgumentParser(description=\n 'Recover timelapses from the ultimaker s5 printer')\nparser.add_argument('-ip', help='specifies the ip of the printer', required\n =True)\nargs = parser.parse_args()\nPRINTER_IP = args.ip\nstart_timelapse_daemon()\n",
"step-5": "#!/usr/local/bin/python3\nimport time, json, os, sqlite3, uuid, json, base64, sys\nimport requests as http\nimport numpy as np\nfrom os.path import isfile, join\nfrom datetime import date, datetime\nfrom argparse import ArgumentParser\n\nPRINTER_IP = \"\"\n\nFRAMERATE = 30\nTIMELAPSE_DURATION = 60\nTIMELAPSE_PATH = \"timelapses\"\nDATABASE_PATH = \"timelapses.db\"\n\n# Checks if a print is running\n#\n# @return boolean the status of the printer\ndef is_printing():\n\ttry:\n\t\tstatus = http.get(\"http://\" + PRINTER_IP + \"/api/v1/printer/status\", timeout=1)\n\t\tif status.json() == \"printing\":\n\t\t\tstate = http.get(\"http://\" + PRINTER_IP + \"/api/v1/print_job/state\", timeout=1).json()\n\t\t\tif state == 'none' or state == 'wait_cleanup' or state == \"wait_user_action\":\n\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\treturn True\n\t\telse:\n\t\t\treturn False;\n\texcept Exception as e:\n\t\treturn False\n\n# Checks if a print is starting\n#\n# @return boolean the status of the calibration\ndef is_pre_printing():\n\tstate = http.get(\"http://\" + PRINTER_IP + \"/api/v1/print_job/state\", timeout=1).json()\n\treturn state == 'pre_print'\n\n# Adds a pre-printing print in the database\n#\n# @returns int the id of the timelapse\ndef register_pre_printing():\n\tdb = sqlite3.connect(DATABASE_PATH)\n\tdb_cur = db.cursor()\n\n\ttitle = http.get(\"http://\" + PRINTER_IP + \"/api/v1/print_job/name\", timeout=1).json()\n\tduration = http.get(\"http://\" + PRINTER_IP + \"/api/v1/print_job/time_total\", timeout=1).json()\n\tstatus = \"pre-printing\"\n\t\n\tdb_cur.execute(\"INSERT INTO 'timelapses' VALUES(NULL, ?, ?, ?, ?, NULL)\", (title, status, duration, date.today()))\n\t\n\tdb.commit()\n\tdb.close()\n\treturn db_cur.lastrowid\n\n# Saves a preview image of the timelapse in the database\ndef store_preview(id):\n\tdb = sqlite3.connect(DATABASE_PATH)\n\tdb_cur = db.cursor()\n\n\tf = open(\"tmp/preview.jpg\", \"rb\")\n\tdb_cur.execute(\"UPDATE timelapses SET preview = ? WHERE id = ?\", (sqlite3.Binary(f.read()), id, ))\n\tf.close()\n\n\tdb.commit()\n\tdb.close()\n\n# Updates a timelapse status\n#\n# @param id the id of the timelapse in the db\n# @param status the status to be updated\ndef update_timelapse_status(id, status):\n\tdb = sqlite3.connect(DATABASE_PATH)\n\tdb_cur = db.cursor()\n\t\n\tdb_cur.execute(\"\"\"\n\t\tUPDATE timelapses SET status = ? WHERE id = ?\n\t\"\"\", (status, id, ))\n\t\n\tdb.commit()\n\tdb.close()\n\n# Checks if timelapses are not too old or if files are not missing\ndef check_timelapses():\n\tdb = sqlite3.connect(DATABASE_PATH)\n\tdb_cur = db.cursor()\n\n\tdb_cur.execute(\"\"\"\n\tCREATE TABLE IF NOT EXISTS timelapses(\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\t\ttitle TEXT,\n\t\tstatus TEXT,\n\t\tduration INTEGER,\n\t\tdate DATE,\n\t\tpreview BLOB)\n\t\"\"\");\n\n\tdb_cur.execute(\"SELECT * from timelapses\")\n\ttimelapses = db_cur.fetchall()\n\t\n\t# checks if timelapse files are not missing\n\tfor timelapse in timelapses:\n\t\tfilepath = get_filepath(timelapse[0])\n\t\tif timelapse[2] == \"pre-printing\" and not is_printing():\n\t\t\tupdate_timelapse_status(timelapse[0], \"failed\")\n\t\telif timelapse[2] == \"printing\" and not is_printing():\n\t\t\tupdate_timelapse_status(timelapse[0], \"failed\")\n\t\telif timelapse[2] == \"missing\":\n\t\t\tif os.path.isfile(filepath):\n\t\t\t\tupdate_timelapse_status(timelapse[0], \"finished\")\n\t\telif timelapse[2] == \"finished\":\n\t\t\tif not os.path.isfile(filepath):\n\t\t\t\tupdate_timelapse_status(timelapse[0], \"missing\")\n\n\t# deletes a timelapse and its file if too old\n\tfor timelapse in timelapses:\n\t\ttimelapseDate = timelapse[4].split(\"-\")\n\t\ttimelapseDate = date(int(timelapseDate[0]), int(timelapseDate[1]), int(timelapseDate[2]))\n\t\tcurrentDate = date.today()\n\t\tif (currentDate - timelapseDate).days > 31:\n\t\t\tfilepath = get_filepath(timelapse[0])\n\t\t\tif os.path.isfile(filepath):\n\t\t\t\tos.remove(filepath)\n\t\t\tdb_cur.execute(\"DELETE FROM timelapses WHERE id = ?\", (timelapse[0], ))\n\n\tdb.commit()\n\tdb.close()\n\n# Gets the filepath of a specific timelapse\n#\n# @param id the id of the timelapse\ndef get_filepath(id):\n\tdb = sqlite3.connect(DATABASE_PATH)\n\tdb_cur = db.cursor()\n\t\n\tdb_cur.execute(\"SELECT title FROM timelapses WHERE id = ?\", (id, ))\n\ttitle = db_cur.fetchone()[0]\n\t\n\tdb.commit()\n\tdb.close()\n\n\treturn os.path.join(TIMELAPSE_PATH, title + str(id) + \".mp4\")\n\ndef start_timelapse_daemon():\n\twhile True:\n\t\tcheck_timelapses()\n\n\t\tprint(\"Waiting for print to start...\")\n\t\twhile not is_printing():\n\t\t\ttime.sleep(5)\n\n\t\tprint(\"Waiting for printer calibration...\")\n\t\tcurrent_print_id = register_pre_printing()\n\t\twhile is_pre_printing():\n\t\t\ttime.sleep(1)\n\n\t\tif not is_printing():\n\t\t\tcontinue\n\n\t\tprint(\"Printing...\")\n\t\tupdate_timelapse_status(current_print_id, \"printing\")\n\t\t# removes existing tmp folder\n\t\tif os.path.isdir(\"tmp\"):\n\t\t\tfor file in os.listdir(\"tmp\"):\n\t\t\t\tfile_path = os.path.join(\"tmp\", file)\n\t\t\t\tif os.path.isfile(file_path):\n\t\t\t\t\tos.remove(file_path)\n\t\telse:\n\t\t\tos.mkdir(\"tmp\")\n\n\t\tduration = http.get(\"http://\" + PRINTER_IP + \"/api/v1/print_job/time_total\").json();\n\t\tframe = 0\n\t\twhile is_printing():\n\t\t\tframe += 1\n\t\t\tres = http.get(\"http://\" + PRINTER_IP + \":8080/?action=snapshot\")\n\t\t\t\n\t\t\tfilepath = \"tmp/\" + str(frame) + \".jpg\"\n\t\t\tf = open(filepath, 'bw')\n\t\t\tf.write(res.content)\n\t\t\tf.close()\n\t\t\t\n\t\t\ttime.sleep(duration / (FRAMERATE * TIMELAPSE_DURATION))\n\t\t\n\t\tupdate_timelapse_status(current_print_id, \"finished\")\n\t\t# generates the video\n\t\tfilepath = get_filepath(current_print_id)\n\t\tif not os.path.isdir(TIMELAPSE_PATH):\n\t\t\tos.mkdir(TIMELAPSE_PATH)\n\t\tos.system(\"ffmpeg -r \" + str(FRAMERATE) + \" -i 'tmp/%d.jpg' -qscale 7 -c:v libx264 \" + filepath)\n\t\t# extracts a preview image\n\t\tos.system(\"ffmpeg -i \" + filepath + \" -vf \\\"select='eq(n,\" + str(5 * frame // 6) + \")'\\\" -vframes 1 tmp/preview.jpg\")\n\t\tstore_preview(current_print_id)\n\t\t\n\t\t# removes the tmp folder\n\t\tfor file in os.listdir(\"tmp\"):\n\t\t\tfile_path = os.path.join(\"tmp\", file)\n\t\t\tif os.path.isfile(file_path):\n\t\t\t\tos.remove(file_path)\n\t\tos.rmdir(\"tmp\")\n\t\tprint(\"Print done!\")\n\nparser = ArgumentParser(description='Recover timelapses from the ultimaker s5 printer')\nparser.add_argument('-ip', help='specifies the ip of the printer', required=True)\nargs = parser.parse_args()\n\nPRINTER_IP = args.ip\n\nstart_timelapse_daemon()\n",
"step-ids": [
8,
9,
10,
11,
12
]
}
|
[
8,
9,
10,
11,
12
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, required=True)
parser.add_argument('--task', type=str, required=True)
args = parser.parse_args()
if not os.path.exists(args.dir):
print('dir:{} not exist'.format(args.dir))
exit(0)
result_dir = args.task
if not os.path.exists(result_dir):
os.makedirs(result_dir)
class_images = {}
dirs = ['same.high', 'same.low', 'diff.high', 'diff.low']
check_info = os.path.join(args.dir, 'info.csv')
if not os.path.exists(check_info):
print('file:{} not exist'.format(check_info))
check_list = {}
start_t = time.time()
with open(check_info, 'r') as f:
line_str = f.readline()
line_str = f.readline()
while line_str:
line_str = line_str.strip()
file_name, label_id, class_id, class_acc = line_str.split(',')
class_acc = float(class_acc)
if file_name == '327_20180115133328530498_00_004_5.jpg':
print('got')
init_id = class_id
if label_id == class_id:
if class_acc < 0.8:
init_id = label_id
_dir = 'same.low'
elif class_acc < 0.95:
_dir = 'same.high'
else:
line_str = f.readline()
continue
elif class_acc < 0.8:
init_id = label_id
_dir = 'diff.low'
else:
_dir = 'diff.high'
dest_dir = os.path.join(result_dir, _dir)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
if _dir not in check_list:
check_list[_dir] = []
task_str = '{},{}\n'.format(file_name, init_id)
check_list[_dir].append(task_str)
dest_path = os.path.join(dest_dir, file_name)
file_path = os.path.join(args.dir, _dir, class_id, file_name)
shutil.copy(file_path, dest_path)
line_str = f.readline()
for _dir, _dir_list in check_list.items():
csv_path = os.path.join(result_dir, _dir, 'ImageType.csv')
with open(csv_path, 'w') as f:
for _str in _dir_list:
f.write(_str)
end_t = time.time()
print('finish in {} s'.format(end_t - start_t))
<|reserved_special_token_1|>
import os
import time
import shutil
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, required=True)
parser.add_argument('--task', type=str, required=True)
args = parser.parse_args()
if not os.path.exists(args.dir):
print('dir:{} not exist'.format(args.dir))
exit(0)
result_dir = args.task
if not os.path.exists(result_dir):
os.makedirs(result_dir)
class_images = {}
dirs = ['same.high', 'same.low', 'diff.high', 'diff.low']
check_info = os.path.join(args.dir, 'info.csv')
if not os.path.exists(check_info):
print('file:{} not exist'.format(check_info))
check_list = {}
start_t = time.time()
with open(check_info, 'r') as f:
line_str = f.readline()
line_str = f.readline()
while line_str:
line_str = line_str.strip()
file_name, label_id, class_id, class_acc = line_str.split(',')
class_acc = float(class_acc)
if file_name == '327_20180115133328530498_00_004_5.jpg':
print('got')
init_id = class_id
if label_id == class_id:
if class_acc < 0.8:
init_id = label_id
_dir = 'same.low'
elif class_acc < 0.95:
_dir = 'same.high'
else:
line_str = f.readline()
continue
elif class_acc < 0.8:
init_id = label_id
_dir = 'diff.low'
else:
_dir = 'diff.high'
dest_dir = os.path.join(result_dir, _dir)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
if _dir not in check_list:
check_list[_dir] = []
task_str = '{},{}\n'.format(file_name, init_id)
check_list[_dir].append(task_str)
dest_path = os.path.join(dest_dir, file_name)
file_path = os.path.join(args.dir, _dir, class_id, file_name)
shutil.copy(file_path, dest_path)
line_str = f.readline()
for _dir, _dir_list in check_list.items():
csv_path = os.path.join(result_dir, _dir, 'ImageType.csv')
with open(csv_path, 'w') as f:
for _str in _dir_list:
f.write(_str)
end_t = time.time()
print('finish in {} s'.format(end_t - start_t))
<|reserved_special_token_1|>
# -*-coding:utf-8-*-
import os
import time
import shutil
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, required=True)
parser.add_argument('--task', type=str, required=True)
args = parser.parse_args()
if not os.path.exists(args.dir):
print("dir:{} not exist".format(args.dir))
exit(0)
result_dir = args.task
if not os.path.exists(result_dir):
os.makedirs(result_dir)
class_images = {}
dirs = ['same.high', 'same.low', 'diff.high', 'diff.low']
check_info = os.path.join(args.dir, "info.csv")
if not os.path.exists(check_info):
print("file:{} not exist".format(check_info))
check_list = {}
start_t = time.time()
with open(check_info, "r") as f:
line_str = f.readline()
# skip first line
line_str = f.readline()
while line_str:
line_str = line_str.strip()
# label_id: id labeled in dataset
# class_id: id predict
file_name, label_id, class_id, class_acc = line_str.split(",")
class_acc = float(class_acc)
if file_name == '327_20180115133328530498_00_004_5.jpg':
print("got")
init_id = class_id
if label_id == class_id:
if class_acc < 0.8:
init_id = label_id
_dir = 'same.low'
elif class_acc < 0.95:
_dir = 'same.high'
else:
line_str = f.readline()
continue
else:
if class_acc < 0.8:
init_id = label_id
_dir = 'diff.low'
else:
_dir = 'diff.high'
dest_dir = os.path.join(result_dir, _dir)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
if _dir not in check_list:
check_list[_dir] = []
task_str = "{},{}\n".format(file_name, init_id)
check_list[_dir].append(task_str)
dest_path = os.path.join(dest_dir, file_name)
file_path = os.path.join(args.dir, _dir, class_id, file_name)
shutil.copy(file_path, dest_path)
line_str = f.readline()
for _dir, _dir_list in check_list.items():
csv_path = os.path.join(result_dir, _dir, "ImageType.csv")
with open(csv_path, "w") as f:
for _str in _dir_list:
f.write(_str)
end_t = time.time()
print("finish in {} s".format(end_t - start_t))
|
flexible
|
{
"blob_id": "dc3a3f5675860792ecfa7dcd5180402d89b669b1",
"index": 8254,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dir', type=str, required=True)\n parser.add_argument('--task', type=str, required=True)\n args = parser.parse_args()\n if not os.path.exists(args.dir):\n print('dir:{} not exist'.format(args.dir))\n exit(0)\n result_dir = args.task\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n class_images = {}\n dirs = ['same.high', 'same.low', 'diff.high', 'diff.low']\n check_info = os.path.join(args.dir, 'info.csv')\n if not os.path.exists(check_info):\n print('file:{} not exist'.format(check_info))\n check_list = {}\n start_t = time.time()\n with open(check_info, 'r') as f:\n line_str = f.readline()\n line_str = f.readline()\n while line_str:\n line_str = line_str.strip()\n file_name, label_id, class_id, class_acc = line_str.split(',')\n class_acc = float(class_acc)\n if file_name == '327_20180115133328530498_00_004_5.jpg':\n print('got')\n init_id = class_id\n if label_id == class_id:\n if class_acc < 0.8:\n init_id = label_id\n _dir = 'same.low'\n elif class_acc < 0.95:\n _dir = 'same.high'\n else:\n line_str = f.readline()\n continue\n elif class_acc < 0.8:\n init_id = label_id\n _dir = 'diff.low'\n else:\n _dir = 'diff.high'\n dest_dir = os.path.join(result_dir, _dir)\n if not os.path.exists(dest_dir):\n os.makedirs(dest_dir)\n if _dir not in check_list:\n check_list[_dir] = []\n task_str = '{},{}\\n'.format(file_name, init_id)\n check_list[_dir].append(task_str)\n dest_path = os.path.join(dest_dir, file_name)\n file_path = os.path.join(args.dir, _dir, class_id, file_name)\n shutil.copy(file_path, dest_path)\n line_str = f.readline()\n for _dir, _dir_list in check_list.items():\n csv_path = os.path.join(result_dir, _dir, 'ImageType.csv')\n with open(csv_path, 'w') as f:\n for _str in _dir_list:\n f.write(_str)\n end_t = time.time()\n print('finish in {} s'.format(end_t - start_t))\n",
"step-3": "import os\nimport time\nimport shutil\nimport argparse\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dir', type=str, required=True)\n parser.add_argument('--task', type=str, required=True)\n args = parser.parse_args()\n if not os.path.exists(args.dir):\n print('dir:{} not exist'.format(args.dir))\n exit(0)\n result_dir = args.task\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n class_images = {}\n dirs = ['same.high', 'same.low', 'diff.high', 'diff.low']\n check_info = os.path.join(args.dir, 'info.csv')\n if not os.path.exists(check_info):\n print('file:{} not exist'.format(check_info))\n check_list = {}\n start_t = time.time()\n with open(check_info, 'r') as f:\n line_str = f.readline()\n line_str = f.readline()\n while line_str:\n line_str = line_str.strip()\n file_name, label_id, class_id, class_acc = line_str.split(',')\n class_acc = float(class_acc)\n if file_name == '327_20180115133328530498_00_004_5.jpg':\n print('got')\n init_id = class_id\n if label_id == class_id:\n if class_acc < 0.8:\n init_id = label_id\n _dir = 'same.low'\n elif class_acc < 0.95:\n _dir = 'same.high'\n else:\n line_str = f.readline()\n continue\n elif class_acc < 0.8:\n init_id = label_id\n _dir = 'diff.low'\n else:\n _dir = 'diff.high'\n dest_dir = os.path.join(result_dir, _dir)\n if not os.path.exists(dest_dir):\n os.makedirs(dest_dir)\n if _dir not in check_list:\n check_list[_dir] = []\n task_str = '{},{}\\n'.format(file_name, init_id)\n check_list[_dir].append(task_str)\n dest_path = os.path.join(dest_dir, file_name)\n file_path = os.path.join(args.dir, _dir, class_id, file_name)\n shutil.copy(file_path, dest_path)\n line_str = f.readline()\n for _dir, _dir_list in check_list.items():\n csv_path = os.path.join(result_dir, _dir, 'ImageType.csv')\n with open(csv_path, 'w') as f:\n for _str in _dir_list:\n f.write(_str)\n end_t = time.time()\n print('finish in {} s'.format(end_t - start_t))\n",
"step-4": "# -*-coding:utf-8-*-\n\nimport os\nimport time\nimport shutil\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--dir', type=str, required=True)\n parser.add_argument('--task', type=str, required=True)\n args = parser.parse_args()\n\n if not os.path.exists(args.dir):\n print(\"dir:{} not exist\".format(args.dir))\n exit(0)\n\n result_dir = args.task\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n\n class_images = {}\n dirs = ['same.high', 'same.low', 'diff.high', 'diff.low']\n\n check_info = os.path.join(args.dir, \"info.csv\")\n if not os.path.exists(check_info):\n print(\"file:{} not exist\".format(check_info))\n\n check_list = {}\n\n start_t = time.time()\n\n with open(check_info, \"r\") as f:\n line_str = f.readline()\n # skip first line\n line_str = f.readline()\n while line_str:\n line_str = line_str.strip()\n\n # label_id: id labeled in dataset\n # class_id: id predict\n file_name, label_id, class_id, class_acc = line_str.split(\",\")\n class_acc = float(class_acc)\n\n if file_name == '327_20180115133328530498_00_004_5.jpg':\n print(\"got\")\n\n init_id = class_id\n if label_id == class_id:\n if class_acc < 0.8:\n init_id = label_id\n _dir = 'same.low'\n elif class_acc < 0.95:\n _dir = 'same.high'\n else:\n line_str = f.readline()\n continue\n else:\n if class_acc < 0.8:\n init_id = label_id\n _dir = 'diff.low'\n else:\n _dir = 'diff.high'\n\n dest_dir = os.path.join(result_dir, _dir)\n if not os.path.exists(dest_dir):\n os.makedirs(dest_dir)\n\n if _dir not in check_list:\n check_list[_dir] = []\n\n task_str = \"{},{}\\n\".format(file_name, init_id)\n check_list[_dir].append(task_str)\n\n dest_path = os.path.join(dest_dir, file_name)\n file_path = os.path.join(args.dir, _dir, class_id, file_name)\n\n shutil.copy(file_path, dest_path)\n\n line_str = f.readline()\n\n for _dir, _dir_list in check_list.items():\n csv_path = os.path.join(result_dir, _dir, \"ImageType.csv\")\n with open(csv_path, \"w\") as f:\n for _str in _dir_list:\n f.write(_str)\n\n end_t = time.time()\n print(\"finish in {} s\".format(end_t - start_t))\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def letterToIndex(letter):
return all_letters.find(letter)
<|reserved_special_token_0|>
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(input_size + hidden_size, output_size)
self.softmax = nn.LogSoftmax()
def forward(self, input, hidden):
combined = torch.cat((input, hidden), 1)
hidden = self.i2h(combined)
output = self.i2o(combined)
output = self.softmax(output)
return output, hidden
def initHidden(self):
return Variable(torch.zeros(1, self.hidden_size))
<|reserved_special_token_0|>
def evaluate(line_tensor):
hidden = rnn.initHidden()
for i in range(line_tensor.size()[0]):
output, hidden = rnn(line_tensor[i], hidden)
return output
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def letterToIndex(letter):
return all_letters.find(letter)
<|reserved_special_token_0|>
def lineToTensor(line):
tensor = torch.zeros(len(line), 1, n_letters)
for li, letter in enumerate(line):
tensor[li][0][letterToIndex(letter)] = 1
return tensor
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(input_size + hidden_size, output_size)
self.softmax = nn.LogSoftmax()
def forward(self, input, hidden):
combined = torch.cat((input, hidden), 1)
hidden = self.i2h(combined)
output = self.i2o(combined)
output = self.softmax(output)
return output, hidden
def initHidden(self):
return Variable(torch.zeros(1, self.hidden_size))
<|reserved_special_token_0|>
def evaluate(line_tensor):
hidden = rnn.initHidden()
for i in range(line_tensor.size()[0]):
output, hidden = rnn(line_tensor[i], hidden)
return output
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def letterToIndex(letter):
return all_letters.find(letter)
def letterToTensor(letter):
tensor = torch.zeros(1, n_letters)
tensor[0][letterToIndex(letter)] = 1
return tensor
def lineToTensor(line):
tensor = torch.zeros(len(line), 1, n_letters)
for li, letter in enumerate(line):
tensor[li][0][letterToIndex(letter)] = 1
return tensor
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(input_size + hidden_size, output_size)
self.softmax = nn.LogSoftmax()
def forward(self, input, hidden):
combined = torch.cat((input, hidden), 1)
hidden = self.i2h(combined)
output = self.i2o(combined)
output = self.softmax(output)
return output, hidden
def initHidden(self):
return Variable(torch.zeros(1, self.hidden_size))
<|reserved_special_token_0|>
rnn.load_state_dict(torch.load('medicalTermsModel'))
def evaluate(line_tensor):
hidden = rnn.initHidden()
for i in range(line_tensor.size()[0]):
output, hidden = rnn(line_tensor[i], hidden)
return output
def predict(input_line, n_predictions=1):
output = evaluate(Variable(lineToTensor(input_line)))
topv, topi = output.data.topk(n_predictions, 1, True)
predictions = []
for i in range(n_predictions):
value = topv[0][i]
category_index = topi[0][i]
predictions.append([value, all_categories[category_index]])
if category_index == 0:
predictions = str(input_line), str(all_categories[category_index])
else:
predictions = str(input_line), str(all_categories[category_index])
return predictions
<|reserved_special_token_1|>
<|reserved_special_token_0|>
all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)
def letterToIndex(letter):
return all_letters.find(letter)
def letterToTensor(letter):
tensor = torch.zeros(1, n_letters)
tensor[0][letterToIndex(letter)] = 1
return tensor
def lineToTensor(line):
tensor = torch.zeros(len(line), 1, n_letters)
for li, letter in enumerate(line):
tensor[li][0][letterToIndex(letter)] = 1
return tensor
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(input_size + hidden_size, output_size)
self.softmax = nn.LogSoftmax()
def forward(self, input, hidden):
combined = torch.cat((input, hidden), 1)
hidden = self.i2h(combined)
output = self.i2o(combined)
output = self.softmax(output)
return output, hidden
def initHidden(self):
return Variable(torch.zeros(1, self.hidden_size))
all_categories = ['Medical Term', 'Common English Term']
n_hidden = 128
n_categories = 2
rnn = RNN(n_letters, n_hidden, n_categories)
rnn.load_state_dict(torch.load('medicalTermsModel'))
def evaluate(line_tensor):
hidden = rnn.initHidden()
for i in range(line_tensor.size()[0]):
output, hidden = rnn(line_tensor[i], hidden)
return output
def predict(input_line, n_predictions=1):
output = evaluate(Variable(lineToTensor(input_line)))
topv, topi = output.data.topk(n_predictions, 1, True)
predictions = []
for i in range(n_predictions):
value = topv[0][i]
category_index = topi[0][i]
predictions.append([value, all_categories[category_index]])
if category_index == 0:
predictions = str(input_line), str(all_categories[category_index])
else:
predictions = str(input_line), str(all_categories[category_index])
return predictions
<|reserved_special_token_1|>
import torch.nn as nn
from torch.autograd import Variable
import torch
import string
all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)
#Find letter index from all_letters, e.g. "a" = 0
def letterToIndex(letter):
return all_letters.find(letter)
#Only for demonstation
def letterToTensor(letter):
tensor = torch.zeros(1, n_letters)
tensor[0][letterToIndex(letter)] = 1
return tensor
#Turn a line into a tensor
#or an array of one-hot letter vectors
def lineToTensor(line):
tensor = torch.zeros(len(line), 1, n_letters)
for li, letter in enumerate(line):
tensor[li][0][letterToIndex(letter)] = 1
return tensor
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(input_size + hidden_size, output_size)
self.softmax = nn.LogSoftmax()
def forward(self, input, hidden):
combined = torch.cat((input, hidden), 1)
hidden = self.i2h(combined)
output = self.i2o(combined)
output = self.softmax(output)
return output, hidden
def initHidden(self):
return Variable(torch.zeros(1, self.hidden_size))
all_categories = ['Medical Term', 'Common English Term']
n_hidden = 128
n_categories = 2
rnn = RNN(n_letters, n_hidden, n_categories)
rnn.load_state_dict(torch.load('medicalTermsModel'))
# Just return an output given a line
def evaluate(line_tensor):
hidden = rnn.initHidden()
for i in range(line_tensor.size()[0]):
output, hidden = rnn(line_tensor[i], hidden)
return output
def predict(input_line, n_predictions=1):
output = evaluate(Variable(lineToTensor(input_line)))
# Get top N categories
topv, topi = output.data.topk(n_predictions, 1, True)
predictions = []
for i in range(n_predictions):
value = topv[0][i]
category_index = topi[0][i]
predictions.append([value, all_categories[category_index]])
if category_index == 0:
# print('\n> %s' % input_line)
predictions = (str(input_line), str(all_categories[category_index]))
else:
predictions = (str(input_line), str(all_categories[category_index]))
return predictions
|
flexible
|
{
"blob_id": "aa24442624aebeb2777f16a826cf59859d7870ba",
"index": 8744,
"step-1": "<mask token>\n\n\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n\n<mask token>\n\n\nclass RNN(nn.Module):\n\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n self.hidden_size = hidden_size\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.softmax = nn.LogSoftmax()\n\n def forward(self, input, hidden):\n combined = torch.cat((input, hidden), 1)\n hidden = self.i2h(combined)\n output = self.i2o(combined)\n output = self.softmax(output)\n return output, hidden\n\n def initHidden(self):\n return Variable(torch.zeros(1, self.hidden_size))\n\n\n<mask token>\n\n\ndef evaluate(line_tensor):\n hidden = rnn.initHidden()\n for i in range(line_tensor.size()[0]):\n output, hidden = rnn(line_tensor[i], hidden)\n return output\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n\n<mask token>\n\n\ndef lineToTensor(line):\n tensor = torch.zeros(len(line), 1, n_letters)\n for li, letter in enumerate(line):\n tensor[li][0][letterToIndex(letter)] = 1\n return tensor\n\n\nclass RNN(nn.Module):\n\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n self.hidden_size = hidden_size\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.softmax = nn.LogSoftmax()\n\n def forward(self, input, hidden):\n combined = torch.cat((input, hidden), 1)\n hidden = self.i2h(combined)\n output = self.i2o(combined)\n output = self.softmax(output)\n return output, hidden\n\n def initHidden(self):\n return Variable(torch.zeros(1, self.hidden_size))\n\n\n<mask token>\n\n\ndef evaluate(line_tensor):\n hidden = rnn.initHidden()\n for i in range(line_tensor.size()[0]):\n output, hidden = rnn(line_tensor[i], hidden)\n return output\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n\ndef letterToTensor(letter):\n tensor = torch.zeros(1, n_letters)\n tensor[0][letterToIndex(letter)] = 1\n return tensor\n\n\ndef lineToTensor(line):\n tensor = torch.zeros(len(line), 1, n_letters)\n for li, letter in enumerate(line):\n tensor[li][0][letterToIndex(letter)] = 1\n return tensor\n\n\nclass RNN(nn.Module):\n\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n self.hidden_size = hidden_size\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.softmax = nn.LogSoftmax()\n\n def forward(self, input, hidden):\n combined = torch.cat((input, hidden), 1)\n hidden = self.i2h(combined)\n output = self.i2o(combined)\n output = self.softmax(output)\n return output, hidden\n\n def initHidden(self):\n return Variable(torch.zeros(1, self.hidden_size))\n\n\n<mask token>\nrnn.load_state_dict(torch.load('medicalTermsModel'))\n\n\ndef evaluate(line_tensor):\n hidden = rnn.initHidden()\n for i in range(line_tensor.size()[0]):\n output, hidden = rnn(line_tensor[i], hidden)\n return output\n\n\ndef predict(input_line, n_predictions=1):\n output = evaluate(Variable(lineToTensor(input_line)))\n topv, topi = output.data.topk(n_predictions, 1, True)\n predictions = []\n for i in range(n_predictions):\n value = topv[0][i]\n category_index = topi[0][i]\n predictions.append([value, all_categories[category_index]])\n if category_index == 0:\n predictions = str(input_line), str(all_categories[category_index])\n else:\n predictions = str(input_line), str(all_categories[category_index])\n return predictions\n",
"step-4": "<mask token>\nall_letters = string.ascii_letters + \" .,;'\"\nn_letters = len(all_letters)\n\n\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n\ndef letterToTensor(letter):\n tensor = torch.zeros(1, n_letters)\n tensor[0][letterToIndex(letter)] = 1\n return tensor\n\n\ndef lineToTensor(line):\n tensor = torch.zeros(len(line), 1, n_letters)\n for li, letter in enumerate(line):\n tensor[li][0][letterToIndex(letter)] = 1\n return tensor\n\n\nclass RNN(nn.Module):\n\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n self.hidden_size = hidden_size\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.softmax = nn.LogSoftmax()\n\n def forward(self, input, hidden):\n combined = torch.cat((input, hidden), 1)\n hidden = self.i2h(combined)\n output = self.i2o(combined)\n output = self.softmax(output)\n return output, hidden\n\n def initHidden(self):\n return Variable(torch.zeros(1, self.hidden_size))\n\n\nall_categories = ['Medical Term', 'Common English Term']\nn_hidden = 128\nn_categories = 2\nrnn = RNN(n_letters, n_hidden, n_categories)\nrnn.load_state_dict(torch.load('medicalTermsModel'))\n\n\ndef evaluate(line_tensor):\n hidden = rnn.initHidden()\n for i in range(line_tensor.size()[0]):\n output, hidden = rnn(line_tensor[i], hidden)\n return output\n\n\ndef predict(input_line, n_predictions=1):\n output = evaluate(Variable(lineToTensor(input_line)))\n topv, topi = output.data.topk(n_predictions, 1, True)\n predictions = []\n for i in range(n_predictions):\n value = topv[0][i]\n category_index = topi[0][i]\n predictions.append([value, all_categories[category_index]])\n if category_index == 0:\n predictions = str(input_line), str(all_categories[category_index])\n else:\n predictions = str(input_line), str(all_categories[category_index])\n return predictions\n",
"step-5": "import torch.nn as nn\nfrom torch.autograd import Variable\nimport torch\nimport string\n\nall_letters = string.ascii_letters + \" .,;'\"\nn_letters = len(all_letters)\n\n#Find letter index from all_letters, e.g. \"a\" = 0\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n#Only for demonstation\ndef letterToTensor(letter):\n tensor = torch.zeros(1, n_letters)\n tensor[0][letterToIndex(letter)] = 1\n return tensor\n\n#Turn a line into a tensor\n#or an array of one-hot letter vectors\n\ndef lineToTensor(line):\n tensor = torch.zeros(len(line), 1, n_letters)\n for li, letter in enumerate(line):\n tensor[li][0][letterToIndex(letter)] = 1\n return tensor\n\nclass RNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n\n self.hidden_size = hidden_size\n\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.softmax = nn.LogSoftmax()\n\n def forward(self, input, hidden):\n combined = torch.cat((input, hidden), 1)\n hidden = self.i2h(combined)\n output = self.i2o(combined)\n output = self.softmax(output)\n return output, hidden\n\n def initHidden(self):\n return Variable(torch.zeros(1, self.hidden_size))\n\nall_categories = ['Medical Term', 'Common English Term']\n\nn_hidden = 128\nn_categories = 2\n\nrnn = RNN(n_letters, n_hidden, n_categories)\nrnn.load_state_dict(torch.load('medicalTermsModel'))\n\n# Just return an output given a line\ndef evaluate(line_tensor):\n hidden = rnn.initHidden()\n\n for i in range(line_tensor.size()[0]):\n output, hidden = rnn(line_tensor[i], hidden)\n\n return output\n\ndef predict(input_line, n_predictions=1):\n\n output = evaluate(Variable(lineToTensor(input_line)))\n\n # Get top N categories\n topv, topi = output.data.topk(n_predictions, 1, True)\n predictions = []\n\n for i in range(n_predictions):\n value = topv[0][i]\n category_index = topi[0][i]\n predictions.append([value, all_categories[category_index]])\n if category_index == 0:\n # print('\\n> %s' % input_line)\n predictions = (str(input_line), str(all_categories[category_index]))\n else:\n predictions = (str(input_line), str(all_categories[category_index]))\n return predictions\n",
"step-ids": [
6,
7,
10,
11,
13
]
}
|
[
6,
7,
10,
11,
13
] |
import zipfile
zzz = zipfile.ZipFile('channel.zip','r')
filestr = '90052'
comment = []
for i in range(1000):
fname = filestr + ".txt"
for j in zzz.infolist():
if j.filename == fname :
print j.comment
comment.append(j.comment)
break
inzzz = zzz.open(fname).read()
print 'fname = ' + fname
print 'inzzz = ' + inzzz
try:
filestr = inzzz.split('is ')[1].split('\n')[0]
except IndexError:
print " ".join(comment)
break
#zzz.read()
|
normal
|
{
"blob_id": "34ad2e6fc7167766dac1ca962cab40511c89ad68",
"index": 7551,
"step-1": "import zipfile\n\nzzz = zipfile.ZipFile('channel.zip','r')\nfilestr = '90052'\ncomment = []\nfor i in range(1000):\n fname = filestr + \".txt\"\n for j in zzz.infolist():\n if j.filename == fname :\n print j.comment\n comment.append(j.comment)\n break\n inzzz = zzz.open(fname).read()\n print 'fname = ' + fname\n print 'inzzz = ' + inzzz\n try:\n filestr = inzzz.split('is ')[1].split('\\n')[0] \n except IndexError:\n print \" \".join(comment)\n break\n\n#zzz.read()\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
"""
7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of
pizza toppings until they enter a 'quit' value. As they enter each topping,
print a message saying you’ll add that topping to their pizza.
"""
if __name__ == '__main__':
topping = None
while topping != "quit":
if topping:
print("I'll add %s to your pizza!" % topping)
topping = input("What topping would you like? (enter 'quit' when you are done.) ")
|
normal
|
{
"blob_id": "4d07795543989fe481e1141756f988d276f82c02",
"index": 5348,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n topping = None\n while topping != 'quit':\n if topping:\n print(\"I'll add %s to your pizza!\" % topping)\n topping = input(\n \"What topping would you like? (enter 'quit' when you are done.) \")\n",
"step-3": "\"\"\"\n7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of\npizza toppings until they enter a 'quit' value. As they enter each topping,\nprint a message saying you’ll add that topping to their pizza.\n\"\"\"\nif __name__ == '__main__':\n topping = None\n while topping != \"quit\":\n if topping:\n print(\"I'll add %s to your pizza!\" % topping)\n topping = input(\"What topping would you like? (enter 'quit' when you are done.) \")",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
def _get_user_name():
"""
Get the current user.
"""
return pwd.getpwuid(os.getuid())[0]
def _user_belongs_to(group_name):
"""
Check that the current user belongs to the ``group_name`` group.
"""
user_name = _get_user_name()
groups = _get_user_groups(user_name)
return group_name in groups
<|reserved_special_token_0|>
def _check_vmware():
"""
Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must
*not* be running together with S2E.
"""
for proc in psutil.process_iter():
try:
if proc.name() == 'vmware-vmx':
raise CommandError(
'S2E uses KVM to build images. VMware is currently running, which is not compatible with KVM. Please close all VMware VMs and try again.'
)
except NoSuchProcess:
pass
def _check_kvm():
"""
Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.
"""
if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):
raise CommandError(
'KVM interface not found - check that /dev/kvm exists. Alternatively, you can disable KVM (-n option) or download pre-built images (-d option)'
)
<|reserved_special_token_0|>
def _get_base_image_and_app(image_name):
x = image_name.split('/')
if len(x) == 1:
return x[0], None
if len(x) == 2:
return x
raise CommandError(f'Invalid image name {image_name}')
<|reserved_special_token_0|>
def _check_product_keys(image_descriptors, image_names):
missing_keys = []
for image_name in image_names:
image = image_descriptors[image_name]
if 'product_key' in image:
if not image['product_key']:
missing_keys.append(image_name)
ios = image_descriptors[image_name].get('os', {})
if 'product_key' in ios:
if not ios['product_key']:
missing_keys.append(image_name)
if missing_keys:
logger.error('The following images require a product key:')
for image in missing_keys:
logger.error(' * %s', image)
raise CommandError('Please update images.json and/or apps.json.')
def _check_iso(templates, app_templates, iso_dir, image_names):
for image_name in image_names:
base_image, app_name = _get_base_image_and_app(image_name)
descriptors = [templates[base_image]]
if app_name:
descriptors.append(app_templates[app_name])
for desc in descriptors:
iso = desc.get('iso', {})
if iso.get('url', ''):
continue
name = iso.get('name', '')
if not name:
continue
if not iso_dir:
raise CommandError(
f'Please use the --iso-dir option to specify the path to a folder that contains {name}'
)
path = os.path.join(iso_dir, name)
if not os.path.exists(path):
raise CommandError(
f'The image {image_name} requires {path}, which could not be found'
)
<|reserved_special_token_0|>
class Command(EnvCommand):
"""
Builds an image.
"""
help = 'Build an image.'
def __init__(self):
super().__init__()
self._headless = True
self._use_kvm = True
self._num_cores = 1
self._has_cow = False
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument('name', help=
'The name of the image to build. If empty, shows available images',
nargs='*')
parser.add_argument('-g', '--gui', action='store_true', help=
'Display QEMU GUI during image build')
parser.add_argument('-c', '--cores', required=False, default=2,
type=int, help=
'The number of cores used when building the VM image. Defaults to 2'
)
parser.add_argument('-x', '--clean', action='store_true', help=
'Deletes all images and rebuild them from scratch')
parser.add_argument('-a', '--archive', action='store_true', help=
'Creates an archive for the specified image')
parser.add_argument('-p', '--ftp-port', required=False, default=
15468, type=int, help=
'Port for the internal FTP server to receive files from guest VMs during build'
)
parser.add_argument('-d', '--download', action='store_true', help=
'Download image from the repository instead of building it')
parser.add_argument('-i', '--iso-dir', help=
'Path to folder that stores ISO files of Windows images')
parser.add_argument('-n', '--no-kvm', action='store_true', help=
'Disable KVM during image build')
def handle(self, *args, **options):
if options['gui']:
self._headless = False
if options['no_kvm']:
self._use_kvm = False
self._num_cores = options['cores']
if not os.path.exists(self.image_path()):
os.makedirs(self.image_path())
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
if options['clean']:
self._invoke_make(img_build_dir, ['clean'])
return
image_names = options['name']
templates = get_image_templates(img_build_dir)
app_templates = get_app_templates(img_build_dir)
images, image_groups, image_descriptors = get_all_images(templates,
app_templates)
if not image_names:
self._print_image_list(images, image_groups, image_descriptors)
print(
"""
Run ``s2e image_build <name>`` to build an image. Note that you must run ``s2e build`` **before** building an image"""
)
return
image_names = translate_image_name(images, image_groups, image_names)
logger.info('The following images will be built:')
for image in image_names:
logger.info(' * %s', image)
if options['download']:
_download_images(self.image_path(), image_names, templates)
return
rule_names = image_names
if options['archive']:
rule_names = _get_archive_rules(self.image_path(), image_names)
iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'
] else None
_check_product_keys(image_descriptors, image_names)
_check_iso(templates, app_templates, iso_dir, image_names)
if self._use_kvm:
_check_kvm()
_check_groups_kvm()
_check_groups_docker()
_check_vmlinux()
self._has_cow = _check_cow(self.image_path())
if self._use_kvm:
_check_virtualbox()
_check_vmware()
if not _is_port_available(options['ftp_port']):
raise CommandError(
f"localhost:{options['ftp_port']} is not available. Check that the port is free or specify a port with --ftp-port"
)
self._clone_kernel()
server = _start_ftp_server(self.image_path(), options['ftp_port'])
self._invoke_make(img_build_dir, rule_names, options['ftp_port'],
iso_dir)
logger.success("Built image(s) '%s'", ' '.join(image_names))
server.close_all()
def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):
env = os.environ.copy()
env['S2E_INSTALL_ROOT'] = self.install_path()
env['S2E_LINUX_KERNELS_ROOT'] = self.source_path(CONSTANTS['repos']
['images']['linux'])
env['OUTDIR'] = self.image_path()
env['QEMU_FTP_PORT'] = str(ftp_port)
env['ISODIR'] = iso_dir if iso_dir else ''
env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'
logger.debug('Invoking makefile with:')
logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])
logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env[
'S2E_LINUX_KERNELS_ROOT'])
logger.debug('export OUTDIR=%s', env['OUTDIR'])
logger.debug('export ISODIR=%s', env.get('ISODIR', ''))
logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get(
'DEBUG_INTERMEDIATE_RULES', ''))
if self._headless:
logger.warning(
'Image creation will run in headless mode. Use --gui to see graphic output for debugging'
)
else:
env['GRAPHICS'] = ''
if not self._use_kvm:
env['QEMU_KVM'] = ''
logger.warning('Image build without KVM. This will be slow')
try:
make = sh.Command('make').bake(file=os.path.join(img_build_dir,
'Makefile'), directory=self.image_path(), _env=env, _fg=True)
make_image = make.bake(j=self._num_cores, r=True,
warn_undefined_variables=True)
make_image(sorted(rule_names))
except ErrorReturnCode as e:
raise CommandError(e) from e
def _clone_kernel(self):
kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])
if os.path.exists(kernels_root):
logger.info('Kernel repository already exists in %s', kernels_root)
return
logger.info('Cloning kernels repository to %s', kernels_root)
kernels_repo = CONSTANTS['repos']['images']['linux']
repos.git_clone_to_source(self.env_path(), kernels_repo)
def _print_image_list(self, images, image_groups, image_descriptors):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
templates = get_image_templates(img_build_dir)
if not templates:
images_json_path = os.path.join(img_build_dir, 'images.json')
raise CommandError(
f'No images available to build. Make sure that {images_json_path} exists and is valid'
)
def get_max_len(lst):
ret = 0
for item in lst:
if len(item) > ret:
ret = len(item)
return ret
print('Available image groups:')
max_group_len = get_max_len(image_groups)
for group in image_groups:
print(f' * {group:{max_group_len}} - Build {group} images')
print('\nAvailable images:')
max_image_len = get_max_len(images)
for image in sorted(images):
print(
f" * {image:{max_image_len}} - {image_descriptors[image]['name']}"
)
def _print_apps_list(self):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
app_templates = get_app_templates(img_build_dir)
if not app_templates:
apps_json_path = os.path.join(img_build_dir, 'apps.json')
raise CommandError(
f'No apps available to build. Make sure that {apps_json_path} exists and is valid'
)
print('Available applications:')
for app_template, desc in sorted(app_templates.items()):
for base_image in desc['base_images']:
print(f" * {base_image}/{app_template} - {desc['name']}")
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def _get_user_name():
"""
Get the current user.
"""
return pwd.getpwuid(os.getuid())[0]
def _user_belongs_to(group_name):
"""
Check that the current user belongs to the ``group_name`` group.
"""
user_name = _get_user_name()
groups = _get_user_groups(user_name)
return group_name in groups
<|reserved_special_token_0|>
def _check_vmware():
"""
Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must
*not* be running together with S2E.
"""
for proc in psutil.process_iter():
try:
if proc.name() == 'vmware-vmx':
raise CommandError(
'S2E uses KVM to build images. VMware is currently running, which is not compatible with KVM. Please close all VMware VMs and try again.'
)
except NoSuchProcess:
pass
def _check_kvm():
"""
Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.
"""
if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):
raise CommandError(
'KVM interface not found - check that /dev/kvm exists. Alternatively, you can disable KVM (-n option) or download pre-built images (-d option)'
)
def _check_vmlinux():
"""
Check that /boot/vmlinux* files are readable. This is important for guestfish.
"""
try:
for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):
with open(f, 'rb'):
pass
except IOError:
raise CommandError(
"""Make sure that the kernels in /boot are readable. This is required for guestfish. Please run the following command:
sudo chmod ugo+r /boot/vmlinu*"""
) from None
<|reserved_special_token_0|>
def _raise_invalid_image(image_name):
raise CommandError(
f'Invalid image name: {image_name}. Run ``s2e image_build`` to list available images'
)
def _get_base_image_and_app(image_name):
x = image_name.split('/')
if len(x) == 1:
return x[0], None
if len(x) == 2:
return x
raise CommandError(f'Invalid image name {image_name}')
def _has_app_image(image_names):
for name in image_names:
if '/' in name:
return True
return False
def _check_product_keys(image_descriptors, image_names):
missing_keys = []
for image_name in image_names:
image = image_descriptors[image_name]
if 'product_key' in image:
if not image['product_key']:
missing_keys.append(image_name)
ios = image_descriptors[image_name].get('os', {})
if 'product_key' in ios:
if not ios['product_key']:
missing_keys.append(image_name)
if missing_keys:
logger.error('The following images require a product key:')
for image in missing_keys:
logger.error(' * %s', image)
raise CommandError('Please update images.json and/or apps.json.')
def _check_iso(templates, app_templates, iso_dir, image_names):
for image_name in image_names:
base_image, app_name = _get_base_image_and_app(image_name)
descriptors = [templates[base_image]]
if app_name:
descriptors.append(app_templates[app_name])
for desc in descriptors:
iso = desc.get('iso', {})
if iso.get('url', ''):
continue
name = iso.get('name', '')
if not name:
continue
if not iso_dir:
raise CommandError(
f'Please use the --iso-dir option to specify the path to a folder that contains {name}'
)
path = os.path.join(iso_dir, name)
if not os.path.exists(path):
raise CommandError(
f'The image {image_name} requires {path}, which could not be found'
)
<|reserved_special_token_0|>
def _start_ftp_server(image_path, port):
authorizer = DummyAuthorizer()
authorizer.add_anonymous(image_path, perm='elradfmwMT')
handler = FTPHandler
handler.authorizer = authorizer
handler.masquerade_address = '10.0.2.2'
handler.timeout = None
server = FTPServer(('127.0.0.1', port), handler)
thread = Thread(target=_run_ftp_server, args=[server])
thread.daemon = True
thread.start()
time.sleep(1)
return server
<|reserved_special_token_0|>
class Command(EnvCommand):
"""
Builds an image.
"""
help = 'Build an image.'
def __init__(self):
super().__init__()
self._headless = True
self._use_kvm = True
self._num_cores = 1
self._has_cow = False
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument('name', help=
'The name of the image to build. If empty, shows available images',
nargs='*')
parser.add_argument('-g', '--gui', action='store_true', help=
'Display QEMU GUI during image build')
parser.add_argument('-c', '--cores', required=False, default=2,
type=int, help=
'The number of cores used when building the VM image. Defaults to 2'
)
parser.add_argument('-x', '--clean', action='store_true', help=
'Deletes all images and rebuild them from scratch')
parser.add_argument('-a', '--archive', action='store_true', help=
'Creates an archive for the specified image')
parser.add_argument('-p', '--ftp-port', required=False, default=
15468, type=int, help=
'Port for the internal FTP server to receive files from guest VMs during build'
)
parser.add_argument('-d', '--download', action='store_true', help=
'Download image from the repository instead of building it')
parser.add_argument('-i', '--iso-dir', help=
'Path to folder that stores ISO files of Windows images')
parser.add_argument('-n', '--no-kvm', action='store_true', help=
'Disable KVM during image build')
def handle(self, *args, **options):
if options['gui']:
self._headless = False
if options['no_kvm']:
self._use_kvm = False
self._num_cores = options['cores']
if not os.path.exists(self.image_path()):
os.makedirs(self.image_path())
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
if options['clean']:
self._invoke_make(img_build_dir, ['clean'])
return
image_names = options['name']
templates = get_image_templates(img_build_dir)
app_templates = get_app_templates(img_build_dir)
images, image_groups, image_descriptors = get_all_images(templates,
app_templates)
if not image_names:
self._print_image_list(images, image_groups, image_descriptors)
print(
"""
Run ``s2e image_build <name>`` to build an image. Note that you must run ``s2e build`` **before** building an image"""
)
return
image_names = translate_image_name(images, image_groups, image_names)
logger.info('The following images will be built:')
for image in image_names:
logger.info(' * %s', image)
if options['download']:
_download_images(self.image_path(), image_names, templates)
return
rule_names = image_names
if options['archive']:
rule_names = _get_archive_rules(self.image_path(), image_names)
iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'
] else None
_check_product_keys(image_descriptors, image_names)
_check_iso(templates, app_templates, iso_dir, image_names)
if self._use_kvm:
_check_kvm()
_check_groups_kvm()
_check_groups_docker()
_check_vmlinux()
self._has_cow = _check_cow(self.image_path())
if self._use_kvm:
_check_virtualbox()
_check_vmware()
if not _is_port_available(options['ftp_port']):
raise CommandError(
f"localhost:{options['ftp_port']} is not available. Check that the port is free or specify a port with --ftp-port"
)
self._clone_kernel()
server = _start_ftp_server(self.image_path(), options['ftp_port'])
self._invoke_make(img_build_dir, rule_names, options['ftp_port'],
iso_dir)
logger.success("Built image(s) '%s'", ' '.join(image_names))
server.close_all()
def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):
env = os.environ.copy()
env['S2E_INSTALL_ROOT'] = self.install_path()
env['S2E_LINUX_KERNELS_ROOT'] = self.source_path(CONSTANTS['repos']
['images']['linux'])
env['OUTDIR'] = self.image_path()
env['QEMU_FTP_PORT'] = str(ftp_port)
env['ISODIR'] = iso_dir if iso_dir else ''
env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'
logger.debug('Invoking makefile with:')
logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])
logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env[
'S2E_LINUX_KERNELS_ROOT'])
logger.debug('export OUTDIR=%s', env['OUTDIR'])
logger.debug('export ISODIR=%s', env.get('ISODIR', ''))
logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get(
'DEBUG_INTERMEDIATE_RULES', ''))
if self._headless:
logger.warning(
'Image creation will run in headless mode. Use --gui to see graphic output for debugging'
)
else:
env['GRAPHICS'] = ''
if not self._use_kvm:
env['QEMU_KVM'] = ''
logger.warning('Image build without KVM. This will be slow')
try:
make = sh.Command('make').bake(file=os.path.join(img_build_dir,
'Makefile'), directory=self.image_path(), _env=env, _fg=True)
make_image = make.bake(j=self._num_cores, r=True,
warn_undefined_variables=True)
make_image(sorted(rule_names))
except ErrorReturnCode as e:
raise CommandError(e) from e
def _clone_kernel(self):
kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])
if os.path.exists(kernels_root):
logger.info('Kernel repository already exists in %s', kernels_root)
return
logger.info('Cloning kernels repository to %s', kernels_root)
kernels_repo = CONSTANTS['repos']['images']['linux']
repos.git_clone_to_source(self.env_path(), kernels_repo)
def _print_image_list(self, images, image_groups, image_descriptors):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
templates = get_image_templates(img_build_dir)
if not templates:
images_json_path = os.path.join(img_build_dir, 'images.json')
raise CommandError(
f'No images available to build. Make sure that {images_json_path} exists and is valid'
)
def get_max_len(lst):
ret = 0
for item in lst:
if len(item) > ret:
ret = len(item)
return ret
print('Available image groups:')
max_group_len = get_max_len(image_groups)
for group in image_groups:
print(f' * {group:{max_group_len}} - Build {group} images')
print('\nAvailable images:')
max_image_len = get_max_len(images)
for image in sorted(images):
print(
f" * {image:{max_image_len}} - {image_descriptors[image]['name']}"
)
def _print_apps_list(self):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
app_templates = get_app_templates(img_build_dir)
if not app_templates:
apps_json_path = os.path.join(img_build_dir, 'apps.json')
raise CommandError(
f'No apps available to build. Make sure that {apps_json_path} exists and is valid'
)
print('Available applications:')
for app_template, desc in sorted(app_templates.items()):
for base_image in desc['base_images']:
print(f" * {base_image}/{app_template} - {desc['name']}")
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def _get_user_name():
"""
Get the current user.
"""
return pwd.getpwuid(os.getuid())[0]
def _user_belongs_to(group_name):
"""
Check that the current user belongs to the ``group_name`` group.
"""
user_name = _get_user_name()
groups = _get_user_groups(user_name)
return group_name in groups
<|reserved_special_token_0|>
def _check_groups_kvm():
"""Being member of KVM is required only when using KVM to build images"""
if not _user_belongs_to('libvirtd') and not _user_belongs_to('kvm'):
_raise_group_error('kvm')
<|reserved_special_token_0|>
def _check_vmware():
"""
Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must
*not* be running together with S2E.
"""
for proc in psutil.process_iter():
try:
if proc.name() == 'vmware-vmx':
raise CommandError(
'S2E uses KVM to build images. VMware is currently running, which is not compatible with KVM. Please close all VMware VMs and try again.'
)
except NoSuchProcess:
pass
def _check_kvm():
"""
Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.
"""
if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):
raise CommandError(
'KVM interface not found - check that /dev/kvm exists. Alternatively, you can disable KVM (-n option) or download pre-built images (-d option)'
)
def _check_vmlinux():
"""
Check that /boot/vmlinux* files are readable. This is important for guestfish.
"""
try:
for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):
with open(f, 'rb'):
pass
except IOError:
raise CommandError(
"""Make sure that the kernels in /boot are readable. This is required for guestfish. Please run the following command:
sudo chmod ugo+r /boot/vmlinu*"""
) from None
def _check_cow(image_dir):
"""
Check that the file system that stores guest images supports copy-on-write.
"""
try:
src = f'{image_dir}/.cowcheck'
dst = f'{image_dir}/.cowcheck1'
sh.touch(src)
sh.cp('--reflink=always', src, dst)
return True
except Exception:
warn_msg = f"""
Copy-on-write check failed.
The file system where images are stored ({image_dir}) does not support copy-on-write.
It is recommended to use an XFS or BTRFS file system with copy-on-write enabled as a storage
location for S2E images, as this can save up to 60% of disk space. The building process checkpoints
intermediate build steps with cp --reflink=auto to make use of copy-on-write if it is available.
How to upgrade:
1. Create an XFS or BTRFS partition large enough to store the images that you need (~300 GB for all images).
Make sure you use reflink=1 to enable copy-on-write when running mkfs.xfs.
2. Create a directory for guest images on that partition (e.g., /mnt/disk1/images)
3. Delete the "images" folder in your S2E environment
4. Create in your S2E environment a symbolic link called "images" to the directory you created in step 2
"""
logger.warning(re.sub('^ {8}', '', warn_msg, flags=re.MULTILINE))
return False
finally:
sh.rm('-f', src)
sh.rm('-f', dst)
def _raise_invalid_image(image_name):
raise CommandError(
f'Invalid image name: {image_name}. Run ``s2e image_build`` to list available images'
)
def _get_base_image_and_app(image_name):
x = image_name.split('/')
if len(x) == 1:
return x[0], None
if len(x) == 2:
return x
raise CommandError(f'Invalid image name {image_name}')
def _has_app_image(image_names):
for name in image_names:
if '/' in name:
return True
return False
def _check_product_keys(image_descriptors, image_names):
missing_keys = []
for image_name in image_names:
image = image_descriptors[image_name]
if 'product_key' in image:
if not image['product_key']:
missing_keys.append(image_name)
ios = image_descriptors[image_name].get('os', {})
if 'product_key' in ios:
if not ios['product_key']:
missing_keys.append(image_name)
if missing_keys:
logger.error('The following images require a product key:')
for image in missing_keys:
logger.error(' * %s', image)
raise CommandError('Please update images.json and/or apps.json.')
def _check_iso(templates, app_templates, iso_dir, image_names):
for image_name in image_names:
base_image, app_name = _get_base_image_and_app(image_name)
descriptors = [templates[base_image]]
if app_name:
descriptors.append(app_templates[app_name])
for desc in descriptors:
iso = desc.get('iso', {})
if iso.get('url', ''):
continue
name = iso.get('name', '')
if not name:
continue
if not iso_dir:
raise CommandError(
f'Please use the --iso-dir option to specify the path to a folder that contains {name}'
)
path = os.path.join(iso_dir, name)
if not os.path.exists(path):
raise CommandError(
f'The image {image_name} requires {path}, which could not be found'
)
<|reserved_special_token_0|>
def _start_ftp_server(image_path, port):
authorizer = DummyAuthorizer()
authorizer.add_anonymous(image_path, perm='elradfmwMT')
handler = FTPHandler
handler.authorizer = authorizer
handler.masquerade_address = '10.0.2.2'
handler.timeout = None
server = FTPServer(('127.0.0.1', port), handler)
thread = Thread(target=_run_ftp_server, args=[server])
thread.daemon = True
thread.start()
time.sleep(1)
return server
<|reserved_special_token_0|>
def _get_archive_rules(image_path, rule_names):
if _has_app_image(rule_names):
raise CommandError(
'Building archives of app images is not supported yet')
archive_rules = []
for r in rule_names:
archive_rules.append(os.path.join(image_path, f'{r}.tar.xz'))
logger.info('The following archives will be built:')
for a in archive_rules:
logger.info(' * %s', a)
return archive_rules
<|reserved_special_token_0|>
class Command(EnvCommand):
"""
Builds an image.
"""
help = 'Build an image.'
def __init__(self):
super().__init__()
self._headless = True
self._use_kvm = True
self._num_cores = 1
self._has_cow = False
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument('name', help=
'The name of the image to build. If empty, shows available images',
nargs='*')
parser.add_argument('-g', '--gui', action='store_true', help=
'Display QEMU GUI during image build')
parser.add_argument('-c', '--cores', required=False, default=2,
type=int, help=
'The number of cores used when building the VM image. Defaults to 2'
)
parser.add_argument('-x', '--clean', action='store_true', help=
'Deletes all images and rebuild them from scratch')
parser.add_argument('-a', '--archive', action='store_true', help=
'Creates an archive for the specified image')
parser.add_argument('-p', '--ftp-port', required=False, default=
15468, type=int, help=
'Port for the internal FTP server to receive files from guest VMs during build'
)
parser.add_argument('-d', '--download', action='store_true', help=
'Download image from the repository instead of building it')
parser.add_argument('-i', '--iso-dir', help=
'Path to folder that stores ISO files of Windows images')
parser.add_argument('-n', '--no-kvm', action='store_true', help=
'Disable KVM during image build')
def handle(self, *args, **options):
if options['gui']:
self._headless = False
if options['no_kvm']:
self._use_kvm = False
self._num_cores = options['cores']
if not os.path.exists(self.image_path()):
os.makedirs(self.image_path())
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
if options['clean']:
self._invoke_make(img_build_dir, ['clean'])
return
image_names = options['name']
templates = get_image_templates(img_build_dir)
app_templates = get_app_templates(img_build_dir)
images, image_groups, image_descriptors = get_all_images(templates,
app_templates)
if not image_names:
self._print_image_list(images, image_groups, image_descriptors)
print(
"""
Run ``s2e image_build <name>`` to build an image. Note that you must run ``s2e build`` **before** building an image"""
)
return
image_names = translate_image_name(images, image_groups, image_names)
logger.info('The following images will be built:')
for image in image_names:
logger.info(' * %s', image)
if options['download']:
_download_images(self.image_path(), image_names, templates)
return
rule_names = image_names
if options['archive']:
rule_names = _get_archive_rules(self.image_path(), image_names)
iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'
] else None
_check_product_keys(image_descriptors, image_names)
_check_iso(templates, app_templates, iso_dir, image_names)
if self._use_kvm:
_check_kvm()
_check_groups_kvm()
_check_groups_docker()
_check_vmlinux()
self._has_cow = _check_cow(self.image_path())
if self._use_kvm:
_check_virtualbox()
_check_vmware()
if not _is_port_available(options['ftp_port']):
raise CommandError(
f"localhost:{options['ftp_port']} is not available. Check that the port is free or specify a port with --ftp-port"
)
self._clone_kernel()
server = _start_ftp_server(self.image_path(), options['ftp_port'])
self._invoke_make(img_build_dir, rule_names, options['ftp_port'],
iso_dir)
logger.success("Built image(s) '%s'", ' '.join(image_names))
server.close_all()
def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):
env = os.environ.copy()
env['S2E_INSTALL_ROOT'] = self.install_path()
env['S2E_LINUX_KERNELS_ROOT'] = self.source_path(CONSTANTS['repos']
['images']['linux'])
env['OUTDIR'] = self.image_path()
env['QEMU_FTP_PORT'] = str(ftp_port)
env['ISODIR'] = iso_dir if iso_dir else ''
env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'
logger.debug('Invoking makefile with:')
logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])
logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env[
'S2E_LINUX_KERNELS_ROOT'])
logger.debug('export OUTDIR=%s', env['OUTDIR'])
logger.debug('export ISODIR=%s', env.get('ISODIR', ''))
logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get(
'DEBUG_INTERMEDIATE_RULES', ''))
if self._headless:
logger.warning(
'Image creation will run in headless mode. Use --gui to see graphic output for debugging'
)
else:
env['GRAPHICS'] = ''
if not self._use_kvm:
env['QEMU_KVM'] = ''
logger.warning('Image build without KVM. This will be slow')
try:
make = sh.Command('make').bake(file=os.path.join(img_build_dir,
'Makefile'), directory=self.image_path(), _env=env, _fg=True)
make_image = make.bake(j=self._num_cores, r=True,
warn_undefined_variables=True)
make_image(sorted(rule_names))
except ErrorReturnCode as e:
raise CommandError(e) from e
def _clone_kernel(self):
kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])
if os.path.exists(kernels_root):
logger.info('Kernel repository already exists in %s', kernels_root)
return
logger.info('Cloning kernels repository to %s', kernels_root)
kernels_repo = CONSTANTS['repos']['images']['linux']
repos.git_clone_to_source(self.env_path(), kernels_repo)
def _print_image_list(self, images, image_groups, image_descriptors):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
templates = get_image_templates(img_build_dir)
if not templates:
images_json_path = os.path.join(img_build_dir, 'images.json')
raise CommandError(
f'No images available to build. Make sure that {images_json_path} exists and is valid'
)
def get_max_len(lst):
ret = 0
for item in lst:
if len(item) > ret:
ret = len(item)
return ret
print('Available image groups:')
max_group_len = get_max_len(image_groups)
for group in image_groups:
print(f' * {group:{max_group_len}} - Build {group} images')
print('\nAvailable images:')
max_image_len = get_max_len(images)
for image in sorted(images):
print(
f" * {image:{max_image_len}} - {image_descriptors[image]['name']}"
)
def _print_apps_list(self):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
app_templates = get_app_templates(img_build_dir)
if not app_templates:
apps_json_path = os.path.join(img_build_dir, 'apps.json')
raise CommandError(
f'No apps available to build. Make sure that {apps_json_path} exists and is valid'
)
print('Available applications:')
for app_template, desc in sorted(app_templates.items()):
for base_image in desc['base_images']:
print(f" * {base_image}/{app_template} - {desc['name']}")
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def _get_user_groups(user_name):
"""
Get a list of groups for the user ``user_name``.
"""
groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]
gid = pwd.getpwnam(user_name).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
return groups
def _get_user_name():
"""
Get the current user.
"""
return pwd.getpwuid(os.getuid())[0]
def _user_belongs_to(group_name):
"""
Check that the current user belongs to the ``group_name`` group.
"""
user_name = _get_user_name()
groups = _get_user_groups(user_name)
return group_name in groups
def _raise_group_error(group_name):
raise CommandError(
f"""You must belong to the {group_name} group in order to build images. Please run the following command, then logout and login:
sudo usermod -a -G {group_name} $(whoami)"""
)
def _check_groups_docker():
"""
Check that the current user belongs to the required groups to both run S2E and build S2E images.
"""
if not _user_belongs_to('docker'):
_raise_group_error('docker')
def _check_groups_kvm():
"""Being member of KVM is required only when using KVM to build images"""
if not _user_belongs_to('libvirtd') and not _user_belongs_to('kvm'):
_raise_group_error('kvm')
def _check_virtualbox():
"""
Check if VirtualBox is running. VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must
*not* be running together with S2E.
"""
for proc in psutil.process_iter():
try:
if proc.name() == 'VBoxHeadless':
raise CommandError(
'S2E uses KVM to build images. VirtualBox is currently running, which is not compatible with KVM. Please close all VirtualBox VMs and try again.'
)
except NoSuchProcess:
pass
def _check_vmware():
"""
Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must
*not* be running together with S2E.
"""
for proc in psutil.process_iter():
try:
if proc.name() == 'vmware-vmx':
raise CommandError(
'S2E uses KVM to build images. VMware is currently running, which is not compatible with KVM. Please close all VMware VMs and try again.'
)
except NoSuchProcess:
pass
def _check_kvm():
"""
Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.
"""
if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):
raise CommandError(
'KVM interface not found - check that /dev/kvm exists. Alternatively, you can disable KVM (-n option) or download pre-built images (-d option)'
)
def _check_vmlinux():
"""
Check that /boot/vmlinux* files are readable. This is important for guestfish.
"""
try:
for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):
with open(f, 'rb'):
pass
except IOError:
raise CommandError(
"""Make sure that the kernels in /boot are readable. This is required for guestfish. Please run the following command:
sudo chmod ugo+r /boot/vmlinu*"""
) from None
def _check_cow(image_dir):
"""
Check that the file system that stores guest images supports copy-on-write.
"""
try:
src = f'{image_dir}/.cowcheck'
dst = f'{image_dir}/.cowcheck1'
sh.touch(src)
sh.cp('--reflink=always', src, dst)
return True
except Exception:
warn_msg = f"""
Copy-on-write check failed.
The file system where images are stored ({image_dir}) does not support copy-on-write.
It is recommended to use an XFS or BTRFS file system with copy-on-write enabled as a storage
location for S2E images, as this can save up to 60% of disk space. The building process checkpoints
intermediate build steps with cp --reflink=auto to make use of copy-on-write if it is available.
How to upgrade:
1. Create an XFS or BTRFS partition large enough to store the images that you need (~300 GB for all images).
Make sure you use reflink=1 to enable copy-on-write when running mkfs.xfs.
2. Create a directory for guest images on that partition (e.g., /mnt/disk1/images)
3. Delete the "images" folder in your S2E environment
4. Create in your S2E environment a symbolic link called "images" to the directory you created in step 2
"""
logger.warning(re.sub('^ {8}', '', warn_msg, flags=re.MULTILINE))
return False
finally:
sh.rm('-f', src)
sh.rm('-f', dst)
def _raise_invalid_image(image_name):
raise CommandError(
f'Invalid image name: {image_name}. Run ``s2e image_build`` to list available images'
)
def _get_base_image_and_app(image_name):
x = image_name.split('/')
if len(x) == 1:
return x[0], None
if len(x) == 2:
return x
raise CommandError(f'Invalid image name {image_name}')
def _has_app_image(image_names):
for name in image_names:
if '/' in name:
return True
return False
def _check_product_keys(image_descriptors, image_names):
missing_keys = []
for image_name in image_names:
image = image_descriptors[image_name]
if 'product_key' in image:
if not image['product_key']:
missing_keys.append(image_name)
ios = image_descriptors[image_name].get('os', {})
if 'product_key' in ios:
if not ios['product_key']:
missing_keys.append(image_name)
if missing_keys:
logger.error('The following images require a product key:')
for image in missing_keys:
logger.error(' * %s', image)
raise CommandError('Please update images.json and/or apps.json.')
def _check_iso(templates, app_templates, iso_dir, image_names):
for image_name in image_names:
base_image, app_name = _get_base_image_and_app(image_name)
descriptors = [templates[base_image]]
if app_name:
descriptors.append(app_templates[app_name])
for desc in descriptors:
iso = desc.get('iso', {})
if iso.get('url', ''):
continue
name = iso.get('name', '')
if not name:
continue
if not iso_dir:
raise CommandError(
f'Please use the --iso-dir option to specify the path to a folder that contains {name}'
)
path = os.path.join(iso_dir, name)
if not os.path.exists(path):
raise CommandError(
f'The image {image_name} requires {path}, which could not be found'
)
def _is_port_available(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('127.0.0.1', port))
return True
except socket.error:
return False
finally:
s.close()
def _start_ftp_server(image_path, port):
authorizer = DummyAuthorizer()
authorizer.add_anonymous(image_path, perm='elradfmwMT')
handler = FTPHandler
handler.authorizer = authorizer
handler.masquerade_address = '10.0.2.2'
handler.timeout = None
server = FTPServer(('127.0.0.1', port), handler)
thread = Thread(target=_run_ftp_server, args=[server])
thread.daemon = True
thread.start()
time.sleep(1)
return server
def _run_ftp_server(server):
try:
server.serve_forever()
finally:
logger.info('FTP server terminated')
server.close_all()
def _get_archive_rules(image_path, rule_names):
if _has_app_image(rule_names):
raise CommandError(
'Building archives of app images is not supported yet')
archive_rules = []
for r in rule_names:
archive_rules.append(os.path.join(image_path, f'{r}.tar.xz'))
logger.info('The following archives will be built:')
for a in archive_rules:
logger.info(' * %s', a)
return archive_rules
<|reserved_special_token_0|>
class Command(EnvCommand):
"""
Builds an image.
"""
help = 'Build an image.'
def __init__(self):
super().__init__()
self._headless = True
self._use_kvm = True
self._num_cores = 1
self._has_cow = False
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument('name', help=
'The name of the image to build. If empty, shows available images',
nargs='*')
parser.add_argument('-g', '--gui', action='store_true', help=
'Display QEMU GUI during image build')
parser.add_argument('-c', '--cores', required=False, default=2,
type=int, help=
'The number of cores used when building the VM image. Defaults to 2'
)
parser.add_argument('-x', '--clean', action='store_true', help=
'Deletes all images and rebuild them from scratch')
parser.add_argument('-a', '--archive', action='store_true', help=
'Creates an archive for the specified image')
parser.add_argument('-p', '--ftp-port', required=False, default=
15468, type=int, help=
'Port for the internal FTP server to receive files from guest VMs during build'
)
parser.add_argument('-d', '--download', action='store_true', help=
'Download image from the repository instead of building it')
parser.add_argument('-i', '--iso-dir', help=
'Path to folder that stores ISO files of Windows images')
parser.add_argument('-n', '--no-kvm', action='store_true', help=
'Disable KVM during image build')
def handle(self, *args, **options):
if options['gui']:
self._headless = False
if options['no_kvm']:
self._use_kvm = False
self._num_cores = options['cores']
if not os.path.exists(self.image_path()):
os.makedirs(self.image_path())
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
if options['clean']:
self._invoke_make(img_build_dir, ['clean'])
return
image_names = options['name']
templates = get_image_templates(img_build_dir)
app_templates = get_app_templates(img_build_dir)
images, image_groups, image_descriptors = get_all_images(templates,
app_templates)
if not image_names:
self._print_image_list(images, image_groups, image_descriptors)
print(
"""
Run ``s2e image_build <name>`` to build an image. Note that you must run ``s2e build`` **before** building an image"""
)
return
image_names = translate_image_name(images, image_groups, image_names)
logger.info('The following images will be built:')
for image in image_names:
logger.info(' * %s', image)
if options['download']:
_download_images(self.image_path(), image_names, templates)
return
rule_names = image_names
if options['archive']:
rule_names = _get_archive_rules(self.image_path(), image_names)
iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'
] else None
_check_product_keys(image_descriptors, image_names)
_check_iso(templates, app_templates, iso_dir, image_names)
if self._use_kvm:
_check_kvm()
_check_groups_kvm()
_check_groups_docker()
_check_vmlinux()
self._has_cow = _check_cow(self.image_path())
if self._use_kvm:
_check_virtualbox()
_check_vmware()
if not _is_port_available(options['ftp_port']):
raise CommandError(
f"localhost:{options['ftp_port']} is not available. Check that the port is free or specify a port with --ftp-port"
)
self._clone_kernel()
server = _start_ftp_server(self.image_path(), options['ftp_port'])
self._invoke_make(img_build_dir, rule_names, options['ftp_port'],
iso_dir)
logger.success("Built image(s) '%s'", ' '.join(image_names))
server.close_all()
def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):
env = os.environ.copy()
env['S2E_INSTALL_ROOT'] = self.install_path()
env['S2E_LINUX_KERNELS_ROOT'] = self.source_path(CONSTANTS['repos']
['images']['linux'])
env['OUTDIR'] = self.image_path()
env['QEMU_FTP_PORT'] = str(ftp_port)
env['ISODIR'] = iso_dir if iso_dir else ''
env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'
logger.debug('Invoking makefile with:')
logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])
logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env[
'S2E_LINUX_KERNELS_ROOT'])
logger.debug('export OUTDIR=%s', env['OUTDIR'])
logger.debug('export ISODIR=%s', env.get('ISODIR', ''))
logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get(
'DEBUG_INTERMEDIATE_RULES', ''))
if self._headless:
logger.warning(
'Image creation will run in headless mode. Use --gui to see graphic output for debugging'
)
else:
env['GRAPHICS'] = ''
if not self._use_kvm:
env['QEMU_KVM'] = ''
logger.warning('Image build without KVM. This will be slow')
try:
make = sh.Command('make').bake(file=os.path.join(img_build_dir,
'Makefile'), directory=self.image_path(), _env=env, _fg=True)
make_image = make.bake(j=self._num_cores, r=True,
warn_undefined_variables=True)
make_image(sorted(rule_names))
except ErrorReturnCode as e:
raise CommandError(e) from e
def _clone_kernel(self):
kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])
if os.path.exists(kernels_root):
logger.info('Kernel repository already exists in %s', kernels_root)
return
logger.info('Cloning kernels repository to %s', kernels_root)
kernels_repo = CONSTANTS['repos']['images']['linux']
repos.git_clone_to_source(self.env_path(), kernels_repo)
def _print_image_list(self, images, image_groups, image_descriptors):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
templates = get_image_templates(img_build_dir)
if not templates:
images_json_path = os.path.join(img_build_dir, 'images.json')
raise CommandError(
f'No images available to build. Make sure that {images_json_path} exists and is valid'
)
def get_max_len(lst):
ret = 0
for item in lst:
if len(item) > ret:
ret = len(item)
return ret
print('Available image groups:')
max_group_len = get_max_len(image_groups)
for group in image_groups:
print(f' * {group:{max_group_len}} - Build {group} images')
print('\nAvailable images:')
max_image_len = get_max_len(images)
for image in sorted(images):
print(
f" * {image:{max_image_len}} - {image_descriptors[image]['name']}"
)
def _print_apps_list(self):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
app_templates = get_app_templates(img_build_dir)
if not app_templates:
apps_json_path = os.path.join(img_build_dir, 'apps.json')
raise CommandError(
f'No apps available to build. Make sure that {apps_json_path} exists and is valid'
)
print('Available applications:')
for app_template, desc in sorted(app_templates.items()):
for base_image in desc['base_images']:
print(f" * {base_image}/{app_template} - {desc['name']}")
<|reserved_special_token_1|>
"""
Copyright (c) 2017 Cyberhaven
Copyright (c) 2017 Dependable Systems Laboratory, EPFL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import glob
import grp
import logging
import os
import pwd
import re
import socket
import time
from threading import Thread
import psutil
from psutil import NoSuchProcess
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import sh
from sh import ErrorReturnCode
from s2e_env import CONSTANTS
from s2e_env.command import EnvCommand, CommandError
from s2e_env.utils import repos
from s2e_env.utils.images import ImageDownloader, get_image_templates, get_app_templates, get_all_images, \
translate_image_name
logger = logging.getLogger('image_build')
def _get_user_groups(user_name):
"""
Get a list of groups for the user ``user_name``.
"""
groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]
gid = pwd.getpwnam(user_name).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
return groups
def _get_user_name():
"""
Get the current user.
"""
return pwd.getpwuid(os.getuid())[0]
def _user_belongs_to(group_name):
"""
Check that the current user belongs to the ``group_name`` group.
"""
user_name = _get_user_name()
groups = _get_user_groups(user_name)
return group_name in groups
def _raise_group_error(group_name):
raise CommandError(f'You must belong to the {group_name} group in order to build '
'images. Please run the following command, then logout '
'and login:\n\n'
f'\tsudo usermod -a -G {group_name} $(whoami)')
def _check_groups_docker():
"""
Check that the current user belongs to the required groups to both run S2E and build S2E images.
"""
if not _user_belongs_to('docker'):
_raise_group_error('docker')
def _check_groups_kvm():
"""Being member of KVM is required only when using KVM to build images"""
if not _user_belongs_to('libvirtd') and not _user_belongs_to('kvm'):
_raise_group_error('kvm')
def _check_virtualbox():
"""
Check if VirtualBox is running. VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must
*not* be running together with S2E.
"""
# Adapted from https://github.com/giampaolo/psutil/issues/132#issuecomment-44017679
# to avoid race conditions
for proc in psutil.process_iter():
try:
if proc.name() == 'VBoxHeadless':
raise CommandError('S2E uses KVM to build images. VirtualBox '
'is currently running, which is not '
'compatible with KVM. Please close all '
'VirtualBox VMs and try again.')
except NoSuchProcess:
pass
def _check_vmware():
"""
Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must
*not* be running together with S2E.
"""
for proc in psutil.process_iter():
try:
if proc.name() == 'vmware-vmx':
raise CommandError('S2E uses KVM to build images. VMware '
'is currently running, which is not '
'compatible with KVM. Please close all '
'VMware VMs and try again.')
except NoSuchProcess:
pass
def _check_kvm():
"""
Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.
"""
if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):
raise CommandError('KVM interface not found - check that /dev/kvm '
'exists. Alternatively, you can disable KVM (-n '
'option) or download pre-built images (-d option)')
def _check_vmlinux():
"""
Check that /boot/vmlinux* files are readable. This is important for guestfish.
"""
try:
for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):
with open(f, 'rb'):
pass
except IOError:
raise CommandError('Make sure that the kernels in /boot are readable. '
'This is required for guestfish. Please run the '
'following command:\n\n'
'sudo chmod ugo+r /boot/vmlinu*') from None
# pylint: disable=no-member
def _check_cow(image_dir):
"""
Check that the file system that stores guest images supports copy-on-write.
"""
try:
src = f'{image_dir}/.cowcheck'
dst = f'{image_dir}/.cowcheck1'
sh.touch(src)
sh.cp('--reflink=always', src, dst)
return True
except Exception:
warn_msg = f"""
Copy-on-write check failed.
The file system where images are stored ({image_dir}) does not support copy-on-write.
It is recommended to use an XFS or BTRFS file system with copy-on-write enabled as a storage
location for S2E images, as this can save up to 60% of disk space. The building process checkpoints
intermediate build steps with cp --reflink=auto to make use of copy-on-write if it is available.
How to upgrade:
1. Create an XFS or BTRFS partition large enough to store the images that you need (~300 GB for all images).
Make sure you use reflink=1 to enable copy-on-write when running mkfs.xfs.
2. Create a directory for guest images on that partition (e.g., /mnt/disk1/images)
3. Delete the "images" folder in your S2E environment
4. Create in your S2E environment a symbolic link called "images" to the directory you created in step 2
"""
logger.warning(re.sub(r'^ {8}', '', warn_msg, flags=re.MULTILINE))
return False
finally:
sh.rm('-f', src)
sh.rm('-f', dst)
def _raise_invalid_image(image_name):
raise CommandError(f'Invalid image name: {image_name}. Run ``s2e image_build`` '
'to list available images')
def _get_base_image_and_app(image_name):
x = image_name.split('/')
if len(x) == 1:
return x[0], None
if len(x) == 2:
return x
raise CommandError(f'Invalid image name {image_name}')
def _has_app_image(image_names):
for name in image_names:
if '/' in name:
return True
return False
def _check_product_keys(image_descriptors, image_names):
missing_keys = []
for image_name in image_names:
image = image_descriptors[image_name]
if 'product_key' in image:
if not image['product_key']:
missing_keys.append(image_name)
ios = image_descriptors[image_name].get('os', {})
if 'product_key' in ios:
if not ios['product_key']:
missing_keys.append(image_name)
if missing_keys:
logger.error('The following images require a product key:')
for image in missing_keys:
logger.error(' * %s', image)
raise CommandError('Please update images.json and/or apps.json.')
def _check_iso(templates, app_templates, iso_dir, image_names):
for image_name in image_names:
base_image, app_name = _get_base_image_and_app(image_name)
descriptors = [templates[base_image]]
if app_name:
descriptors.append(app_templates[app_name])
for desc in descriptors:
iso = desc.get('iso', {})
if iso.get('url', ''):
continue
name = iso.get('name', '')
if not name:
continue
if not iso_dir:
raise CommandError(
'Please use the --iso-dir option to specify the path '
f'to a folder that contains {name}'
)
path = os.path.join(iso_dir, name)
if not os.path.exists(path):
raise CommandError(f'The image {image_name} requires {path}, which could not be found')
def _is_port_available(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(("127.0.0.1", port))
return True
except socket.error:
return False
finally:
s.close()
def _start_ftp_server(image_path, port):
authorizer = DummyAuthorizer()
authorizer.add_anonymous(image_path, perm='elradfmwMT')
handler = FTPHandler
handler.authorizer = authorizer
handler.masquerade_address = '10.0.2.2'
# QEMU slirp won't let the guest reconnect if timeout happens, so we disable it
handler.timeout = None
server = FTPServer(("127.0.0.1", port), handler)
thread = Thread(target=_run_ftp_server, args=[server])
thread.daemon = True
thread.start()
time.sleep(1)
return server
def _run_ftp_server(server):
try:
server.serve_forever()
finally:
logger.info('FTP server terminated')
server.close_all()
def _get_archive_rules(image_path, rule_names):
if _has_app_image(rule_names):
raise CommandError('Building archives of app images is not supported yet')
archive_rules = []
for r in rule_names:
archive_rules.append(os.path.join(image_path, f'{r}.tar.xz'))
logger.info('The following archives will be built:')
for a in archive_rules:
logger.info(' * %s', a)
return archive_rules
def _download_images(image_path, image_names, templates):
if _has_app_image(image_names):
raise CommandError('Downloading of app images is not supported yet')
image_downloader = ImageDownloader(templates)
image_downloader.download_images(image_names, image_path)
logger.info('Successfully downloaded images: %s', ', '.join(image_names))
class Command(EnvCommand):
"""
Builds an image.
"""
help = 'Build an image.'
def __init__(self):
super().__init__()
self._headless = True
self._use_kvm = True
self._num_cores = 1
self._has_cow = False
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument('name',
help='The name of the image to build. If empty,'
' shows available images', nargs='*')
parser.add_argument('-g', '--gui', action='store_true',
help='Display QEMU GUI during image build')
parser.add_argument('-c', '--cores', required=False, default=2,
type=int,
help='The number of cores used when building the '
'VM image. Defaults to 2')
parser.add_argument('-x', '--clean', action='store_true',
help='Deletes all images and rebuild them from '
'scratch')
parser.add_argument('-a', '--archive', action='store_true',
help='Creates an archive for the specified image')
parser.add_argument('-p', '--ftp-port', required=False, default=15468, type=int,
help='Port for the internal FTP server to receive files from guest VMs during build')
parser.add_argument('-d', '--download', action='store_true',
help='Download image from the repository instead '
'of building it')
parser.add_argument('-i', '--iso-dir',
help='Path to folder that stores ISO files of Windows images')
parser.add_argument('-n', '--no-kvm', action='store_true',
help='Disable KVM during image build')
def handle(self, *args, **options):
# If DISPLAY is missing, don't use headless mode
if options['gui']:
self._headless = False
# If KVM has been explicitly disabled, don't use it during the build
if options['no_kvm']:
self._use_kvm = False
self._num_cores = options['cores']
# The path could have been deleted by a previous clean
if not os.path.exists(self.image_path()):
os.makedirs(self.image_path())
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
if options['clean']:
self._invoke_make(img_build_dir, ['clean'])
return
image_names = options['name']
templates = get_image_templates(img_build_dir)
app_templates = get_app_templates(img_build_dir)
images, image_groups, image_descriptors = get_all_images(templates, app_templates)
if not image_names:
self._print_image_list(images, image_groups, image_descriptors)
print('\nRun ``s2e image_build <name>`` to build an image. '
'Note that you must run ``s2e build`` **before** building '
'an image')
return
image_names = translate_image_name(images, image_groups, image_names)
logger.info('The following images will be built:')
for image in image_names:
logger.info(' * %s', image)
if options['download']:
_download_images(self.image_path(), image_names, templates)
return
rule_names = image_names
if options['archive']:
rule_names = _get_archive_rules(self.image_path(), image_names)
iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'] else None
# Check for optional product keys and iso directories.
# These may or may not be required, depending on the set of images.
_check_product_keys(image_descriptors, image_names)
_check_iso(templates, app_templates, iso_dir, image_names)
if self._use_kvm:
_check_kvm()
_check_groups_kvm()
_check_groups_docker()
_check_vmlinux()
self._has_cow = _check_cow(self.image_path())
if self._use_kvm:
_check_virtualbox()
_check_vmware()
if not _is_port_available(options['ftp_port']):
raise CommandError(f'localhost:{options["ftp_port"]} is not available. Check that the port is free or '
'specify a port with --ftp-port')
# Clone kernel if needed.
# This is necessary if the s2e env has been initialized with -b flag.
self._clone_kernel()
server = _start_ftp_server(self.image_path(), options['ftp_port'])
self._invoke_make(img_build_dir, rule_names, options['ftp_port'], iso_dir)
logger.success('Built image(s) \'%s\'', ' '.join(image_names))
server.close_all()
def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):
env = os.environ.copy()
env['S2E_INSTALL_ROOT'] = self.install_path()
env['S2E_LINUX_KERNELS_ROOT'] = \
self.source_path(CONSTANTS['repos']['images']['linux'])
env['OUTDIR'] = self.image_path()
env['QEMU_FTP_PORT'] = str(ftp_port)
env['ISODIR'] = iso_dir if iso_dir else ''
env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'
logger.debug('Invoking makefile with:')
logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])
logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env['S2E_LINUX_KERNELS_ROOT'])
logger.debug('export OUTDIR=%s', env['OUTDIR'])
logger.debug('export ISODIR=%s', env.get('ISODIR', ''))
logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get('DEBUG_INTERMEDIATE_RULES', ''))
if self._headless:
logger.warning('Image creation will run in headless mode. '
'Use --gui to see graphic output for debugging')
else:
env['GRAPHICS'] = ''
if not self._use_kvm:
env['QEMU_KVM'] = ''
logger.warning('Image build without KVM. This will be slow')
try:
make = sh.Command('make').bake(file=os.path.join(img_build_dir,
'Makefile'),
directory=self.image_path(),
_env=env, _fg=True)
make_image = make.bake(j=self._num_cores, r=True, warn_undefined_variables=True)
make_image(sorted(rule_names))
except ErrorReturnCode as e:
raise CommandError(e) from e
def _clone_kernel(self):
kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])
if os.path.exists(kernels_root):
logger.info('Kernel repository already exists in %s', kernels_root)
return
logger.info('Cloning kernels repository to %s', kernels_root)
kernels_repo = CONSTANTS['repos']['images']['linux']
repos.git_clone_to_source(self.env_path(), kernels_repo)
def _print_image_list(self, images, image_groups, image_descriptors):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
templates = get_image_templates(img_build_dir)
if not templates:
images_json_path = os.path.join(img_build_dir, 'images.json')
raise CommandError('No images available to build. Make sure that '
f'{images_json_path} exists and is valid')
def get_max_len(lst):
ret = 0
for item in lst:
if len(item) > ret:
ret = len(item)
return ret
print('Available image groups:')
max_group_len = get_max_len(image_groups)
for group in image_groups:
print(f' * {group:{max_group_len}} - Build {group} images')
print('\nAvailable images:')
max_image_len = get_max_len(images)
for image in sorted(images):
print(f' * {image:{max_image_len}} - {image_descriptors[image]["name"]}')
def _print_apps_list(self):
img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])
app_templates = get_app_templates(img_build_dir)
if not app_templates:
apps_json_path = os.path.join(img_build_dir, 'apps.json')
raise CommandError('No apps available to build. Make sure that '
f'{apps_json_path} exists and is valid')
print('Available applications:')
for app_template, desc in sorted(app_templates.items()):
for base_image in desc['base_images']:
print(f' * {base_image}/{app_template} - {desc["name"]}')
|
flexible
|
{
"blob_id": "e5921edef3d3c56a73f2674f483ea4d1f3577629",
"index": 5186,
"step-1": "<mask token>\n\n\ndef _get_user_name():\n \"\"\"\n Get the current user.\n \"\"\"\n return pwd.getpwuid(os.getuid())[0]\n\n\ndef _user_belongs_to(group_name):\n \"\"\"\n Check that the current user belongs to the ``group_name`` group.\n \"\"\"\n user_name = _get_user_name()\n groups = _get_user_groups(user_name)\n return group_name in groups\n\n\n<mask token>\n\n\ndef _check_vmware():\n \"\"\"\n Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must\n *not* be running together with S2E.\n \"\"\"\n for proc in psutil.process_iter():\n try:\n if proc.name() == 'vmware-vmx':\n raise CommandError(\n 'S2E uses KVM to build images. VMware is currently running, which is not compatible with KVM. Please close all VMware VMs and try again.'\n )\n except NoSuchProcess:\n pass\n\n\ndef _check_kvm():\n \"\"\"\n Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.\n \"\"\"\n if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):\n raise CommandError(\n 'KVM interface not found - check that /dev/kvm exists. Alternatively, you can disable KVM (-n option) or download pre-built images (-d option)'\n )\n\n\n<mask token>\n\n\ndef _get_base_image_and_app(image_name):\n x = image_name.split('/')\n if len(x) == 1:\n return x[0], None\n if len(x) == 2:\n return x\n raise CommandError(f'Invalid image name {image_name}')\n\n\n<mask token>\n\n\ndef _check_product_keys(image_descriptors, image_names):\n missing_keys = []\n for image_name in image_names:\n image = image_descriptors[image_name]\n if 'product_key' in image:\n if not image['product_key']:\n missing_keys.append(image_name)\n ios = image_descriptors[image_name].get('os', {})\n if 'product_key' in ios:\n if not ios['product_key']:\n missing_keys.append(image_name)\n if missing_keys:\n logger.error('The following images require a product key:')\n for image in missing_keys:\n logger.error(' * %s', image)\n raise CommandError('Please update images.json and/or apps.json.')\n\n\ndef _check_iso(templates, app_templates, iso_dir, image_names):\n for image_name in image_names:\n base_image, app_name = _get_base_image_and_app(image_name)\n descriptors = [templates[base_image]]\n if app_name:\n descriptors.append(app_templates[app_name])\n for desc in descriptors:\n iso = desc.get('iso', {})\n if iso.get('url', ''):\n continue\n name = iso.get('name', '')\n if not name:\n continue\n if not iso_dir:\n raise CommandError(\n f'Please use the --iso-dir option to specify the path to a folder that contains {name}'\n )\n path = os.path.join(iso_dir, name)\n if not os.path.exists(path):\n raise CommandError(\n f'The image {image_name} requires {path}, which could not be found'\n )\n\n\n<mask token>\n\n\nclass Command(EnvCommand):\n \"\"\"\n Builds an image.\n \"\"\"\n help = 'Build an image.'\n\n def __init__(self):\n super().__init__()\n self._headless = True\n self._use_kvm = True\n self._num_cores = 1\n self._has_cow = False\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument('name', help=\n 'The name of the image to build. If empty, shows available images',\n nargs='*')\n parser.add_argument('-g', '--gui', action='store_true', help=\n 'Display QEMU GUI during image build')\n parser.add_argument('-c', '--cores', required=False, default=2,\n type=int, help=\n 'The number of cores used when building the VM image. Defaults to 2'\n )\n parser.add_argument('-x', '--clean', action='store_true', help=\n 'Deletes all images and rebuild them from scratch')\n parser.add_argument('-a', '--archive', action='store_true', help=\n 'Creates an archive for the specified image')\n parser.add_argument('-p', '--ftp-port', required=False, default=\n 15468, type=int, help=\n 'Port for the internal FTP server to receive files from guest VMs during build'\n )\n parser.add_argument('-d', '--download', action='store_true', help=\n 'Download image from the repository instead of building it')\n parser.add_argument('-i', '--iso-dir', help=\n 'Path to folder that stores ISO files of Windows images')\n parser.add_argument('-n', '--no-kvm', action='store_true', help=\n 'Disable KVM during image build')\n\n def handle(self, *args, **options):\n if options['gui']:\n self._headless = False\n if options['no_kvm']:\n self._use_kvm = False\n self._num_cores = options['cores']\n if not os.path.exists(self.image_path()):\n os.makedirs(self.image_path())\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n if options['clean']:\n self._invoke_make(img_build_dir, ['clean'])\n return\n image_names = options['name']\n templates = get_image_templates(img_build_dir)\n app_templates = get_app_templates(img_build_dir)\n images, image_groups, image_descriptors = get_all_images(templates,\n app_templates)\n if not image_names:\n self._print_image_list(images, image_groups, image_descriptors)\n print(\n \"\"\"\nRun ``s2e image_build <name>`` to build an image. Note that you must run ``s2e build`` **before** building an image\"\"\"\n )\n return\n image_names = translate_image_name(images, image_groups, image_names)\n logger.info('The following images will be built:')\n for image in image_names:\n logger.info(' * %s', image)\n if options['download']:\n _download_images(self.image_path(), image_names, templates)\n return\n rule_names = image_names\n if options['archive']:\n rule_names = _get_archive_rules(self.image_path(), image_names)\n iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'\n ] else None\n _check_product_keys(image_descriptors, image_names)\n _check_iso(templates, app_templates, iso_dir, image_names)\n if self._use_kvm:\n _check_kvm()\n _check_groups_kvm()\n _check_groups_docker()\n _check_vmlinux()\n self._has_cow = _check_cow(self.image_path())\n if self._use_kvm:\n _check_virtualbox()\n _check_vmware()\n if not _is_port_available(options['ftp_port']):\n raise CommandError(\n f\"localhost:{options['ftp_port']} is not available. Check that the port is free or specify a port with --ftp-port\"\n )\n self._clone_kernel()\n server = _start_ftp_server(self.image_path(), options['ftp_port'])\n self._invoke_make(img_build_dir, rule_names, options['ftp_port'],\n iso_dir)\n logger.success(\"Built image(s) '%s'\", ' '.join(image_names))\n server.close_all()\n\n def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):\n env = os.environ.copy()\n env['S2E_INSTALL_ROOT'] = self.install_path()\n env['S2E_LINUX_KERNELS_ROOT'] = self.source_path(CONSTANTS['repos']\n ['images']['linux'])\n env['OUTDIR'] = self.image_path()\n env['QEMU_FTP_PORT'] = str(ftp_port)\n env['ISODIR'] = iso_dir if iso_dir else ''\n env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'\n logger.debug('Invoking makefile with:')\n logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])\n logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env[\n 'S2E_LINUX_KERNELS_ROOT'])\n logger.debug('export OUTDIR=%s', env['OUTDIR'])\n logger.debug('export ISODIR=%s', env.get('ISODIR', ''))\n logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get(\n 'DEBUG_INTERMEDIATE_RULES', ''))\n if self._headless:\n logger.warning(\n 'Image creation will run in headless mode. Use --gui to see graphic output for debugging'\n )\n else:\n env['GRAPHICS'] = ''\n if not self._use_kvm:\n env['QEMU_KVM'] = ''\n logger.warning('Image build without KVM. This will be slow')\n try:\n make = sh.Command('make').bake(file=os.path.join(img_build_dir,\n 'Makefile'), directory=self.image_path(), _env=env, _fg=True)\n make_image = make.bake(j=self._num_cores, r=True,\n warn_undefined_variables=True)\n make_image(sorted(rule_names))\n except ErrorReturnCode as e:\n raise CommandError(e) from e\n\n def _clone_kernel(self):\n kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])\n if os.path.exists(kernels_root):\n logger.info('Kernel repository already exists in %s', kernels_root)\n return\n logger.info('Cloning kernels repository to %s', kernels_root)\n kernels_repo = CONSTANTS['repos']['images']['linux']\n repos.git_clone_to_source(self.env_path(), kernels_repo)\n\n def _print_image_list(self, images, image_groups, image_descriptors):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n templates = get_image_templates(img_build_dir)\n if not templates:\n images_json_path = os.path.join(img_build_dir, 'images.json')\n raise CommandError(\n f'No images available to build. Make sure that {images_json_path} exists and is valid'\n )\n\n def get_max_len(lst):\n ret = 0\n for item in lst:\n if len(item) > ret:\n ret = len(item)\n return ret\n print('Available image groups:')\n max_group_len = get_max_len(image_groups)\n for group in image_groups:\n print(f' * {group:{max_group_len}} - Build {group} images')\n print('\\nAvailable images:')\n max_image_len = get_max_len(images)\n for image in sorted(images):\n print(\n f\" * {image:{max_image_len}} - {image_descriptors[image]['name']}\"\n )\n\n def _print_apps_list(self):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n app_templates = get_app_templates(img_build_dir)\n if not app_templates:\n apps_json_path = os.path.join(img_build_dir, 'apps.json')\n raise CommandError(\n f'No apps available to build. Make sure that {apps_json_path} exists and is valid'\n )\n print('Available applications:')\n for app_template, desc in sorted(app_templates.items()):\n for base_image in desc['base_images']:\n print(f\" * {base_image}/{app_template} - {desc['name']}\")\n",
"step-2": "<mask token>\n\n\ndef _get_user_name():\n \"\"\"\n Get the current user.\n \"\"\"\n return pwd.getpwuid(os.getuid())[0]\n\n\ndef _user_belongs_to(group_name):\n \"\"\"\n Check that the current user belongs to the ``group_name`` group.\n \"\"\"\n user_name = _get_user_name()\n groups = _get_user_groups(user_name)\n return group_name in groups\n\n\n<mask token>\n\n\ndef _check_vmware():\n \"\"\"\n Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must\n *not* be running together with S2E.\n \"\"\"\n for proc in psutil.process_iter():\n try:\n if proc.name() == 'vmware-vmx':\n raise CommandError(\n 'S2E uses KVM to build images. VMware is currently running, which is not compatible with KVM. Please close all VMware VMs and try again.'\n )\n except NoSuchProcess:\n pass\n\n\ndef _check_kvm():\n \"\"\"\n Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.\n \"\"\"\n if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):\n raise CommandError(\n 'KVM interface not found - check that /dev/kvm exists. Alternatively, you can disable KVM (-n option) or download pre-built images (-d option)'\n )\n\n\ndef _check_vmlinux():\n \"\"\"\n Check that /boot/vmlinux* files are readable. This is important for guestfish.\n \"\"\"\n try:\n for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):\n with open(f, 'rb'):\n pass\n except IOError:\n raise CommandError(\n \"\"\"Make sure that the kernels in /boot are readable. This is required for guestfish. Please run the following command:\n\nsudo chmod ugo+r /boot/vmlinu*\"\"\"\n ) from None\n\n\n<mask token>\n\n\ndef _raise_invalid_image(image_name):\n raise CommandError(\n f'Invalid image name: {image_name}. Run ``s2e image_build`` to list available images'\n )\n\n\ndef _get_base_image_and_app(image_name):\n x = image_name.split('/')\n if len(x) == 1:\n return x[0], None\n if len(x) == 2:\n return x\n raise CommandError(f'Invalid image name {image_name}')\n\n\ndef _has_app_image(image_names):\n for name in image_names:\n if '/' in name:\n return True\n return False\n\n\ndef _check_product_keys(image_descriptors, image_names):\n missing_keys = []\n for image_name in image_names:\n image = image_descriptors[image_name]\n if 'product_key' in image:\n if not image['product_key']:\n missing_keys.append(image_name)\n ios = image_descriptors[image_name].get('os', {})\n if 'product_key' in ios:\n if not ios['product_key']:\n missing_keys.append(image_name)\n if missing_keys:\n logger.error('The following images require a product key:')\n for image in missing_keys:\n logger.error(' * %s', image)\n raise CommandError('Please update images.json and/or apps.json.')\n\n\ndef _check_iso(templates, app_templates, iso_dir, image_names):\n for image_name in image_names:\n base_image, app_name = _get_base_image_and_app(image_name)\n descriptors = [templates[base_image]]\n if app_name:\n descriptors.append(app_templates[app_name])\n for desc in descriptors:\n iso = desc.get('iso', {})\n if iso.get('url', ''):\n continue\n name = iso.get('name', '')\n if not name:\n continue\n if not iso_dir:\n raise CommandError(\n f'Please use the --iso-dir option to specify the path to a folder that contains {name}'\n )\n path = os.path.join(iso_dir, name)\n if not os.path.exists(path):\n raise CommandError(\n f'The image {image_name} requires {path}, which could not be found'\n )\n\n\n<mask token>\n\n\ndef _start_ftp_server(image_path, port):\n authorizer = DummyAuthorizer()\n authorizer.add_anonymous(image_path, perm='elradfmwMT')\n handler = FTPHandler\n handler.authorizer = authorizer\n handler.masquerade_address = '10.0.2.2'\n handler.timeout = None\n server = FTPServer(('127.0.0.1', port), handler)\n thread = Thread(target=_run_ftp_server, args=[server])\n thread.daemon = True\n thread.start()\n time.sleep(1)\n return server\n\n\n<mask token>\n\n\nclass Command(EnvCommand):\n \"\"\"\n Builds an image.\n \"\"\"\n help = 'Build an image.'\n\n def __init__(self):\n super().__init__()\n self._headless = True\n self._use_kvm = True\n self._num_cores = 1\n self._has_cow = False\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument('name', help=\n 'The name of the image to build. If empty, shows available images',\n nargs='*')\n parser.add_argument('-g', '--gui', action='store_true', help=\n 'Display QEMU GUI during image build')\n parser.add_argument('-c', '--cores', required=False, default=2,\n type=int, help=\n 'The number of cores used when building the VM image. Defaults to 2'\n )\n parser.add_argument('-x', '--clean', action='store_true', help=\n 'Deletes all images and rebuild them from scratch')\n parser.add_argument('-a', '--archive', action='store_true', help=\n 'Creates an archive for the specified image')\n parser.add_argument('-p', '--ftp-port', required=False, default=\n 15468, type=int, help=\n 'Port for the internal FTP server to receive files from guest VMs during build'\n )\n parser.add_argument('-d', '--download', action='store_true', help=\n 'Download image from the repository instead of building it')\n parser.add_argument('-i', '--iso-dir', help=\n 'Path to folder that stores ISO files of Windows images')\n parser.add_argument('-n', '--no-kvm', action='store_true', help=\n 'Disable KVM during image build')\n\n def handle(self, *args, **options):\n if options['gui']:\n self._headless = False\n if options['no_kvm']:\n self._use_kvm = False\n self._num_cores = options['cores']\n if not os.path.exists(self.image_path()):\n os.makedirs(self.image_path())\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n if options['clean']:\n self._invoke_make(img_build_dir, ['clean'])\n return\n image_names = options['name']\n templates = get_image_templates(img_build_dir)\n app_templates = get_app_templates(img_build_dir)\n images, image_groups, image_descriptors = get_all_images(templates,\n app_templates)\n if not image_names:\n self._print_image_list(images, image_groups, image_descriptors)\n print(\n \"\"\"\nRun ``s2e image_build <name>`` to build an image. Note that you must run ``s2e build`` **before** building an image\"\"\"\n )\n return\n image_names = translate_image_name(images, image_groups, image_names)\n logger.info('The following images will be built:')\n for image in image_names:\n logger.info(' * %s', image)\n if options['download']:\n _download_images(self.image_path(), image_names, templates)\n return\n rule_names = image_names\n if options['archive']:\n rule_names = _get_archive_rules(self.image_path(), image_names)\n iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'\n ] else None\n _check_product_keys(image_descriptors, image_names)\n _check_iso(templates, app_templates, iso_dir, image_names)\n if self._use_kvm:\n _check_kvm()\n _check_groups_kvm()\n _check_groups_docker()\n _check_vmlinux()\n self._has_cow = _check_cow(self.image_path())\n if self._use_kvm:\n _check_virtualbox()\n _check_vmware()\n if not _is_port_available(options['ftp_port']):\n raise CommandError(\n f\"localhost:{options['ftp_port']} is not available. Check that the port is free or specify a port with --ftp-port\"\n )\n self._clone_kernel()\n server = _start_ftp_server(self.image_path(), options['ftp_port'])\n self._invoke_make(img_build_dir, rule_names, options['ftp_port'],\n iso_dir)\n logger.success(\"Built image(s) '%s'\", ' '.join(image_names))\n server.close_all()\n\n def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):\n env = os.environ.copy()\n env['S2E_INSTALL_ROOT'] = self.install_path()\n env['S2E_LINUX_KERNELS_ROOT'] = self.source_path(CONSTANTS['repos']\n ['images']['linux'])\n env['OUTDIR'] = self.image_path()\n env['QEMU_FTP_PORT'] = str(ftp_port)\n env['ISODIR'] = iso_dir if iso_dir else ''\n env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'\n logger.debug('Invoking makefile with:')\n logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])\n logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env[\n 'S2E_LINUX_KERNELS_ROOT'])\n logger.debug('export OUTDIR=%s', env['OUTDIR'])\n logger.debug('export ISODIR=%s', env.get('ISODIR', ''))\n logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get(\n 'DEBUG_INTERMEDIATE_RULES', ''))\n if self._headless:\n logger.warning(\n 'Image creation will run in headless mode. Use --gui to see graphic output for debugging'\n )\n else:\n env['GRAPHICS'] = ''\n if not self._use_kvm:\n env['QEMU_KVM'] = ''\n logger.warning('Image build without KVM. This will be slow')\n try:\n make = sh.Command('make').bake(file=os.path.join(img_build_dir,\n 'Makefile'), directory=self.image_path(), _env=env, _fg=True)\n make_image = make.bake(j=self._num_cores, r=True,\n warn_undefined_variables=True)\n make_image(sorted(rule_names))\n except ErrorReturnCode as e:\n raise CommandError(e) from e\n\n def _clone_kernel(self):\n kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])\n if os.path.exists(kernels_root):\n logger.info('Kernel repository already exists in %s', kernels_root)\n return\n logger.info('Cloning kernels repository to %s', kernels_root)\n kernels_repo = CONSTANTS['repos']['images']['linux']\n repos.git_clone_to_source(self.env_path(), kernels_repo)\n\n def _print_image_list(self, images, image_groups, image_descriptors):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n templates = get_image_templates(img_build_dir)\n if not templates:\n images_json_path = os.path.join(img_build_dir, 'images.json')\n raise CommandError(\n f'No images available to build. Make sure that {images_json_path} exists and is valid'\n )\n\n def get_max_len(lst):\n ret = 0\n for item in lst:\n if len(item) > ret:\n ret = len(item)\n return ret\n print('Available image groups:')\n max_group_len = get_max_len(image_groups)\n for group in image_groups:\n print(f' * {group:{max_group_len}} - Build {group} images')\n print('\\nAvailable images:')\n max_image_len = get_max_len(images)\n for image in sorted(images):\n print(\n f\" * {image:{max_image_len}} - {image_descriptors[image]['name']}\"\n )\n\n def _print_apps_list(self):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n app_templates = get_app_templates(img_build_dir)\n if not app_templates:\n apps_json_path = os.path.join(img_build_dir, 'apps.json')\n raise CommandError(\n f'No apps available to build. Make sure that {apps_json_path} exists and is valid'\n )\n print('Available applications:')\n for app_template, desc in sorted(app_templates.items()):\n for base_image in desc['base_images']:\n print(f\" * {base_image}/{app_template} - {desc['name']}\")\n",
"step-3": "<mask token>\n\n\ndef _get_user_name():\n \"\"\"\n Get the current user.\n \"\"\"\n return pwd.getpwuid(os.getuid())[0]\n\n\ndef _user_belongs_to(group_name):\n \"\"\"\n Check that the current user belongs to the ``group_name`` group.\n \"\"\"\n user_name = _get_user_name()\n groups = _get_user_groups(user_name)\n return group_name in groups\n\n\n<mask token>\n\n\ndef _check_groups_kvm():\n \"\"\"Being member of KVM is required only when using KVM to build images\"\"\"\n if not _user_belongs_to('libvirtd') and not _user_belongs_to('kvm'):\n _raise_group_error('kvm')\n\n\n<mask token>\n\n\ndef _check_vmware():\n \"\"\"\n Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must\n *not* be running together with S2E.\n \"\"\"\n for proc in psutil.process_iter():\n try:\n if proc.name() == 'vmware-vmx':\n raise CommandError(\n 'S2E uses KVM to build images. VMware is currently running, which is not compatible with KVM. Please close all VMware VMs and try again.'\n )\n except NoSuchProcess:\n pass\n\n\ndef _check_kvm():\n \"\"\"\n Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.\n \"\"\"\n if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):\n raise CommandError(\n 'KVM interface not found - check that /dev/kvm exists. Alternatively, you can disable KVM (-n option) or download pre-built images (-d option)'\n )\n\n\ndef _check_vmlinux():\n \"\"\"\n Check that /boot/vmlinux* files are readable. This is important for guestfish.\n \"\"\"\n try:\n for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):\n with open(f, 'rb'):\n pass\n except IOError:\n raise CommandError(\n \"\"\"Make sure that the kernels in /boot are readable. This is required for guestfish. Please run the following command:\n\nsudo chmod ugo+r /boot/vmlinu*\"\"\"\n ) from None\n\n\ndef _check_cow(image_dir):\n \"\"\"\n Check that the file system that stores guest images supports copy-on-write.\n \"\"\"\n try:\n src = f'{image_dir}/.cowcheck'\n dst = f'{image_dir}/.cowcheck1'\n sh.touch(src)\n sh.cp('--reflink=always', src, dst)\n return True\n except Exception:\n warn_msg = f\"\"\"\n Copy-on-write check failed.\n The file system where images are stored ({image_dir}) does not support copy-on-write.\n It is recommended to use an XFS or BTRFS file system with copy-on-write enabled as a storage\n location for S2E images, as this can save up to 60% of disk space. The building process checkpoints\n intermediate build steps with cp --reflink=auto to make use of copy-on-write if it is available.\n\n How to upgrade:\n 1. Create an XFS or BTRFS partition large enough to store the images that you need (~300 GB for all images).\n Make sure you use reflink=1 to enable copy-on-write when running mkfs.xfs.\n 2. Create a directory for guest images on that partition (e.g., /mnt/disk1/images)\n 3. Delete the \"images\" folder in your S2E environment\n 4. Create in your S2E environment a symbolic link called \"images\" to the directory you created in step 2\n \"\"\"\n logger.warning(re.sub('^ {8}', '', warn_msg, flags=re.MULTILINE))\n return False\n finally:\n sh.rm('-f', src)\n sh.rm('-f', dst)\n\n\ndef _raise_invalid_image(image_name):\n raise CommandError(\n f'Invalid image name: {image_name}. Run ``s2e image_build`` to list available images'\n )\n\n\ndef _get_base_image_and_app(image_name):\n x = image_name.split('/')\n if len(x) == 1:\n return x[0], None\n if len(x) == 2:\n return x\n raise CommandError(f'Invalid image name {image_name}')\n\n\ndef _has_app_image(image_names):\n for name in image_names:\n if '/' in name:\n return True\n return False\n\n\ndef _check_product_keys(image_descriptors, image_names):\n missing_keys = []\n for image_name in image_names:\n image = image_descriptors[image_name]\n if 'product_key' in image:\n if not image['product_key']:\n missing_keys.append(image_name)\n ios = image_descriptors[image_name].get('os', {})\n if 'product_key' in ios:\n if not ios['product_key']:\n missing_keys.append(image_name)\n if missing_keys:\n logger.error('The following images require a product key:')\n for image in missing_keys:\n logger.error(' * %s', image)\n raise CommandError('Please update images.json and/or apps.json.')\n\n\ndef _check_iso(templates, app_templates, iso_dir, image_names):\n for image_name in image_names:\n base_image, app_name = _get_base_image_and_app(image_name)\n descriptors = [templates[base_image]]\n if app_name:\n descriptors.append(app_templates[app_name])\n for desc in descriptors:\n iso = desc.get('iso', {})\n if iso.get('url', ''):\n continue\n name = iso.get('name', '')\n if not name:\n continue\n if not iso_dir:\n raise CommandError(\n f'Please use the --iso-dir option to specify the path to a folder that contains {name}'\n )\n path = os.path.join(iso_dir, name)\n if not os.path.exists(path):\n raise CommandError(\n f'The image {image_name} requires {path}, which could not be found'\n )\n\n\n<mask token>\n\n\ndef _start_ftp_server(image_path, port):\n authorizer = DummyAuthorizer()\n authorizer.add_anonymous(image_path, perm='elradfmwMT')\n handler = FTPHandler\n handler.authorizer = authorizer\n handler.masquerade_address = '10.0.2.2'\n handler.timeout = None\n server = FTPServer(('127.0.0.1', port), handler)\n thread = Thread(target=_run_ftp_server, args=[server])\n thread.daemon = True\n thread.start()\n time.sleep(1)\n return server\n\n\n<mask token>\n\n\ndef _get_archive_rules(image_path, rule_names):\n if _has_app_image(rule_names):\n raise CommandError(\n 'Building archives of app images is not supported yet')\n archive_rules = []\n for r in rule_names:\n archive_rules.append(os.path.join(image_path, f'{r}.tar.xz'))\n logger.info('The following archives will be built:')\n for a in archive_rules:\n logger.info(' * %s', a)\n return archive_rules\n\n\n<mask token>\n\n\nclass Command(EnvCommand):\n \"\"\"\n Builds an image.\n \"\"\"\n help = 'Build an image.'\n\n def __init__(self):\n super().__init__()\n self._headless = True\n self._use_kvm = True\n self._num_cores = 1\n self._has_cow = False\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument('name', help=\n 'The name of the image to build. If empty, shows available images',\n nargs='*')\n parser.add_argument('-g', '--gui', action='store_true', help=\n 'Display QEMU GUI during image build')\n parser.add_argument('-c', '--cores', required=False, default=2,\n type=int, help=\n 'The number of cores used when building the VM image. Defaults to 2'\n )\n parser.add_argument('-x', '--clean', action='store_true', help=\n 'Deletes all images and rebuild them from scratch')\n parser.add_argument('-a', '--archive', action='store_true', help=\n 'Creates an archive for the specified image')\n parser.add_argument('-p', '--ftp-port', required=False, default=\n 15468, type=int, help=\n 'Port for the internal FTP server to receive files from guest VMs during build'\n )\n parser.add_argument('-d', '--download', action='store_true', help=\n 'Download image from the repository instead of building it')\n parser.add_argument('-i', '--iso-dir', help=\n 'Path to folder that stores ISO files of Windows images')\n parser.add_argument('-n', '--no-kvm', action='store_true', help=\n 'Disable KVM during image build')\n\n def handle(self, *args, **options):\n if options['gui']:\n self._headless = False\n if options['no_kvm']:\n self._use_kvm = False\n self._num_cores = options['cores']\n if not os.path.exists(self.image_path()):\n os.makedirs(self.image_path())\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n if options['clean']:\n self._invoke_make(img_build_dir, ['clean'])\n return\n image_names = options['name']\n templates = get_image_templates(img_build_dir)\n app_templates = get_app_templates(img_build_dir)\n images, image_groups, image_descriptors = get_all_images(templates,\n app_templates)\n if not image_names:\n self._print_image_list(images, image_groups, image_descriptors)\n print(\n \"\"\"\nRun ``s2e image_build <name>`` to build an image. Note that you must run ``s2e build`` **before** building an image\"\"\"\n )\n return\n image_names = translate_image_name(images, image_groups, image_names)\n logger.info('The following images will be built:')\n for image in image_names:\n logger.info(' * %s', image)\n if options['download']:\n _download_images(self.image_path(), image_names, templates)\n return\n rule_names = image_names\n if options['archive']:\n rule_names = _get_archive_rules(self.image_path(), image_names)\n iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'\n ] else None\n _check_product_keys(image_descriptors, image_names)\n _check_iso(templates, app_templates, iso_dir, image_names)\n if self._use_kvm:\n _check_kvm()\n _check_groups_kvm()\n _check_groups_docker()\n _check_vmlinux()\n self._has_cow = _check_cow(self.image_path())\n if self._use_kvm:\n _check_virtualbox()\n _check_vmware()\n if not _is_port_available(options['ftp_port']):\n raise CommandError(\n f\"localhost:{options['ftp_port']} is not available. Check that the port is free or specify a port with --ftp-port\"\n )\n self._clone_kernel()\n server = _start_ftp_server(self.image_path(), options['ftp_port'])\n self._invoke_make(img_build_dir, rule_names, options['ftp_port'],\n iso_dir)\n logger.success(\"Built image(s) '%s'\", ' '.join(image_names))\n server.close_all()\n\n def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):\n env = os.environ.copy()\n env['S2E_INSTALL_ROOT'] = self.install_path()\n env['S2E_LINUX_KERNELS_ROOT'] = self.source_path(CONSTANTS['repos']\n ['images']['linux'])\n env['OUTDIR'] = self.image_path()\n env['QEMU_FTP_PORT'] = str(ftp_port)\n env['ISODIR'] = iso_dir if iso_dir else ''\n env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'\n logger.debug('Invoking makefile with:')\n logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])\n logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env[\n 'S2E_LINUX_KERNELS_ROOT'])\n logger.debug('export OUTDIR=%s', env['OUTDIR'])\n logger.debug('export ISODIR=%s', env.get('ISODIR', ''))\n logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get(\n 'DEBUG_INTERMEDIATE_RULES', ''))\n if self._headless:\n logger.warning(\n 'Image creation will run in headless mode. Use --gui to see graphic output for debugging'\n )\n else:\n env['GRAPHICS'] = ''\n if not self._use_kvm:\n env['QEMU_KVM'] = ''\n logger.warning('Image build without KVM. This will be slow')\n try:\n make = sh.Command('make').bake(file=os.path.join(img_build_dir,\n 'Makefile'), directory=self.image_path(), _env=env, _fg=True)\n make_image = make.bake(j=self._num_cores, r=True,\n warn_undefined_variables=True)\n make_image(sorted(rule_names))\n except ErrorReturnCode as e:\n raise CommandError(e) from e\n\n def _clone_kernel(self):\n kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])\n if os.path.exists(kernels_root):\n logger.info('Kernel repository already exists in %s', kernels_root)\n return\n logger.info('Cloning kernels repository to %s', kernels_root)\n kernels_repo = CONSTANTS['repos']['images']['linux']\n repos.git_clone_to_source(self.env_path(), kernels_repo)\n\n def _print_image_list(self, images, image_groups, image_descriptors):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n templates = get_image_templates(img_build_dir)\n if not templates:\n images_json_path = os.path.join(img_build_dir, 'images.json')\n raise CommandError(\n f'No images available to build. Make sure that {images_json_path} exists and is valid'\n )\n\n def get_max_len(lst):\n ret = 0\n for item in lst:\n if len(item) > ret:\n ret = len(item)\n return ret\n print('Available image groups:')\n max_group_len = get_max_len(image_groups)\n for group in image_groups:\n print(f' * {group:{max_group_len}} - Build {group} images')\n print('\\nAvailable images:')\n max_image_len = get_max_len(images)\n for image in sorted(images):\n print(\n f\" * {image:{max_image_len}} - {image_descriptors[image]['name']}\"\n )\n\n def _print_apps_list(self):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n app_templates = get_app_templates(img_build_dir)\n if not app_templates:\n apps_json_path = os.path.join(img_build_dir, 'apps.json')\n raise CommandError(\n f'No apps available to build. Make sure that {apps_json_path} exists and is valid'\n )\n print('Available applications:')\n for app_template, desc in sorted(app_templates.items()):\n for base_image in desc['base_images']:\n print(f\" * {base_image}/{app_template} - {desc['name']}\")\n",
"step-4": "<mask token>\n\n\ndef _get_user_groups(user_name):\n \"\"\"\n Get a list of groups for the user ``user_name``.\n \"\"\"\n groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]\n gid = pwd.getpwnam(user_name).pw_gid\n groups.append(grp.getgrgid(gid).gr_name)\n return groups\n\n\ndef _get_user_name():\n \"\"\"\n Get the current user.\n \"\"\"\n return pwd.getpwuid(os.getuid())[0]\n\n\ndef _user_belongs_to(group_name):\n \"\"\"\n Check that the current user belongs to the ``group_name`` group.\n \"\"\"\n user_name = _get_user_name()\n groups = _get_user_groups(user_name)\n return group_name in groups\n\n\ndef _raise_group_error(group_name):\n raise CommandError(\n f\"\"\"You must belong to the {group_name} group in order to build images. Please run the following command, then logout and login:\n\n\tsudo usermod -a -G {group_name} $(whoami)\"\"\"\n )\n\n\ndef _check_groups_docker():\n \"\"\"\n Check that the current user belongs to the required groups to both run S2E and build S2E images.\n \"\"\"\n if not _user_belongs_to('docker'):\n _raise_group_error('docker')\n\n\ndef _check_groups_kvm():\n \"\"\"Being member of KVM is required only when using KVM to build images\"\"\"\n if not _user_belongs_to('libvirtd') and not _user_belongs_to('kvm'):\n _raise_group_error('kvm')\n\n\ndef _check_virtualbox():\n \"\"\"\n Check if VirtualBox is running. VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must\n *not* be running together with S2E.\n \"\"\"\n for proc in psutil.process_iter():\n try:\n if proc.name() == 'VBoxHeadless':\n raise CommandError(\n 'S2E uses KVM to build images. VirtualBox is currently running, which is not compatible with KVM. Please close all VirtualBox VMs and try again.'\n )\n except NoSuchProcess:\n pass\n\n\ndef _check_vmware():\n \"\"\"\n Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must\n *not* be running together with S2E.\n \"\"\"\n for proc in psutil.process_iter():\n try:\n if proc.name() == 'vmware-vmx':\n raise CommandError(\n 'S2E uses KVM to build images. VMware is currently running, which is not compatible with KVM. Please close all VMware VMs and try again.'\n )\n except NoSuchProcess:\n pass\n\n\ndef _check_kvm():\n \"\"\"\n Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.\n \"\"\"\n if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):\n raise CommandError(\n 'KVM interface not found - check that /dev/kvm exists. Alternatively, you can disable KVM (-n option) or download pre-built images (-d option)'\n )\n\n\ndef _check_vmlinux():\n \"\"\"\n Check that /boot/vmlinux* files are readable. This is important for guestfish.\n \"\"\"\n try:\n for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):\n with open(f, 'rb'):\n pass\n except IOError:\n raise CommandError(\n \"\"\"Make sure that the kernels in /boot are readable. This is required for guestfish. Please run the following command:\n\nsudo chmod ugo+r /boot/vmlinu*\"\"\"\n ) from None\n\n\ndef _check_cow(image_dir):\n \"\"\"\n Check that the file system that stores guest images supports copy-on-write.\n \"\"\"\n try:\n src = f'{image_dir}/.cowcheck'\n dst = f'{image_dir}/.cowcheck1'\n sh.touch(src)\n sh.cp('--reflink=always', src, dst)\n return True\n except Exception:\n warn_msg = f\"\"\"\n Copy-on-write check failed.\n The file system where images are stored ({image_dir}) does not support copy-on-write.\n It is recommended to use an XFS or BTRFS file system with copy-on-write enabled as a storage\n location for S2E images, as this can save up to 60% of disk space. The building process checkpoints\n intermediate build steps with cp --reflink=auto to make use of copy-on-write if it is available.\n\n How to upgrade:\n 1. Create an XFS or BTRFS partition large enough to store the images that you need (~300 GB for all images).\n Make sure you use reflink=1 to enable copy-on-write when running mkfs.xfs.\n 2. Create a directory for guest images on that partition (e.g., /mnt/disk1/images)\n 3. Delete the \"images\" folder in your S2E environment\n 4. Create in your S2E environment a symbolic link called \"images\" to the directory you created in step 2\n \"\"\"\n logger.warning(re.sub('^ {8}', '', warn_msg, flags=re.MULTILINE))\n return False\n finally:\n sh.rm('-f', src)\n sh.rm('-f', dst)\n\n\ndef _raise_invalid_image(image_name):\n raise CommandError(\n f'Invalid image name: {image_name}. Run ``s2e image_build`` to list available images'\n )\n\n\ndef _get_base_image_and_app(image_name):\n x = image_name.split('/')\n if len(x) == 1:\n return x[0], None\n if len(x) == 2:\n return x\n raise CommandError(f'Invalid image name {image_name}')\n\n\ndef _has_app_image(image_names):\n for name in image_names:\n if '/' in name:\n return True\n return False\n\n\ndef _check_product_keys(image_descriptors, image_names):\n missing_keys = []\n for image_name in image_names:\n image = image_descriptors[image_name]\n if 'product_key' in image:\n if not image['product_key']:\n missing_keys.append(image_name)\n ios = image_descriptors[image_name].get('os', {})\n if 'product_key' in ios:\n if not ios['product_key']:\n missing_keys.append(image_name)\n if missing_keys:\n logger.error('The following images require a product key:')\n for image in missing_keys:\n logger.error(' * %s', image)\n raise CommandError('Please update images.json and/or apps.json.')\n\n\ndef _check_iso(templates, app_templates, iso_dir, image_names):\n for image_name in image_names:\n base_image, app_name = _get_base_image_and_app(image_name)\n descriptors = [templates[base_image]]\n if app_name:\n descriptors.append(app_templates[app_name])\n for desc in descriptors:\n iso = desc.get('iso', {})\n if iso.get('url', ''):\n continue\n name = iso.get('name', '')\n if not name:\n continue\n if not iso_dir:\n raise CommandError(\n f'Please use the --iso-dir option to specify the path to a folder that contains {name}'\n )\n path = os.path.join(iso_dir, name)\n if not os.path.exists(path):\n raise CommandError(\n f'The image {image_name} requires {path}, which could not be found'\n )\n\n\ndef _is_port_available(port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.bind(('127.0.0.1', port))\n return True\n except socket.error:\n return False\n finally:\n s.close()\n\n\ndef _start_ftp_server(image_path, port):\n authorizer = DummyAuthorizer()\n authorizer.add_anonymous(image_path, perm='elradfmwMT')\n handler = FTPHandler\n handler.authorizer = authorizer\n handler.masquerade_address = '10.0.2.2'\n handler.timeout = None\n server = FTPServer(('127.0.0.1', port), handler)\n thread = Thread(target=_run_ftp_server, args=[server])\n thread.daemon = True\n thread.start()\n time.sleep(1)\n return server\n\n\ndef _run_ftp_server(server):\n try:\n server.serve_forever()\n finally:\n logger.info('FTP server terminated')\n server.close_all()\n\n\ndef _get_archive_rules(image_path, rule_names):\n if _has_app_image(rule_names):\n raise CommandError(\n 'Building archives of app images is not supported yet')\n archive_rules = []\n for r in rule_names:\n archive_rules.append(os.path.join(image_path, f'{r}.tar.xz'))\n logger.info('The following archives will be built:')\n for a in archive_rules:\n logger.info(' * %s', a)\n return archive_rules\n\n\n<mask token>\n\n\nclass Command(EnvCommand):\n \"\"\"\n Builds an image.\n \"\"\"\n help = 'Build an image.'\n\n def __init__(self):\n super().__init__()\n self._headless = True\n self._use_kvm = True\n self._num_cores = 1\n self._has_cow = False\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument('name', help=\n 'The name of the image to build. If empty, shows available images',\n nargs='*')\n parser.add_argument('-g', '--gui', action='store_true', help=\n 'Display QEMU GUI during image build')\n parser.add_argument('-c', '--cores', required=False, default=2,\n type=int, help=\n 'The number of cores used when building the VM image. Defaults to 2'\n )\n parser.add_argument('-x', '--clean', action='store_true', help=\n 'Deletes all images and rebuild them from scratch')\n parser.add_argument('-a', '--archive', action='store_true', help=\n 'Creates an archive for the specified image')\n parser.add_argument('-p', '--ftp-port', required=False, default=\n 15468, type=int, help=\n 'Port for the internal FTP server to receive files from guest VMs during build'\n )\n parser.add_argument('-d', '--download', action='store_true', help=\n 'Download image from the repository instead of building it')\n parser.add_argument('-i', '--iso-dir', help=\n 'Path to folder that stores ISO files of Windows images')\n parser.add_argument('-n', '--no-kvm', action='store_true', help=\n 'Disable KVM during image build')\n\n def handle(self, *args, **options):\n if options['gui']:\n self._headless = False\n if options['no_kvm']:\n self._use_kvm = False\n self._num_cores = options['cores']\n if not os.path.exists(self.image_path()):\n os.makedirs(self.image_path())\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n if options['clean']:\n self._invoke_make(img_build_dir, ['clean'])\n return\n image_names = options['name']\n templates = get_image_templates(img_build_dir)\n app_templates = get_app_templates(img_build_dir)\n images, image_groups, image_descriptors = get_all_images(templates,\n app_templates)\n if not image_names:\n self._print_image_list(images, image_groups, image_descriptors)\n print(\n \"\"\"\nRun ``s2e image_build <name>`` to build an image. Note that you must run ``s2e build`` **before** building an image\"\"\"\n )\n return\n image_names = translate_image_name(images, image_groups, image_names)\n logger.info('The following images will be built:')\n for image in image_names:\n logger.info(' * %s', image)\n if options['download']:\n _download_images(self.image_path(), image_names, templates)\n return\n rule_names = image_names\n if options['archive']:\n rule_names = _get_archive_rules(self.image_path(), image_names)\n iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'\n ] else None\n _check_product_keys(image_descriptors, image_names)\n _check_iso(templates, app_templates, iso_dir, image_names)\n if self._use_kvm:\n _check_kvm()\n _check_groups_kvm()\n _check_groups_docker()\n _check_vmlinux()\n self._has_cow = _check_cow(self.image_path())\n if self._use_kvm:\n _check_virtualbox()\n _check_vmware()\n if not _is_port_available(options['ftp_port']):\n raise CommandError(\n f\"localhost:{options['ftp_port']} is not available. Check that the port is free or specify a port with --ftp-port\"\n )\n self._clone_kernel()\n server = _start_ftp_server(self.image_path(), options['ftp_port'])\n self._invoke_make(img_build_dir, rule_names, options['ftp_port'],\n iso_dir)\n logger.success(\"Built image(s) '%s'\", ' '.join(image_names))\n server.close_all()\n\n def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):\n env = os.environ.copy()\n env['S2E_INSTALL_ROOT'] = self.install_path()\n env['S2E_LINUX_KERNELS_ROOT'] = self.source_path(CONSTANTS['repos']\n ['images']['linux'])\n env['OUTDIR'] = self.image_path()\n env['QEMU_FTP_PORT'] = str(ftp_port)\n env['ISODIR'] = iso_dir if iso_dir else ''\n env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'\n logger.debug('Invoking makefile with:')\n logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])\n logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env[\n 'S2E_LINUX_KERNELS_ROOT'])\n logger.debug('export OUTDIR=%s', env['OUTDIR'])\n logger.debug('export ISODIR=%s', env.get('ISODIR', ''))\n logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get(\n 'DEBUG_INTERMEDIATE_RULES', ''))\n if self._headless:\n logger.warning(\n 'Image creation will run in headless mode. Use --gui to see graphic output for debugging'\n )\n else:\n env['GRAPHICS'] = ''\n if not self._use_kvm:\n env['QEMU_KVM'] = ''\n logger.warning('Image build without KVM. This will be slow')\n try:\n make = sh.Command('make').bake(file=os.path.join(img_build_dir,\n 'Makefile'), directory=self.image_path(), _env=env, _fg=True)\n make_image = make.bake(j=self._num_cores, r=True,\n warn_undefined_variables=True)\n make_image(sorted(rule_names))\n except ErrorReturnCode as e:\n raise CommandError(e) from e\n\n def _clone_kernel(self):\n kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])\n if os.path.exists(kernels_root):\n logger.info('Kernel repository already exists in %s', kernels_root)\n return\n logger.info('Cloning kernels repository to %s', kernels_root)\n kernels_repo = CONSTANTS['repos']['images']['linux']\n repos.git_clone_to_source(self.env_path(), kernels_repo)\n\n def _print_image_list(self, images, image_groups, image_descriptors):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n templates = get_image_templates(img_build_dir)\n if not templates:\n images_json_path = os.path.join(img_build_dir, 'images.json')\n raise CommandError(\n f'No images available to build. Make sure that {images_json_path} exists and is valid'\n )\n\n def get_max_len(lst):\n ret = 0\n for item in lst:\n if len(item) > ret:\n ret = len(item)\n return ret\n print('Available image groups:')\n max_group_len = get_max_len(image_groups)\n for group in image_groups:\n print(f' * {group:{max_group_len}} - Build {group} images')\n print('\\nAvailable images:')\n max_image_len = get_max_len(images)\n for image in sorted(images):\n print(\n f\" * {image:{max_image_len}} - {image_descriptors[image]['name']}\"\n )\n\n def _print_apps_list(self):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n app_templates = get_app_templates(img_build_dir)\n if not app_templates:\n apps_json_path = os.path.join(img_build_dir, 'apps.json')\n raise CommandError(\n f'No apps available to build. Make sure that {apps_json_path} exists and is valid'\n )\n print('Available applications:')\n for app_template, desc in sorted(app_templates.items()):\n for base_image in desc['base_images']:\n print(f\" * {base_image}/{app_template} - {desc['name']}\")\n",
"step-5": "\"\"\"\nCopyright (c) 2017 Cyberhaven\nCopyright (c) 2017 Dependable Systems Laboratory, EPFL\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\n\nimport glob\nimport grp\nimport logging\nimport os\nimport pwd\nimport re\nimport socket\nimport time\n\nfrom threading import Thread\n\nimport psutil\nfrom psutil import NoSuchProcess\n\nfrom pyftpdlib.authorizers import DummyAuthorizer\nfrom pyftpdlib.handlers import FTPHandler\nfrom pyftpdlib.servers import FTPServer\n\nimport sh\nfrom sh import ErrorReturnCode\n\nfrom s2e_env import CONSTANTS\nfrom s2e_env.command import EnvCommand, CommandError\nfrom s2e_env.utils import repos\nfrom s2e_env.utils.images import ImageDownloader, get_image_templates, get_app_templates, get_all_images, \\\n translate_image_name\n\n\nlogger = logging.getLogger('image_build')\n\n\ndef _get_user_groups(user_name):\n \"\"\"\n Get a list of groups for the user ``user_name``.\n \"\"\"\n groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]\n gid = pwd.getpwnam(user_name).pw_gid\n groups.append(grp.getgrgid(gid).gr_name)\n\n return groups\n\n\ndef _get_user_name():\n \"\"\"\n Get the current user.\n \"\"\"\n return pwd.getpwuid(os.getuid())[0]\n\n\ndef _user_belongs_to(group_name):\n \"\"\"\n Check that the current user belongs to the ``group_name`` group.\n \"\"\"\n user_name = _get_user_name()\n groups = _get_user_groups(user_name)\n return group_name in groups\n\n\ndef _raise_group_error(group_name):\n raise CommandError(f'You must belong to the {group_name} group in order to build '\n 'images. Please run the following command, then logout '\n 'and login:\\n\\n'\n f'\\tsudo usermod -a -G {group_name} $(whoami)')\n\n\ndef _check_groups_docker():\n \"\"\"\n Check that the current user belongs to the required groups to both run S2E and build S2E images.\n \"\"\"\n if not _user_belongs_to('docker'):\n _raise_group_error('docker')\n\n\ndef _check_groups_kvm():\n \"\"\"Being member of KVM is required only when using KVM to build images\"\"\"\n if not _user_belongs_to('libvirtd') and not _user_belongs_to('kvm'):\n _raise_group_error('kvm')\n\n\ndef _check_virtualbox():\n \"\"\"\n Check if VirtualBox is running. VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must\n *not* be running together with S2E.\n \"\"\"\n # Adapted from https://github.com/giampaolo/psutil/issues/132#issuecomment-44017679\n # to avoid race conditions\n for proc in psutil.process_iter():\n try:\n if proc.name() == 'VBoxHeadless':\n raise CommandError('S2E uses KVM to build images. VirtualBox '\n 'is currently running, which is not '\n 'compatible with KVM. Please close all '\n 'VirtualBox VMs and try again.')\n except NoSuchProcess:\n pass\n\n\ndef _check_vmware():\n \"\"\"\n Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must\n *not* be running together with S2E.\n \"\"\"\n for proc in psutil.process_iter():\n try:\n if proc.name() == 'vmware-vmx':\n raise CommandError('S2E uses KVM to build images. VMware '\n 'is currently running, which is not '\n 'compatible with KVM. Please close all '\n 'VMware VMs and try again.')\n except NoSuchProcess:\n pass\n\n\ndef _check_kvm():\n \"\"\"\n Check that the KVM interface exists. This is required by libs2e to communicate with QEMU.\n \"\"\"\n if not os.path.exists(os.path.join(os.sep, 'dev', 'kvm')):\n raise CommandError('KVM interface not found - check that /dev/kvm '\n 'exists. Alternatively, you can disable KVM (-n '\n 'option) or download pre-built images (-d option)')\n\n\ndef _check_vmlinux():\n \"\"\"\n Check that /boot/vmlinux* files are readable. This is important for guestfish.\n \"\"\"\n try:\n for f in glob.glob(os.path.join(os.sep, 'boot', 'vmlinu*')):\n with open(f, 'rb'):\n pass\n except IOError:\n raise CommandError('Make sure that the kernels in /boot are readable. '\n 'This is required for guestfish. Please run the '\n 'following command:\\n\\n'\n 'sudo chmod ugo+r /boot/vmlinu*') from None\n\n\n# pylint: disable=no-member\ndef _check_cow(image_dir):\n \"\"\"\n Check that the file system that stores guest images supports copy-on-write.\n \"\"\"\n try:\n src = f'{image_dir}/.cowcheck'\n dst = f'{image_dir}/.cowcheck1'\n sh.touch(src)\n sh.cp('--reflink=always', src, dst)\n return True\n except Exception:\n warn_msg = f\"\"\"\n Copy-on-write check failed.\n The file system where images are stored ({image_dir}) does not support copy-on-write.\n It is recommended to use an XFS or BTRFS file system with copy-on-write enabled as a storage\n location for S2E images, as this can save up to 60% of disk space. The building process checkpoints\n intermediate build steps with cp --reflink=auto to make use of copy-on-write if it is available.\n\n How to upgrade:\n 1. Create an XFS or BTRFS partition large enough to store the images that you need (~300 GB for all images).\n Make sure you use reflink=1 to enable copy-on-write when running mkfs.xfs.\n 2. Create a directory for guest images on that partition (e.g., /mnt/disk1/images)\n 3. Delete the \"images\" folder in your S2E environment\n 4. Create in your S2E environment a symbolic link called \"images\" to the directory you created in step 2\n \"\"\"\n logger.warning(re.sub(r'^ {8}', '', warn_msg, flags=re.MULTILINE))\n return False\n finally:\n sh.rm('-f', src)\n sh.rm('-f', dst)\n\n\ndef _raise_invalid_image(image_name):\n raise CommandError(f'Invalid image name: {image_name}. Run ``s2e image_build`` '\n 'to list available images')\n\n\ndef _get_base_image_and_app(image_name):\n x = image_name.split('/')\n if len(x) == 1:\n return x[0], None\n if len(x) == 2:\n return x\n raise CommandError(f'Invalid image name {image_name}')\n\n\ndef _has_app_image(image_names):\n for name in image_names:\n if '/' in name:\n return True\n return False\n\n\ndef _check_product_keys(image_descriptors, image_names):\n missing_keys = []\n\n for image_name in image_names:\n image = image_descriptors[image_name]\n\n if 'product_key' in image:\n if not image['product_key']:\n missing_keys.append(image_name)\n\n ios = image_descriptors[image_name].get('os', {})\n if 'product_key' in ios:\n if not ios['product_key']:\n missing_keys.append(image_name)\n\n if missing_keys:\n logger.error('The following images require a product key:')\n for image in missing_keys:\n logger.error(' * %s', image)\n\n raise CommandError('Please update images.json and/or apps.json.')\n\n\ndef _check_iso(templates, app_templates, iso_dir, image_names):\n for image_name in image_names:\n base_image, app_name = _get_base_image_and_app(image_name)\n\n descriptors = [templates[base_image]]\n if app_name:\n descriptors.append(app_templates[app_name])\n\n for desc in descriptors:\n iso = desc.get('iso', {})\n if iso.get('url', ''):\n continue\n\n name = iso.get('name', '')\n if not name:\n continue\n\n if not iso_dir:\n raise CommandError(\n 'Please use the --iso-dir option to specify the path '\n f'to a folder that contains {name}'\n )\n\n path = os.path.join(iso_dir, name)\n if not os.path.exists(path):\n raise CommandError(f'The image {image_name} requires {path}, which could not be found')\n\n\ndef _is_port_available(port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:\n s.bind((\"127.0.0.1\", port))\n return True\n except socket.error:\n return False\n finally:\n s.close()\n\n\ndef _start_ftp_server(image_path, port):\n authorizer = DummyAuthorizer()\n authorizer.add_anonymous(image_path, perm='elradfmwMT')\n handler = FTPHandler\n handler.authorizer = authorizer\n handler.masquerade_address = '10.0.2.2'\n # QEMU slirp won't let the guest reconnect if timeout happens, so we disable it\n handler.timeout = None\n\n server = FTPServer((\"127.0.0.1\", port), handler)\n\n thread = Thread(target=_run_ftp_server, args=[server])\n thread.daemon = True\n thread.start()\n time.sleep(1)\n\n return server\n\n\ndef _run_ftp_server(server):\n try:\n server.serve_forever()\n finally:\n logger.info('FTP server terminated')\n server.close_all()\n\n\ndef _get_archive_rules(image_path, rule_names):\n if _has_app_image(rule_names):\n raise CommandError('Building archives of app images is not supported yet')\n\n archive_rules = []\n for r in rule_names:\n archive_rules.append(os.path.join(image_path, f'{r}.tar.xz'))\n\n logger.info('The following archives will be built:')\n for a in archive_rules:\n logger.info(' * %s', a)\n\n return archive_rules\n\n\ndef _download_images(image_path, image_names, templates):\n if _has_app_image(image_names):\n raise CommandError('Downloading of app images is not supported yet')\n\n image_downloader = ImageDownloader(templates)\n image_downloader.download_images(image_names, image_path)\n\n logger.info('Successfully downloaded images: %s', ', '.join(image_names))\n\n\nclass Command(EnvCommand):\n \"\"\"\n Builds an image.\n \"\"\"\n\n help = 'Build an image.'\n\n def __init__(self):\n super().__init__()\n\n self._headless = True\n self._use_kvm = True\n self._num_cores = 1\n self._has_cow = False\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n\n parser.add_argument('name',\n help='The name of the image to build. If empty,'\n ' shows available images', nargs='*')\n parser.add_argument('-g', '--gui', action='store_true',\n help='Display QEMU GUI during image build')\n parser.add_argument('-c', '--cores', required=False, default=2,\n type=int,\n help='The number of cores used when building the '\n 'VM image. Defaults to 2')\n parser.add_argument('-x', '--clean', action='store_true',\n help='Deletes all images and rebuild them from '\n 'scratch')\n parser.add_argument('-a', '--archive', action='store_true',\n help='Creates an archive for the specified image')\n parser.add_argument('-p', '--ftp-port', required=False, default=15468, type=int,\n help='Port for the internal FTP server to receive files from guest VMs during build')\n parser.add_argument('-d', '--download', action='store_true',\n help='Download image from the repository instead '\n 'of building it')\n parser.add_argument('-i', '--iso-dir',\n help='Path to folder that stores ISO files of Windows images')\n parser.add_argument('-n', '--no-kvm', action='store_true',\n help='Disable KVM during image build')\n\n def handle(self, *args, **options):\n # If DISPLAY is missing, don't use headless mode\n if options['gui']:\n self._headless = False\n\n # If KVM has been explicitly disabled, don't use it during the build\n if options['no_kvm']:\n self._use_kvm = False\n\n self._num_cores = options['cores']\n\n # The path could have been deleted by a previous clean\n if not os.path.exists(self.image_path()):\n os.makedirs(self.image_path())\n\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n\n if options['clean']:\n self._invoke_make(img_build_dir, ['clean'])\n return\n\n image_names = options['name']\n templates = get_image_templates(img_build_dir)\n app_templates = get_app_templates(img_build_dir)\n images, image_groups, image_descriptors = get_all_images(templates, app_templates)\n\n if not image_names:\n self._print_image_list(images, image_groups, image_descriptors)\n print('\\nRun ``s2e image_build <name>`` to build an image. '\n 'Note that you must run ``s2e build`` **before** building '\n 'an image')\n return\n\n image_names = translate_image_name(images, image_groups, image_names)\n logger.info('The following images will be built:')\n for image in image_names:\n logger.info(' * %s', image)\n\n if options['download']:\n _download_images(self.image_path(), image_names, templates)\n return\n\n rule_names = image_names\n\n if options['archive']:\n rule_names = _get_archive_rules(self.image_path(), image_names)\n\n iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'] else None\n\n # Check for optional product keys and iso directories.\n # These may or may not be required, depending on the set of images.\n _check_product_keys(image_descriptors, image_names)\n _check_iso(templates, app_templates, iso_dir, image_names)\n\n if self._use_kvm:\n _check_kvm()\n _check_groups_kvm()\n\n _check_groups_docker()\n _check_vmlinux()\n\n self._has_cow = _check_cow(self.image_path())\n\n if self._use_kvm:\n _check_virtualbox()\n _check_vmware()\n\n if not _is_port_available(options['ftp_port']):\n raise CommandError(f'localhost:{options[\"ftp_port\"]} is not available. Check that the port is free or '\n 'specify a port with --ftp-port')\n\n # Clone kernel if needed.\n # This is necessary if the s2e env has been initialized with -b flag.\n self._clone_kernel()\n\n server = _start_ftp_server(self.image_path(), options['ftp_port'])\n\n self._invoke_make(img_build_dir, rule_names, options['ftp_port'], iso_dir)\n\n logger.success('Built image(s) \\'%s\\'', ' '.join(image_names))\n\n server.close_all()\n\n def _invoke_make(self, img_build_dir, rule_names, ftp_port=0, iso_dir=''):\n env = os.environ.copy()\n env['S2E_INSTALL_ROOT'] = self.install_path()\n env['S2E_LINUX_KERNELS_ROOT'] = \\\n self.source_path(CONSTANTS['repos']['images']['linux'])\n env['OUTDIR'] = self.image_path()\n env['QEMU_FTP_PORT'] = str(ftp_port)\n env['ISODIR'] = iso_dir if iso_dir else ''\n env['DEBUG_INTERMEDIATE_RULES'] = '1' if self._has_cow else '0'\n\n logger.debug('Invoking makefile with:')\n logger.debug('export S2E_INSTALL_ROOT=%s', env['S2E_INSTALL_ROOT'])\n logger.debug('export S2E_LINUX_KERNELS_ROOT=%s', env['S2E_LINUX_KERNELS_ROOT'])\n logger.debug('export OUTDIR=%s', env['OUTDIR'])\n logger.debug('export ISODIR=%s', env.get('ISODIR', ''))\n logger.debug('export DEBUG_INTERMEDIATE_RULES=%s', env.get('DEBUG_INTERMEDIATE_RULES', ''))\n\n if self._headless:\n logger.warning('Image creation will run in headless mode. '\n 'Use --gui to see graphic output for debugging')\n else:\n env['GRAPHICS'] = ''\n\n if not self._use_kvm:\n env['QEMU_KVM'] = ''\n logger.warning('Image build without KVM. This will be slow')\n\n try:\n make = sh.Command('make').bake(file=os.path.join(img_build_dir,\n 'Makefile'),\n directory=self.image_path(),\n _env=env, _fg=True)\n\n make_image = make.bake(j=self._num_cores, r=True, warn_undefined_variables=True)\n make_image(sorted(rule_names))\n except ErrorReturnCode as e:\n raise CommandError(e) from e\n\n def _clone_kernel(self):\n kernels_root = self.source_path(CONSTANTS['repos']['images']['linux'])\n if os.path.exists(kernels_root):\n logger.info('Kernel repository already exists in %s', kernels_root)\n return\n\n logger.info('Cloning kernels repository to %s', kernels_root)\n\n kernels_repo = CONSTANTS['repos']['images']['linux']\n repos.git_clone_to_source(self.env_path(), kernels_repo)\n\n def _print_image_list(self, images, image_groups, image_descriptors):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n templates = get_image_templates(img_build_dir)\n if not templates:\n images_json_path = os.path.join(img_build_dir, 'images.json')\n raise CommandError('No images available to build. Make sure that '\n f'{images_json_path} exists and is valid')\n\n def get_max_len(lst):\n ret = 0\n for item in lst:\n if len(item) > ret:\n ret = len(item)\n return ret\n\n print('Available image groups:')\n max_group_len = get_max_len(image_groups)\n for group in image_groups:\n print(f' * {group:{max_group_len}} - Build {group} images')\n\n print('\\nAvailable images:')\n max_image_len = get_max_len(images)\n for image in sorted(images):\n print(f' * {image:{max_image_len}} - {image_descriptors[image][\"name\"]}')\n\n def _print_apps_list(self):\n img_build_dir = self.source_path(CONSTANTS['repos']['images']['build'])\n app_templates = get_app_templates(img_build_dir)\n if not app_templates:\n apps_json_path = os.path.join(img_build_dir, 'apps.json')\n raise CommandError('No apps available to build. Make sure that '\n f'{apps_json_path} exists and is valid')\n\n print('Available applications:')\n for app_template, desc in sorted(app_templates.items()):\n for base_image in desc['base_images']:\n print(f' * {base_image}/{app_template} - {desc[\"name\"]}')\n",
"step-ids": [
17,
21,
24,
30,
34
]
}
|
[
17,
21,
24,
30,
34
] |
from django.shortcuts import render, redirect
from .models import Courses
from django.views.generic import CreateView, ListView, UpdateView, DeleteView
from .forms import CourceCreateForm
from django.urls import reverse_lazy
from django.urls import reverse
class CourceListView(ListView):
model = Courses
template_name = 'cources/cource_list.html'
context_object_name = 'cources'
class CourceCreateView(CreateView):
template_name = 'cources/create_cource.html'
form_class = CourceCreateForm
success_url = reverse_lazy('cources:cource_list')
class CourceUpdateView(UpdateView):
model = Courses
form_class = CourceCreateForm
template_name = 'cources/course_update.html'
success_url = reverse_lazy('cources:cource_list')
def DeleteView(request, pk):
cource = Courses.objects.filter(pk=pk)
cource.delete()
return redirect(reverse('cources:cource_list'))
|
normal
|
{
"blob_id": "3340277df91f1421dab8d204eddce65b4604432b",
"index": 369,
"step-1": "<mask token>\n\n\nclass CourceCreateView(CreateView):\n template_name = 'cources/create_cource.html'\n form_class = CourceCreateForm\n success_url = reverse_lazy('cources:cource_list')\n\n\nclass CourceUpdateView(UpdateView):\n model = Courses\n form_class = CourceCreateForm\n template_name = 'cources/course_update.html'\n success_url = reverse_lazy('cources:cource_list')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass CourceListView(ListView):\n model = Courses\n template_name = 'cources/cource_list.html'\n context_object_name = 'cources'\n\n\nclass CourceCreateView(CreateView):\n template_name = 'cources/create_cource.html'\n form_class = CourceCreateForm\n success_url = reverse_lazy('cources:cource_list')\n\n\nclass CourceUpdateView(UpdateView):\n model = Courses\n form_class = CourceCreateForm\n template_name = 'cources/course_update.html'\n success_url = reverse_lazy('cources:cource_list')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass CourceListView(ListView):\n model = Courses\n template_name = 'cources/cource_list.html'\n context_object_name = 'cources'\n\n\nclass CourceCreateView(CreateView):\n template_name = 'cources/create_cource.html'\n form_class = CourceCreateForm\n success_url = reverse_lazy('cources:cource_list')\n\n\nclass CourceUpdateView(UpdateView):\n model = Courses\n form_class = CourceCreateForm\n template_name = 'cources/course_update.html'\n success_url = reverse_lazy('cources:cource_list')\n\n\ndef DeleteView(request, pk):\n cource = Courses.objects.filter(pk=pk)\n cource.delete()\n return redirect(reverse('cources:cource_list'))\n",
"step-4": "from django.shortcuts import render, redirect\nfrom .models import Courses\nfrom django.views.generic import CreateView, ListView, UpdateView, DeleteView\nfrom .forms import CourceCreateForm\nfrom django.urls import reverse_lazy\nfrom django.urls import reverse\n\n\nclass CourceListView(ListView):\n model = Courses\n template_name = 'cources/cource_list.html'\n context_object_name = 'cources'\n\n\nclass CourceCreateView(CreateView):\n template_name = 'cources/create_cource.html'\n form_class = CourceCreateForm\n success_url = reverse_lazy('cources:cource_list')\n\n\nclass CourceUpdateView(UpdateView):\n model = Courses\n form_class = CourceCreateForm\n template_name = 'cources/course_update.html'\n success_url = reverse_lazy('cources:cource_list')\n\n\ndef DeleteView(request, pk):\n cource = Courses.objects.filter(pk=pk)\n cource.delete()\n return redirect(reverse('cources:cource_list'))\n",
"step-5": null,
"step-ids": [
4,
6,
7,
8
]
}
|
[
4,
6,
7,
8
] |
<|reserved_special_token_0|>
class Number(Value):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Number(Value):
<|reserved_special_token_0|>
def __str__(self):
return str(self.number)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Number(Value):
def __init__(self, number: int):
if abs(number) > 2 ** 31:
raise SyntaxError(str(number) + ' number is out of range')
self.number = number
def __str__(self):
return str(self.number)
<|reserved_special_token_1|>
from nodes.Value import Value
class Number(Value):
def __init__(self, number: int):
if abs(number) > 2 ** 31:
raise SyntaxError(str(number) + ' number is out of range')
self.number = number
def __str__(self):
return str(self.number)
|
flexible
|
{
"blob_id": "7da274803de80f2864471d00c9d15aff1103372f",
"index": 3648,
"step-1": "<mask token>\n\n\nclass Number(Value):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Number(Value):\n <mask token>\n\n def __str__(self):\n return str(self.number)\n",
"step-3": "<mask token>\n\n\nclass Number(Value):\n\n def __init__(self, number: int):\n if abs(number) > 2 ** 31:\n raise SyntaxError(str(number) + ' number is out of range')\n self.number = number\n\n def __str__(self):\n return str(self.number)\n",
"step-4": "from nodes.Value import Value\n\n\nclass Number(Value):\n\n def __init__(self, number: int):\n if abs(number) > 2 ** 31:\n raise SyntaxError(str(number) + ' number is out of range')\n self.number = number\n\n def __str__(self):\n return str(self.number)\n",
"step-5": null,
"step-ids": [
1,
2,
3,
4
]
}
|
[
1,
2,
3,
4
] |
import tkinter
from tkinter import messagebox
from random import randint
tplyer = 0
tcomp = 0
player = 0
comp = 0
top = tkinter.Tk()
top.resizable(width = False, height =False)
top.geometry("200x100")
def Yes():
global player
global comp
tplayer = randint(1,6)
tcomp = randint(1,6)
message =""
if tplayer>tcomp:
message = "Wygrales!"
player+=1
elif tplayer==tcomp:
message = "Remis"
else:
message = "Przegrales"
comp +=1
messagebox.showinfo( "Wynik", "Gracz: "+str(player)+" Komputer: "+str(comp)+"\nTwoj rzut "+str(tplayer)+"\n"+"Przeciwnik wyrzucil "+str(tcomp)+"\n"+message)
def No():
messagebox.showinfo("Do zobaczenia")
top.quit()
w = tkinter.Label(top,text = "Zagramy w kosci?\n")
B1 = tkinter.Button(top, text ="Tak", command = Yes,width = 10)
B2 = tkinter.Button(top, text = "Nie", command = No,width = 10)
w.grid(row = 0,column = 0)
B1.grid(row = 1, column = 0)
B2.grid(row = 1, column = 1)
top.mainloop()
|
normal
|
{
"blob_id": "0a5baacf17d33dbf6ea69114a8632f7fcef52c3c",
"index": 9419,
"step-1": "<mask token>\n\n\ndef Yes():\n global player\n global comp\n tplayer = randint(1, 6)\n tcomp = randint(1, 6)\n message = ''\n if tplayer > tcomp:\n message = 'Wygrales!'\n player += 1\n elif tplayer == tcomp:\n message = 'Remis'\n else:\n message = 'Przegrales'\n comp += 1\n messagebox.showinfo('Wynik', 'Gracz: ' + str(player) +\n ' Komputer: ' + str(comp) + '\\nTwoj rzut ' + str(tplayer) +\n '\\n' + 'Przeciwnik wyrzucil ' + str(tcomp) + '\\n' + message)\n\n\ndef No():\n messagebox.showinfo('Do zobaczenia')\n top.quit()\n\n\n<mask token>\n",
"step-2": "<mask token>\ntop.resizable(width=False, height=False)\ntop.geometry('200x100')\n\n\ndef Yes():\n global player\n global comp\n tplayer = randint(1, 6)\n tcomp = randint(1, 6)\n message = ''\n if tplayer > tcomp:\n message = 'Wygrales!'\n player += 1\n elif tplayer == tcomp:\n message = 'Remis'\n else:\n message = 'Przegrales'\n comp += 1\n messagebox.showinfo('Wynik', 'Gracz: ' + str(player) +\n ' Komputer: ' + str(comp) + '\\nTwoj rzut ' + str(tplayer) +\n '\\n' + 'Przeciwnik wyrzucil ' + str(tcomp) + '\\n' + message)\n\n\ndef No():\n messagebox.showinfo('Do zobaczenia')\n top.quit()\n\n\n<mask token>\nw.grid(row=0, column=0)\nB1.grid(row=1, column=0)\nB2.grid(row=1, column=1)\ntop.mainloop()\n",
"step-3": "<mask token>\ntplyer = 0\ntcomp = 0\nplayer = 0\ncomp = 0\ntop = tkinter.Tk()\ntop.resizable(width=False, height=False)\ntop.geometry('200x100')\n\n\ndef Yes():\n global player\n global comp\n tplayer = randint(1, 6)\n tcomp = randint(1, 6)\n message = ''\n if tplayer > tcomp:\n message = 'Wygrales!'\n player += 1\n elif tplayer == tcomp:\n message = 'Remis'\n else:\n message = 'Przegrales'\n comp += 1\n messagebox.showinfo('Wynik', 'Gracz: ' + str(player) +\n ' Komputer: ' + str(comp) + '\\nTwoj rzut ' + str(tplayer) +\n '\\n' + 'Przeciwnik wyrzucil ' + str(tcomp) + '\\n' + message)\n\n\ndef No():\n messagebox.showinfo('Do zobaczenia')\n top.quit()\n\n\nw = tkinter.Label(top, text='Zagramy w kosci?\\n')\nB1 = tkinter.Button(top, text='Tak', command=Yes, width=10)\nB2 = tkinter.Button(top, text='Nie', command=No, width=10)\nw.grid(row=0, column=0)\nB1.grid(row=1, column=0)\nB2.grid(row=1, column=1)\ntop.mainloop()\n",
"step-4": "import tkinter\nfrom tkinter import messagebox\nfrom random import randint\ntplyer = 0\ntcomp = 0\nplayer = 0\ncomp = 0\ntop = tkinter.Tk()\ntop.resizable(width=False, height=False)\ntop.geometry('200x100')\n\n\ndef Yes():\n global player\n global comp\n tplayer = randint(1, 6)\n tcomp = randint(1, 6)\n message = ''\n if tplayer > tcomp:\n message = 'Wygrales!'\n player += 1\n elif tplayer == tcomp:\n message = 'Remis'\n else:\n message = 'Przegrales'\n comp += 1\n messagebox.showinfo('Wynik', 'Gracz: ' + str(player) +\n ' Komputer: ' + str(comp) + '\\nTwoj rzut ' + str(tplayer) +\n '\\n' + 'Przeciwnik wyrzucil ' + str(tcomp) + '\\n' + message)\n\n\ndef No():\n messagebox.showinfo('Do zobaczenia')\n top.quit()\n\n\nw = tkinter.Label(top, text='Zagramy w kosci?\\n')\nB1 = tkinter.Button(top, text='Tak', command=Yes, width=10)\nB2 = tkinter.Button(top, text='Nie', command=No, width=10)\nw.grid(row=0, column=0)\nB1.grid(row=1, column=0)\nB2.grid(row=1, column=1)\ntop.mainloop()\n",
"step-5": "import tkinter\nfrom tkinter import messagebox\nfrom random import randint\ntplyer = 0\ntcomp = 0\nplayer = 0\ncomp = 0\ntop = tkinter.Tk()\ntop.resizable(width = False, height =False)\ntop.geometry(\"200x100\")\ndef Yes():\n global player\n global comp\n tplayer = randint(1,6)\n tcomp = randint(1,6)\n message =\"\"\n if tplayer>tcomp:\n message = \"Wygrales!\"\n player+=1\n elif tplayer==tcomp:\n message = \"Remis\"\n else:\n message = \"Przegrales\"\n comp +=1\n messagebox.showinfo( \"Wynik\", \"Gracz: \"+str(player)+\" Komputer: \"+str(comp)+\"\\nTwoj rzut \"+str(tplayer)+\"\\n\"+\"Przeciwnik wyrzucil \"+str(tcomp)+\"\\n\"+message)\ndef No():\n messagebox.showinfo(\"Do zobaczenia\")\n top.quit()\nw = tkinter.Label(top,text = \"Zagramy w kosci?\\n\")\nB1 = tkinter.Button(top, text =\"Tak\", command = Yes,width = 10)\nB2 = tkinter.Button(top, text = \"Nie\", command = No,width = 10)\nw.grid(row = 0,column = 0)\nB1.grid(row = 1, column = 0)\nB2.grid(row = 1, column = 1)\ntop.mainloop()\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
class Person(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Person(object):
def __init__(self, username):
self.username = username
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Person(object):
def __init__(self, username):
self.username = username
def index(request):
context = {'persons': ('鲁班一号', '程咬金', '阿珂')}
return render(request, 'index.html', context=context)
<|reserved_special_token_1|>
from django.shortcuts import render
class Person(object):
def __init__(self, username):
self.username = username
def index(request):
context = {'persons': ('鲁班一号', '程咬金', '阿珂')}
return render(request, 'index.html', context=context)
<|reserved_special_token_1|>
from django.shortcuts import render
class Person(object):
def __init__(self,username):
self.username = username
def index(request):
# p = Person("张三")
# context = {
# 'person': p
# }
# context = {
# 'person': {
# 'username':'zhiliao',
# }
# }
# person.keys()
context = {
'persons': (
'鲁班一号',
'程咬金',
'阿珂'
)
}
return render(request,'index.html',context=context)
|
flexible
|
{
"blob_id": "6d2bc28e7742f1063a04ae96fc195515ad70598b",
"index": 5666,
"step-1": "<mask token>\n\n\nclass Person(object):\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Person(object):\n\n def __init__(self, username):\n self.username = username\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Person(object):\n\n def __init__(self, username):\n self.username = username\n\n\ndef index(request):\n context = {'persons': ('鲁班一号', '程咬金', '阿珂')}\n return render(request, 'index.html', context=context)\n",
"step-4": "from django.shortcuts import render\n\n\nclass Person(object):\n\n def __init__(self, username):\n self.username = username\n\n\ndef index(request):\n context = {'persons': ('鲁班一号', '程咬金', '阿珂')}\n return render(request, 'index.html', context=context)\n",
"step-5": "from django.shortcuts import render\n\nclass Person(object):\n def __init__(self,username):\n self.username = username\n\ndef index(request):\n # p = Person(\"张三\")\n # context = {\n # 'person': p\n # }\n # context = {\n # 'person': {\n # 'username':'zhiliao',\n # }\n # }\n # person.keys()\n context = {\n 'persons': (\n '鲁班一号',\n '程咬金',\n '阿珂'\n )\n }\n return render(request,'index.html',context=context)",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
def scrape_sas():
pprint('Scraping Events')
get_mtb_events()
pprint('Getting categories and stages')
for event in db.session.query(SASEvent):
pprint(event.event_id)
get_categories_and_stages(event.event_reference, event.event_id)
for event_stage in db.session.query(SASEventStage):
pprint('Getting event stage results')
base_event_stage = db.session.query(EventStage).filter(EventStage.
id == event_stage.event_stage_id).first()
if base_event_stage.results:
pprint('Event has results')
else:
write_stage_results(event_stage.stage_reference, event_stage.
event_stage_id, 'event')
for category_stage in db.session.query(SASCategoryStage):
pprint('Getting category stage results')
base_category_stage = db.session.query(CategoryStage).filter(
CategoryStage.id == category_stage.category_stage_id).first()
if base_category_stage.results:
pprint('Category stage has results')
else:
write_stage_results(category_stage.stage_reference,
category_stage.category_stage_id, 'category')
for category in db.session.query(SASCategory):
pprint('Getting category results')
base_category = db.session.query(Category).filter(Category.id ==
category.category_id).first()
if base_category.results:
pprint('Category has results')
elif not base_category.category_stages:
write_category_results(category.stage_reference, category.id)
else:
pprint('No results but has category stages')
pprint('Scrape Complete')
<|reserved_special_token_0|>
def get_categories_and_stages(event_reference, event_id):
event = db.session.query(Event).filter(Event.id == event_id).first()
if event.categories or event.event_stages:
pprint('Event Exists')
else:
url = DESTINATION_URL + event_reference
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.URLError):
return
soup = BeautifulSoup(page, 'html.parser')
check_stages = get_categories(soup, event_id)
def get_categories(soup, event_id):
category_div = soup.find('div', attrs={'id': 'category_container'})
if category_div:
divs = category_div.find_all('div')
for div in divs:
if div.has_attr('data-event-category-id'):
category_reference = div['data-event-category-id']
category_name = div['data-loading-text']
category_own_stage_reference = div['data-event-stage-id']
db_category = Category(category_name, event_id)
db_category_check = db.session.query(Category.name).filter(
(Category.name == category_name) & (Category.event_id ==
event_id))
db_sas_category_check = db.session.query(SASCategory).filter(
(SASCategory.category_reference == category_reference) &
(SASCategory.stage_reference ==
category_own_stage_reference))
if not db.session.query(db_category_check.exists()).scalar():
db.session.add(db_category)
db.session.flush()
if not db.session.query(db_sas_category_check.exists()
).scalar():
db_sas_category = SASCategory(category_reference,
category_own_stage_reference, db_category.id)
db.session.add(db_sas_category)
db.session.flush()
db.session.commit()
if div['data-multiple-event-stages'] == '1':
get_category_stages(soup, db_category.id,
category_reference)
else:
get_event_stages(soup, event_id)
<|reserved_special_token_0|>
def get_event_stages(soup, event_id):
all_event_stage_divs = soup.find('div', class_=
'row categories_stages event-sub-types')
if all_event_stage_divs:
event_stage_divs = all_event_stage_divs.find_all('div')
for event_stage_div in event_stage_divs:
if event_stage_div.has_attr('data-stage-id'):
event_stage_reference = event_stage_div['data-stage-id']
event_stage_name = event_stage_div['data-loading-text']
db_event_stage = EventStage(event_stage_name, event_id)
db_event_stage_check = db.session.query(EventStage.name
).filter((EventStage.name == event_stage_name) & (
EventStage.event_id == event_id))
if not db.session.query(db_event_stage_check.exists()).scalar(
):
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id,
event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.flush()
db.session.commit()
else:
event_stage_reference_div = soup.find('div', class_=
'result-row load-results')
if event_stage_reference_div:
if event_stage_reference_div.has_attr('data-stage'):
event_stage_reference = event_stage_reference_div['data-stage']
sas_event = db.session.query(SASEvent).filter(SASEvent.
event_id == event_id).first()
db_event_stage_check = db.session.query(EventStage.name
).filter((EventStage.name == 'Overall Results') & (
EventStage.event_id == sas_event.event_id))
if not db.session.query(db_event_stage_check.exists()).scalar(
):
db_event_stage = EventStage('Overall Results',
sas_event.event_id)
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id,
event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.commit()
def get_results(event_reference):
url = (
'%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999'
% (DESTINATION_URL, event_reference))
pprint(url)
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.ConnectionResetError):
return
content = page.read().decode('utf-8')
json_content = json.loads(content)
json_results = json_content['rows']
return json_results
def write_stage_results(stage_reference, stage_id, stage_type):
results = get_results(stage_reference)
category_stage_id = None
event_stage_id = None
if stage_type == 'event':
event_stage_id = stage_id
elif stage_type == 'category':
category_stage_id = stage_id
if results:
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter((Result.
position == result['overall_pos']) & (Result.
gender_position == result['gender_pos']) & (Result.time ==
result['time_taken_seconds']) & (Result.event_stage_id ==
event_stage_id) & (Result.category_stage_id ==
category_stage_id))
if not db.session.query(db_result_check.exists()).scalar():
if stage_type == 'category':
db_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], None, category_stage_id, None)
elif stage_type == 'event':
db_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], event_stage_id, None, None)
db.session.add(db_result)
db.session.commit()
def write_category_results(category_reference, category_id):
results = get_results(category_reference)
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter((Result.position ==
result['overall_pos']) & (Result.gender_position == result[
'gender_pos']) & (Result.time == result['time_taken_seconds']) &
(Result.category_id == category_id)).first()
if not db_result_check:
db_category_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], None, None, category_id)
db.session.add(db_category_result)
db.session.commit()
def get_participant(result):
if result['date_of_birth']:
birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d'
).date()
else:
birth_date = None
db_participant_check = db.session.query(Participant).filter((
Participant.first_name == result['first_name']) & (Participant.
last_name == result['last_name']) & (Participant.sex == result[
'person_sex']) & (Participant.birth_date == birth_date))
if not db.session.query(db_participant_check.exists()).scalar():
db_participant = Participant(result['first_name'], result[
'last_name'], result['person_sex'], birth_date)
db.session.add(db_participant)
db.session.commit()
return db_participant.id
else:
return db_participant_check.first().id
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def scrape_sas():
pprint('Scraping Events')
get_mtb_events()
pprint('Getting categories and stages')
for event in db.session.query(SASEvent):
pprint(event.event_id)
get_categories_and_stages(event.event_reference, event.event_id)
for event_stage in db.session.query(SASEventStage):
pprint('Getting event stage results')
base_event_stage = db.session.query(EventStage).filter(EventStage.
id == event_stage.event_stage_id).first()
if base_event_stage.results:
pprint('Event has results')
else:
write_stage_results(event_stage.stage_reference, event_stage.
event_stage_id, 'event')
for category_stage in db.session.query(SASCategoryStage):
pprint('Getting category stage results')
base_category_stage = db.session.query(CategoryStage).filter(
CategoryStage.id == category_stage.category_stage_id).first()
if base_category_stage.results:
pprint('Category stage has results')
else:
write_stage_results(category_stage.stage_reference,
category_stage.category_stage_id, 'category')
for category in db.session.query(SASCategory):
pprint('Getting category results')
base_category = db.session.query(Category).filter(Category.id ==
category.category_id).first()
if base_category.results:
pprint('Category has results')
elif not base_category.category_stages:
write_category_results(category.stage_reference, category.id)
else:
pprint('No results but has category stages')
pprint('Scrape Complete')
<|reserved_special_token_0|>
def get_categories_and_stages(event_reference, event_id):
event = db.session.query(Event).filter(Event.id == event_id).first()
if event.categories or event.event_stages:
pprint('Event Exists')
else:
url = DESTINATION_URL + event_reference
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.URLError):
return
soup = BeautifulSoup(page, 'html.parser')
check_stages = get_categories(soup, event_id)
def get_categories(soup, event_id):
category_div = soup.find('div', attrs={'id': 'category_container'})
if category_div:
divs = category_div.find_all('div')
for div in divs:
if div.has_attr('data-event-category-id'):
category_reference = div['data-event-category-id']
category_name = div['data-loading-text']
category_own_stage_reference = div['data-event-stage-id']
db_category = Category(category_name, event_id)
db_category_check = db.session.query(Category.name).filter(
(Category.name == category_name) & (Category.event_id ==
event_id))
db_sas_category_check = db.session.query(SASCategory).filter(
(SASCategory.category_reference == category_reference) &
(SASCategory.stage_reference ==
category_own_stage_reference))
if not db.session.query(db_category_check.exists()).scalar():
db.session.add(db_category)
db.session.flush()
if not db.session.query(db_sas_category_check.exists()
).scalar():
db_sas_category = SASCategory(category_reference,
category_own_stage_reference, db_category.id)
db.session.add(db_sas_category)
db.session.flush()
db.session.commit()
if div['data-multiple-event-stages'] == '1':
get_category_stages(soup, db_category.id,
category_reference)
else:
get_event_stages(soup, event_id)
def get_category_stages(soup, category_id, category_reference):
stage_group_div = soup.find('div', attrs={'id': 'ec_' + category_reference}
)
stage_divs = stage_group_div.find_all('div')
for stage_div in stage_divs:
if stage_div.has_attr('data-stage-id'):
category_stage_reference = stage_div['data-stage-id']
category_stage_name = stage_div['data-loading-text']
db_category_stage = CategoryStage(category_stage_name, category_id)
db_category_stage_check = db.session.query(CategoryStage.name
).filter((CategoryStage.name == category_stage_name) & (
CategoryStage.category_id == category_id))
if not db.session.query(db_category_stage_check.exists()).scalar():
db.session.add(db_category_stage)
db.session.flush()
db_sas_category_stage = SASCategoryStage(db_category_stage.
id, category_stage_reference)
db.session.add(db_sas_category_stage)
db.session.flush()
db.session.commit()
def get_event_stages(soup, event_id):
all_event_stage_divs = soup.find('div', class_=
'row categories_stages event-sub-types')
if all_event_stage_divs:
event_stage_divs = all_event_stage_divs.find_all('div')
for event_stage_div in event_stage_divs:
if event_stage_div.has_attr('data-stage-id'):
event_stage_reference = event_stage_div['data-stage-id']
event_stage_name = event_stage_div['data-loading-text']
db_event_stage = EventStage(event_stage_name, event_id)
db_event_stage_check = db.session.query(EventStage.name
).filter((EventStage.name == event_stage_name) & (
EventStage.event_id == event_id))
if not db.session.query(db_event_stage_check.exists()).scalar(
):
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id,
event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.flush()
db.session.commit()
else:
event_stage_reference_div = soup.find('div', class_=
'result-row load-results')
if event_stage_reference_div:
if event_stage_reference_div.has_attr('data-stage'):
event_stage_reference = event_stage_reference_div['data-stage']
sas_event = db.session.query(SASEvent).filter(SASEvent.
event_id == event_id).first()
db_event_stage_check = db.session.query(EventStage.name
).filter((EventStage.name == 'Overall Results') & (
EventStage.event_id == sas_event.event_id))
if not db.session.query(db_event_stage_check.exists()).scalar(
):
db_event_stage = EventStage('Overall Results',
sas_event.event_id)
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id,
event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.commit()
def get_results(event_reference):
url = (
'%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999'
% (DESTINATION_URL, event_reference))
pprint(url)
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.ConnectionResetError):
return
content = page.read().decode('utf-8')
json_content = json.loads(content)
json_results = json_content['rows']
return json_results
def write_stage_results(stage_reference, stage_id, stage_type):
results = get_results(stage_reference)
category_stage_id = None
event_stage_id = None
if stage_type == 'event':
event_stage_id = stage_id
elif stage_type == 'category':
category_stage_id = stage_id
if results:
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter((Result.
position == result['overall_pos']) & (Result.
gender_position == result['gender_pos']) & (Result.time ==
result['time_taken_seconds']) & (Result.event_stage_id ==
event_stage_id) & (Result.category_stage_id ==
category_stage_id))
if not db.session.query(db_result_check.exists()).scalar():
if stage_type == 'category':
db_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], None, category_stage_id, None)
elif stage_type == 'event':
db_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], event_stage_id, None, None)
db.session.add(db_result)
db.session.commit()
def write_category_results(category_reference, category_id):
results = get_results(category_reference)
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter((Result.position ==
result['overall_pos']) & (Result.gender_position == result[
'gender_pos']) & (Result.time == result['time_taken_seconds']) &
(Result.category_id == category_id)).first()
if not db_result_check:
db_category_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], None, None, category_id)
db.session.add(db_category_result)
db.session.commit()
def get_participant(result):
if result['date_of_birth']:
birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d'
).date()
else:
birth_date = None
db_participant_check = db.session.query(Participant).filter((
Participant.first_name == result['first_name']) & (Participant.
last_name == result['last_name']) & (Participant.sex == result[
'person_sex']) & (Participant.birth_date == birth_date))
if not db.session.query(db_participant_check.exists()).scalar():
db_participant = Participant(result['first_name'], result[
'last_name'], result['person_sex'], birth_date)
db.session.add(db_participant)
db.session.commit()
return db_participant.id
else:
return db_participant_check.first().id
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def scrape_sas():
pprint('Scraping Events')
get_mtb_events()
pprint('Getting categories and stages')
for event in db.session.query(SASEvent):
pprint(event.event_id)
get_categories_and_stages(event.event_reference, event.event_id)
for event_stage in db.session.query(SASEventStage):
pprint('Getting event stage results')
base_event_stage = db.session.query(EventStage).filter(EventStage.
id == event_stage.event_stage_id).first()
if base_event_stage.results:
pprint('Event has results')
else:
write_stage_results(event_stage.stage_reference, event_stage.
event_stage_id, 'event')
for category_stage in db.session.query(SASCategoryStage):
pprint('Getting category stage results')
base_category_stage = db.session.query(CategoryStage).filter(
CategoryStage.id == category_stage.category_stage_id).first()
if base_category_stage.results:
pprint('Category stage has results')
else:
write_stage_results(category_stage.stage_reference,
category_stage.category_stage_id, 'category')
for category in db.session.query(SASCategory):
pprint('Getting category results')
base_category = db.session.query(Category).filter(Category.id ==
category.category_id).first()
if base_category.results:
pprint('Category has results')
elif not base_category.category_stages:
write_category_results(category.stage_reference, category.id)
else:
pprint('No results but has category stages')
pprint('Scrape Complete')
def get_mtb_events():
for year in YEARS:
url = (
'%s/participants/event-results/fetch-series-by-type?event_type=%s&event_year=%d'
% (DESTINATION_URL, MTB_EVENT_TYPE, year))
try:
page = urllib.request.urlopen(url)
content = page.read().decode('utf-8')
json_content = json.loads(content)
soup = BeautifulSoup(json_content['HTML'], 'html.parser')
anchors = soup.find_all('a')
except (urllib.error.HTTPError, urllib.error.ConnectionResetError):
pass
for anchor in anchors:
event_reference = anchor['href']
divs = anchor.find_all('div')
for div in divs:
if 'event-date' in div['class']:
event_date = div.find(text=True)
elif 'event-title' in div['class']:
event_name = div.find(text=True)
db_date = datetime.strptime(event_date, '%d %b %Y')
db_event = Event(event_name, db_date)
db_check = db.session.query(Event.title).filter(Event.title ==
event_name)
if not db.session.query(db_check.exists()).scalar():
db.session.add(db_event)
db.session.flush()
sas_event = SASEvent(db_event.id, event_reference)
db.session.add(sas_event)
db.session.commit()
def get_categories_and_stages(event_reference, event_id):
event = db.session.query(Event).filter(Event.id == event_id).first()
if event.categories or event.event_stages:
pprint('Event Exists')
else:
url = DESTINATION_URL + event_reference
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.URLError):
return
soup = BeautifulSoup(page, 'html.parser')
check_stages = get_categories(soup, event_id)
def get_categories(soup, event_id):
category_div = soup.find('div', attrs={'id': 'category_container'})
if category_div:
divs = category_div.find_all('div')
for div in divs:
if div.has_attr('data-event-category-id'):
category_reference = div['data-event-category-id']
category_name = div['data-loading-text']
category_own_stage_reference = div['data-event-stage-id']
db_category = Category(category_name, event_id)
db_category_check = db.session.query(Category.name).filter(
(Category.name == category_name) & (Category.event_id ==
event_id))
db_sas_category_check = db.session.query(SASCategory).filter(
(SASCategory.category_reference == category_reference) &
(SASCategory.stage_reference ==
category_own_stage_reference))
if not db.session.query(db_category_check.exists()).scalar():
db.session.add(db_category)
db.session.flush()
if not db.session.query(db_sas_category_check.exists()
).scalar():
db_sas_category = SASCategory(category_reference,
category_own_stage_reference, db_category.id)
db.session.add(db_sas_category)
db.session.flush()
db.session.commit()
if div['data-multiple-event-stages'] == '1':
get_category_stages(soup, db_category.id,
category_reference)
else:
get_event_stages(soup, event_id)
def get_category_stages(soup, category_id, category_reference):
stage_group_div = soup.find('div', attrs={'id': 'ec_' + category_reference}
)
stage_divs = stage_group_div.find_all('div')
for stage_div in stage_divs:
if stage_div.has_attr('data-stage-id'):
category_stage_reference = stage_div['data-stage-id']
category_stage_name = stage_div['data-loading-text']
db_category_stage = CategoryStage(category_stage_name, category_id)
db_category_stage_check = db.session.query(CategoryStage.name
).filter((CategoryStage.name == category_stage_name) & (
CategoryStage.category_id == category_id))
if not db.session.query(db_category_stage_check.exists()).scalar():
db.session.add(db_category_stage)
db.session.flush()
db_sas_category_stage = SASCategoryStage(db_category_stage.
id, category_stage_reference)
db.session.add(db_sas_category_stage)
db.session.flush()
db.session.commit()
def get_event_stages(soup, event_id):
all_event_stage_divs = soup.find('div', class_=
'row categories_stages event-sub-types')
if all_event_stage_divs:
event_stage_divs = all_event_stage_divs.find_all('div')
for event_stage_div in event_stage_divs:
if event_stage_div.has_attr('data-stage-id'):
event_stage_reference = event_stage_div['data-stage-id']
event_stage_name = event_stage_div['data-loading-text']
db_event_stage = EventStage(event_stage_name, event_id)
db_event_stage_check = db.session.query(EventStage.name
).filter((EventStage.name == event_stage_name) & (
EventStage.event_id == event_id))
if not db.session.query(db_event_stage_check.exists()).scalar(
):
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id,
event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.flush()
db.session.commit()
else:
event_stage_reference_div = soup.find('div', class_=
'result-row load-results')
if event_stage_reference_div:
if event_stage_reference_div.has_attr('data-stage'):
event_stage_reference = event_stage_reference_div['data-stage']
sas_event = db.session.query(SASEvent).filter(SASEvent.
event_id == event_id).first()
db_event_stage_check = db.session.query(EventStage.name
).filter((EventStage.name == 'Overall Results') & (
EventStage.event_id == sas_event.event_id))
if not db.session.query(db_event_stage_check.exists()).scalar(
):
db_event_stage = EventStage('Overall Results',
sas_event.event_id)
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id,
event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.commit()
def get_results(event_reference):
url = (
'%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999'
% (DESTINATION_URL, event_reference))
pprint(url)
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.ConnectionResetError):
return
content = page.read().decode('utf-8')
json_content = json.loads(content)
json_results = json_content['rows']
return json_results
def write_stage_results(stage_reference, stage_id, stage_type):
results = get_results(stage_reference)
category_stage_id = None
event_stage_id = None
if stage_type == 'event':
event_stage_id = stage_id
elif stage_type == 'category':
category_stage_id = stage_id
if results:
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter((Result.
position == result['overall_pos']) & (Result.
gender_position == result['gender_pos']) & (Result.time ==
result['time_taken_seconds']) & (Result.event_stage_id ==
event_stage_id) & (Result.category_stage_id ==
category_stage_id))
if not db.session.query(db_result_check.exists()).scalar():
if stage_type == 'category':
db_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], None, category_stage_id, None)
elif stage_type == 'event':
db_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], event_stage_id, None, None)
db.session.add(db_result)
db.session.commit()
def write_category_results(category_reference, category_id):
results = get_results(category_reference)
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter((Result.position ==
result['overall_pos']) & (Result.gender_position == result[
'gender_pos']) & (Result.time == result['time_taken_seconds']) &
(Result.category_id == category_id)).first()
if not db_result_check:
db_category_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], None, None, category_id)
db.session.add(db_category_result)
db.session.commit()
def get_participant(result):
if result['date_of_birth']:
birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d'
).date()
else:
birth_date = None
db_participant_check = db.session.query(Participant).filter((
Participant.first_name == result['first_name']) & (Participant.
last_name == result['last_name']) & (Participant.sex == result[
'person_sex']) & (Participant.birth_date == birth_date))
if not db.session.query(db_participant_check.exists()).scalar():
db_participant = Participant(result['first_name'], result[
'last_name'], result['person_sex'], birth_date)
db.session.add(db_participant)
db.session.commit()
return db_participant.id
else:
return db_participant_check.first().id
<|reserved_special_token_1|>
from bs4 import BeautifulSoup
from pprint import pprint
from scraper.sas.sas_models import SASEvent, SASCategory, SASCategoryStage, SASEventStage
from scraper.base_models.models import Event, Category, CategoryStage, EventStage, Participant, Result
from scraper.sas.sas_config import DESTINATION_URL, MTB_EVENT_TYPE, YEARS
from scraper import db
from datetime import datetime
import urllib
import json
import time
def scrape_sas():
pprint('Scraping Events')
get_mtb_events()
pprint('Getting categories and stages')
for event in db.session.query(SASEvent):
pprint(event.event_id)
get_categories_and_stages(event.event_reference, event.event_id)
for event_stage in db.session.query(SASEventStage):
pprint('Getting event stage results')
base_event_stage = db.session.query(EventStage).filter(EventStage.
id == event_stage.event_stage_id).first()
if base_event_stage.results:
pprint('Event has results')
else:
write_stage_results(event_stage.stage_reference, event_stage.
event_stage_id, 'event')
for category_stage in db.session.query(SASCategoryStage):
pprint('Getting category stage results')
base_category_stage = db.session.query(CategoryStage).filter(
CategoryStage.id == category_stage.category_stage_id).first()
if base_category_stage.results:
pprint('Category stage has results')
else:
write_stage_results(category_stage.stage_reference,
category_stage.category_stage_id, 'category')
for category in db.session.query(SASCategory):
pprint('Getting category results')
base_category = db.session.query(Category).filter(Category.id ==
category.category_id).first()
if base_category.results:
pprint('Category has results')
elif not base_category.category_stages:
write_category_results(category.stage_reference, category.id)
else:
pprint('No results but has category stages')
pprint('Scrape Complete')
def get_mtb_events():
for year in YEARS:
url = (
'%s/participants/event-results/fetch-series-by-type?event_type=%s&event_year=%d'
% (DESTINATION_URL, MTB_EVENT_TYPE, year))
try:
page = urllib.request.urlopen(url)
content = page.read().decode('utf-8')
json_content = json.loads(content)
soup = BeautifulSoup(json_content['HTML'], 'html.parser')
anchors = soup.find_all('a')
except (urllib.error.HTTPError, urllib.error.ConnectionResetError):
pass
for anchor in anchors:
event_reference = anchor['href']
divs = anchor.find_all('div')
for div in divs:
if 'event-date' in div['class']:
event_date = div.find(text=True)
elif 'event-title' in div['class']:
event_name = div.find(text=True)
db_date = datetime.strptime(event_date, '%d %b %Y')
db_event = Event(event_name, db_date)
db_check = db.session.query(Event.title).filter(Event.title ==
event_name)
if not db.session.query(db_check.exists()).scalar():
db.session.add(db_event)
db.session.flush()
sas_event = SASEvent(db_event.id, event_reference)
db.session.add(sas_event)
db.session.commit()
def get_categories_and_stages(event_reference, event_id):
event = db.session.query(Event).filter(Event.id == event_id).first()
if event.categories or event.event_stages:
pprint('Event Exists')
else:
url = DESTINATION_URL + event_reference
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.URLError):
return
soup = BeautifulSoup(page, 'html.parser')
check_stages = get_categories(soup, event_id)
def get_categories(soup, event_id):
category_div = soup.find('div', attrs={'id': 'category_container'})
if category_div:
divs = category_div.find_all('div')
for div in divs:
if div.has_attr('data-event-category-id'):
category_reference = div['data-event-category-id']
category_name = div['data-loading-text']
category_own_stage_reference = div['data-event-stage-id']
db_category = Category(category_name, event_id)
db_category_check = db.session.query(Category.name).filter(
(Category.name == category_name) & (Category.event_id ==
event_id))
db_sas_category_check = db.session.query(SASCategory).filter(
(SASCategory.category_reference == category_reference) &
(SASCategory.stage_reference ==
category_own_stage_reference))
if not db.session.query(db_category_check.exists()).scalar():
db.session.add(db_category)
db.session.flush()
if not db.session.query(db_sas_category_check.exists()
).scalar():
db_sas_category = SASCategory(category_reference,
category_own_stage_reference, db_category.id)
db.session.add(db_sas_category)
db.session.flush()
db.session.commit()
if div['data-multiple-event-stages'] == '1':
get_category_stages(soup, db_category.id,
category_reference)
else:
get_event_stages(soup, event_id)
def get_category_stages(soup, category_id, category_reference):
stage_group_div = soup.find('div', attrs={'id': 'ec_' + category_reference}
)
stage_divs = stage_group_div.find_all('div')
for stage_div in stage_divs:
if stage_div.has_attr('data-stage-id'):
category_stage_reference = stage_div['data-stage-id']
category_stage_name = stage_div['data-loading-text']
db_category_stage = CategoryStage(category_stage_name, category_id)
db_category_stage_check = db.session.query(CategoryStage.name
).filter((CategoryStage.name == category_stage_name) & (
CategoryStage.category_id == category_id))
if not db.session.query(db_category_stage_check.exists()).scalar():
db.session.add(db_category_stage)
db.session.flush()
db_sas_category_stage = SASCategoryStage(db_category_stage.
id, category_stage_reference)
db.session.add(db_sas_category_stage)
db.session.flush()
db.session.commit()
def get_event_stages(soup, event_id):
all_event_stage_divs = soup.find('div', class_=
'row categories_stages event-sub-types')
if all_event_stage_divs:
event_stage_divs = all_event_stage_divs.find_all('div')
for event_stage_div in event_stage_divs:
if event_stage_div.has_attr('data-stage-id'):
event_stage_reference = event_stage_div['data-stage-id']
event_stage_name = event_stage_div['data-loading-text']
db_event_stage = EventStage(event_stage_name, event_id)
db_event_stage_check = db.session.query(EventStage.name
).filter((EventStage.name == event_stage_name) & (
EventStage.event_id == event_id))
if not db.session.query(db_event_stage_check.exists()).scalar(
):
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id,
event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.flush()
db.session.commit()
else:
event_stage_reference_div = soup.find('div', class_=
'result-row load-results')
if event_stage_reference_div:
if event_stage_reference_div.has_attr('data-stage'):
event_stage_reference = event_stage_reference_div['data-stage']
sas_event = db.session.query(SASEvent).filter(SASEvent.
event_id == event_id).first()
db_event_stage_check = db.session.query(EventStage.name
).filter((EventStage.name == 'Overall Results') & (
EventStage.event_id == sas_event.event_id))
if not db.session.query(db_event_stage_check.exists()).scalar(
):
db_event_stage = EventStage('Overall Results',
sas_event.event_id)
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id,
event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.commit()
def get_results(event_reference):
url = (
'%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999'
% (DESTINATION_URL, event_reference))
pprint(url)
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.ConnectionResetError):
return
content = page.read().decode('utf-8')
json_content = json.loads(content)
json_results = json_content['rows']
return json_results
def write_stage_results(stage_reference, stage_id, stage_type):
results = get_results(stage_reference)
category_stage_id = None
event_stage_id = None
if stage_type == 'event':
event_stage_id = stage_id
elif stage_type == 'category':
category_stage_id = stage_id
if results:
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter((Result.
position == result['overall_pos']) & (Result.
gender_position == result['gender_pos']) & (Result.time ==
result['time_taken_seconds']) & (Result.event_stage_id ==
event_stage_id) & (Result.category_stage_id ==
category_stage_id))
if not db.session.query(db_result_check.exists()).scalar():
if stage_type == 'category':
db_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], None, category_stage_id, None)
elif stage_type == 'event':
db_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], event_stage_id, None, None)
db.session.add(db_result)
db.session.commit()
def write_category_results(category_reference, category_id):
results = get_results(category_reference)
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter((Result.position ==
result['overall_pos']) & (Result.gender_position == result[
'gender_pos']) & (Result.time == result['time_taken_seconds']) &
(Result.category_id == category_id)).first()
if not db_result_check:
db_category_result = Result(result['overall_pos'],
participant_id, result['gender_pos'], result[
'time_taken_seconds'], None, None, category_id)
db.session.add(db_category_result)
db.session.commit()
def get_participant(result):
if result['date_of_birth']:
birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d'
).date()
else:
birth_date = None
db_participant_check = db.session.query(Participant).filter((
Participant.first_name == result['first_name']) & (Participant.
last_name == result['last_name']) & (Participant.sex == result[
'person_sex']) & (Participant.birth_date == birth_date))
if not db.session.query(db_participant_check.exists()).scalar():
db_participant = Participant(result['first_name'], result[
'last_name'], result['person_sex'], birth_date)
db.session.add(db_participant)
db.session.commit()
return db_participant.id
else:
return db_participant_check.first().id
<|reserved_special_token_1|>
from bs4 import BeautifulSoup
from pprint import pprint
from scraper.sas.sas_models import SASEvent, SASCategory, SASCategoryStage, SASEventStage
from scraper.base_models.models import Event, Category, CategoryStage, EventStage, Participant, Result
from scraper.sas.sas_config import DESTINATION_URL, MTB_EVENT_TYPE, YEARS
from scraper import db
from datetime import datetime
import urllib
import json
import time
def scrape_sas():
pprint("Scraping Events")
get_mtb_events()
pprint("Getting categories and stages")
for event in db.session.query(SASEvent):
pprint(event.event_id)
get_categories_and_stages(event.event_reference, event.event_id)
#time.sleep(2)
for event_stage in db.session.query(SASEventStage):
pprint("Getting event stage results")
base_event_stage = db.session.query(EventStage).filter(EventStage.id==event_stage.event_stage_id).first()
if (base_event_stage.results):
pprint("Event has results")
else:
write_stage_results(event_stage.stage_reference, event_stage.event_stage_id, "event")
for category_stage in db.session.query(SASCategoryStage):
pprint("Getting category stage results")
base_category_stage = db.session.query(CategoryStage).filter(CategoryStage.id==category_stage.category_stage_id).first()
if (base_category_stage.results):
pprint("Category stage has results")
else:
write_stage_results(category_stage.stage_reference, category_stage.category_stage_id, "category")
for category in db.session.query(SASCategory):
pprint("Getting category results")
base_category = db.session.query(Category).filter(Category.id==category.category_id).first()
if (base_category.results):
pprint("Category has results")
else:
if (not base_category.category_stages):
write_category_results(category.stage_reference, category.id)
else:
pprint("No results but has category stages")
pprint("Scrape Complete")
def get_mtb_events():
for year in YEARS:
url = ("%s/participants/event-results/fetch-series-by-type?event_type=%s&event_year=%d" %
(DESTINATION_URL, MTB_EVENT_TYPE, year))
try:
page = urllib.request.urlopen(url)
content = page.read().decode("utf-8")
json_content = json.loads(content)
soup = BeautifulSoup(json_content['HTML'], "html.parser")
anchors = soup.find_all('a')
except (urllib.error.HTTPError, urllib.error.ConnectionResetError):
pass
for anchor in anchors:
event_reference = anchor["href"]
divs = anchor.find_all('div')
for div in divs:
if ("event-date" in div["class"]):
event_date = (div.find(text=True))
elif ("event-title" in div["class"]):
event_name = (div.find(text=True))
db_date = datetime.strptime(event_date, '%d %b %Y')
db_event = Event(event_name, db_date)
db_check = db.session.query(Event.title).filter(Event.title==event_name)
if not (db.session.query(db_check.exists()).scalar()):
db.session.add(db_event)
db.session.flush()
sas_event = SASEvent(db_event.id, event_reference)
db.session.add(sas_event)
db.session.commit()
def get_categories_and_stages(event_reference, event_id):
event = db.session.query(Event).filter(Event.id==event_id).first()
if (event.categories or event.event_stages):
pprint("Event Exists")
else:
url = (DESTINATION_URL + event_reference)
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.URLError):
return
soup = BeautifulSoup(page, "html.parser")
check_stages = get_categories(soup, event_id)
def get_categories(soup, event_id):
category_div = soup.find('div', attrs={"id" : "category_container"})
#Check to see if event has categories first
if category_div:
divs = category_div.find_all('div')
for div in divs:
if div.has_attr("data-event-category-id"):
#Event has categories
category_reference = div["data-event-category-id"]
category_name = div["data-loading-text"]
category_own_stage_reference = div["data-event-stage-id"]
db_category = Category(category_name, event_id)
#Check both name and event id to allow duplicate names
db_category_check = db.session.query(Category.name).filter(
(Category.name==category_name) &
(Category.event_id==event_id))
#Check SAS category for duplicates as well
db_sas_category_check = db.session.query(SASCategory).filter(
(SASCategory.category_reference==category_reference) &
(SASCategory.stage_reference==category_own_stage_reference))
if not (db.session.query(db_category_check.exists()).scalar()):
db.session.add(db_category)
db.session.flush()
if not (db.session.query(db_sas_category_check.exists()).scalar()):
db_sas_category = SASCategory(category_reference, category_own_stage_reference, db_category.id)
db.session.add(db_sas_category)
db.session.flush()
db.session.commit()
if (div["data-multiple-event-stages"] == "1"):
#Event has stages with their own categories
get_category_stages(soup, db_category.id, category_reference)
else:
#Event does not have categories
get_event_stages(soup, event_id)
def get_category_stages(soup, category_id, category_reference):
stage_group_div = soup.find('div', attrs={"id" : ("ec_" + category_reference)})
stage_divs = stage_group_div.find_all('div')
for stage_div in stage_divs:
if stage_div.has_attr("data-stage-id"):
category_stage_reference = stage_div["data-stage-id"]
category_stage_name = stage_div["data-loading-text"]
db_category_stage = CategoryStage(category_stage_name, category_id)
#Check both name and category id to allow duplicate names
db_category_stage_check = db.session.query(CategoryStage.name).filter(
(CategoryStage.name==category_stage_name) &
(CategoryStage.category_id==category_id))
if not (db.session.query(db_category_stage_check.exists()).scalar()):
db.session.add(db_category_stage)
db.session.flush()
db_sas_category_stage = SASCategoryStage(db_category_stage.id, category_stage_reference)
db.session.add(db_sas_category_stage)
db.session.flush()
db.session.commit()
def get_event_stages(soup, event_id):
all_event_stage_divs = soup.find('div', class_ = "row categories_stages event-sub-types")
#Check if event has stages
if all_event_stage_divs:
event_stage_divs = all_event_stage_divs.find_all ('div')
for event_stage_div in event_stage_divs:
if event_stage_div.has_attr("data-stage-id"):
#Event has stages and no categories
event_stage_reference = event_stage_div["data-stage-id"]
event_stage_name = event_stage_div["data-loading-text"]
db_event_stage = EventStage(event_stage_name, event_id)
#Check if it exists by name and ID and add if it doesn't
db_event_stage_check = db.session.query(EventStage.name).filter(
(EventStage.name==event_stage_name) &
(EventStage.event_id==event_id))
if not (db.session.query(db_event_stage_check.exists()).scalar()):
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id, event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.flush()
db.session.commit()
else:
#Event has no stages or categories
#create new stage for just the overall results, unless event has no results
event_stage_reference_div = soup.find('div', class_ = "result-row load-results")
if event_stage_reference_div:
if event_stage_reference_div.has_attr("data-stage"):
event_stage_reference = event_stage_reference_div["data-stage"]
sas_event = db.session.query(SASEvent).filter(SASEvent.event_id==event_id).first()
db_event_stage_check = db.session.query(EventStage.name).filter(
(EventStage.name=="Overall Results") &
(EventStage.event_id==sas_event.event_id))
if not (db.session.query(db_event_stage_check.exists()).scalar()):
db_event_stage = EventStage("Overall Results", sas_event.event_id)
db.session.add(db_event_stage)
db.session.flush()
db_sas_event_stage = SASEventStage(db_event_stage.id, event_stage_reference)
db.session.add(db_sas_event_stage)
db.session.commit()
def get_results(event_reference):
url = ("%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999" %
(DESTINATION_URL, event_reference))
pprint(url)
try:
page = urllib.request.urlopen(url)
except (urllib.error.HTTPError, urllib.error.ConnectionResetError):
return
content = page.read().decode("utf-8")
json_content = json.loads(content)
json_results = json_content['rows']
return json_results
def write_stage_results(stage_reference, stage_id, stage_type):
results = get_results(stage_reference)
category_stage_id = None
event_stage_id = None
if (stage_type=="event"):
event_stage_id = stage_id
elif (stage_type=="category"):
category_stage_id = stage_id
if results:
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter(
(Result.position==result['overall_pos']) &
(Result.gender_position==result['gender_pos']) &
(Result.time==result['time_taken_seconds']) &
(Result.event_stage_id==event_stage_id) &
(Result.category_stage_id==category_stage_id))
if not (db.session.query(db_result_check.exists()).scalar()):
if (stage_type=="category"):
db_result = Result(result['overall_pos'], participant_id, result['gender_pos'],
result['time_taken_seconds'], None, category_stage_id, None)
elif (stage_type=="event"):
db_result = Result(result['overall_pos'], participant_id, result['gender_pos'],
result['time_taken_seconds'], event_stage_id, None, None)
db.session.add(db_result)
db.session.commit()
def write_category_results(category_reference, category_id):
results = get_results(category_reference)
for result in results:
participant_id = get_participant(result)
db_result_check = db.session.query(Result).filter(
(Result.position==result['overall_pos']) &
(Result.gender_position==result['gender_pos']) &
(Result.time==result['time_taken_seconds']) &
(Result.category_id==category_id)).first()
if not db_result_check:
db_category_result = Result(result['overall_pos'], participant_id,
result['gender_pos'], result['time_taken_seconds'], None, None, category_id)
db.session.add(db_category_result)
db.session.commit()
def get_participant(result):
if result['date_of_birth']:
birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d').date()
else:
birth_date = None
db_participant_check = db.session.query(Participant).filter(
(Participant.first_name==result['first_name']) &
(Participant.last_name==result['last_name']) &
(Participant.sex==result['person_sex']) &
(Participant.birth_date==birth_date))
if not (db.session.query(db_participant_check.exists()).scalar()):
db_participant = Participant(result['first_name'], result['last_name'],
result['person_sex'], birth_date)
db.session.add(db_participant)
db.session.commit()
return db_participant.id
else:
return db_participant_check.first().id
|
flexible
|
{
"blob_id": "ecc351cf95254e0bbc5021eff11c500fa0950bd3",
"index": 2653,
"step-1": "<mask token>\n\n\ndef scrape_sas():\n pprint('Scraping Events')\n get_mtb_events()\n pprint('Getting categories and stages')\n for event in db.session.query(SASEvent):\n pprint(event.event_id)\n get_categories_and_stages(event.event_reference, event.event_id)\n for event_stage in db.session.query(SASEventStage):\n pprint('Getting event stage results')\n base_event_stage = db.session.query(EventStage).filter(EventStage.\n id == event_stage.event_stage_id).first()\n if base_event_stage.results:\n pprint('Event has results')\n else:\n write_stage_results(event_stage.stage_reference, event_stage.\n event_stage_id, 'event')\n for category_stage in db.session.query(SASCategoryStage):\n pprint('Getting category stage results')\n base_category_stage = db.session.query(CategoryStage).filter(\n CategoryStage.id == category_stage.category_stage_id).first()\n if base_category_stage.results:\n pprint('Category stage has results')\n else:\n write_stage_results(category_stage.stage_reference,\n category_stage.category_stage_id, 'category')\n for category in db.session.query(SASCategory):\n pprint('Getting category results')\n base_category = db.session.query(Category).filter(Category.id ==\n category.category_id).first()\n if base_category.results:\n pprint('Category has results')\n elif not base_category.category_stages:\n write_category_results(category.stage_reference, category.id)\n else:\n pprint('No results but has category stages')\n pprint('Scrape Complete')\n\n\n<mask token>\n\n\ndef get_categories_and_stages(event_reference, event_id):\n event = db.session.query(Event).filter(Event.id == event_id).first()\n if event.categories or event.event_stages:\n pprint('Event Exists')\n else:\n url = DESTINATION_URL + event_reference\n try:\n page = urllib.request.urlopen(url)\n except (urllib.error.HTTPError, urllib.error.URLError):\n return\n soup = BeautifulSoup(page, 'html.parser')\n check_stages = get_categories(soup, event_id)\n\n\ndef get_categories(soup, event_id):\n category_div = soup.find('div', attrs={'id': 'category_container'})\n if category_div:\n divs = category_div.find_all('div')\n for div in divs:\n if div.has_attr('data-event-category-id'):\n category_reference = div['data-event-category-id']\n category_name = div['data-loading-text']\n category_own_stage_reference = div['data-event-stage-id']\n db_category = Category(category_name, event_id)\n db_category_check = db.session.query(Category.name).filter(\n (Category.name == category_name) & (Category.event_id ==\n event_id))\n db_sas_category_check = db.session.query(SASCategory).filter(\n (SASCategory.category_reference == category_reference) &\n (SASCategory.stage_reference ==\n category_own_stage_reference))\n if not db.session.query(db_category_check.exists()).scalar():\n db.session.add(db_category)\n db.session.flush()\n if not db.session.query(db_sas_category_check.exists()\n ).scalar():\n db_sas_category = SASCategory(category_reference,\n category_own_stage_reference, db_category.id)\n db.session.add(db_sas_category)\n db.session.flush()\n db.session.commit()\n if div['data-multiple-event-stages'] == '1':\n get_category_stages(soup, db_category.id,\n category_reference)\n else:\n get_event_stages(soup, event_id)\n\n\n<mask token>\n\n\ndef get_event_stages(soup, event_id):\n all_event_stage_divs = soup.find('div', class_=\n 'row categories_stages event-sub-types')\n if all_event_stage_divs:\n event_stage_divs = all_event_stage_divs.find_all('div')\n for event_stage_div in event_stage_divs:\n if event_stage_div.has_attr('data-stage-id'):\n event_stage_reference = event_stage_div['data-stage-id']\n event_stage_name = event_stage_div['data-loading-text']\n db_event_stage = EventStage(event_stage_name, event_id)\n db_event_stage_check = db.session.query(EventStage.name\n ).filter((EventStage.name == event_stage_name) & (\n EventStage.event_id == event_id))\n if not db.session.query(db_event_stage_check.exists()).scalar(\n ):\n db.session.add(db_event_stage)\n db.session.flush()\n db_sas_event_stage = SASEventStage(db_event_stage.id,\n event_stage_reference)\n db.session.add(db_sas_event_stage)\n db.session.flush()\n db.session.commit()\n else:\n event_stage_reference_div = soup.find('div', class_=\n 'result-row load-results')\n if event_stage_reference_div:\n if event_stage_reference_div.has_attr('data-stage'):\n event_stage_reference = event_stage_reference_div['data-stage']\n sas_event = db.session.query(SASEvent).filter(SASEvent.\n event_id == event_id).first()\n db_event_stage_check = db.session.query(EventStage.name\n ).filter((EventStage.name == 'Overall Results') & (\n EventStage.event_id == sas_event.event_id))\n if not db.session.query(db_event_stage_check.exists()).scalar(\n ):\n db_event_stage = EventStage('Overall Results',\n sas_event.event_id)\n db.session.add(db_event_stage)\n db.session.flush()\n db_sas_event_stage = SASEventStage(db_event_stage.id,\n event_stage_reference)\n db.session.add(db_sas_event_stage)\n db.session.commit()\n\n\ndef get_results(event_reference):\n url = (\n '%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999'\n % (DESTINATION_URL, event_reference))\n pprint(url)\n try:\n page = urllib.request.urlopen(url)\n except (urllib.error.HTTPError, urllib.error.ConnectionResetError):\n return\n content = page.read().decode('utf-8')\n json_content = json.loads(content)\n json_results = json_content['rows']\n return json_results\n\n\ndef write_stage_results(stage_reference, stage_id, stage_type):\n results = get_results(stage_reference)\n category_stage_id = None\n event_stage_id = None\n if stage_type == 'event':\n event_stage_id = stage_id\n elif stage_type == 'category':\n category_stage_id = stage_id\n if results:\n for result in results:\n participant_id = get_participant(result)\n db_result_check = db.session.query(Result).filter((Result.\n position == result['overall_pos']) & (Result.\n gender_position == result['gender_pos']) & (Result.time ==\n result['time_taken_seconds']) & (Result.event_stage_id ==\n event_stage_id) & (Result.category_stage_id ==\n category_stage_id))\n if not db.session.query(db_result_check.exists()).scalar():\n if stage_type == 'category':\n db_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], None, category_stage_id, None)\n elif stage_type == 'event':\n db_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], event_stage_id, None, None)\n db.session.add(db_result)\n db.session.commit()\n\n\ndef write_category_results(category_reference, category_id):\n results = get_results(category_reference)\n for result in results:\n participant_id = get_participant(result)\n db_result_check = db.session.query(Result).filter((Result.position ==\n result['overall_pos']) & (Result.gender_position == result[\n 'gender_pos']) & (Result.time == result['time_taken_seconds']) &\n (Result.category_id == category_id)).first()\n if not db_result_check:\n db_category_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], None, None, category_id)\n db.session.add(db_category_result)\n db.session.commit()\n\n\ndef get_participant(result):\n if result['date_of_birth']:\n birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d'\n ).date()\n else:\n birth_date = None\n db_participant_check = db.session.query(Participant).filter((\n Participant.first_name == result['first_name']) & (Participant.\n last_name == result['last_name']) & (Participant.sex == result[\n 'person_sex']) & (Participant.birth_date == birth_date))\n if not db.session.query(db_participant_check.exists()).scalar():\n db_participant = Participant(result['first_name'], result[\n 'last_name'], result['person_sex'], birth_date)\n db.session.add(db_participant)\n db.session.commit()\n return db_participant.id\n else:\n return db_participant_check.first().id\n",
"step-2": "<mask token>\n\n\ndef scrape_sas():\n pprint('Scraping Events')\n get_mtb_events()\n pprint('Getting categories and stages')\n for event in db.session.query(SASEvent):\n pprint(event.event_id)\n get_categories_and_stages(event.event_reference, event.event_id)\n for event_stage in db.session.query(SASEventStage):\n pprint('Getting event stage results')\n base_event_stage = db.session.query(EventStage).filter(EventStage.\n id == event_stage.event_stage_id).first()\n if base_event_stage.results:\n pprint('Event has results')\n else:\n write_stage_results(event_stage.stage_reference, event_stage.\n event_stage_id, 'event')\n for category_stage in db.session.query(SASCategoryStage):\n pprint('Getting category stage results')\n base_category_stage = db.session.query(CategoryStage).filter(\n CategoryStage.id == category_stage.category_stage_id).first()\n if base_category_stage.results:\n pprint('Category stage has results')\n else:\n write_stage_results(category_stage.stage_reference,\n category_stage.category_stage_id, 'category')\n for category in db.session.query(SASCategory):\n pprint('Getting category results')\n base_category = db.session.query(Category).filter(Category.id ==\n category.category_id).first()\n if base_category.results:\n pprint('Category has results')\n elif not base_category.category_stages:\n write_category_results(category.stage_reference, category.id)\n else:\n pprint('No results but has category stages')\n pprint('Scrape Complete')\n\n\n<mask token>\n\n\ndef get_categories_and_stages(event_reference, event_id):\n event = db.session.query(Event).filter(Event.id == event_id).first()\n if event.categories or event.event_stages:\n pprint('Event Exists')\n else:\n url = DESTINATION_URL + event_reference\n try:\n page = urllib.request.urlopen(url)\n except (urllib.error.HTTPError, urllib.error.URLError):\n return\n soup = BeautifulSoup(page, 'html.parser')\n check_stages = get_categories(soup, event_id)\n\n\ndef get_categories(soup, event_id):\n category_div = soup.find('div', attrs={'id': 'category_container'})\n if category_div:\n divs = category_div.find_all('div')\n for div in divs:\n if div.has_attr('data-event-category-id'):\n category_reference = div['data-event-category-id']\n category_name = div['data-loading-text']\n category_own_stage_reference = div['data-event-stage-id']\n db_category = Category(category_name, event_id)\n db_category_check = db.session.query(Category.name).filter(\n (Category.name == category_name) & (Category.event_id ==\n event_id))\n db_sas_category_check = db.session.query(SASCategory).filter(\n (SASCategory.category_reference == category_reference) &\n (SASCategory.stage_reference ==\n category_own_stage_reference))\n if not db.session.query(db_category_check.exists()).scalar():\n db.session.add(db_category)\n db.session.flush()\n if not db.session.query(db_sas_category_check.exists()\n ).scalar():\n db_sas_category = SASCategory(category_reference,\n category_own_stage_reference, db_category.id)\n db.session.add(db_sas_category)\n db.session.flush()\n db.session.commit()\n if div['data-multiple-event-stages'] == '1':\n get_category_stages(soup, db_category.id,\n category_reference)\n else:\n get_event_stages(soup, event_id)\n\n\ndef get_category_stages(soup, category_id, category_reference):\n stage_group_div = soup.find('div', attrs={'id': 'ec_' + category_reference}\n )\n stage_divs = stage_group_div.find_all('div')\n for stage_div in stage_divs:\n if stage_div.has_attr('data-stage-id'):\n category_stage_reference = stage_div['data-stage-id']\n category_stage_name = stage_div['data-loading-text']\n db_category_stage = CategoryStage(category_stage_name, category_id)\n db_category_stage_check = db.session.query(CategoryStage.name\n ).filter((CategoryStage.name == category_stage_name) & (\n CategoryStage.category_id == category_id))\n if not db.session.query(db_category_stage_check.exists()).scalar():\n db.session.add(db_category_stage)\n db.session.flush()\n db_sas_category_stage = SASCategoryStage(db_category_stage.\n id, category_stage_reference)\n db.session.add(db_sas_category_stage)\n db.session.flush()\n db.session.commit()\n\n\ndef get_event_stages(soup, event_id):\n all_event_stage_divs = soup.find('div', class_=\n 'row categories_stages event-sub-types')\n if all_event_stage_divs:\n event_stage_divs = all_event_stage_divs.find_all('div')\n for event_stage_div in event_stage_divs:\n if event_stage_div.has_attr('data-stage-id'):\n event_stage_reference = event_stage_div['data-stage-id']\n event_stage_name = event_stage_div['data-loading-text']\n db_event_stage = EventStage(event_stage_name, event_id)\n db_event_stage_check = db.session.query(EventStage.name\n ).filter((EventStage.name == event_stage_name) & (\n EventStage.event_id == event_id))\n if not db.session.query(db_event_stage_check.exists()).scalar(\n ):\n db.session.add(db_event_stage)\n db.session.flush()\n db_sas_event_stage = SASEventStage(db_event_stage.id,\n event_stage_reference)\n db.session.add(db_sas_event_stage)\n db.session.flush()\n db.session.commit()\n else:\n event_stage_reference_div = soup.find('div', class_=\n 'result-row load-results')\n if event_stage_reference_div:\n if event_stage_reference_div.has_attr('data-stage'):\n event_stage_reference = event_stage_reference_div['data-stage']\n sas_event = db.session.query(SASEvent).filter(SASEvent.\n event_id == event_id).first()\n db_event_stage_check = db.session.query(EventStage.name\n ).filter((EventStage.name == 'Overall Results') & (\n EventStage.event_id == sas_event.event_id))\n if not db.session.query(db_event_stage_check.exists()).scalar(\n ):\n db_event_stage = EventStage('Overall Results',\n sas_event.event_id)\n db.session.add(db_event_stage)\n db.session.flush()\n db_sas_event_stage = SASEventStage(db_event_stage.id,\n event_stage_reference)\n db.session.add(db_sas_event_stage)\n db.session.commit()\n\n\ndef get_results(event_reference):\n url = (\n '%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999'\n % (DESTINATION_URL, event_reference))\n pprint(url)\n try:\n page = urllib.request.urlopen(url)\n except (urllib.error.HTTPError, urllib.error.ConnectionResetError):\n return\n content = page.read().decode('utf-8')\n json_content = json.loads(content)\n json_results = json_content['rows']\n return json_results\n\n\ndef write_stage_results(stage_reference, stage_id, stage_type):\n results = get_results(stage_reference)\n category_stage_id = None\n event_stage_id = None\n if stage_type == 'event':\n event_stage_id = stage_id\n elif stage_type == 'category':\n category_stage_id = stage_id\n if results:\n for result in results:\n participant_id = get_participant(result)\n db_result_check = db.session.query(Result).filter((Result.\n position == result['overall_pos']) & (Result.\n gender_position == result['gender_pos']) & (Result.time ==\n result['time_taken_seconds']) & (Result.event_stage_id ==\n event_stage_id) & (Result.category_stage_id ==\n category_stage_id))\n if not db.session.query(db_result_check.exists()).scalar():\n if stage_type == 'category':\n db_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], None, category_stage_id, None)\n elif stage_type == 'event':\n db_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], event_stage_id, None, None)\n db.session.add(db_result)\n db.session.commit()\n\n\ndef write_category_results(category_reference, category_id):\n results = get_results(category_reference)\n for result in results:\n participant_id = get_participant(result)\n db_result_check = db.session.query(Result).filter((Result.position ==\n result['overall_pos']) & (Result.gender_position == result[\n 'gender_pos']) & (Result.time == result['time_taken_seconds']) &\n (Result.category_id == category_id)).first()\n if not db_result_check:\n db_category_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], None, None, category_id)\n db.session.add(db_category_result)\n db.session.commit()\n\n\ndef get_participant(result):\n if result['date_of_birth']:\n birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d'\n ).date()\n else:\n birth_date = None\n db_participant_check = db.session.query(Participant).filter((\n Participant.first_name == result['first_name']) & (Participant.\n last_name == result['last_name']) & (Participant.sex == result[\n 'person_sex']) & (Participant.birth_date == birth_date))\n if not db.session.query(db_participant_check.exists()).scalar():\n db_participant = Participant(result['first_name'], result[\n 'last_name'], result['person_sex'], birth_date)\n db.session.add(db_participant)\n db.session.commit()\n return db_participant.id\n else:\n return db_participant_check.first().id\n",
"step-3": "<mask token>\n\n\ndef scrape_sas():\n pprint('Scraping Events')\n get_mtb_events()\n pprint('Getting categories and stages')\n for event in db.session.query(SASEvent):\n pprint(event.event_id)\n get_categories_and_stages(event.event_reference, event.event_id)\n for event_stage in db.session.query(SASEventStage):\n pprint('Getting event stage results')\n base_event_stage = db.session.query(EventStage).filter(EventStage.\n id == event_stage.event_stage_id).first()\n if base_event_stage.results:\n pprint('Event has results')\n else:\n write_stage_results(event_stage.stage_reference, event_stage.\n event_stage_id, 'event')\n for category_stage in db.session.query(SASCategoryStage):\n pprint('Getting category stage results')\n base_category_stage = db.session.query(CategoryStage).filter(\n CategoryStage.id == category_stage.category_stage_id).first()\n if base_category_stage.results:\n pprint('Category stage has results')\n else:\n write_stage_results(category_stage.stage_reference,\n category_stage.category_stage_id, 'category')\n for category in db.session.query(SASCategory):\n pprint('Getting category results')\n base_category = db.session.query(Category).filter(Category.id ==\n category.category_id).first()\n if base_category.results:\n pprint('Category has results')\n elif not base_category.category_stages:\n write_category_results(category.stage_reference, category.id)\n else:\n pprint('No results but has category stages')\n pprint('Scrape Complete')\n\n\ndef get_mtb_events():\n for year in YEARS:\n url = (\n '%s/participants/event-results/fetch-series-by-type?event_type=%s&event_year=%d'\n % (DESTINATION_URL, MTB_EVENT_TYPE, year))\n try:\n page = urllib.request.urlopen(url)\n content = page.read().decode('utf-8')\n json_content = json.loads(content)\n soup = BeautifulSoup(json_content['HTML'], 'html.parser')\n anchors = soup.find_all('a')\n except (urllib.error.HTTPError, urllib.error.ConnectionResetError):\n pass\n for anchor in anchors:\n event_reference = anchor['href']\n divs = anchor.find_all('div')\n for div in divs:\n if 'event-date' in div['class']:\n event_date = div.find(text=True)\n elif 'event-title' in div['class']:\n event_name = div.find(text=True)\n db_date = datetime.strptime(event_date, '%d %b %Y')\n db_event = Event(event_name, db_date)\n db_check = db.session.query(Event.title).filter(Event.title ==\n event_name)\n if not db.session.query(db_check.exists()).scalar():\n db.session.add(db_event)\n db.session.flush()\n sas_event = SASEvent(db_event.id, event_reference)\n db.session.add(sas_event)\n db.session.commit()\n\n\ndef get_categories_and_stages(event_reference, event_id):\n event = db.session.query(Event).filter(Event.id == event_id).first()\n if event.categories or event.event_stages:\n pprint('Event Exists')\n else:\n url = DESTINATION_URL + event_reference\n try:\n page = urllib.request.urlopen(url)\n except (urllib.error.HTTPError, urllib.error.URLError):\n return\n soup = BeautifulSoup(page, 'html.parser')\n check_stages = get_categories(soup, event_id)\n\n\ndef get_categories(soup, event_id):\n category_div = soup.find('div', attrs={'id': 'category_container'})\n if category_div:\n divs = category_div.find_all('div')\n for div in divs:\n if div.has_attr('data-event-category-id'):\n category_reference = div['data-event-category-id']\n category_name = div['data-loading-text']\n category_own_stage_reference = div['data-event-stage-id']\n db_category = Category(category_name, event_id)\n db_category_check = db.session.query(Category.name).filter(\n (Category.name == category_name) & (Category.event_id ==\n event_id))\n db_sas_category_check = db.session.query(SASCategory).filter(\n (SASCategory.category_reference == category_reference) &\n (SASCategory.stage_reference ==\n category_own_stage_reference))\n if not db.session.query(db_category_check.exists()).scalar():\n db.session.add(db_category)\n db.session.flush()\n if not db.session.query(db_sas_category_check.exists()\n ).scalar():\n db_sas_category = SASCategory(category_reference,\n category_own_stage_reference, db_category.id)\n db.session.add(db_sas_category)\n db.session.flush()\n db.session.commit()\n if div['data-multiple-event-stages'] == '1':\n get_category_stages(soup, db_category.id,\n category_reference)\n else:\n get_event_stages(soup, event_id)\n\n\ndef get_category_stages(soup, category_id, category_reference):\n stage_group_div = soup.find('div', attrs={'id': 'ec_' + category_reference}\n )\n stage_divs = stage_group_div.find_all('div')\n for stage_div in stage_divs:\n if stage_div.has_attr('data-stage-id'):\n category_stage_reference = stage_div['data-stage-id']\n category_stage_name = stage_div['data-loading-text']\n db_category_stage = CategoryStage(category_stage_name, category_id)\n db_category_stage_check = db.session.query(CategoryStage.name\n ).filter((CategoryStage.name == category_stage_name) & (\n CategoryStage.category_id == category_id))\n if not db.session.query(db_category_stage_check.exists()).scalar():\n db.session.add(db_category_stage)\n db.session.flush()\n db_sas_category_stage = SASCategoryStage(db_category_stage.\n id, category_stage_reference)\n db.session.add(db_sas_category_stage)\n db.session.flush()\n db.session.commit()\n\n\ndef get_event_stages(soup, event_id):\n all_event_stage_divs = soup.find('div', class_=\n 'row categories_stages event-sub-types')\n if all_event_stage_divs:\n event_stage_divs = all_event_stage_divs.find_all('div')\n for event_stage_div in event_stage_divs:\n if event_stage_div.has_attr('data-stage-id'):\n event_stage_reference = event_stage_div['data-stage-id']\n event_stage_name = event_stage_div['data-loading-text']\n db_event_stage = EventStage(event_stage_name, event_id)\n db_event_stage_check = db.session.query(EventStage.name\n ).filter((EventStage.name == event_stage_name) & (\n EventStage.event_id == event_id))\n if not db.session.query(db_event_stage_check.exists()).scalar(\n ):\n db.session.add(db_event_stage)\n db.session.flush()\n db_sas_event_stage = SASEventStage(db_event_stage.id,\n event_stage_reference)\n db.session.add(db_sas_event_stage)\n db.session.flush()\n db.session.commit()\n else:\n event_stage_reference_div = soup.find('div', class_=\n 'result-row load-results')\n if event_stage_reference_div:\n if event_stage_reference_div.has_attr('data-stage'):\n event_stage_reference = event_stage_reference_div['data-stage']\n sas_event = db.session.query(SASEvent).filter(SASEvent.\n event_id == event_id).first()\n db_event_stage_check = db.session.query(EventStage.name\n ).filter((EventStage.name == 'Overall Results') & (\n EventStage.event_id == sas_event.event_id))\n if not db.session.query(db_event_stage_check.exists()).scalar(\n ):\n db_event_stage = EventStage('Overall Results',\n sas_event.event_id)\n db.session.add(db_event_stage)\n db.session.flush()\n db_sas_event_stage = SASEventStage(db_event_stage.id,\n event_stage_reference)\n db.session.add(db_sas_event_stage)\n db.session.commit()\n\n\ndef get_results(event_reference):\n url = (\n '%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999'\n % (DESTINATION_URL, event_reference))\n pprint(url)\n try:\n page = urllib.request.urlopen(url)\n except (urllib.error.HTTPError, urllib.error.ConnectionResetError):\n return\n content = page.read().decode('utf-8')\n json_content = json.loads(content)\n json_results = json_content['rows']\n return json_results\n\n\ndef write_stage_results(stage_reference, stage_id, stage_type):\n results = get_results(stage_reference)\n category_stage_id = None\n event_stage_id = None\n if stage_type == 'event':\n event_stage_id = stage_id\n elif stage_type == 'category':\n category_stage_id = stage_id\n if results:\n for result in results:\n participant_id = get_participant(result)\n db_result_check = db.session.query(Result).filter((Result.\n position == result['overall_pos']) & (Result.\n gender_position == result['gender_pos']) & (Result.time ==\n result['time_taken_seconds']) & (Result.event_stage_id ==\n event_stage_id) & (Result.category_stage_id ==\n category_stage_id))\n if not db.session.query(db_result_check.exists()).scalar():\n if stage_type == 'category':\n db_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], None, category_stage_id, None)\n elif stage_type == 'event':\n db_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], event_stage_id, None, None)\n db.session.add(db_result)\n db.session.commit()\n\n\ndef write_category_results(category_reference, category_id):\n results = get_results(category_reference)\n for result in results:\n participant_id = get_participant(result)\n db_result_check = db.session.query(Result).filter((Result.position ==\n result['overall_pos']) & (Result.gender_position == result[\n 'gender_pos']) & (Result.time == result['time_taken_seconds']) &\n (Result.category_id == category_id)).first()\n if not db_result_check:\n db_category_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], None, None, category_id)\n db.session.add(db_category_result)\n db.session.commit()\n\n\ndef get_participant(result):\n if result['date_of_birth']:\n birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d'\n ).date()\n else:\n birth_date = None\n db_participant_check = db.session.query(Participant).filter((\n Participant.first_name == result['first_name']) & (Participant.\n last_name == result['last_name']) & (Participant.sex == result[\n 'person_sex']) & (Participant.birth_date == birth_date))\n if not db.session.query(db_participant_check.exists()).scalar():\n db_participant = Participant(result['first_name'], result[\n 'last_name'], result['person_sex'], birth_date)\n db.session.add(db_participant)\n db.session.commit()\n return db_participant.id\n else:\n return db_participant_check.first().id\n",
"step-4": "from bs4 import BeautifulSoup\nfrom pprint import pprint\nfrom scraper.sas.sas_models import SASEvent, SASCategory, SASCategoryStage, SASEventStage\nfrom scraper.base_models.models import Event, Category, CategoryStage, EventStage, Participant, Result\nfrom scraper.sas.sas_config import DESTINATION_URL, MTB_EVENT_TYPE, YEARS\nfrom scraper import db\nfrom datetime import datetime\nimport urllib\nimport json\nimport time\n\n\ndef scrape_sas():\n pprint('Scraping Events')\n get_mtb_events()\n pprint('Getting categories and stages')\n for event in db.session.query(SASEvent):\n pprint(event.event_id)\n get_categories_and_stages(event.event_reference, event.event_id)\n for event_stage in db.session.query(SASEventStage):\n pprint('Getting event stage results')\n base_event_stage = db.session.query(EventStage).filter(EventStage.\n id == event_stage.event_stage_id).first()\n if base_event_stage.results:\n pprint('Event has results')\n else:\n write_stage_results(event_stage.stage_reference, event_stage.\n event_stage_id, 'event')\n for category_stage in db.session.query(SASCategoryStage):\n pprint('Getting category stage results')\n base_category_stage = db.session.query(CategoryStage).filter(\n CategoryStage.id == category_stage.category_stage_id).first()\n if base_category_stage.results:\n pprint('Category stage has results')\n else:\n write_stage_results(category_stage.stage_reference,\n category_stage.category_stage_id, 'category')\n for category in db.session.query(SASCategory):\n pprint('Getting category results')\n base_category = db.session.query(Category).filter(Category.id ==\n category.category_id).first()\n if base_category.results:\n pprint('Category has results')\n elif not base_category.category_stages:\n write_category_results(category.stage_reference, category.id)\n else:\n pprint('No results but has category stages')\n pprint('Scrape Complete')\n\n\ndef get_mtb_events():\n for year in YEARS:\n url = (\n '%s/participants/event-results/fetch-series-by-type?event_type=%s&event_year=%d'\n % (DESTINATION_URL, MTB_EVENT_TYPE, year))\n try:\n page = urllib.request.urlopen(url)\n content = page.read().decode('utf-8')\n json_content = json.loads(content)\n soup = BeautifulSoup(json_content['HTML'], 'html.parser')\n anchors = soup.find_all('a')\n except (urllib.error.HTTPError, urllib.error.ConnectionResetError):\n pass\n for anchor in anchors:\n event_reference = anchor['href']\n divs = anchor.find_all('div')\n for div in divs:\n if 'event-date' in div['class']:\n event_date = div.find(text=True)\n elif 'event-title' in div['class']:\n event_name = div.find(text=True)\n db_date = datetime.strptime(event_date, '%d %b %Y')\n db_event = Event(event_name, db_date)\n db_check = db.session.query(Event.title).filter(Event.title ==\n event_name)\n if not db.session.query(db_check.exists()).scalar():\n db.session.add(db_event)\n db.session.flush()\n sas_event = SASEvent(db_event.id, event_reference)\n db.session.add(sas_event)\n db.session.commit()\n\n\ndef get_categories_and_stages(event_reference, event_id):\n event = db.session.query(Event).filter(Event.id == event_id).first()\n if event.categories or event.event_stages:\n pprint('Event Exists')\n else:\n url = DESTINATION_URL + event_reference\n try:\n page = urllib.request.urlopen(url)\n except (urllib.error.HTTPError, urllib.error.URLError):\n return\n soup = BeautifulSoup(page, 'html.parser')\n check_stages = get_categories(soup, event_id)\n\n\ndef get_categories(soup, event_id):\n category_div = soup.find('div', attrs={'id': 'category_container'})\n if category_div:\n divs = category_div.find_all('div')\n for div in divs:\n if div.has_attr('data-event-category-id'):\n category_reference = div['data-event-category-id']\n category_name = div['data-loading-text']\n category_own_stage_reference = div['data-event-stage-id']\n db_category = Category(category_name, event_id)\n db_category_check = db.session.query(Category.name).filter(\n (Category.name == category_name) & (Category.event_id ==\n event_id))\n db_sas_category_check = db.session.query(SASCategory).filter(\n (SASCategory.category_reference == category_reference) &\n (SASCategory.stage_reference ==\n category_own_stage_reference))\n if not db.session.query(db_category_check.exists()).scalar():\n db.session.add(db_category)\n db.session.flush()\n if not db.session.query(db_sas_category_check.exists()\n ).scalar():\n db_sas_category = SASCategory(category_reference,\n category_own_stage_reference, db_category.id)\n db.session.add(db_sas_category)\n db.session.flush()\n db.session.commit()\n if div['data-multiple-event-stages'] == '1':\n get_category_stages(soup, db_category.id,\n category_reference)\n else:\n get_event_stages(soup, event_id)\n\n\ndef get_category_stages(soup, category_id, category_reference):\n stage_group_div = soup.find('div', attrs={'id': 'ec_' + category_reference}\n )\n stage_divs = stage_group_div.find_all('div')\n for stage_div in stage_divs:\n if stage_div.has_attr('data-stage-id'):\n category_stage_reference = stage_div['data-stage-id']\n category_stage_name = stage_div['data-loading-text']\n db_category_stage = CategoryStage(category_stage_name, category_id)\n db_category_stage_check = db.session.query(CategoryStage.name\n ).filter((CategoryStage.name == category_stage_name) & (\n CategoryStage.category_id == category_id))\n if not db.session.query(db_category_stage_check.exists()).scalar():\n db.session.add(db_category_stage)\n db.session.flush()\n db_sas_category_stage = SASCategoryStage(db_category_stage.\n id, category_stage_reference)\n db.session.add(db_sas_category_stage)\n db.session.flush()\n db.session.commit()\n\n\ndef get_event_stages(soup, event_id):\n all_event_stage_divs = soup.find('div', class_=\n 'row categories_stages event-sub-types')\n if all_event_stage_divs:\n event_stage_divs = all_event_stage_divs.find_all('div')\n for event_stage_div in event_stage_divs:\n if event_stage_div.has_attr('data-stage-id'):\n event_stage_reference = event_stage_div['data-stage-id']\n event_stage_name = event_stage_div['data-loading-text']\n db_event_stage = EventStage(event_stage_name, event_id)\n db_event_stage_check = db.session.query(EventStage.name\n ).filter((EventStage.name == event_stage_name) & (\n EventStage.event_id == event_id))\n if not db.session.query(db_event_stage_check.exists()).scalar(\n ):\n db.session.add(db_event_stage)\n db.session.flush()\n db_sas_event_stage = SASEventStage(db_event_stage.id,\n event_stage_reference)\n db.session.add(db_sas_event_stage)\n db.session.flush()\n db.session.commit()\n else:\n event_stage_reference_div = soup.find('div', class_=\n 'result-row load-results')\n if event_stage_reference_div:\n if event_stage_reference_div.has_attr('data-stage'):\n event_stage_reference = event_stage_reference_div['data-stage']\n sas_event = db.session.query(SASEvent).filter(SASEvent.\n event_id == event_id).first()\n db_event_stage_check = db.session.query(EventStage.name\n ).filter((EventStage.name == 'Overall Results') & (\n EventStage.event_id == sas_event.event_id))\n if not db.session.query(db_event_stage_check.exists()).scalar(\n ):\n db_event_stage = EventStage('Overall Results',\n sas_event.event_id)\n db.session.add(db_event_stage)\n db.session.flush()\n db_sas_event_stage = SASEventStage(db_event_stage.id,\n event_stage_reference)\n db.session.add(db_sas_event_stage)\n db.session.commit()\n\n\ndef get_results(event_reference):\n url = (\n '%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999'\n % (DESTINATION_URL, event_reference))\n pprint(url)\n try:\n page = urllib.request.urlopen(url)\n except (urllib.error.HTTPError, urllib.error.ConnectionResetError):\n return\n content = page.read().decode('utf-8')\n json_content = json.loads(content)\n json_results = json_content['rows']\n return json_results\n\n\ndef write_stage_results(stage_reference, stage_id, stage_type):\n results = get_results(stage_reference)\n category_stage_id = None\n event_stage_id = None\n if stage_type == 'event':\n event_stage_id = stage_id\n elif stage_type == 'category':\n category_stage_id = stage_id\n if results:\n for result in results:\n participant_id = get_participant(result)\n db_result_check = db.session.query(Result).filter((Result.\n position == result['overall_pos']) & (Result.\n gender_position == result['gender_pos']) & (Result.time ==\n result['time_taken_seconds']) & (Result.event_stage_id ==\n event_stage_id) & (Result.category_stage_id ==\n category_stage_id))\n if not db.session.query(db_result_check.exists()).scalar():\n if stage_type == 'category':\n db_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], None, category_stage_id, None)\n elif stage_type == 'event':\n db_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], event_stage_id, None, None)\n db.session.add(db_result)\n db.session.commit()\n\n\ndef write_category_results(category_reference, category_id):\n results = get_results(category_reference)\n for result in results:\n participant_id = get_participant(result)\n db_result_check = db.session.query(Result).filter((Result.position ==\n result['overall_pos']) & (Result.gender_position == result[\n 'gender_pos']) & (Result.time == result['time_taken_seconds']) &\n (Result.category_id == category_id)).first()\n if not db_result_check:\n db_category_result = Result(result['overall_pos'],\n participant_id, result['gender_pos'], result[\n 'time_taken_seconds'], None, None, category_id)\n db.session.add(db_category_result)\n db.session.commit()\n\n\ndef get_participant(result):\n if result['date_of_birth']:\n birth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d'\n ).date()\n else:\n birth_date = None\n db_participant_check = db.session.query(Participant).filter((\n Participant.first_name == result['first_name']) & (Participant.\n last_name == result['last_name']) & (Participant.sex == result[\n 'person_sex']) & (Participant.birth_date == birth_date))\n if not db.session.query(db_participant_check.exists()).scalar():\n db_participant = Participant(result['first_name'], result[\n 'last_name'], result['person_sex'], birth_date)\n db.session.add(db_participant)\n db.session.commit()\n return db_participant.id\n else:\n return db_participant_check.first().id\n",
"step-5": "from bs4 import BeautifulSoup\nfrom pprint import pprint \nfrom scraper.sas.sas_models import SASEvent, SASCategory, SASCategoryStage, SASEventStage\nfrom scraper.base_models.models import Event, Category, CategoryStage, EventStage, Participant, Result\nfrom scraper.sas.sas_config import DESTINATION_URL, MTB_EVENT_TYPE, YEARS\nfrom scraper import db\nfrom datetime import datetime\nimport urllib\nimport json \nimport time\n\ndef scrape_sas():\n\tpprint(\"Scraping Events\")\n\tget_mtb_events()\n\tpprint(\"Getting categories and stages\")\n\tfor event in db.session.query(SASEvent):\n\t\tpprint(event.event_id)\n\t\tget_categories_and_stages(event.event_reference, event.event_id)\n\t\t#time.sleep(2)\n\tfor event_stage in db.session.query(SASEventStage):\n\t\tpprint(\"Getting event stage results\")\n\t\tbase_event_stage = db.session.query(EventStage).filter(EventStage.id==event_stage.event_stage_id).first()\n\t\tif (base_event_stage.results):\n\t\t\tpprint(\"Event has results\")\n\t\telse:\n\t\t\twrite_stage_results(event_stage.stage_reference, event_stage.event_stage_id, \"event\")\n\tfor category_stage in db.session.query(SASCategoryStage):\n\t\tpprint(\"Getting category stage results\")\n\t\tbase_category_stage = db.session.query(CategoryStage).filter(CategoryStage.id==category_stage.category_stage_id).first()\n\t\tif (base_category_stage.results):\n\t\t\tpprint(\"Category stage has results\")\n\t\telse: \n\t\t\twrite_stage_results(category_stage.stage_reference, category_stage.category_stage_id, \"category\")\n\tfor category in db.session.query(SASCategory):\n\t\tpprint(\"Getting category results\")\n\t\tbase_category = db.session.query(Category).filter(Category.id==category.category_id).first()\n\t\tif (base_category.results):\n\t\t\tpprint(\"Category has results\")\n\t\telse: \n\t\t\tif (not base_category.category_stages):\n\t\t\t\twrite_category_results(category.stage_reference, category.id)\n\t\t\telse:\n\t\t\t\tpprint(\"No results but has category stages\")\n\tpprint(\"Scrape Complete\")\n\ndef get_mtb_events(): \n\tfor year in YEARS: \n\t\turl = (\"%s/participants/event-results/fetch-series-by-type?event_type=%s&event_year=%d\" % \n\t\t\t (DESTINATION_URL, MTB_EVENT_TYPE, year))\n\t\ttry: \n\t\t\tpage = urllib.request.urlopen(url)\n\t\t\tcontent = page.read().decode(\"utf-8\")\n\t\t\tjson_content = json.loads(content)\n\t\t\tsoup = BeautifulSoup(json_content['HTML'], \"html.parser\")\n\t\t\tanchors = soup.find_all('a')\n\t\texcept (urllib.error.HTTPError, urllib.error.ConnectionResetError):\n\t\t\tpass\n\t\tfor anchor in anchors: \n\t\t\tevent_reference = anchor[\"href\"]\n\t\t\tdivs = anchor.find_all('div')\n\t\t\tfor div in divs:\n\t\t\t\tif (\"event-date\" in div[\"class\"]):\n\t\t\t\t\tevent_date = (div.find(text=True))\n\t\t\t\telif (\"event-title\" in div[\"class\"]):\n\t\t\t\t\tevent_name = (div.find(text=True))\n\t\t\tdb_date = datetime.strptime(event_date, '%d %b %Y')\n\t\t\tdb_event = Event(event_name, db_date)\n\t\t\tdb_check = db.session.query(Event.title).filter(Event.title==event_name)\n\t\t\tif not (db.session.query(db_check.exists()).scalar()):\n\t\t\t\tdb.session.add(db_event)\n\t\t\t\tdb.session.flush()\n\t\t\t\tsas_event = SASEvent(db_event.id, event_reference)\n\t\t\t\tdb.session.add(sas_event)\n\t\t\t\tdb.session.commit()\n\ndef get_categories_and_stages(event_reference, event_id):\n\tevent = db.session.query(Event).filter(Event.id==event_id).first()\n\tif (event.categories or event.event_stages):\n\t\tpprint(\"Event Exists\")\n\telse: \n\t\turl = (DESTINATION_URL + event_reference)\n\t\ttry: \n\t\t\tpage = urllib.request.urlopen(url)\n\t\texcept (urllib.error.HTTPError, urllib.error.URLError):\n\t\t\treturn\n\t\tsoup = BeautifulSoup(page, \"html.parser\")\n\t\tcheck_stages = get_categories(soup, event_id)\n\ndef get_categories(soup, event_id):\n\tcategory_div = soup.find('div', attrs={\"id\" : \"category_container\"})\n\t#Check to see if event has categories first\n\tif category_div:\n\t\tdivs = category_div.find_all('div')\n\t\tfor div in divs: \n\t\t\tif div.has_attr(\"data-event-category-id\"):\n\t\t\t\t#Event has categories\n\t\t\t\tcategory_reference = div[\"data-event-category-id\"]\n\t\t\t\tcategory_name = div[\"data-loading-text\"]\n\t\t\t\tcategory_own_stage_reference = div[\"data-event-stage-id\"]\n\t\t\t\tdb_category = Category(category_name, event_id)\n\t\t\t\t#Check both name and event id to allow duplicate names \n\t\t\t\tdb_category_check = db.session.query(Category.name).filter(\n\t\t\t\t(Category.name==category_name) &\n\t\t\t\t(Category.event_id==event_id))\n\t\t\t\t#Check SAS category for duplicates as well \n\t\t\t\tdb_sas_category_check = db.session.query(SASCategory).filter(\n\t\t\t\t(SASCategory.category_reference==category_reference) &\n\t\t\t\t(SASCategory.stage_reference==category_own_stage_reference))\n\t\t\t\tif not (db.session.query(db_category_check.exists()).scalar()):\n\t\t\t\t\tdb.session.add(db_category)\n\t\t\t\t\tdb.session.flush()\n\t\t\t\t\tif not (db.session.query(db_sas_category_check.exists()).scalar()):\n\t\t\t\t\t\tdb_sas_category = SASCategory(category_reference, category_own_stage_reference, db_category.id)\n\t\t\t\t\t\tdb.session.add(db_sas_category)\n\t\t\t\t\t\tdb.session.flush()\n\t\t\t\t\t\tdb.session.commit()\t\t\t\n\t\t\t\t\tif (div[\"data-multiple-event-stages\"] == \"1\"):\n\t\t\t\t\t\t#Event has stages with their own categories\n\t\t\t\t\t\tget_category_stages(soup, db_category.id, category_reference)\n\telse:\n\t\t#Event does not have categories\n\t\tget_event_stages(soup, event_id)\n\n\ndef get_category_stages(soup, category_id, category_reference):\n\tstage_group_div = soup.find('div', attrs={\"id\" : (\"ec_\" + category_reference)})\n\tstage_divs = stage_group_div.find_all('div')\n\tfor stage_div in stage_divs: \n\t\tif stage_div.has_attr(\"data-stage-id\"):\n\t\t\tcategory_stage_reference = stage_div[\"data-stage-id\"]\n\t\t\tcategory_stage_name = stage_div[\"data-loading-text\"]\n\t\t\tdb_category_stage = CategoryStage(category_stage_name, category_id)\n\t\t\t#Check both name and category id to allow duplicate names \n\t\t\tdb_category_stage_check = db.session.query(CategoryStage.name).filter(\n\t\t\t\t(CategoryStage.name==category_stage_name) &\n\t\t\t\t(CategoryStage.category_id==category_id))\n\t\t\tif not (db.session.query(db_category_stage_check.exists()).scalar()):\n\t\t\t\tdb.session.add(db_category_stage)\n\t\t\t\tdb.session.flush()\n\t\t\t\tdb_sas_category_stage = SASCategoryStage(db_category_stage.id, category_stage_reference)\n\t\t\t\tdb.session.add(db_sas_category_stage)\n\t\t\t\tdb.session.flush()\n\t\t\t\tdb.session.commit()\n\ndef get_event_stages(soup, event_id):\n\tall_event_stage_divs = soup.find('div', class_ = \"row categories_stages event-sub-types\")\n\t#Check if event has stages\n\tif all_event_stage_divs:\n\t\tevent_stage_divs = all_event_stage_divs.find_all ('div')\n\t\tfor event_stage_div in event_stage_divs: \n\t\t\tif event_stage_div.has_attr(\"data-stage-id\"):\n\t\t\t\t#Event has stages and no categories\n\t\t\t\tevent_stage_reference = event_stage_div[\"data-stage-id\"]\n\t\t\t\tevent_stage_name = event_stage_div[\"data-loading-text\"]\n\t\t\t\tdb_event_stage = EventStage(event_stage_name, event_id)\n\t\t\t\t#Check if it exists by name and ID and add if it doesn't\n\t\t\t\tdb_event_stage_check = db.session.query(EventStage.name).filter(\n\t\t\t\t\t(EventStage.name==event_stage_name) &\n\t\t\t\t\t(EventStage.event_id==event_id))\n\t\t\t\tif not (db.session.query(db_event_stage_check.exists()).scalar()):\n\t\t\t\t\tdb.session.add(db_event_stage)\n\t\t\t\t\tdb.session.flush()\n\t\t\t\t\tdb_sas_event_stage = SASEventStage(db_event_stage.id, event_stage_reference)\n\t\t\t\t\tdb.session.add(db_sas_event_stage)\n\t\t\t\t\tdb.session.flush()\n\t\t\t\t\tdb.session.commit()\n\telse: \n\t\t#Event has no stages or categories\n\t\t#create new stage for just the overall results, unless event has no results\n\t\tevent_stage_reference_div = soup.find('div', class_ = \"result-row load-results\")\n\t\tif event_stage_reference_div:\n\t\t\tif event_stage_reference_div.has_attr(\"data-stage\"):\n\t\t\t\tevent_stage_reference = event_stage_reference_div[\"data-stage\"]\n\t\t\t\tsas_event = db.session.query(SASEvent).filter(SASEvent.event_id==event_id).first()\n\t\t\t\tdb_event_stage_check = db.session.query(EventStage.name).filter(\n\t\t\t\t\t(EventStage.name==\"Overall Results\") &\n\t\t\t\t\t(EventStage.event_id==sas_event.event_id))\n\t\t\t\tif not (db.session.query(db_event_stage_check.exists()).scalar()):\n\t\t\t\t\tdb_event_stage = EventStage(\"Overall Results\", sas_event.event_id)\n\t\t\t\t\tdb.session.add(db_event_stage)\n\t\t\t\t\tdb.session.flush()\n\t\t\t\t\tdb_sas_event_stage = SASEventStage(db_event_stage.id, event_stage_reference)\n\t\t\t\t\tdb.session.add(db_sas_event_stage)\n\t\t\t\t\tdb.session.commit()\n\ndef get_results(event_reference): \n\turl = (\"%s/participants/event-results/add-results?stage_id=%s&from=0&count=9999\" % \n\t\t\t (DESTINATION_URL, event_reference))\n\tpprint(url)\n\ttry: \n\t\tpage = urllib.request.urlopen(url)\n\texcept (urllib.error.HTTPError, urllib.error.ConnectionResetError):\n\t\treturn\n\tcontent = page.read().decode(\"utf-8\")\n\tjson_content = json.loads(content)\n\tjson_results = json_content['rows']\n\treturn json_results\n\ndef write_stage_results(stage_reference, stage_id, stage_type):\n\tresults = get_results(stage_reference)\n\tcategory_stage_id = None\n\tevent_stage_id = None\n\tif (stage_type==\"event\"):\n\t\tevent_stage_id = stage_id\n\telif (stage_type==\"category\"):\n\t\tcategory_stage_id = stage_id\n\tif results:\n\t\tfor result in results: \n\t\t\tparticipant_id = get_participant(result)\n\t\t\tdb_result_check = db.session.query(Result).filter(\n\t\t\t\t(Result.position==result['overall_pos']) &\n\t\t\t\t(Result.gender_position==result['gender_pos']) & \n\t\t\t\t(Result.time==result['time_taken_seconds']) & \n\t\t\t\t(Result.event_stage_id==event_stage_id) &\n\t\t\t\t(Result.category_stage_id==category_stage_id))\n\t\t\tif not (db.session.query(db_result_check.exists()).scalar()):\n\t\t\t\tif (stage_type==\"category\"): \n\t\t\t\t\tdb_result = Result(result['overall_pos'], participant_id, result['gender_pos'],\n\t\t\t\t\tresult['time_taken_seconds'], None, category_stage_id, None)\n\t\t\t\telif (stage_type==\"event\"):\n\t\t\t\t\tdb_result = Result(result['overall_pos'], participant_id, result['gender_pos'],\n\t\t\t\t result['time_taken_seconds'], event_stage_id, None, None)\n\t\t\t\tdb.session.add(db_result)\n\t\t\t\tdb.session.commit()\n\ndef write_category_results(category_reference, category_id):\n\tresults = get_results(category_reference)\n\tfor result in results: \n\t\tparticipant_id = get_participant(result)\n\n\t\tdb_result_check = db.session.query(Result).filter(\n\t\t\t(Result.position==result['overall_pos']) &\n\t\t\t(Result.gender_position==result['gender_pos']) & \n\t\t\t(Result.time==result['time_taken_seconds']) & \n\t\t\t(Result.category_id==category_id)).first()\n\t\tif not db_result_check:\n\t\t\tdb_category_result = Result(result['overall_pos'], participant_id,\n\t\t\tresult['gender_pos'], result['time_taken_seconds'], None, None, category_id)\n\t\t\tdb.session.add(db_category_result)\n\t\t\tdb.session.commit()\n\ndef get_participant(result):\n\tif result['date_of_birth']:\n\t\tbirth_date = datetime.strptime(result['date_of_birth'], '%Y-%m-%d').date()\n\telse:\n\t\tbirth_date = None\n\tdb_participant_check = db.session.query(Participant).filter(\n\t\t(Participant.first_name==result['first_name']) &\n\t\t(Participant.last_name==result['last_name']) & \n\t\t(Participant.sex==result['person_sex']) & \n\t\t(Participant.birth_date==birth_date))\n\tif not (db.session.query(db_participant_check.exists()).scalar()):\n\t\tdb_participant = Participant(result['first_name'], result['last_name'],\n\t\tresult['person_sex'], birth_date)\n\t\tdb.session.add(db_participant)\n\t\tdb.session.commit()\n\t\treturn db_participant.id\n\telse: \n\t\treturn db_participant_check.first().id\n\n\n\n",
"step-ids": [
8,
9,
10,
11,
12
]
}
|
[
8,
9,
10,
11,
12
] |
import pandas as pd
from bokeh.models import ColumnDataSource, LinearColorMapper, HoverTool
from bokeh.plotting import figure
from bokeh.transform import transform
from sklearn.metrics import confusion_matrix
from reporter.settings import COLORS
from reporter.metrics import Metric
class ConfusionMatrix(Metric):
def __init__(self):
super().__init__('confusion-matrix')
def generate_data(self):
matrix = confusion_matrix(self.y, self.y_pred)
matrix = pd.DataFrame(matrix, index=self.labels, columns=self.labels)
matrix.index.name = 'Predicted'
matrix.columns.name = 'Actual'
return pd.DataFrame(matrix.stack(), columns=['Value']).reset_index()
def draw(self, size=400):
index_label = 'Predicted'
column_label = 'Actual'
matrix = self.generate_data()
min_val, max_val = matrix.Value.min(), matrix.Value.max()
source = ColumnDataSource(matrix)
mapper = LinearColorMapper(palette=COLORS, low=min_val, high=max_val)
hover = HoverTool(tooltips=[
('Number', f"@Value")
])
p = figure(plot_width=size,
plot_height=size,
title='Confusion Matrix',
tools=[hover],
toolbar_location=None,
x_range=self.labels,
y_range=list(reversed(self.labels)))
p.yaxis.axis_label = index_label
p.xaxis.axis_label = column_label
p.rect(x=column_label,
y=index_label,
width=1,
height=1,
source=source,
fill_color=transform('Value', mapper))
self.plot = p
return p
|
normal
|
{
"blob_id": "9a2002b5ff0fe41f2b5b568f4c278d4376bf4fb1",
"index": 6117,
"step-1": "<mask token>\n\n\nclass ConfusionMatrix(Metric):\n <mask token>\n <mask token>\n\n def draw(self, size=400):\n index_label = 'Predicted'\n column_label = 'Actual'\n matrix = self.generate_data()\n min_val, max_val = matrix.Value.min(), matrix.Value.max()\n source = ColumnDataSource(matrix)\n mapper = LinearColorMapper(palette=COLORS, low=min_val, high=max_val)\n hover = HoverTool(tooltips=[('Number', f'@Value')])\n p = figure(plot_width=size, plot_height=size, title=\n 'Confusion Matrix', tools=[hover], toolbar_location=None,\n x_range=self.labels, y_range=list(reversed(self.labels)))\n p.yaxis.axis_label = index_label\n p.xaxis.axis_label = column_label\n p.rect(x=column_label, y=index_label, width=1, height=1, source=\n source, fill_color=transform('Value', mapper))\n self.plot = p\n return p\n",
"step-2": "<mask token>\n\n\nclass ConfusionMatrix(Metric):\n <mask token>\n\n def generate_data(self):\n matrix = confusion_matrix(self.y, self.y_pred)\n matrix = pd.DataFrame(matrix, index=self.labels, columns=self.labels)\n matrix.index.name = 'Predicted'\n matrix.columns.name = 'Actual'\n return pd.DataFrame(matrix.stack(), columns=['Value']).reset_index()\n\n def draw(self, size=400):\n index_label = 'Predicted'\n column_label = 'Actual'\n matrix = self.generate_data()\n min_val, max_val = matrix.Value.min(), matrix.Value.max()\n source = ColumnDataSource(matrix)\n mapper = LinearColorMapper(palette=COLORS, low=min_val, high=max_val)\n hover = HoverTool(tooltips=[('Number', f'@Value')])\n p = figure(plot_width=size, plot_height=size, title=\n 'Confusion Matrix', tools=[hover], toolbar_location=None,\n x_range=self.labels, y_range=list(reversed(self.labels)))\n p.yaxis.axis_label = index_label\n p.xaxis.axis_label = column_label\n p.rect(x=column_label, y=index_label, width=1, height=1, source=\n source, fill_color=transform('Value', mapper))\n self.plot = p\n return p\n",
"step-3": "<mask token>\n\n\nclass ConfusionMatrix(Metric):\n\n def __init__(self):\n super().__init__('confusion-matrix')\n\n def generate_data(self):\n matrix = confusion_matrix(self.y, self.y_pred)\n matrix = pd.DataFrame(matrix, index=self.labels, columns=self.labels)\n matrix.index.name = 'Predicted'\n matrix.columns.name = 'Actual'\n return pd.DataFrame(matrix.stack(), columns=['Value']).reset_index()\n\n def draw(self, size=400):\n index_label = 'Predicted'\n column_label = 'Actual'\n matrix = self.generate_data()\n min_val, max_val = matrix.Value.min(), matrix.Value.max()\n source = ColumnDataSource(matrix)\n mapper = LinearColorMapper(palette=COLORS, low=min_val, high=max_val)\n hover = HoverTool(tooltips=[('Number', f'@Value')])\n p = figure(plot_width=size, plot_height=size, title=\n 'Confusion Matrix', tools=[hover], toolbar_location=None,\n x_range=self.labels, y_range=list(reversed(self.labels)))\n p.yaxis.axis_label = index_label\n p.xaxis.axis_label = column_label\n p.rect(x=column_label, y=index_label, width=1, height=1, source=\n source, fill_color=transform('Value', mapper))\n self.plot = p\n return p\n",
"step-4": "import pandas as pd\nfrom bokeh.models import ColumnDataSource, LinearColorMapper, HoverTool\nfrom bokeh.plotting import figure\nfrom bokeh.transform import transform\nfrom sklearn.metrics import confusion_matrix\nfrom reporter.settings import COLORS\nfrom reporter.metrics import Metric\n\n\nclass ConfusionMatrix(Metric):\n\n def __init__(self):\n super().__init__('confusion-matrix')\n\n def generate_data(self):\n matrix = confusion_matrix(self.y, self.y_pred)\n matrix = pd.DataFrame(matrix, index=self.labels, columns=self.labels)\n matrix.index.name = 'Predicted'\n matrix.columns.name = 'Actual'\n return pd.DataFrame(matrix.stack(), columns=['Value']).reset_index()\n\n def draw(self, size=400):\n index_label = 'Predicted'\n column_label = 'Actual'\n matrix = self.generate_data()\n min_val, max_val = matrix.Value.min(), matrix.Value.max()\n source = ColumnDataSource(matrix)\n mapper = LinearColorMapper(palette=COLORS, low=min_val, high=max_val)\n hover = HoverTool(tooltips=[('Number', f'@Value')])\n p = figure(plot_width=size, plot_height=size, title=\n 'Confusion Matrix', tools=[hover], toolbar_location=None,\n x_range=self.labels, y_range=list(reversed(self.labels)))\n p.yaxis.axis_label = index_label\n p.xaxis.axis_label = column_label\n p.rect(x=column_label, y=index_label, width=1, height=1, source=\n source, fill_color=transform('Value', mapper))\n self.plot = p\n return p\n",
"step-5": "import pandas as pd\nfrom bokeh.models import ColumnDataSource, LinearColorMapper, HoverTool\nfrom bokeh.plotting import figure\nfrom bokeh.transform import transform\nfrom sklearn.metrics import confusion_matrix\nfrom reporter.settings import COLORS\nfrom reporter.metrics import Metric\n\n\nclass ConfusionMatrix(Metric):\n def __init__(self):\n super().__init__('confusion-matrix')\n\n def generate_data(self):\n matrix = confusion_matrix(self.y, self.y_pred)\n matrix = pd.DataFrame(matrix, index=self.labels, columns=self.labels)\n matrix.index.name = 'Predicted'\n matrix.columns.name = 'Actual'\n return pd.DataFrame(matrix.stack(), columns=['Value']).reset_index()\n\n def draw(self, size=400):\n index_label = 'Predicted'\n column_label = 'Actual'\n\n matrix = self.generate_data()\n min_val, max_val = matrix.Value.min(), matrix.Value.max()\n source = ColumnDataSource(matrix)\n mapper = LinearColorMapper(palette=COLORS, low=min_val, high=max_val)\n\n hover = HoverTool(tooltips=[\n ('Number', f\"@Value\")\n ])\n\n p = figure(plot_width=size,\n plot_height=size,\n title='Confusion Matrix',\n tools=[hover],\n toolbar_location=None,\n x_range=self.labels,\n y_range=list(reversed(self.labels)))\n\n p.yaxis.axis_label = index_label\n p.xaxis.axis_label = column_label\n\n p.rect(x=column_label,\n y=index_label,\n width=1,\n height=1,\n source=source,\n fill_color=transform('Value', mapper))\n self.plot = p\n return p\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.