api-misuse/the-stack-python_api-10k-new · Datasets at Fast360
{
// 获取包含Hugging Face文本的span元素
const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap');
spans.forEach(span => {
if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) {
span.textContent = 'AI快站';
}
});
});
// 替换logo图片的alt属性
document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => {
if (img.alt.match(/Hugging\s*Face/i)) {
img.alt = 'AI快站 logo';
}
});
}
// 替换导航栏中的链接
function replaceNavigationLinks() {
// 已替换标记,防止重复运行
if (window._navLinksReplaced) {
return;
}
// 已经替换过的链接集合,防止重复替换
const replacedLinks = new Set();
// 只在导航栏区域查找和替换链接
const headerArea = document.querySelector('header') || document.querySelector('nav');
if (!headerArea) {
return;
}
// 在导航区域内查找链接
const navLinks = headerArea.querySelectorAll('a');
navLinks.forEach(link => {
// 如果已经替换过,跳过
if (replacedLinks.has(link)) return;
const linkText = link.textContent.trim();
const linkHref = link.getAttribute('href') || '';
// 替换Spaces链接 - 仅替换一次
if (
(linkHref.includes('/spaces') || linkHref === '/spaces' ||
linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) &&
linkText !== 'OCR模型免费转Markdown' &&
linkText !== 'OCR模型免费转Markdown'
) {
link.textContent = 'OCR模型免费转Markdown';
link.href = 'https://fast360.xyz';
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
replacedLinks.add(link);
}
// 删除Posts链接
else if (
(linkHref.includes('/posts') || linkHref === '/posts' ||
linkText === 'Posts' || linkText.match(/^s*Postss*$/i))
) {
if (link.parentNode) {
link.parentNode.removeChild(link);
}
replacedLinks.add(link);
}
// 替换Docs链接 - 仅替换一次
else if (
(linkHref.includes('/docs') || linkHref === '/docs' ||
linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) &&
linkText !== '模型下载攻略'
) {
link.textContent = '模型下载攻略';
link.href = '/';
replacedLinks.add(link);
}
// 删除Enterprise链接
else if (
(linkHref.includes('/enterprise') || linkHref === '/enterprise' ||
linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i))
) {
if (link.parentNode) {
link.parentNode.removeChild(link);
}
replacedLinks.add(link);
}
});
// 查找可能嵌套的Spaces和Posts文本
const textNodes = [];
function findTextNodes(element) {
if (element.nodeType === Node.TEXT_NODE) {
const text = element.textContent.trim();
if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') {
textNodes.push(element);
}
} else {
for (const child of element.childNodes) {
findTextNodes(child);
}
}
}
// 只在导航区域内查找文本节点
findTextNodes(headerArea);
// 替换找到的文本节点
textNodes.forEach(node => {
const text = node.textContent.trim();
if (text === 'Spaces') {
node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown');
} else if (text === 'Posts') {
// 删除Posts文本节点
if (node.parentNode) {
node.parentNode.removeChild(node);
}
} else if (text === 'Enterprise') {
// 删除Enterprise文本节点
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
});
// 标记已替换完成
window._navLinksReplaced = true;
}
// 替换代码区域中的域名
function replaceCodeDomains() {
// 特别处理span.hljs-string和span.njs-string元素
document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => {
if (span.textContent && span.textContent.includes('huggingface.co')) {
span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com');
}
});
// 替换hljs-string类的span中的域名(移除多余的转义符号)
document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => {
if (span.textContent && span.textContent.includes('huggingface.co')) {
span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com');
}
});
// 替换pre和code标签中包含git clone命令的域名
document.querySelectorAll('pre, code').forEach(element => {
if (element.textContent && element.textContent.includes('git clone')) {
const text = element.innerHTML;
if (text.includes('huggingface.co')) {
element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com');
}
}
});
// 处理特定的命令行示例
document.querySelectorAll('pre, code').forEach(element => {
const text = element.innerHTML;
if (text.includes('huggingface.co')) {
// 针对git clone命令的专门处理
if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) {
element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com');
}
}
});
// 特别处理模型下载页面上的代码片段
document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => {
const content = container.innerHTML;
if (content && content.includes('huggingface.co')) {
container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com');
}
});
// 特别处理模型仓库克隆对话框中的代码片段
try {
// 查找包含"Clone this model repository"标题的对话框
const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]');
if (cloneDialog) {
// 查找对话框中所有的代码片段和命令示例
const codeElements = cloneDialog.querySelectorAll('pre, code, span');
codeElements.forEach(element => {
if (element.textContent && element.textContent.includes('huggingface.co')) {
if (element.innerHTML.includes('huggingface.co')) {
element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com');
} else {
element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com');
}
}
});
}
// 更精确地定位克隆命令中的域名
document.querySelectorAll('[data-target]').forEach(container => {
const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string');
codeBlocks.forEach(block => {
if (block.textContent && block.textContent.includes('huggingface.co')) {
if (block.innerHTML.includes('huggingface.co')) {
block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com');
} else {
block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com');
}
}
});
});
} catch (e) {
// 错误处理但不打印日志
}
}
// 当DOM加载完成后执行替换
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
replaceHeaderBranding();
replaceNavigationLinks();
replaceCodeDomains();
// 只在必要时执行替换 - 3秒后再次检查
setTimeout(() => {
if (!window._navLinksReplaced) {
console.log('[Client] 3秒后重新检查导航链接');
replaceNavigationLinks();
}
}, 3000);
});
} else {
replaceHeaderBranding();
replaceNavigationLinks();
replaceCodeDomains();
// 只在必要时执行替换 - 3秒后再次检查
setTimeout(() => {
if (!window._navLinksReplaced) {
console.log('[Client] 3秒后重新检查导航链接');
replaceNavigationLinks();
}
}, 3000);
}
// 增加一个MutationObserver来处理可能的动态元素加载
const observer = new MutationObserver(mutations => {
// 检查是否导航区域有变化
const hasNavChanges = mutations.some(mutation => {
// 检查是否存在header或nav元素变化
return Array.from(mutation.addedNodes).some(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
// 检查是否是导航元素或其子元素
if (node.tagName === 'HEADER' || node.tagName === 'NAV' ||
node.querySelector('header, nav')) {
return true;
}
// 检查是否在导航元素内部
let parent = node.parentElement;
while (parent) {
if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') {
return true;
}
parent = parent.parentElement;
}
}
return false;
});
});
// 只在导航区域有变化时执行替换
if (hasNavChanges) {
// 重置替换状态,允许再次替换
window._navLinksReplaced = false;
replaceHeaderBranding();
replaceNavigationLinks();
}
});
// 开始观察document.body的变化,包括子节点
if (document.body) {
observer.observe(document.body, { childList: true, subtree: true });
} else {
document.addEventListener('DOMContentLoaded', () => {
observer.observe(document.body, { childList: true, subtree: true });
});
}
})();
\n\t\t\t\t\n \n \n \n\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n\n\n\"\"\"\n\nmodel = load_model_from_xml(xml)\n\nsim = MjSim(model)\nviewer = MujocoPyRenderer(sim)\n\n\nsim.reset()\n # After reset jacobians are all zeros\nsim.forward()\ntarget_jacp = np.zeros(3 * sim.model.nv)\ntarget_jacr= np.zeros(3 * sim.model.nv)\n\n\n\nF=np.array([0,0,-9.81*1e-2,0,0,0]).T\n\n#np.testing.assert_allclose(target_jacp, np.zeros(3 * sim.model.nv))\n # After first forward, jacobians are real\n#sim.forward()\nK_diag=2000\nC_diag=100\n\nA_diag=1e-3\n\nK=np.identity(3)*K_diag\nC=np.identity(3)*C_diag\nA=np.identity(3)*A_diag\n\n#K_diag=0.3\n#C_diag=0.05\n\n\nfor i in range(3):\n K[i, i]=K_diag\n C[i,i]=C_diag\n A[i, i] = A_diag\n\n\nx_intial=sim.data.site_xpos[1]\nprint(x_intial)\nx_desired=np.array([0,1,0.3])\n\nv_intial=sim.data.site_xvelp[1]\nv_desired=np.array([0,0,0])\n\na_desired=np.array([0,0,0])\na_intial=np.array([0,0,0])\n\n\ndt=sim.model.opt.timestep\n#sim.data.get_site_jacp('target', jacp=target_jacp)\n # Should be unchanged after steps (zero action)\ngraph=[]\nfor _ in range(100000):\n F[:3]=np.dot(K,x_desired-x_intial)+np.dot(C,v_desired-v_intial)+np.dot(A,a_desired-a_intial)\n H = np.zeros(sim.model.nv* sim.model.nv)\n functions.mj_fullM(sim.model, H, sim.data.qM)\n\n sim.data.get_site_jacp('target', jacp=target_jacp)\n sim.data.get_site_jacr('target', jacr=target_jacr)\n J_L = target_jacp.reshape((3, sim.model.nv))\n J_A = target_jacr.reshape((3, sim.model.nv))\n J = np.concatenate((J_L, J_A), axis=0)\n H_L =np.dot(np.linalg.pinv(J_L.T),np.dot(H.reshape(sim.model.nv, sim.model.nv), np.linalg.pinv(J_L)))\n H_all=np.dot(np.linalg.pinv(J.T),np.dot(H.reshape(sim.model.nv, sim.model.nv), np.linalg.pinv(J)))\n #F_a=np.dot(A,0.3-sim.data.qacc)\n #action = np.dot(J_L.T, np.dot(H_L, F[:3]))+sim.data.qfrc_bias\n action = sim.data.qfrc_bias+np.dot(H.reshape(3,3),np.dot(J_L.T,F[:3]))\n #print(action)\n #action = np.dot(J.T, F)\n sim.data.ctrl[:] = action\n sim.step()\n sim.forward()\n #print(np.max(action))\n #print(sim.data.qacc)\n viewer.render()\n x_intial = sim.data.site_xpos[1]\n a_intial=(v_intial-sim.data.site_xvelp[1])/dt\n print(a_intial)\n v_intial = sim.data.site_xvelp[1]\n normal=np.linalg.norm(x_intial-x_desired)\n #print(normal)\n if normal<0.1:\n print(\"in\")\n if x_desired[0]==0:\n x_desired = np.array([-1, 0, 0.5])\n elif x_desired[0]==1:\n x_desired = np.array([0, 1, 0.3])\n elif x_desired[0] == -1:\n x_desired = np.array([1, 0, 0.5])\n\n\n graph.append(np.abs(x_intial-x_desired))\n # sim.forward()\n\n\nprint(\"the desired is {} and the intial is{}\".format(x_desired,x_intial))\nplt.plot(graph)\nplt.show()"},"apis":{"kind":"string","value":"[((2031, 2055), 'mujoco_py.load_model_from_xml', 'load_model_from_xml', (['xml'], {}), '(xml)\\n', (2050, 2055), False, 'from mujoco_py import MjSim, load_model_from_xml, functions, load_model_from_path, MjSimState, ignore_mujoco_warnings, load_model_from_mjb\\n'), ((2063, 2075), 'mujoco_py.MjSim', 'MjSim', (['model'], {}), '(model)\\n', (2068, 2075), False, 'from mujoco_py import MjSim, load_model_from_xml, functions, load_model_from_path, MjSimState, ignore_mujoco_warnings, load_model_from_mjb\\n'), ((2085, 2106), 'mujoco_py_renderer.MujocoPyRenderer', 'MujocoPyRenderer', (['sim'], {}), '(sim)\\n', (2101, 2106), False, 'from mujoco_py_renderer import SimulationError, XMLError, MujocoPyRenderer\\n'), ((2191, 2217), 'numpy.zeros', 'np.zeros', (['(3 * sim.model.nv)'], {}), '(3 * sim.model.nv)\\n', (2199, 2217), True, 'import numpy as np\\n'), ((2231, 2257), 'numpy.zeros', 'np.zeros', (['(3 * sim.model.nv)'], {}), '(3 * sim.model.nv)\\n', (2239, 2257), True, 'import numpy as np\\n'), ((2702, 2723), 'numpy.array', 'np.array', (['[0, 1, 0.3]'], {}), '([0, 1, 0.3])\\n', (2710, 2723), True, 'import numpy as np\\n'), ((2765, 2784), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\\n', (2773, 2784), True, 'import numpy as np\\n'), ((2794, 2813), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\\n', (2802, 2813), True, 'import numpy as np\\n'), ((2821, 2840), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\\n', (2829, 2840), True, 'import numpy as np\\n'), ((4642, 4657), 'matplotlib.pyplot.plot', 'plt.plot', (['graph'], {}), '(graph)\\n', (4650, 4657), True, 'from matplotlib import pyplot as plt\\n'), ((4658, 4668), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\\n', (4666, 4668), True, 'from matplotlib import pyplot as plt\\n'), ((2263, 2302), 'numpy.array', 'np.array', (['[0, 0, -9.81 * 0.01, 0, 0, 0]'], {}), '([0, 0, -9.81 * 0.01, 0, 0, 0])\\n', (2271, 2302), True, 'import numpy as np\\n'), ((2468, 2482), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\\n', (2479, 2482), True, 'import numpy as np\\n'), ((2492, 2506), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\\n', (2503, 2506), True, 'import numpy as np\\n'), ((2516, 2530), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\\n', (2527, 2530), True, 'import numpy as np\\n'), ((3109, 3146), 'numpy.zeros', 'np.zeros', (['(sim.model.nv * sim.model.nv)'], {}), '(sim.model.nv * sim.model.nv)\\n', (3117, 3146), True, 'import numpy as np\\n'), ((3150, 3195), 'mujoco_py.functions.mj_fullM', 'functions.mj_fullM', (['sim.model', 'H', 'sim.data.qM'], {}), '(sim.model, H, sim.data.qM)\\n', (3168, 3195), False, 'from mujoco_py import MjSim, load_model_from_xml, functions, load_model_from_path, MjSimState, ignore_mujoco_warnings, load_model_from_mjb\\n'), ((3413, 3447), 'numpy.concatenate', 'np.concatenate', (['(J_L, J_A)'], {'axis': '(0)'}), '((J_L, J_A), axis=0)\\n', (3427, 3447), True, 'import numpy as np\\n'), ((4177, 4213), 'numpy.linalg.norm', 'np.linalg.norm', (['(x_intial - x_desired)'], {}), '(x_intial - x_desired)\\n', (4191, 4213), True, 'import numpy as np\\n'), ((3072, 3103), 'numpy.dot', 'np.dot', (['A', '(a_desired - a_intial)'], {}), '(A, a_desired - a_intial)\\n', (3078, 3103), True, 'import numpy as np\\n'), ((3464, 3485), 'numpy.linalg.pinv', 'np.linalg.pinv', (['J_L.T'], {}), '(J_L.T)\\n', (3478, 3485), True, 'import numpy as np\\n'), ((3571, 3590), 'numpy.linalg.pinv', 'np.linalg.pinv', (['J.T'], {}), '(J.T)\\n', (3585, 3590), True, 'import numpy as np\\n'), ((4519, 4547), 'numpy.abs', 'np.abs', (['(x_intial - x_desired)'], {}), '(x_intial - x_desired)\\n', (4525, 4547), True, 'import numpy as np\\n'), ((3014, 3045), 'numpy.dot', 'np.dot', (['K', '(x_desired - x_intial)'], {}), '(K, x_desired - x_intial)\\n', (3020, 3045), True, 'import numpy as np\\n'), ((3043, 3074), 'numpy.dot', 'np.dot', (['C', '(v_desired - v_intial)'], {}), '(C, v_desired - v_intial)\\n', (3049, 3074), True, 'import numpy as np\\n'), ((3532, 3551), 'numpy.linalg.pinv', 'np.linalg.pinv', (['J_L'], {}), '(J_L)\\n', (3546, 3551), True, 'import numpy as np\\n'), ((3637, 3654), 'numpy.linalg.pinv', 'np.linalg.pinv', (['J'], {}), '(J)\\n', (3651, 3654), True, 'import numpy as np\\n'), ((3815, 3835), 'numpy.dot', 'np.dot', (['J_L.T', 'F[:3]'], {}), '(J_L.T, F[:3])\\n', (3821, 3835), True, 'import numpy as np\\n'), ((4322, 4344), 'numpy.array', 'np.array', (['[-1, 0, 0.5]'], {}), '([-1, 0, 0.5])\\n', (4330, 4344), True, 'import numpy as np\\n'), ((4399, 4420), 'numpy.array', 'np.array', (['[0, 1, 0.3]'], {}), '([0, 1, 0.3])\\n', (4407, 4420), True, 'import numpy as np\\n'), ((4478, 4499), 'numpy.array', 'np.array', (['[1, 0, 0.5]'], {}), '([1, 0, 0.5])\\n', (4486, 4499), True, 'import numpy as np\\n')]"}}},{"rowIdx":8401,"cells":{"repo_name":{"kind":"string","value":"seveirbian/gear-old"},"repo_path":{"kind":"string","value":"evaluation/wordpress/pull_docker_images_from_private_registry.py"},"repo_head_hexsha":{"kind":"string","value":"8d3529a9bf42e652a9d7475c9d14e9a6afc69a76"},"content":{"kind":"string","value":"import sys\n# package need to be installed, pip install docker\nimport docker \nimport time\nimport yaml\nimport os\nimport xlwt\n\nauto = False\n\nprivate_registry = \"202.114.10.146:9999/\"\n\n# result\nresult = [[\"tag\", \"finishTime\", \"size\", \"data\"], ]\n\nclass Puller:\n\n def __init__(self, images): \n self.images_to_pull = images\n\n def check(self):\n # detect whether the file exists, if true, delete it\n if os.path.exists(\"./images_pulled.txt\"):\n os.remove(\"./images_pulled.txt\")\n \n def pull(self):\n self.check()\n\n client = docker.from_env()\n # if don't give a tag, then all image under this registry will be pulled\n repos = self.images_to_pull[0][\"repo\"]\n\n for repo in repos:\n tags = self.images_to_pull[1][repo]\n for tag in tags:\n print \"start pulling: \", private_registry+repo, \":\", tag\n\n # get present time\n startTime = time.time()\n\n # get present net data\n cnetdata = get_net_data()\n\n # pull images\n try:\n image_pulled = client.images.pull(repository=private_registry+repo, tag=str(tag))\n\n # print pull time\n finishTime = time.time() - startTime\n\n print \"finished in \" , finishTime, \"s\"\n\n # get image's size\n size = image_pulled.attrs[u'Size'] / 1000000.0\n print \"image size: \", size\n\n data = get_net_data() - cnetdata\n\n print \"pull data: \", data\n\n print \"\\n\"\n\n # record the image and its pulling time\n result.append([tag, finishTime, size, data])\n\n except docker.errors.NotFound:\n print private_registry+repo + \" not found...\\n\\n\"\n except docker.errors.ImageNotFound:\n print private_registry+repo + \" image not fount...\\n\\n\"\n\n if auto != True: \n raw_input(\"Next?\")\n\nclass Generator:\n \n def __init__(self, profilePath=\"\"):\n self.profilePath = profilePath\n \n def generateFromProfile(self):\n if self.profilePath == \"\":\n print \"Error: profile path is null\"\n \n with open(self.profilePath, 'r') as f:\n self.images = yaml.load(f, Loader=yaml.FullLoader)\n\n return self.images\n\ndef get_net_data():\n netCard = \"/proc/net/dev\"\n fd = open(netCard, \"r\")\n\n for line in fd.readlines():\n if line.find(\"enp0s3\") >= 0:\n field = line.split()\n data = float(field[1]) / 1024.0 / 1024.0\n\n fd.close()\n return data\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) == 2:\n auto = True\n\n generator = Generator(os.path.split(os.path.realpath(__file__))[0]+\"/image_versions.yaml\")\n\n images = generator.generateFromProfile()\n\n puller = Puller(images)\n\n puller.pull()\n\n # create a workbook sheet\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet(\"run_time\")\n\n for row in range(len(result)):\n for column in range(len(result[row])):\n sheet.write(row, column, result[row][column])\n\n workbook.save(os.path.split(os.path.realpath(__file__))[0]+\"/pull.xls\")"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8402,"cells":{"repo_name":{"kind":"string","value":"sibeshkar/jiminy"},"repo_path":{"kind":"string","value":"jiminy/envs/vnc_wog.py"},"repo_head_hexsha":{"kind":"string","value":"7754f86fb0f246e7d039ea0cbfd9950fcae4adfb"},"content":{"kind":"string","value":"from jiminy.envs import vnc_env\nfrom jiminy.spaces import VNCActionSpace\n\n\nclass WorldOfGooEnv(vnc_env.VNCEnv):\n def __init__(self):\n super(WorldOfGooEnv, self).__init__()\n # TODO: set action space screen shape to match\n # HACK: empty keys list fails for some weird reason, give it an 'a'\n self.action_space = VNCActionSpace(keys=['a'], buttonmasks=[1])\n"},"apis":{"kind":"string","value":"[((341, 384), 'jiminy.spaces.VNCActionSpace', 'VNCActionSpace', ([], {'keys': \"['a']\", 'buttonmasks': '[1]'}), \"(keys=['a'], buttonmasks=[1])\\n\", (355, 384), False, 'from jiminy.spaces import VNCActionSpace\\n')]"}}},{"rowIdx":8403,"cells":{"repo_name":{"kind":"string","value":"arj119/FedML"},"repo_path":{"kind":"string","value":"fedml_api/standalone/federated_sgan/fedssgan_api.py"},"repo_head_hexsha":{"kind":"string","value":"5b7c098659f3e61f9e44583965300d8d0829f7a8"},"content":{"kind":"string","value":"import copy\nimport logging\nimport random\nfrom typing import List, Tuple\n\nimport numpy as np\nimport torch\nimport wandb\nfrom torch.utils.data import ConcatDataset\n\nfrom fedml_api.standalone.fedavg.my_model_trainer import MyModelTrainer\nfrom fedml_api.standalone.federated_sgan.ac_gan_model_trainer import ACGANModelTrainer\nfrom fedml_api.standalone.federated_sgan.client import FedSSGANClient\nfrom fedml_api.standalone.federated_sgan.model_trainer import FedSSGANModelTrainer\nfrom fedml_api.standalone.utils.HeterogeneousModelBaseTrainerAPI import HeterogeneousModelBaseTrainerAPI\n\n\nclass FedSSGANAPI(HeterogeneousModelBaseTrainerAPI):\n def __init__(self, dataset, device, args, adapter_model, client_models: List[Tuple[torch.nn.Module, int]]):\n \"\"\"\n Args:\n dataset: Dataset presplit into data loaders\n device: Device to run training on\n args: Additional args\n client_models: List of client models and their frequency participating (assuming a stateful algorithm for simplicity)\n \"\"\"\n super().__init__(dataset, device, args)\n\n self.global_model = MyModelTrainer(adapter_model)\n\n self._setup_clients(self.train_data_local_num_dict, self.train_data_local_dict, self.test_data_local_dict,\n client_models)\n\n self._plot_client_training_data_distribution()\n\n def _setup_clients(self, train_data_local_num_dict, train_data_local_dict, test_data_local_dict,\n client_models):\n logging.info(\"############setup_clients (START)#############\")\n\n c_idx = 0\n for local_model, freq in client_models:\n for i in range(freq):\n model_trainer = ACGANModelTrainer(\n copy.deepcopy(self.global_model.model),\n copy.deepcopy(local_model)\n )\n c = FedSSGANClient(c_idx, train_data_local_dict[c_idx], test_data_local_dict[c_idx],\n train_data_local_num_dict[c_idx], self.test_global, self.args, self.device,\n model_trainer)\n c_idx += 1\n self.client_list.append(c)\n\n logging.info(\"############setup_clients (END)#############\")\n\n def train(self):\n logging.info('\\n###############Pre-Training clients#############\\n')\n for i, c in enumerate(self.client_list):\n logging.info(f'Pre=training client: {i}')\n c.pre_train()\n logging.info('###############Pre-Training clients (END)###########\\n')\n\n unlabelled_synthesised_data = None\n w_global = self.global_model.get_model_params()\n for round_idx in range(self.args.comm_round):\n\n logging.info(\"################Communication round : {}\".format(round_idx))\n\n w_locals = []\n synthesised_data_locals = []\n client_synthesised_data_lens = {'round': round_idx}\n\n client: FedSSGANClient\n for idx, client in enumerate(self.client_list):\n # Update client synthetic datasets\n # client.set_synthetic_dataset(unlabelled_synthesised_data)\n\n # Local round\n w = client.train(copy.deepcopy(w_global), round_idx)\n # self.logger.info(\"local weights = \" + str(w))\n w_locals.append((client.get_sample_number(), copy.deepcopy(w)))\n\n # synthetic_data = client.generate_synthetic_dataset()\n # if synthetic_data is not None:\n # synthesised_data_locals.append(synthetic_data)\n # client_synthesised_data_lens[f'Client_{idx}: Synthetic Dataset Size'] = len(synthetic_data)\n # else:\n # client_synthesised_data_lens[f'Client_{idx}: Synthetic Dataset Size'] = 0\n #\n # if len(synthesised_data_locals) > 0:\n # unlabelled_synthesised_data = ConcatDataset(synthesised_data_locals)\n # logging.info(f'\\n Synthetic Unlabelled Dataset Size: {len(unlabelled_synthesised_data)}\\n')\n # client_synthesised_data_lens['Total Synthetic Dataset Size'] = len(unlabelled_synthesised_data)\n # else:\n # unlabelled_synthesised_data = None\n # client_synthesised_data_lens['Total Synthetic Dataset Size'] = 0\n\n # wandb.log(client_synthesised_data_lens)\n\n # update global weights\n w_global = self._aggregate(w_locals)\n self.global_model.set_model_params(w_global)\n\n # test results\n # at last round\n if round_idx == self.args.comm_round - 1:\n self._local_test_on_all_clients(round_idx)\n # per {frequency_of_the_test} round\n elif round_idx % self.args.frequency_of_the_test == 0:\n if self.args.dataset.startswith(\"stackoverflow\"):\n self._local_test_on_validation_set(round_idx)\n else:\n self._local_test_on_all_clients(round_idx)\n"},"apis":{"kind":"string","value":"[((1127, 1156), 'fedml_api.standalone.fedavg.my_model_trainer.MyModelTrainer', 'MyModelTrainer', (['adapter_model'], {}), '(adapter_model)\\n', (1141, 1156), False, 'from fedml_api.standalone.fedavg.my_model_trainer import MyModelTrainer\\n'), ((1521, 1583), 'logging.info', 'logging.info', (['\"\"\"############setup_clients (START)#############\"\"\"'], {}), \"('############setup_clients (START)#############')\\n\", (1533, 1583), False, 'import logging\\n'), ((2202, 2262), 'logging.info', 'logging.info', (['\"\"\"############setup_clients (END)#############\"\"\"'], {}), \"('############setup_clients (END)#############')\\n\", (2214, 2262), False, 'import logging\\n'), ((2293, 2363), 'logging.info', 'logging.info', (['\"\"\"\\n###############Pre-Training clients#############\\n\"\"\"'], {}), '(\"\"\"\\n###############Pre-Training clients#############\\n\"\"\")\\n', (2305, 2363), False, 'import logging\\n'), ((2499, 2569), 'logging.info', 'logging.info', (['\"\"\"###############Pre-Training clients (END)###########\\n\"\"\"'], {}), \"('###############Pre-Training clients (END)###########\\\\n')\\n\", (2511, 2569), False, 'import logging\\n'), ((2423, 2464), 'logging.info', 'logging.info', (['f\"\"\"Pre=training client: {i}\"\"\"'], {}), \"(f'Pre=training client: {i}')\\n\", (2435, 2464), False, 'import logging\\n'), ((1881, 2061), 'fedml_api.standalone.federated_sgan.client.FedSSGANClient', 'FedSSGANClient', (['c_idx', 'train_data_local_dict[c_idx]', 'test_data_local_dict[c_idx]', 'train_data_local_num_dict[c_idx]', 'self.test_global', 'self.args', 'self.device', 'model_trainer'], {}), '(c_idx, train_data_local_dict[c_idx], test_data_local_dict[\\n c_idx], train_data_local_num_dict[c_idx], self.test_global, self.args,\\n self.device, model_trainer)\\n', (1895, 2061), False, 'from fedml_api.standalone.federated_sgan.client import FedSSGANClient\\n'), ((1756, 1794), 'copy.deepcopy', 'copy.deepcopy', (['self.global_model.model'], {}), '(self.global_model.model)\\n', (1769, 1794), False, 'import copy\\n'), ((1816, 1842), 'copy.deepcopy', 'copy.deepcopy', (['local_model'], {}), '(local_model)\\n', (1829, 1842), False, 'import copy\\n'), ((3231, 3254), 'copy.deepcopy', 'copy.deepcopy', (['w_global'], {}), '(w_global)\\n', (3244, 3254), False, 'import copy\\n'), ((3392, 3408), 'copy.deepcopy', 'copy.deepcopy', (['w'], {}), '(w)\\n', (3405, 3408), False, 'import copy\\n')]"}}},{"rowIdx":8404,"cells":{"repo_name":{"kind":"string","value":"arjun-sai-krishnan/tamil-morpho-embeddings"},"repo_path":{"kind":"string","value":"pytorch-word2vec-master/csv.py"},"repo_head_hexsha":{"kind":"string","value":"a33bcb427d635dba3b1857f26ea7ab287e1a44c5"},"content":{"kind":"string","value":"#!/usr/bin/env python3\n\nimport argparse\nfrom collections import Counter\nimport pdb\nimport pickle\nimport re\nimport sys\nimport time\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\nimport torch.multiprocessing as mp\n\nimport data_producer\n\nfrom multiprocessing import set_start_method\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--train\", type=str, default=\"\", help=\"training file\")\nparser.add_argument(\"--vocab\", type=str, default=\"\", help=\"vocab pickle file\")\nparser.add_argument(\"--save\", type=str, default=\"csv.pth.tar\", help=\"saved model filename\")\nparser.add_argument(\"--size\", type=int, default=300, help=\"word embedding dimension\")\nparser.add_argument(\"--window\", type=int, default=5, help=\"context window size\")\nparser.add_argument(\"--sample\", type=float, default=1e-5, help=\"subsample threshold\")\nparser.add_argument(\"--negative\", type=int, default=10, help=\"number of negative samples\")\nparser.add_argument(\"--delta\", type=float, default=0.15, help=\"create new sense for a type if similarity lower than this value.\")\nparser.add_argument(\"--min_count\", type=int, default=5, help=\"minimum frequency of a word\")\nparser.add_argument(\"--processes\", type=int, default=4, help=\"number of processes\")\nparser.add_argument(\"--num_workers\", type=int, default=6, help=\"number of workers for data processsing\")\nparser.add_argument(\"--iter\", type=int, default=3, help=\"number of iterations\")\nparser.add_argument(\"--lr\", type=float, default=-1.0, help=\"initial learning rate\")\nparser.add_argument(\"--batch_size\", type=int, default=100, help=\"(max) batch size\")\nparser.add_argument(\"--cuda\", action='store_true', default=False, help=\"enable cuda\")\nparser.add_argument(\"--multi_proto\", action='store_true', default=False, help=\"True: multi-prototype, False:single-prototype\")\n\nMAX_SENT_LEN = 1000\n\n# Build the vocabulary.\ndef file_split(f, delim=' \\t\\n', bufsize=1024):\n prev = ''\n while True:\n s = f.read(bufsize)\n if not s:\n break\n tokens = re.split('['+delim+']{1,}', s)\n if len(tokens) > 1:\n yield prev + tokens[0]\n prev = tokens[-1]\n for x in tokens[1:-1]:\n yield x\n else:\n prev += s\n if prev:\n yield prev\n\ndef build_vocab(args):\n vocab = Counter()\n word_count = 0\n for word in file_split(open(args.train)):\n vocab[word] += 1\n word_count += 1\n if word_count % 10000 == 0:\n sys.stdout.write('%d\\r' % len(vocab))\n freq = {k:v for k,v in vocab.items() if v >= args.min_count}\n word_count = sum([freq[k] for k in freq])\n word_list = sorted(freq, key=freq.get, reverse=True)\n word2idx = {}\n for i,w in enumerate(word_list):\n word2idx[w] = i\n\n print(\"Vocab size: %ld\" % len(word2idx))\n print(\"Words in train file: %ld\" % word_count)\n vars(args)['vocab_size'] = len(word2idx)\n vars(args)['train_words'] = word_count\n\n return word2idx, word_list, freq\n\n\nclass CSV(nn.Module):\n def __init__(self, args):\n super(CSV, self).__init__()\n self.global_embs = nn.Embedding(args.vocab_size+1, args.size, padding_idx=args.vocab_size, sparse=True)\n self.sense_embs = nn.Embedding(args.vocab_size*5, args.size, sparse=True)\n self.ctx_weight = torch.nn.Parameter(torch.ones(2*args.window, args.size))\n self.word2sense = [ [i] for i in range(args.vocab_size) ]\n '''\n word2sense = np.zeros((args.vocab_size, 5), dtype='int32') \n for i in range(args.vocab_size): \n word2sense[i, 0] = i\n self.word2sense = torch.nn.Parameter(torch.from_numpy(word2sense).int())\n self.word_sense_cnts = torch.nn.Parameter(torch.ones((args.vocab_size,)).int())\n '''\n\n self.global_embs.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n self.sense_embs.weight.data.uniform_(-0.5/args.size, 0.5/args.size)\n\n self.n_senses = args.vocab_size\n self.sense_capacity = args.vocab_size*5\n self.batch_size = args.batch_size\n self.size = args.size\n self.window = args.window\n self.negative = args.negative\n self.pad_idx = args.vocab_size\n\n def get_context_feats(self, ctx_type_indices):\n ctx_type_embs = self.global_embs(ctx_type_indices)\n return torch.sum(ctx_type_embs * self.ctx_weight, 1).cpu().data.numpy()\n\n def get_possible_sense_embs(self, type_indices, cuda=True):\n sense_indices = []\n sense2idx = {}\n for type_id in type_indices:\n for s_id in self.word2sense[type_id]:\n if s_id not in sense2idx:\n sense2idx[s_id] = len(sense_indices)\n sense_indices.append( s_id )\n sense_indices = np.array(sense_indices)\n\n if cuda:\n sense_embs = self.sense_embs(Variable(torch.LongTensor(sense_indices).cuda()))\n return sense2idx, sense_embs.cpu().data.numpy()\n else:\n sense_embs = self.sense_embs(Variable(torch.LongTensor(sense_indices)))\n return sense2idx, sense_embs.data.numpy()\n\n def forward(self, data):\n ctx_type_indices = data[:, 0:2*self.window]\n pos_sense_idx = data[:, 2*self.window+1]\n neg_sense_indices = data[:, 2*self.window+2:2*self.window+2+self.negative]\n neg_mask = data[:, 2*self.window+2+self.negative:].float()\n\n ctx_type_embs = self.global_embs(ctx_type_indices)\n pos_sense_embs = self.sense_embs(pos_sense_idx)\n neg_sense_embs = self.sense_embs(neg_sense_indices)\n\n ctx_feats = torch.sum(ctx_type_embs * self.ctx_weight, 1, keepdim=True)\n\n # Neg Log Likelihood\n pos_ips = torch.sum(ctx_feats[:,0,:] * pos_sense_embs, 1)\n pos_loss = torch.sum( -F.logsigmoid(torch.clamp(pos_ips,max=10,min=-10)))\n neg_ips = torch.bmm(neg_sense_embs, ctx_feats.permute(0,2,1))[:,:,0]\n neg_loss = torch.sum( -F.logsigmoid(torch.clamp(-neg_ips,max=10,min=-10)) * neg_mask )\n\n return pos_loss + neg_loss\n\n\n# Initialize model.\ndef init_net(args):\n if args.lr == -1.0:\n vars(args)['lr'] = 0.05\n return CSV(args)\n\ndef save_model(filename, model, args, word2idx):\n torch.save({\n 'word2idx':word2idx,\n 'args':args,\n #'word2sense': model.word2sense,\n 'n_senses': model.n_senses,\n 'params': model.state_dict()\n }, filename)\n\ndef load_model(filename):\n checkpoint = torch.load(filename)\n word2idx = checkpoint['word2idx']\n args = checkpoint['args']\n model = CSV(args)\n if args.cuda:\n model.cuda()\n\n model.global_embs.weight.data = checkpoint['params']['global_embs.weight']\n model.sense_embs.weight.data = checkpoint['params']['sense_embs.weight']\n model.ctx_weight.data = checkpoint['params']['ctx_weight']\n model.word2sense = checkpoint['word2sense']\n #model.word2sense.data = checkpoint['params']['word2sense'] \n #model.word_sense_cnts.data = checkpoint['params']['word_sense_cnts'] \n model.n_senses = checkpoint['n_senses']\n\n return model, word2idx\n\n# Training\ndef train_process_sent_producer(p_id, data_queue, word_count_actual, word_list, word2idx, freq, args):\n n_proc = 1 if args.stage == 2 else args.processes\n N = 1 if args.stage == 2 else args.iter\n neg = 0 if args.stage == 2 else args.negative\n\n if args.negative > 0:\n table_ptr_val = data_producer.init_unigram_table(word_list, freq, args.train_words)\n\n train_file = open(args.train)\n file_pos = args.file_size * p_id // n_proc\n train_file.seek(file_pos, 0)\n while True:\n try:\n train_file.read(1)\n except UnicodeDecodeError:\n file_pos -= 1\n train_file.seek(file_pos, 0)\n else:\n train_file.seek(file_pos, 0)\n break\n\n batch_count = 0\n batch_placeholder = np.zeros((args.batch_size, 2*args.window+2+2*neg), 'int64')\n\n for it in range(N):\n train_file.seek(file_pos, 0)\n\n last_word_cnt = 0\n word_cnt = 0\n sentence = []\n prev = ''\n eof = False\n while True:\n if eof or train_file.tell() > file_pos + args.file_size / n_proc:\n break\n\n while True:\n s = train_file.read(1)\n if not s:\n eof = True\n break\n elif s == ' ' or s == '\\t':\n if prev in word2idx:\n sentence.append(prev)\n prev = ''\n if len(sentence) >= MAX_SENT_LEN:\n break\n elif s == '\\n':\n if prev in word2idx:\n sentence.append(prev)\n prev = ''\n break\n else:\n prev += s\n\n if len(sentence) > 0:\n # subsampling\n sent_id = []\n if args.sample != 0:\n sent_len = len(sentence)\n i = 0\n while i < sent_len:\n word = sentence[i]\n f = freq[word] / args.train_words\n pb = (np.sqrt(f / args.sample) + 1) * args.sample / f;\n\n if pb > np.random.random_sample():\n sent_id.append( word2idx[word] )\n i += 1\n\n if len(sent_id) < 2:\n word_cnt += len(sentence)\n sentence.clear()\n continue\n\n next_random = (2**24) * np.random.randint(0, 2**24) + np.random.randint(0, 2**24)\n chunk = data_producer.cbow_producer(sent_id, len(sent_id), table_ptr_val, args.window,\n neg, args.vocab_size, args.batch_size, next_random)\n\n chunk_pos = 0\n while chunk_pos < chunk.shape[0]:\n remain_space = args.batch_size - batch_count\n remain_chunk = chunk.shape[0] - chunk_pos\n\n if remain_chunk < remain_space:\n take_from_chunk = remain_chunk\n else:\n take_from_chunk = remain_space\n\n batch_placeholder[batch_count:batch_count+take_from_chunk, :] = chunk[chunk_pos:chunk_pos+take_from_chunk, :]\n batch_count += take_from_chunk\n\n if batch_count == args.batch_size:\n data_queue.put(batch_placeholder)\n batch_count = 0\n\n chunk_pos += take_from_chunk\n\n word_cnt += len(sentence)\n if word_cnt - last_word_cnt > 10000:\n with word_count_actual.get_lock():\n word_count_actual.value += word_cnt - last_word_cnt\n last_word_cnt = word_cnt\n sentence.clear()\n\n with word_count_actual.get_lock():\n word_count_actual.value += word_cnt - last_word_cnt\n print(p_id, it, file_pos, train_file.tell(), args.file_size)\n if batch_count > 0:\n data_queue.put(batch_placeholder[:batch_count,:])\n data_queue.put(None)\n print(p_id, file_pos, train_file.tell(), args.file_size)\n\ndef train_process(p_id, word_count_actual, word2idx, word_list, freq, args, model):\n data_queue = mp.SimpleQueue()\n\n lr = args.lr\n #optimizer = optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=lr)\n optimizer = optim.Adagrad(filter(lambda p: p.requires_grad, model.parameters()), lr=lr)\n\n t = mp.Process(target=train_process_sent_producer, args=(p_id, data_queue, word_count_actual, word_list, word2idx, freq, args))\n t.start()\n\n #n_iter = 1 if args.stage == 2 else args.iter\n n_iter = args.iter\n # get from data_queue and feed to model\n prev_word_cnt = 0\n while True:\n chunk = data_queue.get()\n if chunk is None:\n break\n else:\n # lr anneal & output\n if word_count_actual.value - prev_word_cnt > 10000:\n #if args.lr_anneal:\n # lr = args.lr * (1 - word_count_actual.value / (n_iter * args.train_words))\n # if lr < 0.0001 * args.lr:\n # lr = 0.0001 * args.lr\n # for param_group in optimizer.param_groups:\n # param_group['lr'] = lr\n\n #sys.stdout.write(\"\\rAlpha: %0.8f, Progess: %0.2f, Words/sec: %f, word_cnt: %d\" % (lr, word_count_actual.value / (n_iter * args.train_words) * 100, word_count_actual.value / (time.monotonic() - args.t_start), word_count_actual.value))\n sys.stdout.write(\"\\rProgess: %0.2f, Words/sec: %f, word_cnt: %d\" % (word_count_actual.value / (n_iter * args.train_words) * 100, word_count_actual.value / (time.monotonic() - args.t_start), word_count_actual.value))\n sys.stdout.flush()\n prev_word_cnt = word_count_actual.value\n\n if args.stage == 1:\n if args.cuda:\n data = Variable(torch.LongTensor(chunk).cuda(), requires_grad=False)\n else:\n data = Variable(torch.LongTensor(chunk), requires_grad=False)\n\n optimizer.zero_grad()\n loss = model(data)\n loss.backward()\n optimizer.step()\n model.global_embs.weight.data[args.vocab_size].fill_(0)\n\n elif args.stage == 3:\n if args.cuda:\n data = Variable(torch.LongTensor(chunk).cuda(), requires_grad=False)\n else:\n data = Variable(torch.LongTensor(chunk), requires_grad=False)\n\n #type_ids = chunk[:, 2*args.window+1:2*args.window+2+2*args.negative]\n type_ids = chunk[:, 2*args.window+1:2*args.window+2+args.negative]\n type_ids = np.reshape(type_ids, (type_ids.shape[0] * type_ids.shape[1]))\n sense2idx, sense_embs = model.get_possible_sense_embs(type_ids.tolist())\n\n # get type_idx from chunk, and do sense selection here.\n context_feats = model.get_context_feats(data[:, :2*args.window])\n\n chunk = data_producer.select_sense(chunk, context_feats, sense2idx, sense_embs,\n model.word2sense, chunk.shape[0], args.size, args.window, args.negative)\n\n if args.cuda:\n data = Variable(torch.LongTensor(chunk).cuda(), requires_grad=False)\n else:\n data = Variable(torch.LongTensor(chunk), requires_grad=False)\n\n optimizer.zero_grad()\n loss = model(data)\n loss.backward()\n optimizer.step()\n model.global_embs.weight.data[args.vocab_size].fill_(0)\n t.join()\n\ndef train_process_stage2(p_id, word_count_actual, word2idx, word_list, freq, args, model):\n data_queue = mp.SimpleQueue()\n\n sense_embs = model.sense_embs.weight.data.numpy()\n counter_list = np.zeros((model.sense_capacity), dtype='float32')\n\n t = mp.Process(target=train_process_sent_producer, args=(p_id, data_queue, word_count_actual, word_list, word2idx, freq, args))\n t.start()\n\n n_iter = 1\n # get from data_queue and feed to model\n prev_word_cnt = 0\n while True:\n chunk = data_queue.get()\n if chunk is None:\n break\n else:\n if word_count_actual.value - prev_word_cnt > 10000:\n sys.stdout.write(\"\\rProgess: %0.2f, Words/sec: %f, word_cnt: %d\" % (word_count_actual.value / (n_iter * args.train_words) * 100, word_count_actual.value / (time.monotonic() - args.t_start), word_count_actual.value))\n sys.stdout.flush()\n prev_word_cnt = word_count_actual.value\n\n if args.cuda:\n data = Variable(torch.LongTensor(chunk).cuda(), requires_grad=False)\n else:\n data = Variable(torch.LongTensor(chunk), requires_grad=False)\n\n context_feats = model.get_context_feats(data[:, :2*args.window])\n\n # update sense_embs\n create_cnt = data_producer.create_n_update_sense(chunk[:, 2*args.window+1], context_feats, sense_embs, model.word2sense, counter_list, chunk.shape[0], args.size, args.delta, model.n_senses)\n model.n_senses += create_cnt\n\n #if model.n_senses + args.batch_size > model.sense_capacity:\n # new_capacity = model.sense_capacity * 3 // 2\n # counter_list = np.concatenate( (counter_list, np.ones((new_capacity - model.sense_capacity),dtype='float32')), axis=0)\n # zero = np.zeros((new_capacity - model.sense_capacity, args.size), 'float32')\n # sense_embs = np.concatenate((sense_embs, zero), 0)\n # model.sense_capacity = new_capacity\n # print(\"\\nexapnded sense_embs: %d\" % model.n_senses)\n t.join()\n\n sense_embs[:model.n_senses, :] = sense_embs[:model.n_senses, :] / counter_list[:model.n_senses, None]\n\n\nif __name__ == '__main__':\n set_start_method('forkserver')\n\n args = parser.parse_args()\n print(\"Starting training using file %s\" % args.train)\n train_file = open(args.train)\n train_file.seek(0, 2)\n vars(args)['file_size'] = train_file.tell()\n\n word_count_actual = mp.Value('L', 0)\n\n if args.vocab == '':\n word2idx, word_list, freq = build_vocab(args) \n else:\n with open(args.vocab, 'rb') as f: \n word2idx, word_list, freq, pos2idx, dep2id = pickle.load(f)\n word_count = sum([freq[k] for k in freq])\n vars(args)['vocab_size'] = len(word2idx)\n vars(args)['train_words'] = word_count\n print(\"Vocab size: %ld\" % len(word2idx))\n print(\"Words in train file: %ld\" % word_count)\n\n model = init_net(args)\n model.share_memory()\n if args.cuda:\n model.cuda()\n\n # stage 1, learn robust context representation.\n vars(args)['stage'] = 1\n print(\"Stage 1\")\n vars(args)['lr_anneal'] = True\n vars(args)['t_start'] = time.monotonic()\n processes = []\n for p_id in range(args.processes):\n p = mp.Process(target=train_process, args=(p_id, word_count_actual, word2idx, word_list, freq, args, model))\n p.start()\n processes.append(p)\n\n for p in processes:\n p.join()\n del processes\n print(\"\\nStage 1, \", time.monotonic() - args.t_start, \" secs \", word_count_actual.value)\n filename = args.save\n if not filename.endswith('.pth.tar'):\n filename += '.stage1.pth.tar'\n save_model(filename, model, args, word2idx)\n\n if args.multi_proto:\n # stage 2, create new sense in a non-parametric way.\n # Freeze model paramters except sense_embs, and use only 1 process to prevent race condition\n old_batch_size = vars(args)['batch_size']\n model.global_embs.requires_grad = False\n model.ctx_weight.requires_grad = False\n model.sense_embs = model.sense_embs.cpu()\n vars(args)['stage'] = 2\n vars(args)['batch_size'] = 5000\n print(\"\\nStage 2\")\n word_count_actual.value = 0\n vars(args)['t_start'] = time.monotonic()\n train_process_stage2(0, word_count_actual, word2idx, word_list, freq, args, model)\n\n if args.cuda:\n model.cuda()\n print(\"\\nStage 2, \", time.monotonic() - args.t_start, \" secs\")\n print(\"Current # of senses: %d\" % model.n_senses)\n pdb.set_trace()\n filename = args.save\n if not filename.endswith('.pth.tar'):\n filename += '.stage2.pth.tar'\n save_model(filename, model, args, word2idx)\n\n # stage 3, no more sense creation.\n vars(args)['lr'] = args.lr * 0.01\n vars(args)['batch_size'] = old_batch_size\n model.global_embs.requires_grad = True\n model.ctx_weight.requires_grad = True\n vars(args)['stage'] = 3\n print(\"\\nBegin stage 3\")\n word_count_actual.value = 0\n vars(args)['t_start'] = time.monotonic()\n processes = []\n for p_id in range(args.processes):\n p = mp.Process(target=train_process, args=(p_id, word_count_actual, word2idx, word_list, freq, args, model))\n p.start()\n processes.append(p)\n\n for p in processes:\n p.join()\n\n print(\"\\nStage 3, \", time.monotonic() - args.t_start, \" secs\")\n\n # save model\n filename = args.save\n if not filename.endswith('.pth.tar'):\n filename += '.stage3.pth.tar'\n save_model(filename, model, args, word2idx)\n print(\"\")\n\n\n"},"apis":{"kind":"string","value":"[((390, 415), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\\n', (413, 415), False, 'import argparse\\n'), ((2370, 2379), 'collections.Counter', 'Counter', ([], {}), '()\\n', (2377, 2379), False, 'from collections import Counter\\n'), ((6620, 6640), 'torch.load', 'torch.load', (['filename'], {}), '(filename)\\n', (6630, 6640), False, 'import torch\\n'), ((8116, 8183), 'numpy.zeros', 'np.zeros', (['(args.batch_size, 2 * args.window + 2 + 2 * neg)', '\"\"\"int64\"\"\"'], {}), \"((args.batch_size, 2 * args.window + 2 + 2 * neg), 'int64')\\n\", (8124, 8183), True, 'import numpy as np\\n'), ((11626, 11642), 'torch.multiprocessing.SimpleQueue', 'mp.SimpleQueue', ([], {}), '()\\n', (11640, 11642), True, 'import torch.multiprocessing as mp\\n'), ((11851, 11978), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'train_process_sent_producer', 'args': '(p_id, data_queue, word_count_actual, word_list, word2idx, freq, args)'}), '(target=train_process_sent_producer, args=(p_id, data_queue,\\n word_count_actual, word_list, word2idx, freq, args))\\n', (11861, 11978), True, 'import torch.multiprocessing as mp\\n'), ((15228, 15244), 'torch.multiprocessing.SimpleQueue', 'mp.SimpleQueue', ([], {}), '()\\n', (15242, 15244), True, 'import torch.multiprocessing as mp\\n'), ((15319, 15366), 'numpy.zeros', 'np.zeros', (['model.sense_capacity'], {'dtype': '\"\"\"float32\"\"\"'}), \"(model.sense_capacity, dtype='float32')\\n\", (15327, 15366), True, 'import numpy as np\\n'), ((15378, 15505), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'train_process_sent_producer', 'args': '(p_id, data_queue, word_count_actual, word_list, word2idx, freq, args)'}), '(target=train_process_sent_producer, args=(p_id, data_queue,\\n word_count_actual, word_list, word2idx, freq, args))\\n', (15388, 15505), True, 'import torch.multiprocessing as mp\\n'), ((17363, 17393), 'multiprocessing.set_start_method', 'set_start_method', (['\"\"\"forkserver\"\"\"'], {}), \"('forkserver')\\n\", (17379, 17393), False, 'from multiprocessing import set_start_method\\n'), ((17617, 17633), 'torch.multiprocessing.Value', 'mp.Value', (['\"\"\"L\"\"\"', '(0)'], {}), \"('L', 0)\\n\", (17625, 17633), True, 'import torch.multiprocessing as mp\\n'), ((18431, 18447), 'time.monotonic', 'time.monotonic', ([], {}), '()\\n', (18445, 18447), False, 'import time\\n'), ((2083, 2117), 're.split', 're.split', ([\"('[' + delim + ']{1,}')\", 's'], {}), \"('[' + delim + ']{1,}', s)\\n\", (2091, 2117), False, 'import re\\n'), ((3167, 3257), 'torch.nn.Embedding', 'nn.Embedding', (['(args.vocab_size + 1)', 'args.size'], {'padding_idx': 'args.vocab_size', 'sparse': '(True)'}), '(args.vocab_size + 1, args.size, padding_idx=args.vocab_size,\\n sparse=True)\\n', (3179, 3257), True, 'import torch.nn as nn\\n'), ((3278, 3335), 'torch.nn.Embedding', 'nn.Embedding', (['(args.vocab_size * 5)', 'args.size'], {'sparse': '(True)'}), '(args.vocab_size * 5, args.size, sparse=True)\\n', (3290, 3335), True, 'import torch.nn as nn\\n'), ((4940, 4963), 'numpy.array', 'np.array', (['sense_indices'], {}), '(sense_indices)\\n', (4948, 4963), True, 'import numpy as np\\n'), ((5763, 5822), 'torch.sum', 'torch.sum', (['(ctx_type_embs * self.ctx_weight)', '(1)'], {'keepdim': '(True)'}), '(ctx_type_embs * self.ctx_weight, 1, keepdim=True)\\n', (5772, 5822), False, 'import torch\\n'), ((5871, 5922), 'torch.sum', 'torch.sum', (['(ctx_feats[:, (0), :] * pos_sense_embs)', '(1)'], {}), '(ctx_feats[:, (0), :] * pos_sense_embs, 1)\\n', (5880, 5922), False, 'import torch\\n'), ((7653, 7720), 'data_producer.init_unigram_table', 'data_producer.init_unigram_table', (['word_list', 'freq', 'args.train_words'], {}), '(word_list, freq, args.train_words)\\n', (7685, 7720), False, 'import data_producer\\n'), ((18518, 18626), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'train_process', 'args': '(p_id, word_count_actual, word2idx, word_list, freq, args, model)'}), '(target=train_process, args=(p_id, word_count_actual, word2idx,\\n word_list, freq, args, model))\\n', (18528, 18626), True, 'import torch.multiprocessing as mp\\n'), ((19525, 19541), 'time.monotonic', 'time.monotonic', ([], {}), '()\\n', (19539, 19541), False, 'import time\\n'), ((19818, 19833), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\\n', (19831, 19833), False, 'import pdb\\n'), ((20365, 20381), 'time.monotonic', 'time.monotonic', ([], {}), '()\\n', (20379, 20381), False, 'import time\\n'), ((3379, 3417), 'torch.ones', 'torch.ones', (['(2 * args.window)', 'args.size'], {}), '(2 * args.window, args.size)\\n', (3389, 3417), False, 'import torch\\n'), ((16436, 16627), 'data_producer.create_n_update_sense', 'data_producer.create_n_update_sense', (['chunk[:, (2 * args.window + 1)]', 'context_feats', 'sense_embs', 'model.word2sense', 'counter_list', 'chunk.shape[0]', 'args.size', 'args.delta', 'model.n_senses'], {}), '(chunk[:, (2 * args.window + 1)],\\n context_feats, sense_embs, model.word2sense, counter_list, chunk.shape[\\n 0], args.size, args.delta, model.n_senses)\\n', (16471, 16627), False, 'import data_producer\\n'), ((17889, 17903), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\\n', (17900, 17903), False, 'import pickle\\n'), ((18754, 18770), 'time.monotonic', 'time.monotonic', ([], {}), '()\\n', (18768, 18770), False, 'import time\\n'), ((20464, 20572), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'train_process', 'args': '(p_id, word_count_actual, word2idx, word_list, freq, args, model)'}), '(target=train_process, args=(p_id, word_count_actual, word2idx,\\n word_list, freq, args, model))\\n', (20474, 20572), True, 'import torch.multiprocessing as mp\\n'), ((13171, 13189), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\\n', (13187, 13189), False, 'import sys\\n'), ((16017, 16035), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\\n', (16033, 16035), False, 'import sys\\n'), ((19710, 19726), 'time.monotonic', 'time.monotonic', ([], {}), '()\\n', (19724, 19726), False, 'import time\\n'), ((20703, 20719), 'time.monotonic', 'time.monotonic', ([], {}), '()\\n', (20717, 20719), False, 'import time\\n'), ((5197, 5228), 'torch.LongTensor', 'torch.LongTensor', (['sense_indices'], {}), '(sense_indices)\\n', (5213, 5228), False, 'import torch\\n'), ((5963, 6000), 'torch.clamp', 'torch.clamp', (['pos_ips'], {'max': '(10)', 'min': '(-10)'}), '(pos_ips, max=10, min=-10)\\n', (5974, 6000), False, 'import torch\\n'), ((9880, 9909), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 ** 24)'], {}), '(0, 2 ** 24)\\n', (9897, 9909), True, 'import numpy as np\\n'), ((14168, 14227), 'numpy.reshape', 'np.reshape', (['type_ids', '(type_ids.shape[0] * type_ids.shape[1])'], {}), '(type_ids, type_ids.shape[0] * type_ids.shape[1])\\n', (14178, 14227), True, 'import numpy as np\\n'), ((14498, 14646), 'data_producer.select_sense', 'data_producer.select_sense', (['chunk', 'context_feats', 'sense2idx', 'sense_embs', 'model.word2sense', 'chunk.shape[0]', 'args.size', 'args.window', 'args.negative'], {}), '(chunk, context_feats, sense2idx, sense_embs,\\n model.word2sense, chunk.shape[0], args.size, args.window, args.negative)\\n', (14524, 14646), False, 'import data_producer\\n'), ((16254, 16277), 'torch.LongTensor', 'torch.LongTensor', (['chunk'], {}), '(chunk)\\n', (16270, 16277), False, 'import torch\\n'), ((6122, 6160), 'torch.clamp', 'torch.clamp', (['(-neg_ips)'], {'max': '(10)', 'min': '(-10)'}), '(-neg_ips, max=10, min=-10)\\n', (6133, 6160), False, 'import torch\\n'), ((9850, 9879), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 ** 24)'], {}), '(0, 2 ** 24)\\n', (9867, 9879), True, 'import numpy as np\\n'), ((13456, 13479), 'torch.LongTensor', 'torch.LongTensor', (['chunk'], {}), '(chunk)\\n', (13472, 13479), False, 'import torch\\n'), ((4501, 4546), 'torch.sum', 'torch.sum', (['(ctx_type_embs * self.ctx_weight)', '(1)'], {}), '(ctx_type_embs * self.ctx_weight, 1)\\n', (4510, 4546), False, 'import torch\\n'), ((5032, 5063), 'torch.LongTensor', 'torch.LongTensor', (['sense_indices'], {}), '(sense_indices)\\n', (5048, 5063), False, 'import torch\\n'), ((9540, 9565), 'numpy.random.random_sample', 'np.random.random_sample', ([], {}), '()\\n', (9563, 9565), True, 'import numpy as np\\n'), ((13925, 13948), 'torch.LongTensor', 'torch.LongTensor', (['chunk'], {}), '(chunk)\\n', (13941, 13948), False, 'import torch\\n'), ((14849, 14872), 'torch.LongTensor', 'torch.LongTensor', (['chunk'], {}), '(chunk)\\n', (14865, 14872), False, 'import torch\\n'), ((16151, 16174), 'torch.LongTensor', 'torch.LongTensor', (['chunk'], {}), '(chunk)\\n', (16167, 16174), False, 'import torch\\n'), ((13345, 13368), 'torch.LongTensor', 'torch.LongTensor', (['chunk'], {}), '(chunk)\\n', (13361, 13368), False, 'import torch\\n'), ((9458, 9482), 'numpy.sqrt', 'np.sqrt', (['(f / args.sample)'], {}), '(f / args.sample)\\n', (9465, 9482), True, 'import numpy as np\\n'), ((13095, 13111), 'time.monotonic', 'time.monotonic', ([], {}), '()\\n', (13109, 13111), False, 'import time\\n'), ((13814, 13837), 'torch.LongTensor', 'torch.LongTensor', (['chunk'], {}), '(chunk)\\n', (13830, 13837), False, 'import torch\\n'), ((14738, 14761), 'torch.LongTensor', 'torch.LongTensor', (['chunk'], {}), '(chunk)\\n', (14754, 14761), False, 'import torch\\n'), ((15941, 15957), 'time.monotonic', 'time.monotonic', ([], {}), '()\\n', (15955, 15957), False, 'import time\\n')]"}}},{"rowIdx":8405,"cells":{"repo_name":{"kind":"string","value":"ProEgitim/Python-Dersleri-BEM"},"repo_path":{"kind":"string","value":"Ogrenciler/Varol/buyuksayi.py"},"repo_head_hexsha":{"kind":"string","value":"b25e9fdb1fa3026925a46b2fcbcba348726b775c"},"content":{"kind":"string","value":"sayi1 = int(input(\"1. Sayı: \"))\nsayi2 = int(input(\"2. Sayı: \"))\nsayi3 = int(input(\"3. Sayı: \"))\nsayi4 = int(input(\"4. Sayı: \"))\nsayi5 = int(input(\"5. Sayı: \"))\nsayilar=[];\nsayilar.append(sayi1)\nsayilar.append(sayi2)\nsayilar.append(sayi3)\nsayilar.append(sayi4)\nsayilar.append(sayi5)\nsayilar.sort()\nprint(\"En büyük sayimiz..\",sayilar[-1])\n\n\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8406,"cells":{"repo_name":{"kind":"string","value":"MouseHu/emdqn"},"repo_path":{"kind":"string","value":"baselines/deepq/build_graph_mfec.py"},"repo_head_hexsha":{"kind":"string","value":"ba907e959f21dd0b5a17117accccae9c82a79a3b"},"content":{"kind":"string","value":"\"\"\"Deep Q learning graph\n\nThe functions in this file can are used to create the following functions:\n\n======= act ========\n\n Function to chose an action given an observation\n\n Parameters\n ----------\n observation: object\n Observation that can be feed into the output of make_obs_ph\n stochastic: bool\n if set to False all the actions are always deterministic (default False)\n update_eps_ph: float\n update epsilon a new value, if negative not update happens\n (default: no update)\n\n Returns\n -------\n Tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be performed for\n every element of the batch.\n\n\n======= train =======\n\n Function that takes a transition (s,a,r,s') and optimizes Bellman equation's error:\n\n td_error = Q(s,a) - (r + gamma * max_a' Q(s', a'))\n loss = huber_loss[td_error]\n\n Parameters\n ----------\n obs_t: object\n a batch of observations\n action: np.array\n actions that were selected upon seeing obs_t.\n dtype must be int32 and shape must be (batch_size,)\n reward: np.array\n immediate reward attained after executing those actions\n dtype must be float32 and shape must be (batch_size,)\n obs_tp1: object\n observations that followed obs_t\n done: np.array\n 1 if obs_t was the last observation in the episode and 0 otherwise\n obs_tp1 gets ignored, but must be of the valid shape.\n dtype must be float32 and shape must be (batch_size,)\n weight: np.array\n imporance weights for every element of the batch (gradient is multiplied\n by the importance weight) dtype must be float32 and shape must be (batch_size,)\n\n Returns\n -------\n td_error: np.array\n a list of differences between Q(s,a) and the target in Bellman's equation.\n dtype is float32 and shape is (batch_size,)\n\n======= update_target ========\n\n copy the parameters from optimized Q function to the target Q function.\n In Q learning we actually optimize the following error:\n\n Q(s,a) - (r + gamma * max_a' Q'(s', a'))\n\n Where Q' is lagging behind Q to stablize the learning. For example for Atari\n\n Q' is set to Q once every 10000 updates training steps.\n\n\"\"\"\nimport tensorflow as tf\nimport baselines.common.tf_util as U\nimport numpy as np\n\n\ndef build_act_mf(make_obs_ph, q_func, z_noise, num_actions, scope=\"deepq\", reuse=None):\n with tf.variable_scope(scope, reuse=reuse):\n observations_ph = U.ensure_tf_input(make_obs_ph(\"observation\"))\n q, q_deterministic, v_mean, v_logvar, z_mean, z_logvar, recon_obs = q_func(observations_ph.get(), z_noise,\n num_actions,\n scope=\"q_func\",\n reuse=tf.AUTO_REUSE)\n\n act = U.function(inputs=[observations_ph,z_noise],\n outputs=[z_mean, z_logvar])\n\n return act\n\n\ndef build_train_mf(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, scope=\"mfec\",\n alpha=1.0, beta=1.0, theta=1.0, latent_dim=32, ib=True, reuse=None):\n \"\"\"Creates the train function:\n\n Parameters\n ----------\n make_obs_ph: str -> tf.placeholder or TfInput\n a function that takes a name and creates a placeholder of input with that name\n q_func: (tf.Variable, int, str, bool) -> tf.Variable\n the model that takes the following inputs:\n observation_in: object\n the output of observation placeholder\n num_actions: int\n number of actions\n scope: str\n reuse: bool\n should be passed to outer variable scope\n and returns a tensor of shape (batch_size, num_actions) with values of every action.\n num_actions: int\n number of actions\n reuse: bool\n whether or not to reuse the graph variables\n optimizer: tf.train.Optimizer\n optimizer to use for the Q-learning objective.\n grad_norm_clipping: float or None\n clip gradient norms to this value. If None no clipping is performed.\n gamma: float\n discount rate.\n double_q: bool\n if true will use Double Q Learning (https://arxiv.org/abs/1509.06461).\n In general it is a good idea to keep it enabled.\n scope: str or VariableScope\n optional scope for variable_scope.\n reuse: bool or None\n whether or not the variables should be reused. To be able to reuse the scope must be given.\n\n Returns\n -------\n act: (tf.Variable, bool, float) -> tf.Variable\n function to select and action given observation.\n` See the top of the file for details.\n train: (object, np.array, np.array, object, np.array, np.array) -> np.array\n optimize the error in Bellman's equation.\n` See the top of the file for details.\n update_target: () -> ()\n copy the parameters from optimized Q function to the target Q function.\n` See the top of the file for details.\n debug: {str: function}\n a bunch of functions to print debug data like q_values.\n \"\"\"\n act_noise = tf.placeholder(tf.float32, [None, latent_dim], name=\"act_noise\")\n act_f = build_act_mf(make_obs_ph, q_func, act_noise, num_actions, scope=scope, reuse=reuse)\n\n with tf.variable_scope(scope, reuse=reuse):\n # set up placeholders\n\n # EMDQN\n\n obs_vae_input = U.ensure_tf_input(make_obs_ph(\"obs_vae\"))\n z_noise_vae = tf.placeholder(tf.float32, [None, latent_dim], name=\"z_noise_vae\")\n inputs = [obs_vae_input,z_noise_vae]\n if ib:\n qec_input = tf.placeholder(tf.float32, [None], name='qec')\n inputs.append(qec_input)\n outputs = []\n\n q_vae, q_deterministic_vae, v_mean_vae, v_logvar_vae, z_mean_vae, z_logvar_vae, recon_obs = q_func(obs_vae_input.get(),\n z_noise_vae, num_actions,\n scope=\"q_func\",\n reuse=True)\n q_func_vars = U.scope_vars(U.absolute_scope_name(\"q_func\"))\n\n encoder_loss = -1 + z_mean_vae ** 2 + tf.exp(z_logvar_vae) - z_logvar_vae\n\n total_loss = tf.reduce_mean(beta * encoder_loss)\n decoder_loss = tf.keras.losses.binary_crossentropy(tf.reshape(recon_obs, [-1]), tf.reshape(\n tf.dtypes.cast(obs_vae_input._placeholder, tf.float32), [-1]))\n print(\"here\", z_mean_vae.shape, z_logvar_vae.shape, encoder_loss.shape, decoder_loss.shape)\n vae_loss = beta * encoder_loss + theta * decoder_loss\n outputs.append(encoder_loss)\n outputs.append(decoder_loss)\n outputs.append(vae_loss)\n total_loss += tf.reduce_mean(theta * decoder_loss)\n if ib:\n ib_loss = (v_mean_vae - tf.stop_gradient(tf.expand_dims(qec_input, 1))) ** 2 / tf.exp(\n v_logvar_vae) + v_logvar_vae\n print(\"here2\", v_mean_vae.shape, tf.expand_dims(qec_input, 1).shape, v_logvar_vae.shape, ib_loss.shape)\n total_ib_loss = alpha * ib_loss + beta * encoder_loss\n outputs.append(total_ib_loss)\n total_loss += tf.reduce_mean(alpha * ib_loss)\n\n if grad_norm_clipping is not None:\n optimize_expr = U.minimize_and_clip(optimizer,\n total_loss,\n var_list=q_func_vars,\n clip_val=grad_norm_clipping)\n else:\n optimize_expr = optimizer.minimize(total_loss, var_list=q_func_vars)\n # Create callable functions\n # EMDQN\n total_loss_summary = tf.summary.scalar(\"total loss\", total_loss)\n z_var_summary = tf.summary.scalar(\"z_var\", tf.reduce_mean(tf.exp(z_logvar_vae)))\n encoder_loss_summary = tf.summary.scalar(\"encoder loss\", tf.reduce_mean(encoder_loss))\n decoder_loss_summary = tf.summary.scalar(\"decoder loss\", tf.reduce_mean(decoder_loss))\n summaries = [total_loss_summary, z_var_summary, encoder_loss_summary, decoder_loss_summary]\n if ib:\n ib_loss_summary = tf.summary.scalar(\"ib loss\", tf.reduce_mean(ib_loss))\n total_ib_loss_summary = tf.summary.scalar(\"total ib loss\", tf.reduce_mean(total_ib_loss))\n summaries.append(ib_loss_summary)\n summaries.append(total_ib_loss_summary)\n\n summary = tf.summary.merge(summaries)\n outputs.append(summary)\n\n train = U.function(\n inputs=inputs,\n outputs=[total_loss,summary],\n updates=[optimize_expr]\n )\n\n return act_f, train\n"},"apis":{"kind":"string","value":"[((5243, 5307), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, latent_dim]'], {'name': '\"\"\"act_noise\"\"\"'}), \"(tf.float32, [None, latent_dim], name='act_noise')\\n\", (5257, 5307), True, 'import tensorflow as tf\\n'), ((2438, 2475), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'reuse'}), '(scope, reuse=reuse)\\n', (2455, 2475), True, 'import tensorflow as tf\\n'), ((2927, 3000), 'baselines.common.tf_util.function', 'U.function', ([], {'inputs': '[observations_ph, z_noise]', 'outputs': '[z_mean, z_logvar]'}), '(inputs=[observations_ph, z_noise], outputs=[z_mean, z_logvar])\\n', (2937, 3000), True, 'import baselines.common.tf_util as U\\n'), ((5414, 5451), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'reuse'}), '(scope, reuse=reuse)\\n', (5431, 5451), True, 'import tensorflow as tf\\n'), ((5589, 5655), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, latent_dim]'], {'name': '\"\"\"z_noise_vae\"\"\"'}), \"(tf.float32, [None, latent_dim], name='z_noise_vae')\\n\", (5603, 5655), True, 'import tensorflow as tf\\n'), ((6459, 6494), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(beta * encoder_loss)'], {}), '(beta * encoder_loss)\\n', (6473, 6494), True, 'import tensorflow as tf\\n'), ((6961, 6997), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(theta * decoder_loss)'], {}), '(theta * decoder_loss)\\n', (6975, 6997), True, 'import tensorflow as tf\\n'), ((7925, 7968), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['\"\"\"total loss\"\"\"', 'total_loss'], {}), \"('total loss', total_loss)\\n\", (7942, 7968), True, 'import tensorflow as tf\\n'), ((8666, 8693), 'tensorflow.summary.merge', 'tf.summary.merge', (['summaries'], {}), '(summaries)\\n', (8682, 8693), True, 'import tensorflow as tf\\n'), ((8743, 8829), 'baselines.common.tf_util.function', 'U.function', ([], {'inputs': 'inputs', 'outputs': '[total_loss, summary]', 'updates': '[optimize_expr]'}), '(inputs=inputs, outputs=[total_loss, summary], updates=[\\n optimize_expr])\\n', (8753, 8829), True, 'import baselines.common.tf_util as U\\n'), ((5740, 5786), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '\"\"\"qec\"\"\"'}), \"(tf.float32, [None], name='qec')\\n\", (5754, 5786), True, 'import tensorflow as tf\\n'), ((6321, 6352), 'baselines.common.tf_util.absolute_scope_name', 'U.absolute_scope_name', (['\"\"\"q_func\"\"\"'], {}), \"('q_func')\\n\", (6342, 6352), True, 'import baselines.common.tf_util as U\\n'), ((6554, 6581), 'tensorflow.reshape', 'tf.reshape', (['recon_obs', '[-1]'], {}), '(recon_obs, [-1])\\n', (6564, 6581), True, 'import tensorflow as tf\\n'), ((7407, 7438), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(alpha * ib_loss)'], {}), '(alpha * ib_loss)\\n', (7421, 7438), True, 'import tensorflow as tf\\n'), ((7511, 7609), 'baselines.common.tf_util.minimize_and_clip', 'U.minimize_and_clip', (['optimizer', 'total_loss'], {'var_list': 'q_func_vars', 'clip_val': 'grad_norm_clipping'}), '(optimizer, total_loss, var_list=q_func_vars, clip_val=\\n grad_norm_clipping)\\n', (7530, 7609), True, 'import baselines.common.tf_util as U\\n'), ((8123, 8151), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['encoder_loss'], {}), '(encoder_loss)\\n', (8137, 8151), True, 'import tensorflow as tf\\n'), ((8218, 8246), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['decoder_loss'], {}), '(decoder_loss)\\n', (8232, 8246), True, 'import tensorflow as tf\\n'), ((6401, 6421), 'tensorflow.exp', 'tf.exp', (['z_logvar_vae'], {}), '(z_logvar_vae)\\n', (6407, 6421), True, 'import tensorflow as tf\\n'), ((6607, 6661), 'tensorflow.dtypes.cast', 'tf.dtypes.cast', (['obs_vae_input._placeholder', 'tf.float32'], {}), '(obs_vae_input._placeholder, tf.float32)\\n', (6621, 6661), True, 'import tensorflow as tf\\n'), ((8035, 8055), 'tensorflow.exp', 'tf.exp', (['z_logvar_vae'], {}), '(z_logvar_vae)\\n', (8041, 8055), True, 'import tensorflow as tf\\n'), ((8422, 8445), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['ib_loss'], {}), '(ib_loss)\\n', (8436, 8445), True, 'import tensorflow as tf\\n'), ((8518, 8547), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['total_ib_loss'], {}), '(total_ib_loss)\\n', (8532, 8547), True, 'import tensorflow as tf\\n'), ((7104, 7124), 'tensorflow.exp', 'tf.exp', (['v_logvar_vae'], {}), '(v_logvar_vae)\\n', (7110, 7124), True, 'import tensorflow as tf\\n'), ((7202, 7230), 'tensorflow.expand_dims', 'tf.expand_dims', (['qec_input', '(1)'], {}), '(qec_input, 1)\\n', (7216, 7230), True, 'import tensorflow as tf\\n'), ((7066, 7094), 'tensorflow.expand_dims', 'tf.expand_dims', (['qec_input', '(1)'], {}), '(qec_input, 1)\\n', (7080, 7094), True, 'import tensorflow as tf\\n')]"}}},{"rowIdx":8407,"cells":{"repo_name":{"kind":"string","value":"frodre/LMR"},"repo_path":{"kind":"string","value":"tests/test_prior.py"},"repo_head_hexsha":{"kind":"string","value":"4c00d3f9db96447e69bd3f426d59524f7b5f3ef5"},"content":{"kind":"string","value":"import sys\n\nsys.path.append('../')\n\nimport LMR_config as cfg\nimport LMR_prior\nimport numpy as np\nimport pytest\n\n\ndef test_prior_seed():\n cfg_obj = cfg.Config(**{'core':{'seed': 2}})\n prior_cfg = cfg_obj.prior\n prior_source = '20cr'\n datadir_prior = 'data'\n datafile_prior = '[vardef_template]_gridded_dat.nc'\n state_variables = {'air': 'anom'}\n state_kind = 'anom'\n\n X = LMR_prior.prior_assignment(prior_source)\n\n X.prior_datadir = datadir_prior\n X.prior_datafile = datafile_prior\n X.statevars = state_variables\n X.Nens = 1\n X.detrend = False\n X.kind = state_kind\n X.avgInterval = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n X.populate_ensemble(prior_source, prior_cfg)\n\n X2 = LMR_prior.prior_assignment(prior_source)\n\n X2.prior_datadir = datadir_prior\n X2.prior_datafile = datafile_prior\n X2.statevars = state_variables\n X2.Nens = 1\n X2.detrend = False\n X2.kind = state_kind\n X2.avgInterval = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n X2.populate_ensemble(prior_source, prior_cfg)\n\n np.testing.assert_equal(X2.ens, X.ens)\n\n\ndef test_prior_use_full_prior():\n cfg_obj = cfg.Config(**{'core': {'seed': None}})\n prior_cfg = cfg_obj.prior\n prior_source = '20cr'\n datadir_prior = 'data'\n datafile_prior = '[vardef_template]_gridded_dat.nc'\n state_variables = {'air': 'anom'}\n state_kind = 'anom'\n avgInterval = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n X = LMR_prior.prior_assignment(prior_source)\n\n X.prior_datadir = datadir_prior\n X.prior_datafile = datafile_prior\n X.statevars = state_variables\n X.Nens = None\n X.detrend = False\n X.kind = state_kind\n X.avgInterval = avgInterval\n\n X.populate_ensemble(prior_source, prior_cfg)\n\n X2 = LMR_prior.prior_assignment(prior_source)\n X2.prior_datadir = datadir_prior\n X2.prior_datafile = datafile_prior\n X2.statevars = state_variables\n X2.Nens = None\n X2.detrend = False\n X2.kind = state_kind\n X2.avgInterval = avgInterval\n\n X2.read_prior()\n\n # Transform full prior into ensemble-like shape\n prior_vals = X2.prior_dict['air']['value']\n prior_vals = prior_vals.reshape(prior_vals.shape[0], -1)\n prior_vals = prior_vals.T\n\n np.testing.assert_equal(X.ens, prior_vals)\n\n\n\n\n"},"apis":{"kind":"string","value":"[((12, 34), 'sys.path.append', 'sys.path.append', (['\"\"\"../\"\"\"'], {}), \"('../')\\n\", (27, 34), False, 'import sys\\n'), ((150, 185), 'LMR_config.Config', 'cfg.Config', ([], {}), \"(**{'core': {'seed': 2}})\\n\", (160, 185), True, 'import LMR_config as cfg\\n'), ((395, 435), 'LMR_prior.prior_assignment', 'LMR_prior.prior_assignment', (['prior_source'], {}), '(prior_source)\\n', (421, 435), False, 'import LMR_prior\\n'), ((715, 755), 'LMR_prior.prior_assignment', 'LMR_prior.prior_assignment', (['prior_source'], {}), '(prior_source)\\n', (741, 755), False, 'import LMR_prior\\n'), ((1038, 1076), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['X2.ens', 'X.ens'], {}), '(X2.ens, X.ens)\\n', (1061, 1076), True, 'import numpy as np\\n'), ((1126, 1164), 'LMR_config.Config', 'cfg.Config', ([], {}), \"(**{'core': {'seed': None}})\\n\", (1136, 1164), True, 'import LMR_config as cfg\\n'), ((1422, 1462), 'LMR_prior.prior_assignment', 'LMR_prior.prior_assignment', (['prior_source'], {}), '(prior_source)\\n', (1448, 1462), False, 'import LMR_prior\\n'), ((1728, 1768), 'LMR_prior.prior_assignment', 'LMR_prior.prior_assignment', (['prior_source'], {}), '(prior_source)\\n', (1754, 1768), False, 'import LMR_prior\\n'), ((2197, 2239), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['X.ens', 'prior_vals'], {}), '(X.ens, prior_vals)\\n', (2220, 2239), True, 'import numpy as np\\n')]"}}},{"rowIdx":8408,"cells":{"repo_name":{"kind":"string","value":"juanjo3ns/SalGAN2"},"repo_path":{"kind":"string","value":"src/salgan_dhf1k/train_bce.py"},"repo_head_hexsha":{"kind":"string","value":"ac52af743b94961cdb44c5d89774b72fc8acfd3e"},"content":{"kind":"string","value":"import os\n\nfrom dataloader.datasetDHF1K import DHF1K\nfrom torch.utils.data import DataLoader\nfrom utils.salgan_utils import save_model, get_lr_optimizer\nfrom utils.sendTelegram import send\nfrom utils.printer import param_print\nfrom utils.salgan_generator import create_model, add_bn\nfrom evaluation.fast_evaluation import compute_metrics\n\nimport numpy as np\n\nimport torch\nfrom torch.nn import AvgPool2d\nfrom torch.nn.modules.loss import BCELoss\nimport torch.backends.cudnn as cudnn\nfrom torch.optim import SGD, Adam\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR\nfrom time import time\n\nfrom IPython import embed\nfrom tensorboard_logger import configure, log_value, log_histogram\n\n\nTRAIN = 'train'\nVAL = 'val'\nTEST = 'test'\n\ndef add_layer_weights(vgg_weights):\n\t# Mean of RGB weights of first layer with size [64,1,3,3]\n\tlayer1 = vgg_weights['0.weight']\n\tmean_rgb = layer1.mean(dim=1,keepdim=True)\n\tvgg_weights['0.weight'] = torch.cat([layer1.cuda(),mean_rgb.cuda()],1)\n\t# We could do it easily accessing to the weights trought model[0].weight and change dimension 1, but as we\n\t# already have the 4th channel we'd be doing the mean of all of the channels, inicializing it in the wrong way.\n\treturn vgg_weights\n\ndef train_eval(mode, model, optimizer, dataloader):\n\tif mode == TRAIN:\n\t\tN = len(ds_train)/batch_size\n\t\tmodel.train()\n\telse:\n\t\tN = len(ds_validate)/batch_size\n\t\tmodel.eval()\n\n\ttotal_loss = []\n\t#iterate epoch...\n\t#iterate epoch...\n\tfor i, X in enumerate(dataloader[mode]):\n\t\tinputs = X[0].cuda()\n\t\t# noramlize saliency maps values between [0,1]\n\t\tgt_maps = X[1].cuda()/255\n\t\tembed()\n\t\tpredictions = model.forward(inputs).squeeze()\n\t\t# reduce size for loss\n\t\treduce_size = AvgPool2d((4,4))\n\t\tpred_ = reduce_size(predictions)\n\t\tgt_maps_ = reduce_size(gt_maps)\n\n\t\tpred_ = pred_.view(pred_.size()[0], -1)\n\t\tgt_maps_ = gt_maps_.view(gt_maps_.size()[0], -1)\n\n\t\tloss = bce_loss(pred_, gt_maps_)\n\n\t\t# make actual step update\n\t\tif mode==TRAIN:\n\t\t\t# compute gradients\n\t\t\tloss.backward()\n\t\t\t# step optimizer\n\t\t\toptimizer.step()\n\t\t\t# reset grads for next step\n\t\t\toptimizer.zero_grad()\n\n\n\t\tprint(\"\\t{}/{} loss:{}\".format(i, int(N), loss.item()), end=\"\\r\")\n\t\ttotal_loss.append(loss.item())\n\n\ttotal_loss=np.mean(total_loss)\n\treturn total_loss\n\n\n\nif __name__ == '__main__':\n\timport argparse\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--path_out\", default='sal_dhf1k_adamdepthcoordaugm2_frombestsaldepth',\n\t\t\t\ttype=str,\n\t\t\t\thelp=\"\"\"set output path for the trained model\"\"\")\n\tparser.add_argument(\"--batch_size\", default=12,\n\t\t\t\ttype=int,\n\t\t\t\thelp=\"\"\"Set batch size\"\"\")\n\tparser.add_argument(\"--n_epochs\", default=10, type=int,\n\t\t\t\thelp=\"\"\"Set total number of epochs\"\"\")\n\tparser.add_argument(\"--depth\", default=False, type=bool,\n\t\t\t\thelp=\"\"\"Enable 4th channel with depth\"\"\")\n\tparser.add_argument(\"--augment\", default=False, type=bool,\n\t\t\t\thelp=\"\"\"Enable data augmentation\"\"\")\n\tparser.add_argument(\"--coord\", default=False, type=bool,\n\t\t\t\thelp=\"\"\"Enable coordconv\"\"\")\n\tparser.add_argument(\"--flow\", default=False, type=bool,\n\t\t\t\thelp=\"\"\"Enable opticalflow\"\"\")\n\tparser.add_argument(\"--lr\", type=float, default=0.00001,\n\t\t\t\thelp=\"\"\"Learning rate for training\"\"\")\n\tparser.add_argument(\"--patience\", type=int, default=3,\n\t\t\t\thelp=\"\"\"Patience for learning rate scheduler (default 10)\"\"\")\n\targs = parser.parse_args()\n\n\n\t# set output path ==========================================================\n\tpath_out = '../trained_models/batch12_/' + args.path_out\n\n\tif not os.path.exists(path_out):\n\t\t# create output path\n\t\tos.makedirs(path_out)\n\n\t\t# create output for models\n\t\tpath_models = os.path.join(path_out, 'models')\n\t\tif not os.path.exists(path_models):\n\t\t\tos.makedirs(path_models)\n\n\t# tensorboard\n\tconfigure(\"{}\".format(path_out), flush_secs=5)\n\n\t# data =====================================================================\n\tbatch_size = args.batch_size\n\tn_epochs = args.n_epochs\n\tlr = args.lr\n\tDEPTH = args.depth\n\tAUGMENT = args.augment\n\tCOORD = args.coord\n\tFLOW = args.flow\n\t# Datasets for DHF1K\n\tds_train = DHF1K(mode=TRAIN, transformation=True, depth=DEPTH, d_augm=AUGMENT, coord=COORD)\n\tds_validate = DHF1K(mode=VAL, transformation=False, depth=DEPTH, d_augm=False, coord=COORD)\n\n\t# Dataloaders\n\tdataloader = {\n\t\tTRAIN: DataLoader(ds_train, batch_size=batch_size,\n\t\t\t\t\t\t\t\tshuffle=True, num_workers=2),\n\t\tVAL: DataLoader(ds_validate, batch_size=batch_size,\n\t\t\t\t\t\t\t\tshuffle=False, num_workers=2)\n\t}\n\n\n\t# POSSIBILITY OF CHOOSING GPU\n\ttorch.cuda.set_device(1)\n\t# MODEL INITIALIZATION\n\tprint(\"Init model...\")\n\tvgg_weights = torch.load('../trained_models/salgan_baseline.pt')['state_dict']\n\tmodel = create_model(3)\n\t# if DEPTH and COORD:\n\t# \tmodel = create_model(6)\n\t# \tfor i in range(0,3):\n\t# \t\tvgg_weights = add_layer_weights(vgg_weights)\n\t# elif DEPTH:\n\t# \tmodel = create_model(4)\n\t# \tadd_layer_weights(vgg_weights)\n\t# elif COORD:\n\t# \tmodel = create_model(5)\n\t# \tfor i in range(0,2):\n\t# \t\tvgg_weights = add_layer_weights(vgg_weights)\n\t# else: model = create_model(3)\n\t# Instead of adding manually the layer of new weights, we could use strict=False\n\tmodel.load_state_dict(vgg_weights)\n\n\t# Add batch normalization to current model if needed\n\tmodel = add_bn(model)\n\n\tmodel.train()\n\tmodel.cuda()\n\tcudnn.benchmark = True\n\n\t# NOT WORKING UNMOUNTED DISK\n\t# If we have the two GPU's available we are going to use both\n\t# if torch.cuda.device_count() > 1:\n\t# \tprint(\"Using \", torch.cuda.device_count(), \"GPUs!\")\n\t# \tmodel = torch.nn.DataParallel(model)\n\n\n\t# LOSS FUNCTION\n\tbce_loss = BCELoss()\n\n\t# FINE-TUNE WHOLE NETWORK OR JUST DECODER => uncomment / or different lr for each part\n\t# decoder_parameters = []\n\t# base_params = []\n\t# for i, (a, p) in enumerate(model.named_parameters()):\n\t# \tembed()\n\t# \tif i>25:\n\t# \t\t# print(i, a, p.shape)\n\t# \t\tdecoder_parameters.append(p)\n\t# \telse:\n\t# \t\tbase_params.append(p)\n\t\t\t# If you wanna train just the decoder put this\n\t\t\t# p.requires_grad = False\n\n\t# ADAM OPTIMIZER\n\toptimizer = Adam(model.parameters(),\n\t\t\t\t\tlr = lr,\n\t\t\t\t\tweight_decay=0.000001)\n\n\n\t# STOCHASTIC GRADIENT DESCENT OPTIMIZER\n\t# optimizer = SGD(model.parameters(),\n\t# \t\t\t\tlr = 0.00001,\n\t# \t\t\t\tmomentum=0.9,\n\t# \t\t\t\tweight_decay=0.00001,\n\t# \t\t\t\tnesterov=True)\n\n\t# NUMBER OF TOTAL PARAMETERS\n\t# pytorch_total_params = sum(p.numel() for p in model.parameters())\n\t# NUMBER OF TRAINABLE PARAMETERS\n\ttrainable_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n\tprint(\"Trainable parameters: \", trainable_parameters)\n\tsend(\"Trainable parameters: \" + str(trainable_parameters))\n\tsend(\"Experiment: \" + args.path_out)\n\n\t# PRINT TABLE OF PARAMETERS\n\tparam_print([path_out,\"\",DEPTH,AUGMENT,COORD,FLOW,batch_size,lr,n_epochs, trainable_parameters])\n\n\t# set learning rate scheduler\n\t# ReduceLROnPlateau(\n\t\t# optimizer,\n\t\t# mode (str) 'min':lr es reduira quan la metrica no es redueixi mes, 'max' al contrari,\n\t\t# factor (float) factor de reduccio de la lr,\n\t\t# patience (int) num epochs sense millora a partir dels quals es redueix lr,\n\t\t# verbose (bool),\n\t# )\n\t# scheduler = ReduceLROnPlateau(optimizer,\n\t# \t\t\t\t\t\t\t'min',\n\t# \t\t\t\t\t\t\tpatience=args.patience,\n\t# \t\t\t\t\t\t\tverbose=True)\n\tscheduler = StepLR(optimizer, step_size=3, gamma=0.1)\n\tbest_loss=9999999\n\n\t# main loop training =======================================================\n\tfor id_epoch in range(n_epochs):\n\t\tfor mode in [VAL, TRAIN]:\n\t\t\t# select dataloader\n\t\t\tdata_iterator = dataloader[mode]\n\t\t\t#\n\t\t\t# # saliency metrics\n\t\t\t# if mode ==VAL:\n\t\t\t# \tprint(\"Evaluating metrics....\")\n\t\t\t# \t# only do 100 images from validation\n\t\t\t# \tmetrics = compute_metrics(model, 100, DEPTH, COORD)\n\t\t\t#\n\t\t\t# \t# log metric values\n\t\t\t# \tfor metric in metrics.keys():\n\t\t\t# \t\tlog_value(\"Metrics/{}\".format(metric),\n\t\t\t# \t\t\t\t\tmetrics[metric], id_epoch)\n\t\t\t#\n\t\t\t# # get epoch loss\n\t\t\t# print(\"--> {} epoch {}\".format(mode, id_epoch))\n\n\n\t\t\tepoch_loss = train_eval(mode, model, optimizer, dataloader)\n\n\t\t\tlr = list(get_lr_optimizer(optimizer))[0]\n\t\t\tprint(\"-----------\")\n\t\t\tprint(\"Done! {} epoch {} loss {} lr {}\".format(mode, id_epoch, epoch_loss, lr))\n\t\t\tsend(\"{} epoch {}/{} loss {}\".format(mode, id_epoch, n_epochs, epoch_loss))\n\t\t\tprint(\"\\n\")\n\n\t\t\t# record loss\n\t\t\tlog_value(\"loss/{}\".format(mode), epoch_loss, id_epoch)\n\t\t\tlog_value(\"lr/{}\".format(mode), lr, id_epoch)\n\t\t\t# for v in model.state_dict():\n\t\t\t# \tlog_histogram(\"Layer {}\".format(v), model.state_dict()[v], id_epoch)\n\t\t\tif (id_epoch%2)==0:\n\t\t\t\tsave_model(model, optimizer, id_epoch, path_out, name_model='{:03d}'.format(id_epoch))\n\t\t\t# store model if val loss improves\n\t\t\tif mode==VAL:\n\t\t\t\tif best_loss > epoch_loss:\n\t\t\t\t\t# update loss\n\t\t\t\t\tbest_loss = epoch_loss\n\n\t\t\t\t\tsave_model(model, optimizer, id_epoch, path_out, name_model='best')\n\t\t\t\t# scheduler.step(epoch_loss)\n\t\t\t\tscheduler.step()\n"},"apis":{"kind":"string","value":"[((2215, 2234), 'numpy.mean', 'np.mean', (['total_loss'], {}), '(total_loss)\\n', (2222, 2234), True, 'import numpy as np\\n'), ((2311, 2336), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\\n', (2334, 2336), False, 'import argparse\\n'), ((4025, 4110), 'dataloader.datasetDHF1K.DHF1K', 'DHF1K', ([], {'mode': 'TRAIN', 'transformation': '(True)', 'depth': 'DEPTH', 'd_augm': 'AUGMENT', 'coord': 'COORD'}), '(mode=TRAIN, transformation=True, depth=DEPTH, d_augm=AUGMENT, coord=COORD\\n )\\n', (4030, 4110), False, 'from dataloader.datasetDHF1K import DHF1K\\n'), ((4121, 4198), 'dataloader.datasetDHF1K.DHF1K', 'DHF1K', ([], {'mode': 'VAL', 'transformation': '(False)', 'depth': 'DEPTH', 'd_augm': '(False)', 'coord': 'COORD'}), '(mode=VAL, transformation=False, depth=DEPTH, d_augm=False, coord=COORD)\\n', (4126, 4198), False, 'from dataloader.datasetDHF1K import DHF1K\\n'), ((4451, 4475), 'torch.cuda.set_device', 'torch.cuda.set_device', (['(1)'], {}), '(1)\\n', (4472, 4475), False, 'import torch\\n'), ((4613, 4628), 'utils.salgan_generator.create_model', 'create_model', (['(3)'], {}), '(3)\\n', (4625, 4628), False, 'from utils.salgan_generator import create_model, add_bn\\n'), ((5166, 5179), 'utils.salgan_generator.add_bn', 'add_bn', (['model'], {}), '(model)\\n', (5172, 5179), False, 'from utils.salgan_generator import create_model, add_bn\\n'), ((5493, 5502), 'torch.nn.modules.loss.BCELoss', 'BCELoss', ([], {}), '()\\n', (5500, 5502), False, 'from torch.nn.modules.loss import BCELoss\\n'), ((6509, 6545), 'utils.sendTelegram.send', 'send', ([\"('Experiment: ' + args.path_out)\"], {}), \"('Experiment: ' + args.path_out)\\n\", (6513, 6545), False, 'from utils.sendTelegram import send\\n'), ((6577, 6685), 'utils.printer.param_print', 'param_print', ([\"[path_out, '', DEPTH, AUGMENT, COORD, FLOW, batch_size, lr, n_epochs,\\n trainable_parameters]\"], {}), \"([path_out, '', DEPTH, AUGMENT, COORD, FLOW, batch_size, lr,\\n n_epochs, trainable_parameters])\\n\", (6588, 6685), False, 'from utils.printer import param_print\\n'), ((7118, 7159), 'torch.optim.lr_scheduler.StepLR', 'StepLR', (['optimizer'], {'step_size': '(3)', 'gamma': '(0.1)'}), '(optimizer, step_size=3, gamma=0.1)\\n', (7124, 7159), False, 'from torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR\\n'), ((1601, 1608), 'IPython.embed', 'embed', ([], {}), '()\\n', (1606, 1608), False, 'from IPython import embed\\n'), ((1698, 1715), 'torch.nn.AvgPool2d', 'AvgPool2d', (['(4, 4)'], {}), '((4, 4))\\n', (1707, 1715), False, 'from torch.nn import AvgPool2d\\n'), ((3478, 3502), 'os.path.exists', 'os.path.exists', (['path_out'], {}), '(path_out)\\n', (3492, 3502), False, 'import os\\n'), ((3529, 3550), 'os.makedirs', 'os.makedirs', (['path_out'], {}), '(path_out)\\n', (3540, 3550), False, 'import os\\n'), ((3597, 3629), 'os.path.join', 'os.path.join', (['path_out', '\"\"\"models\"\"\"'], {}), \"(path_out, 'models')\\n\", (3609, 3629), False, 'import os\\n'), ((4240, 4312), 'torch.utils.data.DataLoader', 'DataLoader', (['ds_train'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(2)'}), '(ds_train, batch_size=batch_size, shuffle=True, num_workers=2)\\n', (4250, 4312), False, 'from torch.utils.data import DataLoader\\n'), ((4329, 4405), 'torch.utils.data.DataLoader', 'DataLoader', (['ds_validate'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(2)'}), '(ds_validate, batch_size=batch_size, shuffle=False, num_workers=2)\\n', (4339, 4405), False, 'from torch.utils.data import DataLoader\\n'), ((4539, 4589), 'torch.load', 'torch.load', (['\"\"\"../trained_models/salgan_baseline.pt\"\"\"'], {}), \"('../trained_models/salgan_baseline.pt')\\n\", (4549, 4589), False, 'import torch\\n'), ((3639, 3666), 'os.path.exists', 'os.path.exists', (['path_models'], {}), '(path_models)\\n', (3653, 3666), False, 'import os\\n'), ((3671, 3695), 'os.makedirs', 'os.makedirs', (['path_models'], {}), '(path_models)\\n', (3682, 3695), False, 'import os\\n'), ((7876, 7903), 'utils.salgan_utils.get_lr_optimizer', 'get_lr_optimizer', (['optimizer'], {}), '(optimizer)\\n', (7892, 7903), False, 'from utils.salgan_utils import save_model, get_lr_optimizer\\n'), ((8597, 8664), 'utils.salgan_utils.save_model', 'save_model', (['model', 'optimizer', 'id_epoch', 'path_out'], {'name_model': '\"\"\"best\"\"\"'}), \"(model, optimizer, id_epoch, path_out, name_model='best')\\n\", (8607, 8664), False, 'from utils.salgan_utils import save_model, get_lr_optimizer\\n')]"}}},{"rowIdx":8409,"cells":{"repo_name":{"kind":"string","value":"tracon/dragontail"},"repo_path":{"kind":"string","value":"dragontail/content/models/basicpage.py"},"repo_head_hexsha":{"kind":"string","value":"aae860acb5fe400015557f659b6d4221b939747a"},"content":{"kind":"string","value":" # encoding: utf-8\n\nfrom django.db import models\n\nfrom wagtail.wagtailcore.models import Page\nfrom wagtail.wagtailcore.fields import StreamField\nfrom wagtail.wagtailcore import blocks\nfrom wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel\nfrom wagtail.wagtailimages.blocks import ImageChooserBlock\n\n\nclass BasicPage(Page):\n body = StreamField([\n ('paragraph', blocks.RichTextBlock()),\n ('image', ImageChooserBlock()),\n ])\n\n content_panels = Page.content_panels + [\n StreamFieldPanel('body'),\n ]\n\n def get_template(self, request, *args, **kwargs):\n from .templatesettings import TemplateSettings\n\n template_settings = TemplateSettings.for_site(request.site)\n\n return template_settings.basic_page_template"},"apis":{"kind":"string","value":"[((518, 542), 'wagtail.wagtailadmin.edit_handlers.StreamFieldPanel', 'StreamFieldPanel', (['\"\"\"body\"\"\"'], {}), \"('body')\\n\", (534, 542), False, 'from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel\\n'), ((392, 414), 'wagtail.wagtailcore.blocks.RichTextBlock', 'blocks.RichTextBlock', ([], {}), '()\\n', (412, 414), False, 'from wagtail.wagtailcore import blocks\\n'), ((435, 454), 'wagtail.wagtailimages.blocks.ImageChooserBlock', 'ImageChooserBlock', ([], {}), '()\\n', (452, 454), False, 'from wagtail.wagtailimages.blocks import ImageChooserBlock\\n')]"}}},{"rowIdx":8410,"cells":{"repo_name":{"kind":"string","value":"infapy/infapy"},"repo_path":{"kind":"string","value":"infapy/v3/agentService.py"},"repo_head_hexsha":{"kind":"string","value":"0cb11310130be70ce1b647aa5ede929c1eb9b2ce"},"content":{"kind":"string","value":"# Copyright (c) 2021-Present (Prashanth Pradeep)\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport requests as re\nimport infapy\nfrom infapy.exceptions import InvalidDetailsProvided\n\nclass AgentService():\n def __init__(self,v3,v3BaseURL,v3SessionID):\n self._v3 = v3\n self._v3BaseURL = v3BaseURL\n self._v3SessionID = v3SessionID\n \n def updateAgentService(self,serviceName, serviceAction, agentId):\n url=self._v3BaseURL + \"/public/core/v3/agent/service\"\n headers = {'Content-Type': \"application/json\", 'Accept': \"application/json\",\"INFA-SESSION-ID\":self._v3SessionID}\n body = {\n 'serviceName':serviceName,\n 'serviceAction':serviceAction,\n 'agentId':agentId}\n\n infapy.log.info(\"agentService API URL - \" + url)\n infapy.log.info(\"API Headers: \" + str(headers))\n infapy.log.info(\"Body: \" + str(body))\n\n try:\n response = re.post(url=url, json=body, headers=headers)\n data = response.json()\n infapy.log.debug(str(data))\n try:\n if (\"error\" in data):\n infapy.log.error(\"Please validate the details passed\")\n infapy.log.error(str(data))\n raise InvalidDetailsProvided\n except Exception as e:\n infapy.log.exception(e)\n raise\n except Exception as e:\n infapy.log.exception(e)\n raise\n infapy.log.info(data[\"message\"]) \n return data"},"apis":{"kind":"string","value":"[((1249, 1297), 'infapy.log.info', 'infapy.log.info', ([\"('agentService API URL - ' + url)\"], {}), \"('agentService API URL - ' + url)\\n\", (1264, 1297), False, 'import infapy\\n'), ((1974, 2006), 'infapy.log.info', 'infapy.log.info', ([\"data['message']\"], {}), \"(data['message'])\\n\", (1989, 2006), False, 'import infapy\\n'), ((1437, 1481), 'requests.post', 're.post', ([], {'url': 'url', 'json': 'body', 'headers': 'headers'}), '(url=url, json=body, headers=headers)\\n', (1444, 1481), True, 'import requests as re\\n'), ((1924, 1947), 'infapy.log.exception', 'infapy.log.exception', (['e'], {}), '(e)\\n', (1944, 1947), False, 'import infapy\\n'), ((1632, 1686), 'infapy.log.error', 'infapy.log.error', (['\"\"\"Please validate the details passed\"\"\"'], {}), \"('Please validate the details passed')\\n\", (1648, 1686), False, 'import infapy\\n'), ((1835, 1858), 'infapy.log.exception', 'infapy.log.exception', (['e'], {}), '(e)\\n', (1855, 1858), False, 'import infapy\\n')]"}}},{"rowIdx":8411,"cells":{"repo_name":{"kind":"string","value":"pengwow/test-demo"},"repo_path":{"kind":"string","value":"home_application/views.py"},"repo_head_hexsha":{"kind":"string","value":"9d5c460b534d93d84f39ae24db82aa101027d199"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"\nTencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.\nCopyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at http://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and limitations under the License.\n\"\"\"\n\nfrom common.mymako import render_mako_context, render_json\nfrom blueking.component.shortcuts import get_client_by_request\nfrom django.views.decorators.csrf import csrf_exempt\nfrom models import TEST, HostDisk, ScriptExecInfo\nimport json\nimport base64\n\n\ndef home(request):\n \"\"\"\n 首页\n \"\"\"\n\n # yewu = [\n # {'id': 1, \"name\": u\"业务1\"},\n # {'id': 2, \"name\": u\"业务2\"},\n # {'id': 3, \"name\": u\"业务3\"},\n # ]\n\n # 从环境配置获取APP信息,从request获取当前用户信息\n client = get_client_by_request(request)\n\n kwargs = {}\n result = client.cc.search_business(kwargs)\n print(result)\n yewu = result['data']['info']\n return render_mako_context(request, '/home_application/home.html',\n {\n \"yewu\": yewu,\n \"AAA\": u\"业务列表\"\n })\n\n\ndef submit_template(request):\n \"\"\"\n 首页\n \"\"\"\n print(request.body)\n return render_json({\"1111111\": \"dddddddddd\"})\n\n\ndef dev_guide(request):\n \"\"\"\n 开发指引\n \"\"\"\n return render_mako_context(request, '/home_application/dev_guide.html')\n\n\ndef contactus(request):\n \"\"\"\n 联系我们\n \"\"\"\n return render_mako_context(request, '/home_application/contact.html')\n\n\ndef tijiao(request):\n data = json.loads(request.body)\n print(type(data))\n sss = TEST(**data)\n sss.save()\n return render_json({\"DATA\": \"AAAAAAAA\"})\n\n\ndef host_disk(request):\n host_list = HostDisk.objects.all()\n re_list = list()\n for item in host_list:\n temp_dict = dict()\n temp_dict['os'] = item.os\n temp_dict['host_ip'] = item.host_ip\n temp_dict['host_name'] = item.host_name\n temp_dict['host_path'] = item.host_path\n temp_dict['create_time'] = item.create_time\n re_list.append(temp_dict)\n\n print(re_list)\n return render_mako_context(request,\n '/home_application/host_disk.html',\n {'host_all': re_list}\n )\n\n\ndef host_tijiao(request):\n data = request.body\n print(type(data))\n data = json.loads(data)\n\n host = HostDisk(**data)\n host.save()\n return render_json({\"status\": \"OK\"})\n\n\ndef host_script(request):\n # 根据作业id查询日志\n data = ScriptExecInfo.objects.all()\n client = get_client_by_request(request)\n script_all = list()\n for item in data:\n temp_dict = dict()\n kwargs = {}\n kwargs['bk_biz_id'] = item.bk_biz_id\n kwargs['job_instance_id'] = item.job_instance_id\n result = client.job.get_job_instance_log(kwargs)\n log_content = result['data'][0]['step_results'][0]['ip_logs'][0]['log_content']\n temp_dict['host_ip'] = item.host_ip\n temp_dict['log_content'] = log_content\n temp_dict['script_content'] = item.script_content\n temp_dict['create_time'] = item.create_time\n script_all.append(temp_dict)\n\n return render_mako_context(request,\n '/home_application/host_script.html',\n {'script_all': script_all},\n )\n\n\ndef script_tijiao(request):\n try:\n print(request.user.username)\n except Exception as e:\n print(str(e))\n data = json.loads(request.body)\n client = get_client_by_request(request)\n kwargs = {}\n result = client.cc.search_business(kwargs)\n bk_biz_id = result['data']['info'][0]['bk_biz_id']\n\n script_content = base64.b64encode(data['script_content'])\n kwargs = dict()\n kwargs['bk_biz_id'] = bk_biz_id\n kwargs['script_content'] = script_content\n kwargs[\"account\"] = \"root\"\n kwargs['ip_list'] = [{'bk_cloud_id': 0, \"ip\": data['host_ip']}]\n result = client.job.fast_execute_script(kwargs)\n\n script_dict = dict()\n script_dict[\"host_ip\"] = data['host_ip']\n script_dict[\"script_content\"] = data['script_content']\n script_dict[\"job_instance_id\"] = result['data']['job_instance_id']\n script_dict['bk_biz_id'] = bk_biz_id\n scriptexecinfo = ScriptExecInfo(**script_dict)\n scriptexecinfo.save()\n\n return render_json({\"status\": \"OK\"})\n\n\n# ####################其他\ndef other(request):\n return render_mako_context(request, '/home_application/other.html')\n\n@csrf_exempt # 注意:需要添加此装饰器\ndef upload_file(request):\n # 接收的为文件列表,需要遍历操作\n files = request.FILES\n for item in files:\n _file = files.get(item)\n print(_file.name)\n print(_file.size)\n with open('./' + str(_file.name), 'wb') as fd:\n fd.write(_file.file.read())\n return render_json({\"status\": \"OK\"})\n\n\ndef download_file(request):\n \"\"\"\n 文件下载\n :param request:\n :return: 文件response\n \"\"\"\n from django.http import FileResponse\n # 接收文件名请求\n file_name = request.GET.get('filename')\n fd = open('./' + file_name, 'rb')\n response = FileResponse(fd)\n response['Content-Type'] = 'application/octet-stream'\n response['Content-Disposition'] = 'attachment;filename=\"%s\"' % file_name\n\n return response\n"},"apis":{"kind":"string","value":"[((1175, 1205), 'blueking.component.shortcuts.get_client_by_request', 'get_client_by_request', (['request'], {}), '(request)\\n', (1196, 1205), False, 'from blueking.component.shortcuts import get_client_by_request\\n'), ((1333, 1428), 'common.mymako.render_mako_context', 'render_mako_context', (['request', '\"\"\"/home_application/home.html\"\"\"', \"{'yewu': yewu, 'AAA': u'业务列表'}\"], {}), \"(request, '/home_application/home.html', {'yewu': yewu,\\n 'AAA': u'业务列表'})\\n\", (1352, 1428), False, 'from common.mymako import render_mako_context, render_json\\n'), ((1649, 1687), 'common.mymako.render_json', 'render_json', ([\"{'1111111': 'dddddddddd'}\"], {}), \"({'1111111': 'dddddddddd'})\\n\", (1660, 1687), False, 'from common.mymako import render_mako_context, render_json\\n'), ((1750, 1814), 'common.mymako.render_mako_context', 'render_mako_context', (['request', '\"\"\"/home_application/dev_guide.html\"\"\"'], {}), \"(request, '/home_application/dev_guide.html')\\n\", (1769, 1814), False, 'from common.mymako import render_mako_context, render_json\\n'), ((1877, 1939), 'common.mymako.render_mako_context', 'render_mako_context', (['request', '\"\"\"/home_application/contact.html\"\"\"'], {}), \"(request, '/home_application/contact.html')\\n\", (1896, 1939), False, 'from common.mymako import render_mako_context, render_json\\n'), ((1974, 1998), 'json.loads', 'json.loads', (['request.body'], {}), '(request.body)\\n', (1984, 1998), False, 'import json\\n'), ((2031, 2043), 'models.TEST', 'TEST', ([], {}), '(**data)\\n', (2035, 2043), False, 'from models import TEST, HostDisk, ScriptExecInfo\\n'), ((2070, 2103), 'common.mymako.render_json', 'render_json', ([\"{'DATA': 'AAAAAAAA'}\"], {}), \"({'DATA': 'AAAAAAAA'})\\n\", (2081, 2103), False, 'from common.mymako import render_mako_context, render_json\\n'), ((2146, 2168), 'models.HostDisk.objects.all', 'HostDisk.objects.all', ([], {}), '()\\n', (2166, 2168), False, 'from models import TEST, HostDisk, ScriptExecInfo\\n'), ((2535, 2627), 'common.mymako.render_mako_context', 'render_mako_context', (['request', '\"\"\"/home_application/host_disk.html\"\"\"', \"{'host_all': re_list}\"], {}), \"(request, '/home_application/host_disk.html', {\\n 'host_all': re_list})\\n\", (2554, 2627), False, 'from common.mymako import render_mako_context, render_json\\n'), ((2802, 2818), 'json.loads', 'json.loads', (['data'], {}), '(data)\\n', (2812, 2818), False, 'import json\\n'), ((2831, 2847), 'models.HostDisk', 'HostDisk', ([], {}), '(**data)\\n', (2839, 2847), False, 'from models import TEST, HostDisk, ScriptExecInfo\\n'), ((2875, 2904), 'common.mymako.render_json', 'render_json', ([\"{'status': 'OK'}\"], {}), \"({'status': 'OK'})\\n\", (2886, 2904), False, 'from common.mymako import render_mako_context, render_json\\n'), ((2961, 2989), 'models.ScriptExecInfo.objects.all', 'ScriptExecInfo.objects.all', ([], {}), '()\\n', (2987, 2989), False, 'from models import TEST, HostDisk, ScriptExecInfo\\n'), ((3003, 3033), 'blueking.component.shortcuts.get_client_by_request', 'get_client_by_request', (['request'], {}), '(request)\\n', (3024, 3033), False, 'from blueking.component.shortcuts import get_client_by_request\\n'), ((3624, 3723), 'common.mymako.render_mako_context', 'render_mako_context', (['request', '\"\"\"/home_application/host_script.html\"\"\"', \"{'script_all': script_all}\"], {}), \"(request, '/home_application/host_script.html', {\\n 'script_all': script_all})\\n\", (3643, 3723), False, 'from common.mymako import render_mako_context, render_json\\n'), ((3950, 3974), 'json.loads', 'json.loads', (['request.body'], {}), '(request.body)\\n', (3960, 3974), False, 'import json\\n'), ((3988, 4018), 'blueking.component.shortcuts.get_client_by_request', 'get_client_by_request', (['request'], {}), '(request)\\n', (4009, 4018), False, 'from blueking.component.shortcuts import get_client_by_request\\n'), ((4159, 4199), 'base64.b64encode', 'base64.b64encode', ([\"data['script_content']\"], {}), \"(data['script_content'])\\n\", (4175, 4199), False, 'import base64\\n'), ((4716, 4745), 'models.ScriptExecInfo', 'ScriptExecInfo', ([], {}), '(**script_dict)\\n', (4730, 4745), False, 'from models import TEST, HostDisk, ScriptExecInfo\\n'), ((4784, 4813), 'common.mymako.render_json', 'render_json', ([\"{'status': 'OK'}\"], {}), \"({'status': 'OK'})\\n\", (4795, 4813), False, 'from common.mymako import render_mako_context, render_json\\n'), ((4872, 4932), 'common.mymako.render_mako_context', 'render_mako_context', (['request', '\"\"\"/home_application/other.html\"\"\"'], {}), \"(request, '/home_application/other.html')\\n\", (4891, 4932), False, 'from common.mymako import render_mako_context, render_json\\n'), ((5249, 5278), 'common.mymako.render_json', 'render_json', ([\"{'status': 'OK'}\"], {}), \"({'status': 'OK'})\\n\", (5260, 5278), False, 'from common.mymako import render_mako_context, render_json\\n'), ((5530, 5546), 'django.http.FileResponse', 'FileResponse', (['fd'], {}), '(fd)\\n', (5542, 5546), False, 'from django.http import FileResponse\\n')]"}}},{"rowIdx":8412,"cells":{"repo_name":{"kind":"string","value":"moseskim/Expert-Python-Programming-Fourth-Edition"},"repo_path":{"kind":"string","value":"Chapter 6/09 - The built-in multiprocessing module/basic_multiprocessing.py"},"repo_head_hexsha":{"kind":"string","value":"5160f974deb2365597b7be9cc032f24bfa13471a"},"content":{"kind":"string","value":"\"\"\"\n\"멀티프로세싱\"절 예시\n`multiprocessing` 모듈을 이용해 새로운 프로세스들을\n생성하는 방법을 설명한다.\n\"\"\"\nfrom multiprocessing import Process\nimport os\n\n\ndef work(identifier):\n print(f'Hey, I am the process ' f'{identifier}, pid: {os.getpid()}')\n\n\ndef main():\n processes = [Process(target=work, args=(number,)) for number in range(5)]\n for process in processes:\n process.start()\n\n while processes:\n processes.pop().join()\n\n\nif __name__ == \"__main__\":\n main()\n"},"apis":{"kind":"string","value":"[((247, 283), 'multiprocessing.Process', 'Process', ([], {'target': 'work', 'args': '(number,)'}), '(target=work, args=(number,))\\n', (254, 283), False, 'from multiprocessing import Process\\n'), ((154, 165), 'os.getpid', 'os.getpid', ([], {}), '()\\n', (163, 165), False, 'import os\\n')]"}}},{"rowIdx":8413,"cells":{"repo_name":{"kind":"string","value":"dominoFire/sweeper"},"repo_path":{"kind":"string","value":"sweeper/cloud/localhost/manager.py"},"repo_head_hexsha":{"kind":"string","value":"26c5497b81c8d0c50671f8ab75c1cf5c4c8191c9"},"content":{"kind":"string","value":"__author__ = '@dominofire'\n\nimport os\n\nfrom sweeper.cloud import resource_config_combinations\nfrom sweeper.cloud.localhost import resource_config_factory as config_factory\nfrom sweeper.resource import Resource\n\n\ndef possible_configs(num):\n configs = config_factory.list_configs()\n combs = resource_config_combinations(num, configs)\n\n return combs\n\n\ndef create_resource(name, config_object):\n res = Resource(config_object, name, 'localhost', None, None)\n\n return res\n\n\ndef mount_distributed_file_system(name, vm_resources):\n vm_first = vm_resources[0]\n vm_first.execute_command('mkdir ./fileshare')\n\n return os.path.join(os.getcwd(), 'fileshare')\n"},"apis":{"kind":"string","value":"[((253, 282), 'sweeper.cloud.localhost.resource_config_factory.list_configs', 'config_factory.list_configs', ([], {}), '()\\n', (280, 282), True, 'from sweeper.cloud.localhost import resource_config_factory as config_factory\\n'), ((295, 337), 'sweeper.cloud.resource_config_combinations', 'resource_config_combinations', (['num', 'configs'], {}), '(num, configs)\\n', (323, 337), False, 'from sweeper.cloud import resource_config_combinations\\n'), ((410, 464), 'sweeper.resource.Resource', 'Resource', (['config_object', 'name', '\"\"\"localhost\"\"\"', 'None', 'None'], {}), \"(config_object, name, 'localhost', None, None)\\n\", (418, 464), False, 'from sweeper.resource import Resource\\n'), ((644, 655), 'os.getcwd', 'os.getcwd', ([], {}), '()\\n', (653, 655), False, 'import os\\n')]"}}},{"rowIdx":8414,"cells":{"repo_name":{"kind":"string","value":"BACtaki/tfx"},"repo_path":{"kind":"string","value":"tfx/orchestration/experimental/core/service_jobs_test.py"},"repo_head_hexsha":{"kind":"string","value":"29db845200beccbb0ffa1e1e1a091e314a3a470f"},"content":{"kind":"string","value":"# Copyright 2021 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for tfx.orchestration.experimental.core.service_jobs.\"\"\"\n\nfrom absl.testing.absltest import mock\nimport tensorflow as tf\nfrom tfx.orchestration.experimental.core import service_jobs\nfrom tfx.orchestration.experimental.core import test_utils\n\n\nclass ExceptionHandlingServiceJobManagerWrapperTest(test_utils.TfxTest):\n\n def setUp(self):\n super().setUp()\n self._mock_service_job_manager = mock.create_autospec(\n service_jobs.ServiceJobManager, instance=True)\n self._mock_service_job_manager.ensure_node_services.return_value = (\n service_jobs.ServiceStatus.SUCCESS)\n self._mock_service_job_manager.stop_node_services.return_value = True\n self._mock_service_job_manager.is_pure_service_node.return_value = True\n self._mock_service_job_manager.is_mixed_service_node.return_value = False\n self._wrapper = service_jobs.ExceptionHandlingServiceJobManagerWrapper(\n self._mock_service_job_manager)\n\n def test_calls_forwarded_to_underlying_instance(self):\n self.assertEqual(service_jobs.ServiceStatus.SUCCESS,\n self._wrapper.ensure_node_services(mock.Mock(), 'node1'))\n self.assertTrue(self._wrapper.stop_node_services(mock.Mock(), 'node2'))\n self.assertTrue(self._wrapper.is_pure_service_node(mock.Mock(), 'node3'))\n self.assertFalse(self._wrapper.is_mixed_service_node(mock.Mock(), 'node4'))\n self._mock_service_job_manager.ensure_node_services.assert_called_once_with(\n mock.ANY, 'node1')\n self._mock_service_job_manager.stop_node_services.assert_called_once_with(\n mock.ANY, 'node2')\n self._mock_service_job_manager.is_pure_service_node.assert_called_once_with(\n mock.ANY, 'node3')\n self._mock_service_job_manager.is_mixed_service_node.assert_called_once_with(\n mock.ANY, 'node4')\n\n def test_ensure_node_services_exception_handling(self):\n self._mock_service_job_manager.ensure_node_services.side_effect = RuntimeError(\n 'test error')\n self.assertEqual(service_jobs.ServiceStatus.FAILED,\n self._wrapper.ensure_node_services(mock.Mock(), 'node1'))\n self._mock_service_job_manager.ensure_node_services.assert_called_once_with(\n mock.ANY, 'node1')\n\n def test_stop_node_services_exception_handling(self):\n self._mock_service_job_manager.stop_node_services.side_effect = RuntimeError(\n 'test error')\n self.assertFalse(self._wrapper.stop_node_services(mock.Mock(), 'node2'))\n self._mock_service_job_manager.stop_node_services.assert_called_once_with(\n mock.ANY, 'node2')\n\n\nif __name__ == '__main__':\n tf.test.main()\n"},"apis":{"kind":"string","value":"[((3178, 3192), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\\n', (3190, 3192), True, 'import tensorflow as tf\\n'), ((998, 1065), 'absl.testing.absltest.mock.create_autospec', 'mock.create_autospec', (['service_jobs.ServiceJobManager'], {'instance': '(True)'}), '(service_jobs.ServiceJobManager, instance=True)\\n', (1018, 1065), False, 'from absl.testing.absltest import mock\\n'), ((1440, 1531), 'tfx.orchestration.experimental.core.service_jobs.ExceptionHandlingServiceJobManagerWrapper', 'service_jobs.ExceptionHandlingServiceJobManagerWrapper', (['self._mock_service_job_manager'], {}), '(self.\\n _mock_service_job_manager)\\n', (1494, 1531), False, 'from tfx.orchestration.experimental.core import service_jobs\\n'), ((1707, 1718), 'absl.testing.absltest.mock.Mock', 'mock.Mock', ([], {}), '()\\n', (1716, 1718), False, 'from absl.testing.absltest import mock\\n'), ((1783, 1794), 'absl.testing.absltest.mock.Mock', 'mock.Mock', ([], {}), '()\\n', (1792, 1794), False, 'from absl.testing.absltest import mock\\n'), ((1861, 1872), 'absl.testing.absltest.mock.Mock', 'mock.Mock', ([], {}), '()\\n', (1870, 1872), False, 'from absl.testing.absltest import mock\\n'), ((1941, 1952), 'absl.testing.absltest.mock.Mock', 'mock.Mock', ([], {}), '()\\n', (1950, 1952), False, 'from absl.testing.absltest import mock\\n'), ((2672, 2683), 'absl.testing.absltest.mock.Mock', 'mock.Mock', ([], {}), '()\\n', (2681, 2683), False, 'from absl.testing.absltest import mock\\n'), ((3018, 3029), 'absl.testing.absltest.mock.Mock', 'mock.Mock', ([], {}), '()\\n', (3027, 3029), False, 'from absl.testing.absltest import mock\\n')]"}}},{"rowIdx":8415,"cells":{"repo_name":{"kind":"string","value":"kundajelab/dragonn"},"repo_path":{"kind":"string","value":"dragonn/models.py"},"repo_head_hexsha":{"kind":"string","value":"431e7c6b94a82972ac0fc3ef76d76e9ce8ba67fc"},"content":{"kind":"string","value":"from __future__ import absolute_import, division, print_function\nimport matplotlib\nimport numpy as np\nimport os\nimport subprocess\nimport sys\nimport tempfile\nmatplotlib.use('pdf')\nimport matplotlib.pyplot as plt\nfrom abc import abstractmethod, ABCMeta\nfrom dragonn.metrics import ClassificationResult\nfrom sklearn.svm import SVC as scikit_SVC\nfrom sklearn.tree import DecisionTreeClassifier as scikit_DecisionTree\nfrom sklearn.ensemble import RandomForestClassifier\nfrom keras.models import load_model\nfrom dragonn.runtime_metrics import *\nfrom dragonn.custom_losses import * \nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef load_dragonn_model(model_string):\n custom_objects={\"recall\":recall,\n \"sensitivity\":recall,\n \"specificity\":specificity,\n \"fpr\":fpr,\n \"fnr\":fnr,\n \"fdr\":fdr,\n \"precision\":precision,\n \"f1\":f1,\n \"spearman_corr\":spearman_corr,\n \"ambig_binary_crossentropy\":ambig_binary_crossentropy,\n \"ambig_mean_squared_error\":ambig_mean_squared_error} \n model=load_model(model_string,custom_objects=custom_objects)\n return model\n\n\nclass Model(object):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def __init__(self, **hyperparameters):\n pass\n\n @abstractmethod\n def train(self, X, y, validation_data):\n pass\n\n @abstractmethod\n def predict(self, X):\n pass\n\n def test(self, X, y):\n return ClassificationResult(y, self.predict(X))\n\n def score(self, X, y, metric):\n return self.test(X, y)[metric]\n\n\nclass SequenceDNN(Model):\n \"\"\"\n Sequence DNN models.\n\n Parameters\n ----------\n seq_length : int, optional\n length of input sequence.\n keras_model : instance of keras.models.Sequential, optional\n seq_length or keras_model must be specified.\n num_tasks : int, optional\n number of tasks. Default: 1.\n num_filters : list[int] | tuple[int]\n number of convolutional filters in each layer. Default: (15,).\n conv_width : list[int] | tuple[int]\n width of each layer's convolutional filters. Default: (15,).\n pool_width : int\n width of max pooling after the last layer. Default: 35.\n L1 : float\n strength of L1 penalty.\n dropout : float\n dropout probability in every convolutional layer. Default: 0.\n verbose: int\n Verbosity level during training. Valida values: 0, 1, 2.\n\n Returns\n -------\n Compiled DNN model.\n \"\"\"\n\n def __init__(self, seq_length=None, keras_model=None,\n use_RNN=False, num_tasks=1,\n num_filters=(15, 15, 15), conv_width=(15, 15, 15),\n pool_width=35, GRU_size=35, TDD_size=15,\n L1=0, dropout=0.0, num_epochs=100, verbose=1):\n from keras.models import Sequential\n from keras.layers.core import (\n Activation, Dense, Dropout, Flatten,\n Permute, Reshape\n )\n from keras.layers.convolutional import Convolution2D, MaxPooling2D\n from keras.layers.recurrent import GRU\n from keras.regularizers import l1\n self.num_tasks = num_tasks\n self.num_epochs = num_epochs\n self.verbose = verbose\n self.train_metrics = []\n self.valid_metrics = []\n if keras_model is not None and seq_length is None:\n self.model = keras_model\n self.num_tasks = keras_model.layers[-1].output_shape[-1]\n elif seq_length is not None and keras_model is None:\n self.model = Sequential()\n assert len(num_filters) == len(conv_width)\n for i, (nb_filter, nb_col) in enumerate(zip(num_filters, conv_width)):\n conv_height = 4 if i == 0 else 1\n self.model.add(Convolution2D(\n nb_filter=nb_filter, nb_row=conv_height,\n nb_col=nb_col, activation='linear',\n init='he_normal', input_shape=(1, 4, seq_length),\n W_regularizer=l1(L1), b_regularizer=l1(L1)))\n self.model.add(Activation('relu'))\n self.model.add(Dropout(dropout))\n self.model.add(MaxPooling2D(pool_size=(1, pool_width)))\n if use_RNN:\n num_max_pool_outputs = self.model.layers[-1].output_shape[-1]\n self.model.add(Reshape((num_filters[-1], num_max_pool_outputs)))\n self.model.add(Permute((2, 1)))\n self.model.add(GRU(GRU_size, return_sequences=True))\n self.model.add(TimeDistributedDense(TDD_size, activation='relu'))\n self.model.add(Flatten())\n self.model.add(Dense(output_dim=self.num_tasks))\n self.model.add(Activation('sigmoid'))\n self.model.compile(optimizer='adam', loss='binary_crossentropy')\n else:\n raise ValueError(\"Exactly one of seq_length or keras_model must be specified!\")\n\n def train(self, X, y, validation_data, early_stopping_metric='Loss',\n early_stopping_patience=5, save_best_model_to_prefix=None):\n if y.dtype != bool:\n assert set(np.unique(y)) == {0, 1}\n y = y.astype(bool)\n multitask = y.shape[1] > 1\n if not multitask:\n num_positives = y.sum()\n num_sequences = len(y)\n num_negatives = num_sequences - num_positives\n if self.verbose >= 1:\n print('Training model (* indicates new best result)...')\n X_valid, y_valid = validation_data\n early_stopping_wait = 0\n best_metric = np.inf if early_stopping_metric == 'Loss' else -np.inf\n for epoch in range(1, self.num_epochs + 1):\n self.model.fit(X, y, batch_size=128, nb_epoch=1,\n class_weight={True: num_sequences / num_positives,\n False: num_sequences / num_negatives}\n if not multitask else None, verbose=self.verbose >= 2)\n epoch_train_metrics = self.test(X, y)\n epoch_valid_metrics = self.test(X_valid, y_valid)\n self.train_metrics.append(epoch_train_metrics)\n self.valid_metrics.append(epoch_valid_metrics)\n if self.verbose >= 1:\n print('Epoch {}:'.format(epoch))\n print('Train {}'.format(epoch_train_metrics))\n print('Valid {}'.format(epoch_valid_metrics), end='')\n current_metric = epoch_valid_metrics[early_stopping_metric].mean()\n if (early_stopping_metric == 'Loss') == (current_metric <= best_metric):\n if self.verbose >= 1:\n print(' *')\n best_metric = current_metric\n best_epoch = epoch\n early_stopping_wait = 0\n if save_best_model_to_prefix is not None:\n self.save(save_best_model_to_prefix)\n else:\n if self.verbose >= 1:\n print()\n if early_stopping_wait >= early_stopping_patience:\n break\n early_stopping_wait += 1\n if self.verbose >= 1:\n print('Finished training after {} epochs.'.format(epoch))\n if save_best_model_to_prefix is not None:\n print(\"The best model's architecture and weights (from epoch {0}) \"\n 'were saved to {1}.arch.json and {1}.weights.h5'.format(\n best_epoch, save_best_model_to_prefix))\n\n def predict(self, X):\n return self.model.predict(X, batch_size=128, verbose=False)\n\n def get_sequence_filters(self):\n \"\"\"\n Returns 3D array of 2D sequence filters.\n \"\"\"\n return self.model.layers[0].get_weights()[0].squeeze(axis=1)\n\n\n\n @staticmethod\n def _plot_scores(X, output_directory, peak_width, score_func, score_name):\n from dragonn.plot import plot_bases_on_ax\n scores = score_func(X).squeeze(axis=2) # (num_task, num_samples, num_bases, sequence_length)\n try:\n os.makedirs(output_directory)\n except OSError:\n pass\n num_tasks = len(scores)\n for task_index, task_scores in enumerate(scores):\n for sequence_index, sequence_scores in enumerate(task_scores):\n # sequence_scores is num_bases x sequence_length\n basewise_max_sequence_scores = sequence_scores.max(axis=0)\n plt.clf()\n figure, (top_axis, bottom_axis) = plt.subplots(2)\n top_axis.plot(range(1, len(basewise_max_sequence_scores) + 1),\n basewise_max_sequence_scores)\n top_axis.set_title('{} scores (motif highlighted)'.format(score_name))\n peak_position = basewise_max_sequence_scores.argmax()\n top_axis.axvspan(peak_position - peak_width, peak_position + peak_width,\n color='grey', alpha=0.1)\n peak_sequence_scores = sequence_scores[:, peak_position - peak_width :\n peak_position + peak_width].T\n # Set non-max letter_heights to zero\n letter_heights = np.zeros_like(peak_sequence_scores)\n letter_heights[np.arange(len(letter_heights)),\n peak_sequence_scores.argmax(axis=1)] = \\\n basewise_max_sequence_scores[peak_position - peak_width :\n peak_position + peak_width]\n plot_bases_on_ax(letter_heights, bottom_axis)\n bottom_axis.set_xticklabels(tuple(map(\n str, np.arange(peak_position - peak_width, peak_position + peak_width + 1))))\n bottom_axis.tick_params(axis='x', labelsize='small')\n plt.xlabel('Position')\n plt.ylabel('Score')\n plt.savefig(os.path.join(output_directory, 'sequence_{}{}'.format(\n sequence_index, '_task_{}'.format(task_index) if num_tasks > 1 else '')))\n plt.close()\n\n def plot_deeplift(self, X, output_directory, peak_width=10):\n self._plot_scores(X, output_directory, peak_width,\n score_func=self.deeplift, score_name='DeepLift')\n\n def plot_in_silico_mutagenesis(self, X, output_directory, peak_width=10):\n self._plot_scores(X, output_directory, peak_width,\n score_func=self.in_silico_mutagenesis, score_name='ISM')\n\n def plot_architecture(self, output_file):\n from dragonn.visualize_util import plot as plot_keras_model\n plot_keras_model(self.model, output_file, show_shape=True)\n\n def save(self, save_best_model_to_prefix):\n arch_fname = save_best_model_to_prefix + '.arch.json'\n weights_fname = save_best_model_to_prefix + '.weights.h5'\n open(arch_fname, 'w').write(self.model.to_json())\n self.model.save_weights(weights_fname, overwrite=True)\n\n @staticmethod\n def load(model_hdf5_fname=None, arch_fname=None, weights_fname=None):\n if model_hdf5_fname!=None:\n from keras.models import load_model\n sequence_dnn=SequenceDNN(keras_model=load_model(model_hdf5_fname))\n else:\n from keras.models import model_from_json\n model_json_string = open(arch_fname).read()\n sequence_dnn = SequenceDNN(keras_model=model_from_json(model_json_string))\n if weights_fname is not None:\n sequence_dnn.model.load_weights(weights_fname)\n return sequence_dnn\n\nclass MotifScoreRNN(Model):\n\n def __init__(self, input_shape, gru_size=10, tdd_size=4):\n from keras.models import Sequential\n from keras.layers.core import (\n Activation, Dense, Flatten, TimeDistributedDense\n )\n from keras.layers.recurrent import GRU\n self.model = Sequential()\n self.model.add(GRU(gru_size, return_sequences=True,\n input_shape=input_shape))\n if tdd_size is not None:\n self.model.add(TimeDistributedDense(tdd_size))\n self.model.add(Flatten())\n self.model.add(Dense(1))\n self.model.add(Activation('sigmoid'))\n print('Compiling model...')\n self.model.compile(optimizer='adam', loss='binary_crossentropy')\n\n def train(self, X, y, validation_data):\n from keras.callbacks import EarlyStopping\n print('Training model...')\n multitask = y.shape[1] > 1\n if not multitask:\n num_positives = y.sum()\n num_sequences = len(y)\n num_negatives = num_sequences - num_positives\n self.model.fit(\n X, y, batch_size=128, nb_epoch=100,\n validation_data=validation_data,\n class_weight={True: num_sequences / num_positives,\n False: num_sequences / num_negatives}\n if not multitask else None,\n callbacks=[EarlyStopping(monitor='val_loss', patience=10)],\n verbose=True)\n\n def predict(self, X):\n return self.model.predict(X, batch_size=128, verbose=False)\n\n\nclass gkmSVM(Model):\n\n def __init__(self, prefix='./gkmSVM', word_length=11, mismatches=3, C=1,\n threads=1, cache_memory=100, verbosity=4):\n self.word_length = word_length\n self.mismatches = mismatches\n self.C = C\n self.threads = threads\n self.prefix = '_'.join(map(str, (prefix, word_length, mismatches, C)))\n options_list = zip(\n ['-l', '-d', '-c', '-T', '-m', '-v'],\n map(str, (word_length, mismatches, C, threads, cache_memory, verbosity)))\n self.options = ' '.join([' '.join(option) for option in options_list])\n\n @property\n def model_file(self):\n model_fname = '{}.model.txt'.format(self.prefix)\n return model_fname if os.path.isfile(model_fname) else None\n\n @staticmethod\n def encode_sequence_into_fasta_file(sequence_iterator, ofname):\n \"\"\"writes sequences into fasta file\n \"\"\"\n with open(ofname, \"w\") as wf:\n for i, seq in enumerate(sequence_iterator):\n print('>{}'.format(i), file=wf)\n print(seq, file=wf)\n\n def train(self, X, y, validation_data=None):\n \"\"\"\n Trains gkm-svm, saves model file.\n \"\"\"\n y = y.squeeze()\n pos_sequence = X[y]\n neg_sequence = X[~y]\n pos_fname = \"%s.pos_seq.fa\" % self.prefix\n neg_fname = \"%s.neg_seq.fa\" % self.prefix\n # create temporary fasta files\n self.encode_sequence_into_fasta_file(pos_sequence, pos_fname)\n self.encode_sequence_into_fasta_file(neg_sequence, neg_fname)\n # run command\n command = ' '.join(\n ('gkmtrain', self.options, pos_fname, neg_fname, self.prefix))\n process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)\n process.wait() # wait for it to finish\n # remove fasta files\n os.system(\"rm %s\" % pos_fname)\n os.system(\"rm %s\" % neg_fname)\n\n def predict(self, X):\n if self.model_file is None:\n raise RuntimeError(\"GkmSvm hasn't been trained!\")\n # write test fasta file\n test_fname = \"%s.test.fa\" % self.prefix\n self.encode_sequence_into_fasta_file(X, test_fname)\n # test gkmsvm\n temp_ofp = tempfile.NamedTemporaryFile()\n threads_option = '-T %s' % (str(self.threads))\n command = ' '.join(['gkmpredict',\n test_fname,\n self.model_file,\n temp_ofp.name,\n threads_option])\n process = subprocess.Popen(command, shell=True)\n process.wait() # wait for it to finish\n os.system(\"rm %s\" % test_fname) # remove fasta file\n # get classification results\n temp_ofp.seek(0)\n y = np.array([line.split()[-1] for line in temp_ofp], dtype=float)\n temp_ofp.close()\n return np.expand_dims(y, 1)\n\n\nclass SVC(Model):\n\n def __init__(self):\n self.classifier = scikit_SVC(probability=True, kernel='linear')\n\n def train(self, X, y, validation_data=None):\n self.classifier.fit(X, y)\n\n def predict(self, X):\n return self.classifier.predict_proba(X)[:, 1:]\n\n\nclass DecisionTree(Model):\n\n def __init__(self):\n self.classifier = scikit_DecisionTree()\n\n def train(self, X, y, validation_data=None):\n self.classifier.fit(X, y)\n\n def predict(self, X):\n predictions = np.asarray(self.classifier.predict_proba(X))[..., 1]\n if len(predictions.shape) == 2: # multitask\n predictions = predictions.T\n else: # single-task\n predictions = np.expand_dims(predictions, 1)\n return predictions\n\n\nclass RandomForest(DecisionTree):\n\n def __init__(self):\n self.classifier = RandomForestClassifier(n_estimators=100)\n"},"apis":{"kind":"string","value":"[((157, 178), 'matplotlib.use', 'matplotlib.use', (['\"\"\"pdf\"\"\"'], {}), \"('pdf')\\n\", (171, 178), False, 'import matplotlib\\n'), ((592, 625), 'warnings.filterwarnings', 'warnings.filterwarnings', (['\"\"\"ignore\"\"\"'], {}), \"('ignore')\\n\", (615, 625), False, 'import warnings\\n'), ((1169, 1224), 'keras.models.load_model', 'load_model', (['model_string'], {'custom_objects': 'custom_objects'}), '(model_string, custom_objects=custom_objects)\\n', (1179, 1224), False, 'from keras.models import load_model\\n'), ((10729, 10787), 'dragonn.visualize_util.plot', 'plot_keras_model', (['self.model', 'output_file'], {'show_shape': '(True)'}), '(self.model, output_file, show_shape=True)\\n', (10745, 10787), True, 'from dragonn.visualize_util import plot as plot_keras_model\\n'), ((11998, 12010), 'keras.models.Sequential', 'Sequential', ([], {}), '()\\n', (12008, 12010), False, 'from keras.models import Sequential\\n'), ((14950, 15011), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdout': 'subprocess.PIPE', 'shell': '(True)'}), '(command, stdout=subprocess.PIPE, shell=True)\\n', (14966, 15011), False, 'import subprocess\\n'), ((15097, 15127), 'os.system', 'os.system', ([\"('rm %s' % pos_fname)\"], {}), \"('rm %s' % pos_fname)\\n\", (15106, 15127), False, 'import os\\n'), ((15136, 15166), 'os.system', 'os.system', ([\"('rm %s' % neg_fname)\"], {}), \"('rm %s' % neg_fname)\\n\", (15145, 15166), False, 'import os\\n'), ((15473, 15502), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\\n', (15500, 15502), False, 'import tempfile\\n'), ((15791, 15828), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'shell': '(True)'}), '(command, shell=True)\\n', (15807, 15828), False, 'import subprocess\\n'), ((15885, 15916), 'os.system', 'os.system', ([\"('rm %s' % test_fname)\"], {}), \"('rm %s' % test_fname)\\n\", (15894, 15916), False, 'import os\\n'), ((16115, 16135), 'numpy.expand_dims', 'np.expand_dims', (['y', '(1)'], {}), '(y, 1)\\n', (16129, 16135), True, 'import numpy as np\\n'), ((16207, 16252), 'sklearn.svm.SVC', 'scikit_SVC', ([], {'probability': '(True)', 'kernel': '\"\"\"linear\"\"\"'}), \"(probability=True, kernel='linear')\\n\", (16217, 16252), True, 'from sklearn.svm import SVC as scikit_SVC\\n'), ((16499, 16520), 'sklearn.tree.DecisionTreeClassifier', 'scikit_DecisionTree', ([], {}), '()\\n', (16518, 16520), True, 'from sklearn.tree import DecisionTreeClassifier as scikit_DecisionTree\\n'), ((17000, 17040), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(100)'}), '(n_estimators=100)\\n', (17022, 17040), False, 'from sklearn.ensemble import RandomForestClassifier\\n'), ((8123, 8152), 'os.makedirs', 'os.makedirs', (['output_directory'], {}), '(output_directory)\\n', (8134, 8152), False, 'import os\\n'), ((12034, 12095), 'keras.layers.recurrent.GRU', 'GRU', (['gru_size'], {'return_sequences': '(True)', 'input_shape': 'input_shape'}), '(gru_size, return_sequences=True, input_shape=input_shape)\\n', (12037, 12095), False, 'from keras.layers.recurrent import GRU\\n'), ((12239, 12248), 'keras.layers.core.Flatten', 'Flatten', ([], {}), '()\\n', (12246, 12248), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((12273, 12281), 'keras.layers.core.Dense', 'Dense', (['(1)'], {}), '(1)\\n', (12278, 12281), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((12306, 12327), 'keras.layers.core.Activation', 'Activation', (['\"\"\"sigmoid\"\"\"'], {}), \"('sigmoid')\\n\", (12316, 12327), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((13972, 13999), 'os.path.isfile', 'os.path.isfile', (['model_fname'], {}), '(model_fname)\\n', (13986, 13999), False, 'import os\\n'), ((16855, 16885), 'numpy.expand_dims', 'np.expand_dims', (['predictions', '(1)'], {}), '(predictions, 1)\\n', (16869, 16885), True, 'import numpy as np\\n'), ((3636, 3648), 'keras.models.Sequential', 'Sequential', ([], {}), '()\\n', (3646, 3648), False, 'from keras.models import Sequential\\n'), ((8515, 8524), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\\n', (8522, 8524), True, 'import matplotlib.pyplot as plt\\n'), ((8575, 8590), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\\n', (8587, 8590), True, 'import matplotlib.pyplot as plt\\n'), ((9295, 9330), 'numpy.zeros_like', 'np.zeros_like', (['peak_sequence_scores'], {}), '(peak_sequence_scores)\\n', (9308, 9330), True, 'import numpy as np\\n'), ((9637, 9682), 'dragonn.plot.plot_bases_on_ax', 'plot_bases_on_ax', (['letter_heights', 'bottom_axis'], {}), '(letter_heights, bottom_axis)\\n', (9653, 9682), False, 'from dragonn.plot import plot_bases_on_ax\\n'), ((9921, 9943), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['\"\"\"Position\"\"\"'], {}), \"('Position')\\n\", (9931, 9943), True, 'import matplotlib.pyplot as plt\\n'), ((9960, 9979), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['\"\"\"Score\"\"\"'], {}), \"('Score')\\n\", (9970, 9979), True, 'import matplotlib.pyplot as plt\\n'), ((10173, 10184), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\\n', (10182, 10184), True, 'import matplotlib.pyplot as plt\\n'), ((12184, 12214), 'keras.layers.core.TimeDistributedDense', 'TimeDistributedDense', (['tdd_size'], {}), '(tdd_size)\\n', (12204, 12214), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((4261, 4300), 'keras.layers.convolutional.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(1, pool_width)'}), '(pool_size=(1, pool_width))\\n', (4273, 4300), False, 'from keras.layers.convolutional import Convolution2D, MaxPooling2D\\n'), ((4711, 4720), 'keras.layers.core.Flatten', 'Flatten', ([], {}), '()\\n', (4718, 4720), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((4749, 4781), 'keras.layers.core.Dense', 'Dense', ([], {'output_dim': 'self.num_tasks'}), '(output_dim=self.num_tasks)\\n', (4754, 4781), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((4810, 4831), 'keras.layers.core.Activation', 'Activation', (['\"\"\"sigmoid\"\"\"'], {}), \"('sigmoid')\\n\", (4820, 4831), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((5215, 5227), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\\n', (5224, 5227), True, 'import numpy as np\\n'), ((11310, 11338), 'keras.models.load_model', 'load_model', (['model_hdf5_fname'], {}), '(model_hdf5_fname)\\n', (11320, 11338), False, 'from keras.models import load_model\\n'), ((11514, 11548), 'keras.models.model_from_json', 'model_from_json', (['model_json_string'], {}), '(model_json_string)\\n', (11529, 11548), False, 'from keras.models import model_from_json\\n'), ((13065, 13111), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '\"\"\"val_loss\"\"\"', 'patience': '(10)'}), \"(monitor='val_loss', patience=10)\\n\", (13078, 13111), False, 'from keras.callbacks import EarlyStopping\\n'), ((4165, 4183), 'keras.layers.core.Activation', 'Activation', (['\"\"\"relu\"\"\"'], {}), \"('relu')\\n\", (4175, 4183), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((4216, 4232), 'keras.layers.core.Dropout', 'Dropout', (['dropout'], {}), '(dropout)\\n', (4223, 4232), False, 'from keras.layers.core import Activation, Dense, Dropout, Flatten, Permute, Reshape\\n'), ((4435, 4483), 'keras.layers.core.Reshape', 'Reshape', (['(num_filters[-1], num_max_pool_outputs)'], {}), '((num_filters[-1], num_max_pool_outputs))\\n', (4442, 4483), False, 'from keras.layers.core import Activation, Dense, Dropout, Flatten, Permute, Reshape\\n'), ((4516, 4531), 'keras.layers.core.Permute', 'Permute', (['(2, 1)'], {}), '((2, 1))\\n', (4523, 4531), False, 'from keras.layers.core import Activation, Dense, Dropout, Flatten, Permute, Reshape\\n'), ((4564, 4600), 'keras.layers.recurrent.GRU', 'GRU', (['GRU_size'], {'return_sequences': '(True)'}), '(GRU_size, return_sequences=True)\\n', (4567, 4600), False, 'from keras.layers.recurrent import GRU\\n'), ((4633, 4682), 'keras.layers.core.TimeDistributedDense', 'TimeDistributedDense', (['TDD_size'], {'activation': '\"\"\"relu\"\"\"'}), \"(TDD_size, activation='relu')\\n\", (4653, 4682), False, 'from keras.layers.core import Activation, Dense, Flatten, TimeDistributedDense\\n'), ((9763, 9832), 'numpy.arange', 'np.arange', (['(peak_position - peak_width)', '(peak_position + peak_width + 1)'], {}), '(peak_position - peak_width, peak_position + peak_width + 1)\\n', (9772, 9832), True, 'import numpy as np\\n'), ((4103, 4109), 'keras.regularizers.l1', 'l1', (['L1'], {}), '(L1)\\n', (4105, 4109), False, 'from keras.regularizers import l1\\n'), ((4125, 4131), 'keras.regularizers.l1', 'l1', (['L1'], {}), '(L1)\\n', (4127, 4131), False, 'from keras.regularizers import l1\\n')]"}}},{"rowIdx":8416,"cells":{"repo_name":{"kind":"string","value":"haltu/velmu-mpass-demo"},"repo_path":{"kind":"string","value":"src/mpass/mpass/migrations/0001_initial.py"},"repo_head_hexsha":{"kind":"string","value":"19eb0e14fa6710e4aee5d47c898cf570bf7621e5"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n# Generated by Django 1.11.10 on 2018-03-20 08:34\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport parler.models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='AuthenticationSource',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('modified_at', models.DateTimeField(auto_now=True)),\n ('auth_id', models.CharField(max_length=128)),\n ('icon_url', models.CharField(blank=True, max_length=2048, null=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=(parler.models.TranslatableModelMixin, models.Model),\n ),\n migrations.CreateModel(\n name='AuthenticationSourceTranslation',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('language_code', models.CharField(db_index=True, max_length=15, verbose_name='Language')),\n ('title', models.CharField(max_length=2048)),\n ('master', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='translations', to='mpass.AuthenticationSource')),\n ],\n options={\n 'managed': True,\n 'db_table': 'mpass_authenticationsource_translation',\n 'db_tablespace': '',\n 'default_permissions': (),\n 'verbose_name': 'authentication source Translation',\n },\n ),\n migrations.CreateModel(\n name='AuthenticationTag',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('modified_at', models.DateTimeField(auto_now=True)),\n ('tag_id', models.CharField(max_length=128)),\n ],\n options={\n 'abstract': False,\n },\n bases=(parler.models.TranslatableModelMixin, models.Model),\n ),\n migrations.CreateModel(\n name='AuthenticationTagTranslation',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('language_code', models.CharField(db_index=True, max_length=15, verbose_name='Language')),\n ('title', models.CharField(max_length=2048)),\n ('master', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='translations', to='mpass.AuthenticationTag')),\n ],\n options={\n 'managed': True,\n 'db_table': 'mpass_authenticationtag_translation',\n 'db_tablespace': '',\n 'default_permissions': (),\n 'verbose_name': 'authentication tag Translation',\n },\n ),\n migrations.AddField(\n model_name='authenticationsource',\n name='tags',\n field=models.ManyToManyField(blank=True, to='mpass.AuthenticationTag'),\n ),\n migrations.AlterUniqueTogether(\n name='authenticationtagtranslation',\n unique_together=set([('language_code', 'master')]),\n ),\n migrations.AlterUniqueTogether(\n name='authenticationsourcetranslation',\n unique_together=set([('language_code', 'master')]),\n ),\n ]\n"},"apis":{"kind":"string","value":"[((3452, 3516), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'to': '\"\"\"mpass.AuthenticationTag\"\"\"'}), \"(blank=True, to='mpass.AuthenticationTag')\\n\", (3474, 3516), False, 'from django.db import migrations, models\\n'), ((436, 529), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '\"\"\"ID\"\"\"'}), \"(auto_created=True, primary_key=True, serialize=False,\\n verbose_name='ID')\\n\", (452, 529), False, 'from django.db import migrations, models\\n'), ((559, 598), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\\n', (579, 598), False, 'from django.db import migrations, models\\n'), ((633, 668), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\\n', (653, 668), False, 'from django.db import migrations, models\\n'), ((699, 731), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)'}), '(max_length=128)\\n', (715, 731), False, 'from django.db import migrations, models\\n'), ((763, 819), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(2048)', 'null': '(True)'}), '(blank=True, max_length=2048, null=True)\\n', (779, 819), False, 'from django.db import migrations, models\\n'), ((1120, 1213), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '\"\"\"ID\"\"\"'}), \"(auto_created=True, primary_key=True, serialize=False,\\n verbose_name='ID')\\n\", (1136, 1213), False, 'from django.db import migrations, models\\n'), ((1246, 1317), 'django.db.models.CharField', 'models.CharField', ([], {'db_index': '(True)', 'max_length': '(15)', 'verbose_name': '\"\"\"Language\"\"\"'}), \"(db_index=True, max_length=15, verbose_name='Language')\\n\", (1262, 1317), False, 'from django.db import migrations, models\\n'), ((1346, 1379), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2048)'}), '(max_length=2048)\\n', (1362, 1379), False, 'from django.db import migrations, models\\n'), ((1409, 1570), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'editable': '(False)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '\"\"\"translations\"\"\"', 'to': '\"\"\"mpass.AuthenticationSource\"\"\"'}), \"(editable=False, null=True, on_delete=django.db.models.\\n deletion.CASCADE, related_name='translations', to=\\n 'mpass.AuthenticationSource')\\n\", (1426, 1570), False, 'from django.db import migrations, models\\n'), ((1992, 2085), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '\"\"\"ID\"\"\"'}), \"(auto_created=True, primary_key=True, serialize=False,\\n verbose_name='ID')\\n\", (2008, 2085), False, 'from django.db import migrations, models\\n'), ((2115, 2154), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\\n', (2135, 2154), False, 'from django.db import migrations, models\\n'), ((2189, 2224), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\\n', (2209, 2224), False, 'from django.db import migrations, models\\n'), ((2254, 2286), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)'}), '(max_length=128)\\n', (2270, 2286), False, 'from django.db import migrations, models\\n'), ((2584, 2677), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '\"\"\"ID\"\"\"'}), \"(auto_created=True, primary_key=True, serialize=False,\\n verbose_name='ID')\\n\", (2600, 2677), False, 'from django.db import migrations, models\\n'), ((2710, 2781), 'django.db.models.CharField', 'models.CharField', ([], {'db_index': '(True)', 'max_length': '(15)', 'verbose_name': '\"\"\"Language\"\"\"'}), \"(db_index=True, max_length=15, verbose_name='Language')\\n\", (2726, 2781), False, 'from django.db import migrations, models\\n'), ((2810, 2843), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2048)'}), '(max_length=2048)\\n', (2826, 2843), False, 'from django.db import migrations, models\\n'), ((2873, 3031), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'editable': '(False)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '\"\"\"translations\"\"\"', 'to': '\"\"\"mpass.AuthenticationTag\"\"\"'}), \"(editable=False, null=True, on_delete=django.db.models.\\n deletion.CASCADE, related_name='translations', to='mpass.AuthenticationTag'\\n )\\n\", (2890, 3031), False, 'from django.db import migrations, models\\n')]"}}},{"rowIdx":8417,"cells":{"repo_name":{"kind":"string","value":"fractalego/dgt"},"repo_path":{"kind":"string","value":"dgt/inference/forward_inference.py"},"repo_head_hexsha":{"kind":"string","value":"6781b9445d93c4a1680ab3d5636803c81062cc67"},"content":{"kind":"string","value":"import logging\nimport random\n\nfrom dgt.graph.graph_matcher import GraphWeightedMatch\nfrom dgt.utils import graph_iterations\n\n_logger = logging.getLogger(__name__)\n\n\ndef find_weight_between(s, first, last):\n try:\n start = s.index(first) + len(first)\n end = s.index(last, start)\n return s[start:end]\n except ValueError:\n return 1\n\n\ndef clean_between(s, first, last):\n try:\n start = s.index(first) + len(first)\n end = s.index(last, start)\n new_s = s[:start - 1] + s[end + 1:]\n return new_s\n except ValueError:\n return s\n\n\ndef eliminate_spaces(line):\n line = line.replace(' ', '')\n line = line.replace('\\t', '')\n line = line.replace('\\n', '')\n return line\n\n\nclass UniqueNamesModifier:\n def apply(self, g):\n from ..auxiliary import get_random_name\n substitution_dict = {}\n for v in g.vs:\n random_name = get_random_name()\n old_name = v['name']\n new_name = old_name + random_name\n v['name'] = new_name\n substitution_dict[old_name] = new_name\n try:\n for v in g.vs:\n referring_name = v['refers_to']\n if referring_name:\n v['refers_to'] = substitution_dict[referring_name]\n except Exception as e:\n _logger.warning(\"Exception while substituting refers_to ID: \" + str(e))\n for e in g.es:\n e['name'] += get_random_name()\n\n\nclass BaseForwardInference:\n def compute(self):\n return None\n\n\nclass ForwardInference(BaseForwardInference):\n _unique = UniqueNamesModifier()\n\n def __init__(self, data, knowledge, permutation_shift, max_depth=1):\n self.permutations = permutation_shift\n self.data = data\n self.knowledge = knowledge\n self._max_depth = max_depth\n self.permutation_shift = permutation_shift\n\n def __apply_clause_to_graph(self, rule, data, i):\n drs = data.copy()\n drs.visit(self._unique)\n w = 1\n\n iterations = graph_iterations(drs._g)\n if not iterations:\n return drs, 0\n drs._g = iterations[self.permutations[i] % len(iterations)]\n\n if not rule.gradient:\n weighted_match = GraphWeightedMatch(rule.get_hypothesis(), self.knowledge._metric,\n self.knowledge._relations_metric)\n w = drs.visit(weighted_match)\n\n is_match = drs.visit(rule)\n if not is_match:\n return drs, 0\n return drs, w\n\n def _compute_step(self, data_tuple, i):\n \"\"\"\n Applies all the rules to a drs\n :return: all the variants of the drs after a rule match as a pair (, )\n \"\"\"\n data = data_tuple[0]\n prior_w = data_tuple[1]\n\n clauses = self.knowledge.ask_rule(data)\n results = []\n for clause_tuple in clauses:\n rule = clause_tuple[0]\n rule_weight = rule.weight\n prior_rules = list(data_tuple[2])\n if rule in prior_rules: # A rule can be used only once per path\n continue\n drs, w = self.__apply_clause_to_graph(rule, data, i)\n if w > 0:\n prior_rules.append(rule)\n prior_rules.append(drs)\n results.append((drs, prior_w * w * rule_weight, prior_rules))\n return results\n\n def compute(self):\n results = []\n to_process = [(self.data, 1, [self.data])]\n for i in range(self._max_depth):\n new_results = []\n for data_tuple in to_process:\n new_results += self._compute_step(data_tuple, i)\n if not new_results:\n break\n to_process = sorted(new_results, key=lambda x: -x[1])\n results += to_process\n results = sorted(results, key=lambda x: -x[1])\n return results\n"},"apis":{"kind":"string","value":"[((135, 162), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\\n', (152, 162), False, 'import logging\\n'), ((2049, 2073), 'dgt.utils.graph_iterations', 'graph_iterations', (['drs._g'], {}), '(drs._g)\\n', (2065, 2073), False, 'from dgt.utils import graph_iterations\\n')]"}}},{"rowIdx":8418,"cells":{"repo_name":{"kind":"string","value":"ikekilinc/dnnSuperBinoculars"},"repo_path":{"kind":"string","value":"serverPythonClient/client.py"},"repo_head_hexsha":{"kind":"string","value":"b0fc584b1d449961bdbab37cf9d72c0b466f197f"},"content":{"kind":"string","value":"import argparse\nimport cv2\n\nimport common\n# from .utils.cropAtCenter import cropImageCenter\n# from cropAtCenter import cropImageCenter\n\nfrom gabriel_client.websocket_client import WebsocketClient\nfrom gabriel_client.opencv_adapter import OpencvAdapter\n\nDEFAULT_SERVER_HOST = '128.2.212.50'\nDEFAULT_ZOOM_FACTOR = 10\n\ndef preprocess(frame):\n # return frame\n\n print(type(frame), frame.shape)\n\n width, height = frame.shape[1], frame.shape[0]\n\n left = int(width/2 * (1 - 1/DEFAULT_ZOOM_FACTOR))\n top = int(height/2 * (1 - 1/DEFAULT_ZOOM_FACTOR))\n right = int(width/2 * (1 + 1/DEFAULT_ZOOM_FACTOR))\n bottom = int(height/2 * (1 + 1/DEFAULT_ZOOM_FACTOR))\n\n cropped_frame = frame[top:bottom, left:right]\n return cropped_frame\n\n\ndef produce_extras():\n return None\n\n\ndef consume_frame(frame, _):\n cv2.imshow('Image from server', frame)\n cv2.waitKey(1)\n\n\ndef main():\n common.configure_logging()\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'source_name', nargs='?', default=common.DEFAULT_SOURCE_NAME)\n parser.add_argument('server_host', nargs='?', default=DEFAULT_SERVER_HOST)\n args = parser.parse_args()\n\n capture = cv2.VideoCapture(0)\n opencv_adapter = OpencvAdapter(\n preprocess, produce_extras, consume_frame, capture, args.source_name)\n\n client = WebsocketClient(\n args.server_host, common.WEBSOCKET_PORT,\n opencv_adapter.get_producer_wrappers(), opencv_adapter.consumer)\n client.launch()\n\n\nif __name__ == '__main__':\n main()\n"},"apis":{"kind":"string","value":"[((819, 857), 'cv2.imshow', 'cv2.imshow', (['\"\"\"Image from server\"\"\"', 'frame'], {}), \"('Image from server', frame)\\n\", (829, 857), False, 'import cv2\\n'), ((862, 876), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\\n', (873, 876), False, 'import cv2\\n'), ((895, 921), 'common.configure_logging', 'common.configure_logging', ([], {}), '()\\n', (919, 921), False, 'import common\\n'), ((935, 960), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\\n', (958, 960), False, 'import argparse\\n'), ((1181, 1200), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\\n', (1197, 1200), False, 'import cv2\\n'), ((1222, 1310), 'gabriel_client.opencv_adapter.OpencvAdapter', 'OpencvAdapter', (['preprocess', 'produce_extras', 'consume_frame', 'capture', 'args.source_name'], {}), '(preprocess, produce_extras, consume_frame, capture, args.\\n source_name)\\n', (1235, 1310), False, 'from gabriel_client.opencv_adapter import OpencvAdapter\\n')]"}}},{"rowIdx":8419,"cells":{"repo_name":{"kind":"string","value":"SharsDela/BankCardRecognize"},"repo_path":{"kind":"string","value":"src/DeepCard.API/batch.py"},"repo_head_hexsha":{"kind":"string","value":"ce80589bc5a5afaba2b97b1ccab35354fb99b548"},"content":{"kind":"string","value":"from api import get_result\nimport os\nimport shutil\nfrom glob import glob\nfrom PIL import Image\n\nif __name__ == '__main__':\n image_files = glob('./test_images/*.*')\n result_dir = './test_results'\n if os.path.exists(result_dir):\n shutil.rmtree(result_dir)\n os.mkdir(result_dir)\n\n txt_file = os.path.join(result_dir, 'result.txt')\n txt_f = open(txt_file, 'w')\n\n for image_file in sorted(image_files):\n if \".gitkeep\" in image_files:\n continue\n print(\"Finded file\", image_file, end=\" \")\n result = get_result(Image.open(image_file))\n print(\":\", result)\n txt_f.write(image_file.split('/')[-1].split('.')[0] + ':' + result + '\\n')\n \n txt_f.close()"},"apis":{"kind":"string","value":"[((141, 166), 'glob.glob', 'glob', (['\"\"\"./test_images/*.*\"\"\"'], {}), \"('./test_images/*.*')\\n\", (145, 166), False, 'from glob import glob\\n'), ((208, 234), 'os.path.exists', 'os.path.exists', (['result_dir'], {}), '(result_dir)\\n', (222, 234), False, 'import os\\n'), ((274, 294), 'os.mkdir', 'os.mkdir', (['result_dir'], {}), '(result_dir)\\n', (282, 294), False, 'import os\\n'), ((311, 349), 'os.path.join', 'os.path.join', (['result_dir', '\"\"\"result.txt\"\"\"'], {}), \"(result_dir, 'result.txt')\\n\", (323, 349), False, 'import os\\n'), ((244, 269), 'shutil.rmtree', 'shutil.rmtree', (['result_dir'], {}), '(result_dir)\\n', (257, 269), False, 'import shutil\\n'), ((563, 585), 'PIL.Image.open', 'Image.open', (['image_file'], {}), '(image_file)\\n', (573, 585), False, 'from PIL import Image\\n')]"}}},{"rowIdx":8420,"cells":{"repo_name":{"kind":"string","value":"MaximeBaudette/PyCIM"},"repo_path":{"kind":"string","value":"CIM14/ENTSOE/Equipment/Core/Curve.py"},"repo_head_hexsha":{"kind":"string","value":"d68ee5ccfc1d32d44c5cd09fb173142fb5ff4f14"},"content":{"kind":"string","value":"# Copyright (C) 2010-2011 Richard Lincoln\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n\nfrom CIM14.ENTSOE.Equipment.Core.IdentifiedObject import IdentifiedObject\n\nclass Curve(IdentifiedObject):\n \"\"\"A multi-purpose curve or functional relationship between an independent variable (X-axis) and dependent (Y-axis) variables.\n \"\"\"\n\n def __init__(self, y1Unit=\"A\", curveStyle=\"straightLineYValues\", xUnit=\"A\", CurveDatas=None, *args, **kw_args):\n \"\"\"Initialises a new 'Curve' instance.\n\n @param y1Unit: The Y1-axis units of measure. Values are: \"A\", \"rad\", \"none\", \"g\", \"W/Hz\", \"V\", \"m2\", \"VA\", \"VArh\", \"N\", \"Pa\", \"VAh\", \"F\", \"H\", \"Hz-1\", \"W/s\", \"J\", \"m\", \"S\", \"min\", \"deg\", \"J/s\", \"s\", \"Wh\", \"m3\", \"oC\", \"V/VAr\", \"s-1\", \"h\", \"W\", \"ohm\", \"Hz\", \"VAr\", \"kg/J\"\n @param curveStyle: The style or shape of the curve. Values are: \"straightLineYValues\", \"rampYValue\", \"constantYValue\", \"formula\"\n @param xUnit: The X-axis units of measure. Values are: \"A\", \"rad\", \"none\", \"g\", \"W/Hz\", \"V\", \"m2\", \"VA\", \"VArh\", \"N\", \"Pa\", \"VAh\", \"F\", \"H\", \"Hz-1\", \"W/s\", \"J\", \"m\", \"S\", \"min\", \"deg\", \"J/s\", \"s\", \"Wh\", \"m3\", \"oC\", \"V/VAr\", \"s-1\", \"h\", \"W\", \"ohm\", \"Hz\", \"VAr\", \"kg/J\"\n @param CurveDatas: The point data values that define a curve\n \"\"\"\n #: The Y1-axis units of measure. Values are: \"A\", \"rad\", \"none\", \"g\", \"W/Hz\", \"V\", \"m2\", \"VA\", \"VArh\", \"N\", \"Pa\", \"VAh\", \"F\", \"H\", \"Hz-1\", \"W/s\", \"J\", \"m\", \"S\", \"min\", \"deg\", \"J/s\", \"s\", \"Wh\", \"m3\", \"oC\", \"V/VAr\", \"s-1\", \"h\", \"W\", \"ohm\", \"Hz\", \"VAr\", \"kg/J\"\n self.y1Unit = y1Unit\n\n #: The style or shape of the curve. Values are: \"straightLineYValues\", \"rampYValue\", \"constantYValue\", \"formula\"\n self.curveStyle = curveStyle\n\n #: The X-axis units of measure. Values are: \"A\", \"rad\", \"none\", \"g\", \"W/Hz\", \"V\", \"m2\", \"VA\", \"VArh\", \"N\", \"Pa\", \"VAh\", \"F\", \"H\", \"Hz-1\", \"W/s\", \"J\", \"m\", \"S\", \"min\", \"deg\", \"J/s\", \"s\", \"Wh\", \"m3\", \"oC\", \"V/VAr\", \"s-1\", \"h\", \"W\", \"ohm\", \"Hz\", \"VAr\", \"kg/J\"\n self.xUnit = xUnit\n\n self._CurveDatas = []\n self.CurveDatas = [] if CurveDatas is None else CurveDatas\n\n super(Curve, self).__init__(*args, **kw_args)\n\n _attrs = [\"y1Unit\", \"curveStyle\", \"xUnit\"]\n _attr_types = {\"y1Unit\": str, \"curveStyle\": str, \"xUnit\": str}\n _defaults = {\"y1Unit\": \"A\", \"curveStyle\": \"straightLineYValues\", \"xUnit\": \"A\"}\n _enums = {\"y1Unit\": \"UnitSymbol\", \"curveStyle\": \"CurveStyle\", \"xUnit\": \"UnitSymbol\"}\n _refs = [\"CurveDatas\"]\n _many_refs = [\"CurveDatas\"]\n\n def getCurveDatas(self):\n \"\"\"The point data values that define a curve\n \"\"\"\n return self._CurveDatas\n\n def setCurveDatas(self, value):\n for x in self._CurveDatas:\n x.Curve = None\n for y in value:\n y._Curve = self\n self._CurveDatas = value\n\n CurveDatas = property(getCurveDatas, setCurveDatas)\n\n def addCurveDatas(self, *CurveDatas):\n for obj in CurveDatas:\n obj.Curve = self\n\n def removeCurveDatas(self, *CurveDatas):\n for obj in CurveDatas:\n obj.Curve = None\n\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8421,"cells":{"repo_name":{"kind":"string","value":"unclenachoduh/python-fluent"},"repo_path":{"kind":"string","value":"fluent/syntax/errors.py"},"repo_head_hexsha":{"kind":"string","value":"1d15bdc94a37ecb488a80aefcdd37b8cb5535f73"},"content":{"kind":"string","value":"from __future__ import unicode_literals\n\n\nclass ParseError(Exception):\n def __init__(self, code, *args):\n self.code = code\n self.args = args\n self.message = get_error_message(code, args)\n\n\ndef get_error_message(code, args):\n if code == 'E00001':\n return 'Generic error'\n if code == 'E0002':\n return 'Expected an entry start'\n if code == 'E0003':\n return 'Expected token: \"{}\"'.format(args[0])\n if code == 'E0004':\n return 'Expected a character from range: \"{}\"'.format(args[0])\n if code == 'E0005':\n msg = 'Expected message \"{}\" to have a value or attributes'\n return msg.format(args[0])\n if code == 'E0006':\n msg = 'Expected term \"{}\" to have a value'\n return msg.format(args[0])\n if code == 'E0007':\n return 'Keyword cannot end with a whitespace'\n if code == 'E0008':\n return 'The callee has to be a simple, upper-case identifier'\n if code == 'E0009':\n return 'The key has to be a simple identifier'\n if code == 'E0010':\n return 'Expected one of the variants to be marked as default (*)'\n if code == 'E0011':\n return 'Expected at least one variant after \"->\"'\n if code == 'E0012':\n return 'Expected value'\n if code == 'E0013':\n return 'Expected variant key'\n if code == 'E0014':\n return 'Expected literal'\n if code == 'E0015':\n return 'Only one variant can be marked as default (*)'\n if code == 'E0016':\n return 'Message references cannot be used as selectors'\n if code == 'E0017':\n return 'Variants cannot be used as selectors'\n if code == 'E0018':\n return 'Attributes of messages cannot be used as selectors'\n if code == 'E0019':\n return 'Attributes of terms cannot be used as placeables'\n if code == 'E0020':\n return 'Unterminated string expression'\n if code == 'E0021':\n return 'Positional arguments must not follow named arguments'\n if code == 'E0022':\n return 'Named arguments must be unique'\n if code == 'E0023':\n return 'VariantLists are only allowed inside of other VariantLists.'\n if code == 'E0024':\n return 'Cannot access variants of a message.'\n if code == 'E0025':\n return 'Unknown escape sequence: {}'.format(args[0])\n if code == 'E0026':\n return 'Invalid Unicode escape sequence: {}'.format(args[0])\n return code\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8422,"cells":{"repo_name":{"kind":"string","value":"jdddog/mag-archiver"},"repo_path":{"kind":"string","value":"tests/test_mag.py"},"repo_head_hexsha":{"kind":"string","value":"079e735e610d6b81b3ac8dc479d4f93bb0aacb11"},"content":{"kind":"string","value":"# Copyright 2020 Curtin University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Author: James Diprose\n\n\nimport os\nimport unittest\nfrom unittest.mock import patch\n\nimport pendulum\nfrom azure.common import AzureMissingResourceHttpError\nfrom azure.cosmosdb.table.tableservice import TableService\nfrom azure.storage.blob import ContainerProperties\n\nfrom mag_archiver.azure import create_table\nfrom mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, \\\n hide_if_not_none\n\n\nclass TestMag(unittest.TestCase):\n\n def test_hide_if_not_none(self):\n # Test that None is returned for None\n value = hide_if_not_none(None)\n self.assertEqual(value, None)\n\n # Test that 'hidden' is returned: string\n value = hide_if_not_none('hello world')\n self.assertEqual(value, 'hidden')\n\n # Test that 'hidden' is returned: integer\n value = hide_if_not_none(123)\n self.assertEqual(value, 'hidden')\n\n def test_make_mag_query(self):\n start_date = pendulum.datetime(year=2020, month=4, day=1)\n end_date = pendulum.datetime(year=2020, month=5, day=1)\n\n # No parameters\n query = make_mag_query()\n self.assertEqual(query, '')\n\n # State parameter\n query = make_mag_query(state=MagState.discovered)\n self.assertEqual(query, \"State eq 'discovered'\")\n\n query = make_mag_query(state=MagState.archived)\n self.assertEqual(query, \"State eq 'archived'\")\n\n query = make_mag_query(state=MagState.done)\n self.assertEqual(query, \"State eq 'done'\")\n\n # Start date parameter\n query = make_mag_query(start_date=start_date, date_type=MagDateType.release)\n self.assertEqual(query, \"ReleaseDate ge datetime'2020-04-01T00:00Z'\")\n\n query = make_mag_query(start_date=start_date, date_type=MagDateType.discovered)\n self.assertEqual(query, \"DiscoveredDate ge datetime'2020-04-01T00:00Z'\")\n\n query = make_mag_query(start_date=start_date, date_type=MagDateType.archived)\n self.assertEqual(query, \"ArchivedDate ge datetime'2020-04-01T00:00Z'\")\n\n query = make_mag_query(start_date=start_date, date_type=MagDateType.done)\n self.assertEqual(query, \"DoneDate ge datetime'2020-04-01T00:00Z'\")\n\n # End date parameter\n query = make_mag_query(end_date=end_date, date_type=MagDateType.release)\n self.assertEqual(query, \"ReleaseDate lt datetime'2020-05-01T00:00Z'\")\n\n query = make_mag_query(end_date=end_date, date_type=MagDateType.discovered)\n self.assertEqual(query, \"DiscoveredDate lt datetime'2020-05-01T00:00Z'\")\n\n query = make_mag_query(end_date=end_date, date_type=MagDateType.archived)\n self.assertEqual(query, \"ArchivedDate lt datetime'2020-05-01T00:00Z'\")\n\n query = make_mag_query(end_date=end_date, date_type=MagDateType.done)\n self.assertEqual(query, \"DoneDate lt datetime'2020-05-01T00:00Z'\")\n\n # Start date, end date and date type\n query = make_mag_query(start_date=start_date, end_date=end_date, date_type=MagDateType.release)\n self.assertEqual(query, \"ReleaseDate ge datetime'2020-04-01T00:00Z' and ReleaseDate lt \"\n \"datetime'2020-05-01T00:00Z'\")\n\n query = make_mag_query(start_date=start_date, end_date=end_date, date_type=MagDateType.discovered)\n self.assertEqual(query, \"DiscoveredDate ge datetime'2020-04-01T00:00Z' and DiscoveredDate lt \"\n \"datetime'2020-05-01T00:00Z'\")\n\n query = make_mag_query(start_date=start_date, end_date=end_date, date_type=MagDateType.archived)\n self.assertEqual(query, \"ArchivedDate ge datetime'2020-04-01T00:00Z' and ArchivedDate lt \"\n \"datetime'2020-05-01T00:00Z'\")\n\n query = make_mag_query(start_date=start_date, end_date=end_date, date_type=MagDateType.done)\n self.assertEqual(query, \"DoneDate ge datetime'2020-04-01T00:00Z' and DoneDate lt \"\n \"datetime'2020-05-01T00:00Z'\")\n\n # State, start date, end date and date type\n query = make_mag_query(state=MagState.discovered, start_date=start_date, end_date=end_date,\n date_type=MagDateType.discovered)\n self.assertEqual(query, \"State eq 'discovered' and DiscoveredDate ge datetime'2020-04-01T00:00Z' \"\n \"and DiscoveredDate lt datetime'2020-05-01T00:00Z'\")\n\n query = make_mag_query(state=MagState.archived, start_date=start_date, end_date=end_date,\n date_type=MagDateType.archived)\n self.assertEqual(query, \"State eq 'archived' and ArchivedDate ge datetime'2020-04-01T00:00Z' \"\n \"and ArchivedDate lt datetime'2020-05-01T00:00Z'\")\n\n query = make_mag_query(state=MagState.done, start_date=start_date, end_date=end_date,\n date_type=MagDateType.done)\n self.assertEqual(query, \"State eq 'done' and DoneDate ge datetime'2020-04-01T00:00Z' \"\n \"and DoneDate lt datetime'2020-05-01T00:00Z'\")\n\n\ndef make_mag_release(account_name: str, account_key: str, year: int, month: int, day: int):\n min_date = pendulum.datetime(1601, 1, 1)\n partition_key_ = 'mag'\n row_key_ = f'mag-{year:0>4d}-{month:0>2d}-{day:0>2d}'\n state_ = MagState.discovered\n task_ = MagTask.not_started\n release_date_ = pendulum.datetime(year=year, month=month, day=day)\n source_container_ = row_key_\n source_container_last_modified_ = pendulum.datetime(year=year, month=month, day=day, hour=1)\n release_container_ = ''\n release_path_ = ''\n discovered_date_ = pendulum.datetime(year=year, month=month, day=day, hour=2)\n archived_date_ = min_date\n done_date_ = min_date\n return MagRelease(partition_key_, row_key_, state_, task_, release_date_, source_container_,\n source_container_last_modified_, release_container_, release_path_, discovered_date_,\n archived_date_, done_date_, account_name=account_name, account_key=account_key)\n\n\nclass TestMagRelease(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(TestMagRelease, self).__init__(*args, **kwargs)\n self.account_name = os.getenv('STORAGE_ACCOUNT_NAME')\n self.account_key = os.getenv('STORAGE_ACCOUNT_KEY')\n create_table(self.account_name, self.account_key, MagRelease.TABLE_NAME)\n\n def test_secrets_hidden(self):\n # Check that account key is hidden\n account_name = 'myaccountname'\n secret = 'secret'\n\n # Check that account_key and sas_token are hidden\n release = make_mag_release(account_name, secret, 2020, 1, 1)\n self.assertIn('account_key=hidden', release.__repr__())\n self.assertNotIn(secret, release.__str__())\n self.assertNotIn(secret, release.__repr__())\n\n # Check that account_key is None\n release = make_mag_release(account_name, None, 2020, 1, 1)\n self.assertIn('account_key=None', release.__repr__())\n\n def test_create(self):\n release = make_mag_release(self.account_name, self.account_key, 2019, 6, 1)\n try:\n success = release.create()\n self.assertTrue(success)\n finally:\n release.delete()\n\n def test_delete(self):\n release = make_mag_release(self.account_name, self.account_key, 2019, 6, 1)\n\n # Check that we can create and then delete\n release.create()\n release.delete()\n\n # Check that second delete fails\n with self.assertRaises(AzureMissingResourceHttpError):\n release.delete()\n\n def test_update(self):\n release = make_mag_release(self.account_name, self.account_key, 2019, 6, 1)\n try:\n release.create()\n\n # Update release\n release.state = MagState.archived\n release.archived_date = pendulum.utcnow().microsecond_(0)\n release.update()\n\n # Verify that release is updated\n service = TableService(account_name=self.account_name, account_key=self.account_key)\n entity = service.get_entity(MagRelease.TABLE_NAME, release.partition_key, release.row_key)\n updated_release = MagRelease.from_entity(entity)\n self.assertEqual(release.state, updated_release.state)\n self.assertEqual(release.archived_date, updated_release.archived_date)\n finally:\n release.delete()\n\n\ndef make_containers():\n containers = []\n cp1 = ContainerProperties()\n cp1.name = 'mag-2020-04-17'\n cp1.last_modified = pendulum.datetime(year=2020, month=4, day=18)\n containers.append(cp1)\n\n cp3 = ContainerProperties()\n cp3.name = 'mag-2020-05-01'\n cp3.last_modified = pendulum.datetime(year=2020, month=5, day=1)\n containers.append(cp3)\n\n cp2 = ContainerProperties()\n cp2.name = 'mag-2020-04-24'\n cp2.last_modified = pendulum.datetime(year=2020, month=4, day=25)\n containers.append(cp2)\n\n return containers\n\n\nclass TestMagArchiverClient(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n super(TestMagArchiverClient, self).__init__(*args, **kwargs)\n self.account_name = os.getenv('STORAGE_ACCOUNT_NAME')\n self.account_key = os.getenv('STORAGE_ACCOUNT_KEY')\n create_table(self.account_name, self.account_key, MagRelease.TABLE_NAME)\n\n def test_secrets_hidden(self):\n # Check that account key is hidden\n account_name = 'myaccountname'\n secret = 'secret'\n\n # Check that account_key and sas_token are hidden\n client = MagArchiverClient(account_name=account_name, account_key=secret, sas_token=secret)\n expected = f'MagArchiverClient(account_name={account_name}, account_key=hidden, sas_token=hidden)'\n self.assertEqual(client.__str__(), expected)\n self.assertEqual(client.__repr__(), expected)\n self.assertNotIn(secret, client.__str__())\n self.assertNotIn(secret, client.__repr__())\n\n # Check that account_key and sas_token are None\n client = MagArchiverClient(account_name=account_name)\n expected = f'MagArchiverClient(account_name={account_name}, account_key=None, sas_token=None)'\n self.assertEqual(client.__str__(), expected)\n self.assertEqual(client.__repr__(), expected)\n\n @patch('mag_archiver.mag.list_containers')\n @patch('pendulum.datetime.now')\n def test_list_containers(self, mock_now, mock_list_containers):\n # Mock time\n mock_now.return_value = pendulum.datetime(year=2020, month=5, day=1, minute=10)\n\n # Mock containers\n containers_in = make_containers()\n mock_list_containers.return_value = containers_in\n\n # Test that 2 containers are returned when last_modified_thresh=1\n client = MagArchiverClient(account_name=self.account_name, account_key=self.account_key)\n containers_out = client.list_containers(last_modified_thresh=1)\n self.assertEqual(len(containers_out), 2)\n\n # Test that 3 containers are returned when last_modified_thresh=0\n containers_out = client.list_containers(last_modified_thresh=0)\n self.assertEqual(len(containers_out), 3)\n\n # Test sort order reverse=False\n self.assertEqual(containers_in[0].name, containers_out[0].name)\n self.assertEqual(containers_in[2].name, containers_out[1].name)\n self.assertEqual(containers_in[1].name, containers_out[2].name)\n\n # Test sort order reverse=True\n containers_out = client.list_containers(last_modified_thresh=0, reverse=True)\n self.assertEqual(len(containers_out), 3)\n self.assertEqual(containers_in[1].name, containers_out[0].name)\n self.assertEqual(containers_in[2].name, containers_out[1].name)\n self.assertEqual(containers_in[0].name, containers_out[2].name)\n\n @patch('mag_archiver.mag.list_containers')\n @patch('pendulum.datetime.now')\n def test_update_releases(self, mock_now, mock_list_containers):\n # Mock time\n mock_now.return_value = pendulum.datetime(year=2020, month=5, day=1, minute=10)\n\n # Mock containers\n containers_in = make_containers()\n mock_list_containers.return_value = containers_in\n\n # Mock fetching of containers\n client = MagArchiverClient(account_name=self.account_name, account_key=self.account_key)\n containers = client.list_containers(last_modified_thresh=1)\n\n try:\n # Update releases based on containers\n num_updated, num_errors = client.update_releases(containers)\n self.assertEqual(num_updated, 2)\n self.assertEqual(num_errors, 0)\n finally:\n # Clean up\n service = TableService(account_name=self.account_name, account_key=self.account_key)\n for container in containers:\n service.delete_entity(MagRelease.TABLE_NAME, 'mag', container.name.replace(\"mag-\", \"\"))\n\n @patch('mag_archiver.mag.list_containers')\n @patch('pendulum.datetime.now')\n def test_list_releases(self, mock_now, mock_list_containers):\n # Mock time\n mock_now.return_value = pendulum.datetime(year=2020, month=5, day=1, hour=1)\n\n # Mock containers\n containers_in = make_containers()\n mock_list_containers.return_value = containers_in\n\n # Mock fetching of containers\n client = MagArchiverClient(account_name=self.account_name, account_key=self.account_key)\n containers = client.list_containers(last_modified_thresh=1)\n\n try:\n # Update releases based on containers\n num_updated, num_errors = client.update_releases(containers)\n self.assertEqual(num_updated, 3)\n self.assertEqual(num_errors, 0)\n\n # Two releases\n start_date = pendulum.datetime(year=2020, month=4, day=17)\n end_date = pendulum.datetime(year=2020, month=5, day=1)\n releases = client.list_releases(start_date=start_date, end_date=end_date, state=MagState.discovered,\n date_type=MagDateType.release)\n self.assertEqual(len(releases), 2)\n\n # 1 release\n start_date = pendulum.datetime(year=2020, month=4, day=17, minute=1)\n end_date = pendulum.datetime(year=2020, month=5, day=1)\n releases = client.list_releases(start_date=start_date, end_date=end_date, state=MagState.discovered,\n date_type=MagDateType.release)\n self.assertEqual(len(releases), 1)\n\n # Three releases\n start_date = pendulum.datetime(year=2020, month=4, day=17)\n end_date = pendulum.datetime(year=2020, month=5, day=1, minute=1)\n releases = client.list_releases(start_date=start_date, end_date=end_date, state=MagState.discovered,\n date_type=MagDateType.release, reverse=False)\n self.assertEqual(len(releases), 3)\n\n # Sorting reverse=False\n self.assertEqual(releases[0].row_key, '2020-04-17')\n self.assertEqual(releases[1].row_key, '2020-04-24')\n self.assertEqual(releases[2].row_key, '2020-05-01')\n\n # Sorting reverse=True\n releases = client.list_releases(start_date=start_date, end_date=end_date,\n state=MagState.discovered, date_type=MagDateType.release,\n reverse=True)\n self.assertEqual(releases[0].row_key, '2020-05-01')\n self.assertEqual(releases[1].row_key, '2020-04-24')\n self.assertEqual(releases[2].row_key, '2020-04-17')\n\n finally:\n # Clean up\n service = TableService(account_name=self.account_name, account_key=self.account_key)\n for container in containers:\n service.delete_entity(MagRelease.TABLE_NAME, 'mag', container.name.replace(\"mag-\", \"\"))\n"},"apis":{"kind":"string","value":"[((5771, 5800), 'pendulum.datetime', 'pendulum.datetime', (['(1601)', '(1)', '(1)'], {}), '(1601, 1, 1)\\n', (5788, 5800), False, 'import pendulum\\n'), ((5971, 6021), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': 'year', 'month': 'month', 'day': 'day'}), '(year=year, month=month, day=day)\\n', (5988, 6021), False, 'import pendulum\\n'), ((6093, 6151), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': 'year', 'month': 'month', 'day': 'day', 'hour': '(1)'}), '(year=year, month=month, day=day, hour=1)\\n', (6110, 6151), False, 'import pendulum\\n'), ((6226, 6284), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': 'year', 'month': 'month', 'day': 'day', 'hour': '(2)'}), '(year=year, month=month, day=day, hour=2)\\n', (6243, 6284), False, 'import pendulum\\n'), ((6352, 6615), 'mag_archiver.mag.MagRelease', 'MagRelease', (['partition_key_', 'row_key_', 'state_', 'task_', 'release_date_', 'source_container_', 'source_container_last_modified_', 'release_container_', 'release_path_', 'discovered_date_', 'archived_date_', 'done_date_'], {'account_name': 'account_name', 'account_key': 'account_key'}), '(partition_key_, row_key_, state_, task_, release_date_,\\n source_container_, source_container_last_modified_, release_container_,\\n release_path_, discovered_date_, archived_date_, done_date_,\\n account_name=account_name, account_key=account_key)\\n', (6362, 6615), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((9091, 9112), 'azure.storage.blob.ContainerProperties', 'ContainerProperties', ([], {}), '()\\n', (9110, 9112), False, 'from azure.storage.blob import ContainerProperties\\n'), ((9169, 9214), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(4)', 'day': '(18)'}), '(year=2020, month=4, day=18)\\n', (9186, 9214), False, 'import pendulum\\n'), ((9253, 9274), 'azure.storage.blob.ContainerProperties', 'ContainerProperties', ([], {}), '()\\n', (9272, 9274), False, 'from azure.storage.blob import ContainerProperties\\n'), ((9331, 9375), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(5)', 'day': '(1)'}), '(year=2020, month=5, day=1)\\n', (9348, 9375), False, 'import pendulum\\n'), ((9414, 9435), 'azure.storage.blob.ContainerProperties', 'ContainerProperties', ([], {}), '()\\n', (9433, 9435), False, 'from azure.storage.blob import ContainerProperties\\n'), ((9492, 9537), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(4)', 'day': '(25)'}), '(year=2020, month=4, day=25)\\n', (9509, 9537), False, 'import pendulum\\n'), ((10907, 10948), 'unittest.mock.patch', 'patch', (['\"\"\"mag_archiver.mag.list_containers\"\"\"'], {}), \"('mag_archiver.mag.list_containers')\\n\", (10912, 10948), False, 'from unittest.mock import patch\\n'), ((10954, 10984), 'unittest.mock.patch', 'patch', (['\"\"\"pendulum.datetime.now\"\"\"'], {}), \"('pendulum.datetime.now')\\n\", (10959, 10984), False, 'from unittest.mock import patch\\n'), ((12431, 12472), 'unittest.mock.patch', 'patch', (['\"\"\"mag_archiver.mag.list_containers\"\"\"'], {}), \"('mag_archiver.mag.list_containers')\\n\", (12436, 12472), False, 'from unittest.mock import patch\\n'), ((12478, 12508), 'unittest.mock.patch', 'patch', (['\"\"\"pendulum.datetime.now\"\"\"'], {}), \"('pendulum.datetime.now')\\n\", (12483, 12508), False, 'from unittest.mock import patch\\n'), ((13530, 13571), 'unittest.mock.patch', 'patch', (['\"\"\"mag_archiver.mag.list_containers\"\"\"'], {}), \"('mag_archiver.mag.list_containers')\\n\", (13535, 13571), False, 'from unittest.mock import patch\\n'), ((13577, 13607), 'unittest.mock.patch', 'patch', (['\"\"\"pendulum.datetime.now\"\"\"'], {}), \"('pendulum.datetime.now')\\n\", (13582, 13607), False, 'from unittest.mock import patch\\n'), ((1158, 1180), 'mag_archiver.mag.hide_if_not_none', 'hide_if_not_none', (['None'], {}), '(None)\\n', (1174, 1180), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((1285, 1316), 'mag_archiver.mag.hide_if_not_none', 'hide_if_not_none', (['\"\"\"hello world\"\"\"'], {}), \"('hello world')\\n\", (1301, 1316), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((1426, 1447), 'mag_archiver.mag.hide_if_not_none', 'hide_if_not_none', (['(123)'], {}), '(123)\\n', (1442, 1447), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((1547, 1591), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(4)', 'day': '(1)'}), '(year=2020, month=4, day=1)\\n', (1564, 1591), False, 'import pendulum\\n'), ((1611, 1655), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(5)', 'day': '(1)'}), '(year=2020, month=5, day=1)\\n', (1628, 1655), False, 'import pendulum\\n'), ((1697, 1713), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {}), '()\\n', (1711, 1713), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((1793, 1834), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'state': 'MagState.discovered'}), '(state=MagState.discovered)\\n', (1807, 1834), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((1909, 1948), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'state': 'MagState.archived'}), '(state=MagState.archived)\\n', (1923, 1948), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((2021, 2056), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'state': 'MagState.done'}), '(state=MagState.done)\\n', (2035, 2056), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((2156, 2224), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'start_date': 'start_date', 'date_type': 'MagDateType.release'}), '(start_date=start_date, date_type=MagDateType.release)\\n', (2170, 2224), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((2320, 2391), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'start_date': 'start_date', 'date_type': 'MagDateType.discovered'}), '(start_date=start_date, date_type=MagDateType.discovered)\\n', (2334, 2391), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((2490, 2559), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'start_date': 'start_date', 'date_type': 'MagDateType.archived'}), '(start_date=start_date, date_type=MagDateType.archived)\\n', (2504, 2559), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((2656, 2721), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'start_date': 'start_date', 'date_type': 'MagDateType.done'}), '(start_date=start_date, date_type=MagDateType.done)\\n', (2670, 2721), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((2843, 2907), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'end_date': 'end_date', 'date_type': 'MagDateType.release'}), '(end_date=end_date, date_type=MagDateType.release)\\n', (2857, 2907), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((3003, 3070), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'end_date': 'end_date', 'date_type': 'MagDateType.discovered'}), '(end_date=end_date, date_type=MagDateType.discovered)\\n', (3017, 3070), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((3169, 3234), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'end_date': 'end_date', 'date_type': 'MagDateType.archived'}), '(end_date=end_date, date_type=MagDateType.archived)\\n', (3183, 3234), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((3331, 3392), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'end_date': 'end_date', 'date_type': 'MagDateType.done'}), '(end_date=end_date, date_type=MagDateType.done)\\n', (3345, 3392), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((3530, 3622), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'start_date': 'start_date', 'end_date': 'end_date', 'date_type': 'MagDateType.release'}), '(start_date=start_date, end_date=end_date, date_type=\\n MagDateType.release)\\n', (3544, 3622), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((3795, 3890), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'start_date': 'start_date', 'end_date': 'end_date', 'date_type': 'MagDateType.discovered'}), '(start_date=start_date, end_date=end_date, date_type=\\n MagDateType.discovered)\\n', (3809, 3890), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((4069, 4162), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'start_date': 'start_date', 'end_date': 'end_date', 'date_type': 'MagDateType.archived'}), '(start_date=start_date, end_date=end_date, date_type=\\n MagDateType.archived)\\n', (4083, 4162), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((4337, 4426), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'start_date': 'start_date', 'end_date': 'end_date', 'date_type': 'MagDateType.done'}), '(start_date=start_date, end_date=end_date, date_type=\\n MagDateType.done)\\n', (4351, 4426), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((4645, 4767), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'state': 'MagState.discovered', 'start_date': 'start_date', 'end_date': 'end_date', 'date_type': 'MagDateType.discovered'}), '(state=MagState.discovered, start_date=start_date, end_date=\\n end_date, date_type=MagDateType.discovered)\\n', (4659, 4767), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((5003, 5121), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'state': 'MagState.archived', 'start_date': 'start_date', 'end_date': 'end_date', 'date_type': 'MagDateType.archived'}), '(state=MagState.archived, start_date=start_date, end_date=\\n end_date, date_type=MagDateType.archived)\\n', (5017, 5121), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((5351, 5461), 'mag_archiver.mag.make_mag_query', 'make_mag_query', ([], {'state': 'MagState.done', 'start_date': 'start_date', 'end_date': 'end_date', 'date_type': 'MagDateType.done'}), '(state=MagState.done, start_date=start_date, end_date=\\n end_date, date_type=MagDateType.done)\\n', (5365, 5461), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((6822, 6855), 'os.getenv', 'os.getenv', (['\"\"\"STORAGE_ACCOUNT_NAME\"\"\"'], {}), \"('STORAGE_ACCOUNT_NAME')\\n\", (6831, 6855), False, 'import os\\n'), ((6883, 6915), 'os.getenv', 'os.getenv', (['\"\"\"STORAGE_ACCOUNT_KEY\"\"\"'], {}), \"('STORAGE_ACCOUNT_KEY')\\n\", (6892, 6915), False, 'import os\\n'), ((6924, 6996), 'mag_archiver.azure.create_table', 'create_table', (['self.account_name', 'self.account_key', 'MagRelease.TABLE_NAME'], {}), '(self.account_name, self.account_key, MagRelease.TABLE_NAME)\\n', (6936, 6996), False, 'from mag_archiver.azure import create_table\\n'), ((9777, 9810), 'os.getenv', 'os.getenv', (['\"\"\"STORAGE_ACCOUNT_NAME\"\"\"'], {}), \"('STORAGE_ACCOUNT_NAME')\\n\", (9786, 9810), False, 'import os\\n'), ((9838, 9870), 'os.getenv', 'os.getenv', (['\"\"\"STORAGE_ACCOUNT_KEY\"\"\"'], {}), \"('STORAGE_ACCOUNT_KEY')\\n\", (9847, 9870), False, 'import os\\n'), ((9879, 9951), 'mag_archiver.azure.create_table', 'create_table', (['self.account_name', 'self.account_key', 'MagRelease.TABLE_NAME'], {}), '(self.account_name, self.account_key, MagRelease.TABLE_NAME)\\n', (9891, 9951), False, 'from mag_archiver.azure import create_table\\n'), ((10172, 10259), 'mag_archiver.mag.MagArchiverClient', 'MagArchiverClient', ([], {'account_name': 'account_name', 'account_key': 'secret', 'sas_token': 'secret'}), '(account_name=account_name, account_key=secret, sas_token=\\n secret)\\n', (10189, 10259), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((10646, 10690), 'mag_archiver.mag.MagArchiverClient', 'MagArchiverClient', ([], {'account_name': 'account_name'}), '(account_name=account_name)\\n', (10663, 10690), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((11105, 11160), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(5)', 'day': '(1)', 'minute': '(10)'}), '(year=2020, month=5, day=1, minute=10)\\n', (11122, 11160), False, 'import pendulum\\n'), ((11380, 11459), 'mag_archiver.mag.MagArchiverClient', 'MagArchiverClient', ([], {'account_name': 'self.account_name', 'account_key': 'self.account_key'}), '(account_name=self.account_name, account_key=self.account_key)\\n', (11397, 11459), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((12629, 12684), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(5)', 'day': '(1)', 'minute': '(10)'}), '(year=2020, month=5, day=1, minute=10)\\n', (12646, 12684), False, 'import pendulum\\n'), ((12868, 12947), 'mag_archiver.mag.MagArchiverClient', 'MagArchiverClient', ([], {'account_name': 'self.account_name', 'account_key': 'self.account_key'}), '(account_name=self.account_name, account_key=self.account_key)\\n', (12885, 12947), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((13726, 13778), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(5)', 'day': '(1)', 'hour': '(1)'}), '(year=2020, month=5, day=1, hour=1)\\n', (13743, 13778), False, 'import pendulum\\n'), ((13962, 14041), 'mag_archiver.mag.MagArchiverClient', 'MagArchiverClient', ([], {'account_name': 'self.account_name', 'account_key': 'self.account_key'}), '(account_name=self.account_name, account_key=self.account_key)\\n', (13979, 14041), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((8601, 8675), 'azure.cosmosdb.table.tableservice.TableService', 'TableService', ([], {'account_name': 'self.account_name', 'account_key': 'self.account_key'}), '(account_name=self.account_name, account_key=self.account_key)\\n', (8613, 8675), False, 'from azure.cosmosdb.table.tableservice import TableService\\n'), ((8809, 8839), 'mag_archiver.mag.MagRelease.from_entity', 'MagRelease.from_entity', (['entity'], {}), '(entity)\\n', (8831, 8839), False, 'from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, hide_if_not_none\\n'), ((13304, 13378), 'azure.cosmosdb.table.tableservice.TableService', 'TableService', ([], {'account_name': 'self.account_name', 'account_key': 'self.account_key'}), '(account_name=self.account_name, account_key=self.account_key)\\n', (13316, 13378), False, 'from azure.cosmosdb.table.tableservice import TableService\\n'), ((14389, 14434), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(4)', 'day': '(17)'}), '(year=2020, month=4, day=17)\\n', (14406, 14434), False, 'import pendulum\\n'), ((14458, 14502), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(5)', 'day': '(1)'}), '(year=2020, month=5, day=1)\\n', (14475, 14502), False, 'import pendulum\\n'), ((14788, 14843), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(4)', 'day': '(17)', 'minute': '(1)'}), '(year=2020, month=4, day=17, minute=1)\\n', (14805, 14843), False, 'import pendulum\\n'), ((14867, 14911), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(5)', 'day': '(1)'}), '(year=2020, month=5, day=1)\\n', (14884, 14911), False, 'import pendulum\\n'), ((15202, 15247), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(4)', 'day': '(17)'}), '(year=2020, month=4, day=17)\\n', (15219, 15247), False, 'import pendulum\\n'), ((15271, 15325), 'pendulum.datetime', 'pendulum.datetime', ([], {'year': '(2020)', 'month': '(5)', 'day': '(1)', 'minute': '(1)'}), '(year=2020, month=5, day=1, minute=1)\\n', (15288, 15325), False, 'import pendulum\\n'), ((16342, 16416), 'azure.cosmosdb.table.tableservice.TableService', 'TableService', ([], {'account_name': 'self.account_name', 'account_key': 'self.account_key'}), '(account_name=self.account_name, account_key=self.account_key)\\n', (16354, 16416), False, 'from azure.cosmosdb.table.tableservice import TableService\\n'), ((8470, 8487), 'pendulum.utcnow', 'pendulum.utcnow', ([], {}), '()\\n', (8485, 8487), False, 'import pendulum\\n')]"}}},{"rowIdx":8423,"cells":{"repo_name":{"kind":"string","value":"jacob-heglund/socialsensing-jh"},"repo_path":{"kind":"string","value":"twitterinfrastructure/CH-Data-Public.py"},"repo_head_hexsha":{"kind":"string","value":"fd6d2d749f40fee46bee749ff868212bf117a747"},"content":{"kind":"string","value":"'''\nCreated on Mar 22, 2018\nEdited on Jan 11, 2019\n\n@author: npvance2\n@author: curtisd2\n\nVariables that will need to be edited/personalized:\n monitorID in Variables() (line 27)\n projectStartDate in Variables() (line 28)\n projectEndDate in Variables() (line 29)\n authToken in getAuthToken() (line 49)\n consumer_key in twitterAPI() (line 62)\n consumer_secret in twitterAPI() (line 63)\n access_token in twitterAPI() (line 64)\n access_secret in twitterAPI() (line 65)\n'''\n\nfrom datetime import date, timedelta\nimport urllib.request\nimport json\nimport csv\nimport tweepy\nfrom tweepy import OAuthHandler\n\ndef Variables():\n monitorID = \"9926183772\" # The numerical ID for your Crimson Hexagon monitor\n startDate = \"yyyy-mm-dd\" # Date must be in yyyy-mm-dd format\n endDate = \"yyyy-mm-dd\" # Date must be in yyyy-mm-dd format\n variableMap = {}\n variableMap['monitorID'] = monitorID\n variableMap['startDate'] = startDate\n variableMap['endDate'] = endDate\n return variableMap\n\ndef getURL(): #provides URL for Crimson API\n urlStart = \"https://api.crimsonhexagon.com/api\"\n return urlStart\n\n\n###########\n#\n# You'll need to generate your own Crimson API key/token from here:\n# https://apidocs.crimsonhexagon.com/reference\n#\n###########\n\ndef getAuthToken(): #provides auth token needed to access Crimson API\n authToken = ''\n authToken = \"&auth=\"+authToken\n return authToken\n\n###########\n#\n# You'll need to add your own Twitter API keys here.\n# Instructions on generating API keys: https://developer.twitter.com/en/docs/basics/authentication/guides/access-tokens.html\n# API reference guide: https://developer.twitter.com/en/docs/api-reference-index.html\n#\n###########\n\ndef twitterAPI(): #Provides access keys for Twitter API\n consumer_key = '2S1Z7Giq0oOf3w0R0sJUPnLFx'\n consumer_secret = '9IPOE8dqWzUPseAPHeNxTTv1jAr9BNj8mF2ryw8DIud8Ot8VCe'\n access_token = '998275516892409858-hQ1pk5wKg1YyxUrbiFkuFHKHqztPMNE'\n access_secret = 'gsXqGx1gU93HkKNDupTPt56ZnAmmalsaSNBUuoBToraBw'\n\n if (consumer_key == '') or (consumer_secret =='') or (access_token =='') or (access_secret ==''):\n print(\"Not all Twitter keys have been entered, please add them to the script and try again\")\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_secret)\n api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n return api\n\n\ndef getTwitterURL(): #provides URL for Twitter api\n urlStart = \"https://api.twitter.com/1.1/statuses/lookup.json?id=\"\n return urlStart\n\ndef DatePull(startdate, enddate):\n listArray = []\n startdate = date(int(startdate[0:4]), int(startdate[5:7]), int(startdate[8:10]))\n enddate = date(int(enddate[0:4]), int(enddate[5:7]), int(enddate[8:10]))\n \n while startdate <= enddate:\n listArray.append(str(startdate))\n startdate += timedelta(days=1)\n return listArray\n\n\ndef main():\n monitorID = Variables()['monitorID']\n projectStartDate = Variables()['startDate']\n projectEndDate = Variables()['endDate']\n fPath = \"Monitor-\"+monitorID+'-from-'+projectStartDate+'-to-'+projectEndDate+'.csv'\n lineArray = DatePull(projectStartDate, projectEndDate)\n print(\"------------------------------\")\n print(\"MonitorID is \"+monitorID)\n print(lineArray[0],lineArray[-1])\n \n with open(fPath, 'w', newline = '', encoding = 'utf-8') as f:\n writer = csv.writer(f)\n header = [\"PostType\",\"PostDate\",\"PostTime\",\"URL\",\"TweetID\",\"Contents\",\"RetweetCount\",\"FavoriteCount\",\"Location\",\"Language\",\"Sentiment\",\"NeutralScore\",\"PositiveScore\",\"NegativeScore\",\"Followers\",\"Friends\",\"Author\",\"AuthorGender\",\"AuthorTweets\"]\n writer.writerow(header)\n \n for i in range(len(lineArray)-1):\n print(lineArray[i])\n startDate = lineArray[i]\n endDate = lineArray[i+1]\n\n dates = \"&start=\"+startDate+\"&end=\"+endDate #Combines start and end date into format needed for API call\n urlStart = getURL() #Gets URL\n authToken = getAuthToken() #Gets auth token\n endpoint = \"/monitor/posts?id=\"; #endpoint needed for this query\n extendLimit = \"&extendLimit=true\" #extends call number from 500 to 10,000\n fullContents = \"&fullContents=true\" #Brings back full contents for Blog and Tumblr posts which are usually truncated around search keywords. This can occasionally disrupt CSV formatting.\n urlData = urlStart+endpoint+monitorID+authToken+dates+extendLimit+fullContents #Combines all API calls parts into full URL\n \n webURL = urllib.request.urlopen(urlData)\n \n if (webURL.getcode() == 200):\n\n with open(fPath, 'a', newline='', encoding='utf-8') as f:\n writer = csv.writer(f)\n \n data = webURL.read().decode('utf8')\n theJSON = json.loads(data)\n \n postDates = [] #These initialize the attributes of the final output\n postTimes = []\n urls = []\n contents = []\n authors = []\n authorGenders = []\n locations = []\n languages = []\n postTypes = []\n sentiments = []\n neutralScore = []\n positiveScore = []\n negativeScore = []\n tweetIDs = []\n followers = []\n friends = []\n retweetCounts = []\n favoritesCount = []\n statusesCount = []\n tweetCount = 0\n tempTweetIDs = []\n \n api = twitterAPI()\n c = 0\n \n for i in theJSON[\"posts\"]:\n postDates.append(\"\")\n postTimes.append(\"\")\n \n if ('date' in i): #identifies date posted\n tempDate = str(i[\"date\"])\n dateTime = tempDate.split(\"T\")\n postDates[c] = dateTime[0]\n postTimes[c] = dateTime[1]\n \n urls.append(i[\"url\"])\n \n contents.append(\"\")\n if ('contents' in i): #identifies post contents\n contents[c] = i[\"contents\"].replace(\",\",\"\").replace(\"\\n\",\" \") #replaces commas and new lines to facilitate CSV formatting, this occasionally missed new lines in some blog posts which I'm working to fix\n \n authors.append(\"\")\n if ('author' in i): #identifies author\n authors[c] = i[\"author\"].replace(\",\",\"\")\n \n authorGenders.append(\"\")\n if ('authorGender' in i): #identifies author gender\n authorGenders[c] = i[\"authorGender\"]\n \n locations.append(\"\")\n if ('location' in i): #identifies location\n locations[c] = i[\"location\"].replace(\",\",\"\")\n \n languages.append(\"\")\n if ('language' in i): #identifies language specified in the author's profile\n languages[c] = i[\"language\"]\n \n postTypes.append(i[\"type\"]) #identifies the type of post, i.e. Twitter, Tumblr, Blog\n \n tweetIDs.append(\"\")\n \n followers.append(\"\")\n \n friends.append(\"\")\n \n retweetCounts.append(\"\")\n \n favoritesCount.append(\"\")\n \n statusesCount.append(\"\")\n \n if postTypes[c] == \"Twitter\": #if the post type is Twitter it goes through more processing\n tweetCount = tweetCount + 1 #counts number of tweets\n tweetSplit = urls[c].split(\"status/\") #splits URL to get tweetID\n tweetIDs[c] = tweetSplit[1]\n tempTweetIDs.append(tweetIDs[c])\n \n if tweetCount == 100: #the max number of TweetIDs in one API call is 100 so a call is run every 100 tweets identified\n \n tweepys = api.statuses_lookup(id_=tempTweetIDs) #call to Twitter API\n \n for tweet in tweepys:\n tempID = tweet.id_str #finds tweetsID\n postMatch = 0\n \n for idMatch in tweetIDs:\n if idMatch==tempID: #matches tweetID in Twitter API call to tweetID stored from Crimson API\n tempDate = str(tweet.created_at).replace(\" \",\" \") #These all fill the matching Crimson attributes to those found in the Twitter API\n dateTime = tempDate.split(\" \")\n postDates[postMatch] = dateTime[0]\n postTimes[postMatch] = dateTime[1]\n contents[postMatch] = tweet.text.replace(\",\",\"\")\n authors[postMatch] = tweet.author.screen_name\n followers[postMatch] = str(tweet.author.followers_count)\n friends[postMatch] = str(tweet.author.friends_count)\n retweetCounts[postMatch] = str(tweet.retweet_count)\n favoritesCount[postMatch] = str(tweet.favorite_count)\n statusesCount[postMatch] = str(tweet.author.statuses_count)\n \n postMatch = postMatch + 1\n \n tweetCount = 0 #clears tweet count for a new 100\n tempTweetIDs = [] #clears tweetIDs for next call\n \n sentiments.append(\"\")\n \n neutralScore.append(\"\")\n \n positiveScore.append(\"\")\n \n negativeScore.append(\"\")\n \n if ('categoryScores' in i): #finds sentiment value and matching attribute\n for l in i[\"categoryScores\"]:\n catName = l[\"categoryName\"]\n if catName == \"Basic Neutral\":\n neutralScore[c] = l[\"score\"]\n elif catName ==\"Basic Positive\":\n positiveScore[c] = l[\"score\"]\n elif catName == \"Basic Negative\":\n negativeScore[c] = l[\"score\"]\n \n if neutralScore[c] > positiveScore[c] and neutralScore[c] > negativeScore[c]:\n sentiments[c] = \"Basic Neutral\"\n \n if positiveScore[c] > neutralScore[c] and positiveScore[c] > negativeScore[c]:\n sentiments[c] = \"Basic Positive\"\n \n if negativeScore[c] > positiveScore[c] and negativeScore[c] > neutralScore[c]:\n sentiments[c] = \"Basic Negative\"\n \n c = c + 1\n \n if len(tempTweetIDs) != 0: #after loop the Twitter API call must run one more time to clean up all the tweets since the last 100\n try:\n tweepys = api.statuses_lookup(id_=tempTweetIDs) \n \n for tweet in tweepys:\n tempID = tweet.id_str\n postMatch = 0\n \n for idMatch in tweetIDs:\n if idMatch==tempID:\n tempDate = str(tweet.created_at).replace(\" \",\" \")\n dateTime = tempDate.split(\" \")\n postDates[postMatch] = dateTime[0]\n postTimes[postMatch] = dateTime[1]\n contents[postMatch] = tweet.text.replace(\",\",\"\")\n authors[postMatch] = tweet.author.screen_name\n followers[postMatch] = str(tweet.author.followers_count)\n friends[postMatch] = str(tweet.author.friends_count)\n retweetCounts[postMatch] = str(tweet.retweet_count)\n favoritesCount[postMatch] = str(tweet.favorite_count)\n statusesCount[postMatch] = str(tweet.author.statuses_count)\n postMatch = postMatch + 1\n tweetCount = 0\n except:\n print(\"Tweepy error: skipping cleanup\")\n \n \n pC = 0\n for pDate in postDates: #iterates through the word lists and prints matching posts to CSV\n csvRow=[postTypes[pC], pDate, postTimes[pC], urls[pC], str(tweetIDs[pC]), contents[pC].replace(\"\\n\",\" \"), retweetCounts[pC], favoritesCount[pC], locations[pC], languages[pC], sentiments[pC], str(neutralScore[pC]), str(positiveScore[pC]), str(negativeScore[pC]), followers[pC], friends[pC], authors[pC], authorGenders[pC], statusesCount[pC]]\n writer.writerow(csvRow)\n pC = pC + 1\n \n else:\n print(\"Server Error, No Data\" + str(webURL.getcode())) #displays error if Crimson URL fails\n\nif __name__ == '__main__':\n main()\n"},"apis":{"kind":"string","value":"[((2285, 2328), 'tweepy.OAuthHandler', 'OAuthHandler', (['consumer_key', 'consumer_secret'], {}), '(consumer_key, consumer_secret)\\n', (2297, 2328), False, 'from tweepy import OAuthHandler\\n'), ((2394, 2467), 'tweepy.API', 'tweepy.API', (['auth'], {'wait_on_rate_limit': '(True)', 'wait_on_rate_limit_notify': '(True)'}), '(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\\n', (2404, 2467), False, 'import tweepy\\n'), ((2941, 2958), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\\n', (2950, 2958), False, 'from datetime import date, timedelta\\n'), ((3493, 3506), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\\n', (3503, 3506), False, 'import csv\\n'), ((4810, 4823), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\\n', (4820, 4823), False, 'import csv\\n'), ((4913, 4929), 'json.loads', 'json.loads', (['data'], {}), '(data)\\n', (4923, 4929), False, 'import json\\n')]"}}},{"rowIdx":8424,"cells":{"repo_name":{"kind":"string","value":"danhnguyen48/slurm-elastic-computing"},"repo_path":{"kind":"string","value":"roles/slurm/files/startnode.py"},"repo_head_hexsha":{"kind":"string","value":"0793cf23677169a6d9dceea0793118bc00c0913e"},"content":{"kind":"string","value":"#! /opt/cloud_sdk/bin/python\n\nimport asyncio\nimport logging\nimport subprocess\nimport sys\nimport citc_cloud\n\n\n\ndef handle_exception(exc_type, exc_value, exc_traceback):\n if issubclass(exc_type, KeyboardInterrupt):\n sys.__excepthook__(exc_type, exc_value, exc_traceback)\n return\n\n log.critical(\"Uncaught exception\", exc_info=(exc_type, exc_value, exc_traceback))\n\n\nasync def main() -> None:\n nodespace = citc_cloud.get_nodespace()\n\n keys_file = \"/home/slurm/opc_authorized_keys\"\n\n with open(keys_file) as kf:\n ssh_keys = kf.read()\n\n hosts = subprocess.run([\"scontrol\", \"show\", \"hostnames\", sys.argv[1]], stdout=subprocess.PIPE).stdout.decode().split()\n\n await asyncio.gather(*(\n citc_cloud.start_node( log, host, nodespace, ssh_keys)\n for host in hosts\n ))\n\nsys.excepthook = handle_exception\n\nif __name__ == \"__main__\":\n log = logging.getLogger(\"startnode\")\n log.setLevel(logging.INFO)\n handler = logging.FileHandler('/var/log/slurm/elastic.log')\n formatter = logging.Formatter('%(asctime)s %(name)-10s %(levelname)-8s %(message)s')\n handler.setFormatter(formatter)\n log.addHandler(handler)\n\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(main())\n finally:\n loop.close()\n"},"apis":{"kind":"string","value":"[((425, 451), 'citc_cloud.get_nodespace', 'citc_cloud.get_nodespace', ([], {}), '()\\n', (449, 451), False, 'import citc_cloud\\n'), ((887, 917), 'logging.getLogger', 'logging.getLogger', (['\"\"\"startnode\"\"\"'], {}), \"('startnode')\\n\", (904, 917), False, 'import logging\\n'), ((963, 1012), 'logging.FileHandler', 'logging.FileHandler', (['\"\"\"/var/log/slurm/elastic.log\"\"\"'], {}), \"('/var/log/slurm/elastic.log')\\n\", (982, 1012), False, 'import logging\\n'), ((1029, 1101), 'logging.Formatter', 'logging.Formatter', (['\"\"\"%(asctime)s %(name)-10s %(levelname)-8s %(message)s\"\"\"'], {}), \"('%(asctime)s %(name)-10s %(levelname)-8s %(message)s')\\n\", (1046, 1101), False, 'import logging\\n'), ((1178, 1202), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\\n', (1200, 1202), False, 'import asyncio\\n'), ((224, 278), 'sys.__excepthook__', 'sys.__excepthook__', (['exc_type', 'exc_value', 'exc_traceback'], {}), '(exc_type, exc_value, exc_traceback)\\n', (242, 278), False, 'import sys\\n'), ((726, 779), 'citc_cloud.start_node', 'citc_cloud.start_node', (['log', 'host', 'nodespace', 'ssh_keys'], {}), '(log, host, nodespace, ssh_keys)\\n', (747, 779), False, 'import citc_cloud\\n'), ((578, 669), 'subprocess.run', 'subprocess.run', ([\"['scontrol', 'show', 'hostnames', sys.argv[1]]\"], {'stdout': 'subprocess.PIPE'}), \"(['scontrol', 'show', 'hostnames', sys.argv[1]], stdout=\\n subprocess.PIPE)\\n\", (592, 669), False, 'import subprocess\\n')]"}}},{"rowIdx":8425,"cells":{"repo_name":{"kind":"string","value":"BryanRiel/pyre"},"repo_path":{"kind":"string","value":"tests/pyre/components/component_class_registration_model.py"},"repo_head_hexsha":{"kind":"string","value":"179359634a7091979cced427b6133dd0ec4726ea"},"content":{"kind":"string","value":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# michael a.g. aïvázis\n# orthologue\n# (c) 1998-2018 all rights reserved\n#\n\n\n\"\"\"\nVerify that component registration interacts correctly with the pyre configurator model\n\"\"\"\n\n# access\n# print(\" -- importing pyre\")\nimport pyre\n# print(\" -- done\")\n\n\ndef declare():\n\n # declare a protocol\n class protocol(pyre.protocol):\n \"\"\"a protocol\"\"\"\n # properties\n p1 = pyre.properties.str()\n p2 = pyre.properties.str()\n # behavior\n @pyre.provides\n def do(self):\n \"\"\"behave\"\"\"\n\n # declare a component\n class component(pyre.component, family=\"test\", implements=protocol):\n \"\"\"a component\"\"\"\n # traits\n p1 = pyre.properties.str(default=\"p1\")\n p2 = pyre.properties.str(default=\"p2\")\n\n @pyre.export\n def do(self):\n \"\"\"behave\"\"\"\n return \"component\"\n\n return component\n\n\ndef test():\n\n # and the model\n model = pyre.executive.nameserver\n # model.dump(pattern='test')\n\n # print(\" -- making some configuration changes\")\n # add an assignment\n model['test.p1'] = 'step 1'\n # an alias\n model.alias(alias='p1', target='test.p1')\n # and a reference to the alias\n model['ref'] = '{p1}'\n # check that they point to the same slot\n assert model.retrieve(name='p1') == model.retrieve(name='test.p1')\n # save the nodes\n ref = model.retrieve(name='ref')\n step_0 = model.retrieve(name='test.p1')\n\n # now declare the component and its protocol\n # print(\" -- declaring components\")\n component = declare()\n # print(\" -- done\")\n\n # model.dump(pattern='')\n assert component.p1 == 'step 1'\n assert component.p2 == 'p2'\n\n # check that the model is as we expect\n # model.dump()\n assert model['test.p1'] == component.p1\n assert model['test.p2'] == component.p2\n # how about the alias and the reference?\n assert model['ref'] == component.p1\n assert model['p1'] == component.p1\n\n # make a late registration to what is now the component trait\n model['test.p2'] = 'step 2'\n # model.dump(pattern='test')\n # and check\n assert component.p1 == 'step 1'\n assert component.p2 == 'step 2'\n\n return\n\n\n\n# main\nif __name__ == \"__main__\":\n test()\n\n\n# end of file\n"},"apis":{"kind":"string","value":"[((430, 451), 'pyre.properties.str', 'pyre.properties.str', ([], {}), '()\\n', (449, 451), False, 'import pyre\\n'), ((465, 486), 'pyre.properties.str', 'pyre.properties.str', ([], {}), '()\\n', (484, 486), False, 'import pyre\\n'), ((732, 765), 'pyre.properties.str', 'pyre.properties.str', ([], {'default': '\"\"\"p1\"\"\"'}), \"(default='p1')\\n\", (751, 765), False, 'import pyre\\n'), ((779, 812), 'pyre.properties.str', 'pyre.properties.str', ([], {'default': '\"\"\"p2\"\"\"'}), \"(default='p2')\\n\", (798, 812), False, 'import pyre\\n')]"}}},{"rowIdx":8426,"cells":{"repo_name":{"kind":"string","value":"carlmontanari/nssh"},"repo_path":{"kind":"string","value":"tests/unit/transport/plugins/asyncssh/test_asyncssh_transport.py"},"repo_head_hexsha":{"kind":"string","value":"fa2277ea0b8fdb81de3064e1d48bad9264f0cd64"},"content":{"kind":"string","value":"import asyncio\nfrom io import BytesIO\n\nimport pytest\nfrom asyncssh.connection import SSHClientConnection\nfrom asyncssh.stream import SSHReader\n\nfrom scrapli.exceptions import ScrapliConnectionNotOpened, ScrapliTimeout\n\n\nclass DumbContainer:\n def __init__(self):\n self.preferred_auth = ()\n\n def __getattr__(self, item):\n # options has a billion attributes, just return None, doesnt matter for this test\n return None\n\n\ndef test_close(monkeypatch, asyncssh_transport):\n def _close(cls):\n pass\n\n monkeypatch.setattr(\n \"asyncssh.connection.SSHClientConnection.close\",\n _close,\n )\n\n # lie and pretend the session is already assigned\n options = DumbContainer()\n asyncssh_transport.session = SSHClientConnection(\n loop=asyncio.get_event_loop_policy().get_event_loop(), options=options\n )\n\n asyncssh_transport.close()\n\n assert asyncssh_transport.session is None\n assert asyncssh_transport.stdin is None\n assert asyncssh_transport.stdout is None\n\n\ndef test_close_catch_brokenpipe(monkeypatch, asyncssh_transport):\n def _close(cls):\n raise BrokenPipeError\n\n monkeypatch.setattr(\n \"asyncssh.connection.SSHClientConnection.close\",\n _close,\n )\n\n # lie and pretend the session is already assigned\n options = DumbContainer()\n asyncssh_transport.session = SSHClientConnection(\n loop=asyncio.get_event_loop_policy().get_event_loop(), options=options\n )\n\n asyncssh_transport.close()\n\n assert asyncssh_transport.session is None\n assert asyncssh_transport.stdin is None\n assert asyncssh_transport.stdout is None\n\n\ndef test_isalive_no_session(asyncssh_transport):\n assert asyncssh_transport.isalive() is False\n\n\ndef test_isalive(asyncssh_transport):\n # lie and pretend the session is already assigned\n options = DumbContainer()\n asyncssh_transport.session = SSHClientConnection(\n loop=asyncio.get_event_loop_policy().get_event_loop(), options=options\n )\n\n # lie and tell asyncssh auth is done\n asyncssh_transport.session._auth_complete = True\n\n # also have to lie and create a transport and have it return False when is_closing is called\n asyncssh_transport.session._transport = DumbContainer()\n asyncssh_transport.session._transport.is_closing = lambda: False\n\n assert asyncssh_transport.isalive() is True\n\n\ndef test_isalive_attribute_error(asyncssh_transport):\n # lie and pretend the session is already assigned\n options = DumbContainer()\n asyncssh_transport.session = SSHClientConnection(\n loop=asyncio.get_event_loop_policy().get_event_loop(), options=options\n )\n\n # lie and tell asyncssh auth is done\n asyncssh_transport.session._auth_complete = True\n\n assert asyncssh_transport.isalive() is False\n\n\nasync def test_read(monkeypatch, asyncssh_transport):\n async def _read(cls, _):\n return b\"somebytes\"\n\n monkeypatch.setattr(\n \"asyncssh.stream.SSHReader.read\",\n _read,\n )\n\n # lie and pretend the session is already assigned/stdout is already a thing\n asyncssh_transport.stdout = SSHReader(\"\", \"\")\n\n assert await asyncssh_transport.read() == b\"somebytes\"\n\n\nasync def test_read_exception_not_open(asyncssh_transport):\n with pytest.raises(ScrapliConnectionNotOpened):\n await asyncssh_transport.read()\n\n\nasync def test_read_exception_timeout(monkeypatch, asyncssh_transport):\n async def _read(cls, _):\n await asyncio.sleep(0.5)\n\n monkeypatch.setattr(\n \"asyncssh.stream.SSHReader.read\",\n _read,\n )\n\n # lie and pretend the session is already assigned/stdout is already a thing\n asyncssh_transport.stdout = SSHReader(\"\", \"\")\n asyncssh_transport._base_transport_args.timeout_transport = 0.1\n\n with pytest.raises(ScrapliTimeout):\n await asyncssh_transport.read()\n\n\ndef test_write(asyncssh_transport):\n asyncssh_transport.stdin = BytesIO()\n asyncssh_transport.write(b\"blah\")\n asyncssh_transport.stdin.seek(0)\n assert asyncssh_transport.stdin.read() == b\"blah\"\n\n\ndef test_write_exception(asyncssh_transport):\n with pytest.raises(ScrapliConnectionNotOpened):\n asyncssh_transport.write(\"blah\")\n"},"apis":{"kind":"string","value":"[((3113, 3130), 'asyncssh.stream.SSHReader', 'SSHReader', (['\"\"\"\"\"\"', '\"\"\"\"\"\"'], {}), \"('', '')\\n\", (3122, 3130), False, 'from asyncssh.stream import SSHReader\\n'), ((3683, 3700), 'asyncssh.stream.SSHReader', 'SSHReader', (['\"\"\"\"\"\"', '\"\"\"\"\"\"'], {}), \"('', '')\\n\", (3692, 3700), False, 'from asyncssh.stream import SSHReader\\n'), ((3919, 3928), 'io.BytesIO', 'BytesIO', ([], {}), '()\\n', (3926, 3928), False, 'from io import BytesIO\\n'), ((3262, 3303), 'pytest.raises', 'pytest.raises', (['ScrapliConnectionNotOpened'], {}), '(ScrapliConnectionNotOpened)\\n', (3275, 3303), False, 'import pytest\\n'), ((3779, 3808), 'pytest.raises', 'pytest.raises', (['ScrapliTimeout'], {}), '(ScrapliTimeout)\\n', (3792, 3808), False, 'import pytest\\n'), ((4115, 4156), 'pytest.raises', 'pytest.raises', (['ScrapliConnectionNotOpened'], {}), '(ScrapliConnectionNotOpened)\\n', (4128, 4156), False, 'import pytest\\n'), ((3462, 3480), 'asyncio.sleep', 'asyncio.sleep', (['(0.5)'], {}), '(0.5)\\n', (3475, 3480), False, 'import asyncio\\n'), ((784, 815), 'asyncio.get_event_loop_policy', 'asyncio.get_event_loop_policy', ([], {}), '()\\n', (813, 815), False, 'import asyncio\\n'), ((1400, 1431), 'asyncio.get_event_loop_policy', 'asyncio.get_event_loop_policy', ([], {}), '()\\n', (1429, 1431), False, 'import asyncio\\n'), ((1931, 1962), 'asyncio.get_event_loop_policy', 'asyncio.get_event_loop_policy', ([], {}), '()\\n', (1960, 1962), False, 'import asyncio\\n'), ((2581, 2612), 'asyncio.get_event_loop_policy', 'asyncio.get_event_loop_policy', ([], {}), '()\\n', (2610, 2612), False, 'import asyncio\\n')]"}}},{"rowIdx":8427,"cells":{"repo_name":{"kind":"string","value":"Mozilla-GitHub-Standards/93f18f14efcf5fdfc0e04f9bf247f66baf46663f37b1d2087ab8d850abc90803"},"repo_path":{"kind":"string","value":"apps/ignite/views.py"},"repo_head_hexsha":{"kind":"string","value":"4e374b4d52dfb9039ebe543e7f27682189022307"},"content":{"kind":"string","value":"from django.shortcuts import get_object_or_404\nimport jingo\nimport waffle\n\nfrom django.contrib.auth.models import User\nfrom challenges.models import Submission, Category\nfrom projects.models import Project\nfrom blogs.models import BlogEntry\nfrom events.models import Event\n\n\ndef splash(request, project, slug, template_name='ignite/splash.html'):\n \"\"\"Show an individual project challenge.\"\"\"\n project = get_object_or_404(Project, slug=project)\n challenge = get_object_or_404(project.challenge_set, slug=slug)\n num_blogs = 3\n # have we announced the winners yet - switch template\n if waffle.switch_is_active('announce_winners'):\n template_name = 'ignite/homepage-winners.html'\n num_blogs = 5\n blogs = BlogEntry.objects.filter(\n page='splash'\n ).order_by(\"-updated\",)[:num_blogs]\n # if the dev challenge is open we want to only show dev entries\n if request.development.is_open:\n entries = (Submission.objects.visible()\n .filter(phase__challenge=challenge)\n .filter(phase__name=\"Development\")\n .order_by(\"?\"))\n num_entries = len(entries)\n entries_from = 'apps'\n if num_entries < 5:\n entries = (Submission.objects.visible()\n .filter(phase__challenge=challenge)\n .filter(phase__name=\"Ideation\")\n .order_by(\"?\"))\n entries_from = 'ideas'\n else:\n entries = (Submission.objects.visible()\n .filter(phase__challenge=challenge)\n .filter(phase__name=\"Ideation\")\n .order_by(\"?\"))\n entries_from = 'ideas'\n\n event_list = Event.objects.get_featured()[:5]\n return jingo.render(request, template_name, {\n 'challenge': challenge,\n 'project': project,\n 'phases': list(enumerate(challenge.phases.all(), start=1)),\n 'entries': entries[:5],\n 'categories': Category.objects.all(),\n 'blogs': blogs,\n 'event_list': event_list,\n 'entries_from': entries_from,\n })\n\n\ndef about(request, project, slug, template_name='ignite/about.html'):\n if waffle.switch_is_active('announce_winners'):\n template_name = 'ignite/about-winners.html'\n return jingo.render(request, template_name)\n\n\ndef judges(request, project, slug, template_name='challenges/all_judges.html'):\n \"\"\" List all judges we have in the system \"\"\"\n profiles = []\n for judge in User.objects.filter(groups__name='Judges'):\n profile = judge.get_profile()\n # we only want to show featured profiles\n if profile.featured == True:\n profiles.append(profile)\n\n\n return jingo.render(request, 'ignite/judges.html', {\n 'profiles': profiles\n })\n\n\ndef terms(request, project, slug, template_name='static/terms_conditions.html'):\n return jingo.render(request, template_name, {})\n\n\ndef terms_development(request, project, slug, template_name='static/terms_conditions_development.html'):\n return jingo.render(request, template_name, {})\n\n\ndef fail(request, template_name='404.html'):\n return jingo.render(request, template_name, {}, status=404)\n\n\ndef app_fail(request, template_name='500.html'):\n return jingo.render(request, template_name, {}, status=500)\n\n\ndef action_unavailable_response(request, message=None,\n template_name=\"action_unavailable.html\"):\n \"\"\"Generic page for unavailable actions\"\"\"\n context = {'message': message}\n return jingo.render(request, template_name, context, status=403)\n"},"apis":{"kind":"string","value":"[((409, 449), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Project'], {'slug': 'project'}), '(Project, slug=project)\\n', (426, 449), False, 'from django.shortcuts import get_object_or_404\\n'), ((466, 517), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['project.challenge_set'], {'slug': 'slug'}), '(project.challenge_set, slug=slug)\\n', (483, 517), False, 'from django.shortcuts import get_object_or_404\\n'), ((601, 644), 'waffle.switch_is_active', 'waffle.switch_is_active', (['\"\"\"announce_winners\"\"\"'], {}), \"('announce_winners')\\n\", (624, 644), False, 'import waffle\\n'), ((2285, 2328), 'waffle.switch_is_active', 'waffle.switch_is_active', (['\"\"\"announce_winners\"\"\"'], {}), \"('announce_winners')\\n\", (2308, 2328), False, 'import waffle\\n'), ((2393, 2429), 'jingo.render', 'jingo.render', (['request', 'template_name'], {}), '(request, template_name)\\n', (2405, 2429), False, 'import jingo\\n'), ((2597, 2639), 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', ([], {'groups__name': '\"\"\"Judges\"\"\"'}), \"(groups__name='Judges')\\n\", (2616, 2639), False, 'from django.contrib.auth.models import User\\n'), ((2815, 2882), 'jingo.render', 'jingo.render', (['request', '\"\"\"ignite/judges.html\"\"\"', \"{'profiles': profiles}\"], {}), \"(request, 'ignite/judges.html', {'profiles': profiles})\\n\", (2827, 2882), False, 'import jingo\\n'), ((2991, 3031), 'jingo.render', 'jingo.render', (['request', 'template_name', '{}'], {}), '(request, template_name, {})\\n', (3003, 3031), False, 'import jingo\\n'), ((3150, 3190), 'jingo.render', 'jingo.render', (['request', 'template_name', '{}'], {}), '(request, template_name, {})\\n', (3162, 3190), False, 'import jingo\\n'), ((3249, 3301), 'jingo.render', 'jingo.render', (['request', 'template_name', '{}'], {'status': '(404)'}), '(request, template_name, {}, status=404)\\n', (3261, 3301), False, 'import jingo\\n'), ((3364, 3416), 'jingo.render', 'jingo.render', (['request', 'template_name', '{}'], {'status': '(500)'}), '(request, template_name, {}, status=500)\\n', (3376, 3416), False, 'import jingo\\n'), ((3641, 3698), 'jingo.render', 'jingo.render', (['request', 'template_name', 'context'], {'status': '(403)'}), '(request, template_name, context, status=403)\\n', (3653, 3698), False, 'import jingo\\n'), ((1814, 1842), 'events.models.Event.objects.get_featured', 'Event.objects.get_featured', ([], {}), '()\\n', (1840, 1842), False, 'from events.models import Event\\n'), ((2079, 2101), 'challenges.models.Category.objects.all', 'Category.objects.all', ([], {}), '()\\n', (2099, 2101), False, 'from challenges.models import Submission, Category\\n'), ((735, 774), 'blogs.models.BlogEntry.objects.filter', 'BlogEntry.objects.filter', ([], {'page': '\"\"\"splash\"\"\"'}), \"(page='splash')\\n\", (759, 774), False, 'from blogs.models import BlogEntry\\n'), ((946, 974), 'challenges.models.Submission.objects.visible', 'Submission.objects.visible', ([], {}), '()\\n', (972, 974), False, 'from challenges.models import Submission, Category\\n'), ((1553, 1581), 'challenges.models.Submission.objects.visible', 'Submission.objects.visible', ([], {}), '()\\n', (1579, 1581), False, 'from challenges.models import Submission, Category\\n'), ((1277, 1305), 'challenges.models.Submission.objects.visible', 'Submission.objects.visible', ([], {}), '()\\n', (1303, 1305), False, 'from challenges.models import Submission, Category\\n')]"}}},{"rowIdx":8428,"cells":{"repo_name":{"kind":"string","value":"thebouv/IUS-Hacktoberfest"},"repo_path":{"kind":"string","value":"dataPresenter.py"},"repo_head_hexsha":{"kind":"string","value":"084634ec2feff3e81862d85b3938e1ae2c5aadff"},"content":{"kind":"string","value":"from plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nimport plotly.io as pio\nfrom dataProcessor import parseLabels, parseLangs\nimport plotly.io as pio\nimport os \n\nyears = parseLabels()\nlangs = parseLangs()\n\n#make the plotly results\n\nfig = make_subplots(\n rows=1, cols=2,\n specs=[[{\"type\": \"xy\"}, {\"type\": \"domain\"}]],\n)\n\nfig.add_trace(go.Bar(y = list(langs.values()), x = list(langs.keys()), showlegend=False),\n row=1, col=1)\n\n\nfig.add_trace(go.Pie(values = list(years.values()), labels = list(years.keys())),\n row=1, col=2)\n\n\nfig.update_layout(height=600)\n\npio.write_html(fig, 'index.html', auto_open=True)\n\n"},"apis":{"kind":"string","value":"[((194, 207), 'dataProcessor.parseLabels', 'parseLabels', ([], {}), '()\\n', (205, 207), False, 'from dataProcessor import parseLabels, parseLangs\\n'), ((216, 228), 'dataProcessor.parseLangs', 'parseLangs', ([], {}), '()\\n', (226, 228), False, 'from dataProcessor import parseLabels, parseLangs\\n'), ((262, 337), 'plotly.subplots.make_subplots', 'make_subplots', ([], {'rows': '(1)', 'cols': '(2)', 'specs': \"[[{'type': 'xy'}, {'type': 'domain'}]]\"}), \"(rows=1, cols=2, specs=[[{'type': 'xy'}, {'type': 'domain'}]])\\n\", (275, 337), False, 'from plotly.subplots import make_subplots\\n'), ((613, 662), 'plotly.io.write_html', 'pio.write_html', (['fig', '\"\"\"index.html\"\"\"'], {'auto_open': '(True)'}), \"(fig, 'index.html', auto_open=True)\\n\", (627, 662), True, 'import plotly.io as pio\\n')]"}}},{"rowIdx":8429,"cells":{"repo_name":{"kind":"string","value":"Sairam954/bdl-benchmarks"},"repo_path":{"kind":"string","value":"bdlb/diabetic_retinopathy_diagnosis/benchmark.py"},"repo_head_hexsha":{"kind":"string","value":"6fbc855ca51403ad8f64b6be30ed92f6118c6cae"},"content":{"kind":"string","value":"# Copyright 2019 BDL Benchmarks Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Diabetic retinopathy diagnosis BDL Benchmark.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport os\nfrom typing import Callable\nfrom typing import Dict\nfrom typing import Optional\nfrom typing import Sequence\nfrom typing import Text\nfrom typing import Tuple\nfrom typing import Union\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom absl import logging\n\nfrom ..core import transforms\nfrom ..core.benchmark import Benchmark\nfrom ..core.benchmark import BenchmarkInfo\nfrom ..core.benchmark import DataSplits\nfrom ..core.constants import DATA_DIR\nfrom ..core.levels import Level\n\ntfk = tf.keras\n\n_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR = os.path.join(\n DATA_DIR, \"downloads\", \"manual\", \"diabetic_retinopathy_diagnosis\")\n\n\nclass DiabeticRetinopathyDiagnosisBecnhmark(Benchmark):\n \"\"\"Diabetic retinopathy diagnosis benchmark class.\"\"\"\n\n def __init__(\n self,\n level: Union[Text, Level],\n batch_size: int = 64,\n data_dir: Optional[Text] = None,\n download_and_prepare: bool = False,\n ):\n \"\"\"Constructs a benchmark object.\n\n Args:\n level: `Level` or `str, downstream task level.\n batch_size: (optional) `int`, number of datapoints\n per mini-batch.\n data_dir: (optional) `str`, path to parent data directory.\n download_and_prepare: (optional) `bool`, if the data is not available\n it downloads and preprocesses it.\n \"\"\"\n self.__level = level if isinstance(level, Level) else Level.from_str(level)\n try:\n self.__ds = self.load(level=level,\n batch_size=batch_size,\n data_dir=data_dir or DATA_DIR)\n except AssertionError:\n if not download_and_prepare:\n raise\n else:\n logging.info(\n \"Data not found, `DiabeticRetinopathyDiagnosisBecnhmark.download_and_prepare()`\"\n \" is now running...\")\n self.download_and_prepare()\n\n @classmethod\n def evaluate(\n cls,\n estimator: Callable[[np.ndarray], Tuple[np.ndarray, np.ndarray]],\n dataset: tf.data.Dataset,\n output_dir: Optional[Text] = None,\n name: Optional[Text] = None,\n ) -> Dict[Text, float]:\n \"\"\"Evaluates an `estimator` on the `mode` benchmark dataset.\n\n Args:\n estimator: `lambda x: mu_x, uncertainty_x`, an uncertainty estimation\n function, which returns `mean_x` and predictive `uncertainty_x`.\n dataset: `tf.data.Dataset`, on which dataset to performance evaluation.\n output_dir: (optional) `str`, directory to save figures.\n name: (optional) `str`, the name of the method.\n \"\"\"\n import inspect\n import tqdm\n import tensorflow_datasets as tfds\n from sklearn.metrics import roc_auc_score\n from sklearn.metrics import accuracy_score\n import matplotlib.pyplot as plt\n\n # Containers used for caching performance evaluation\n y_true = list()\n y_pred = list()\n y_uncertainty = list()\n\n # Convert to NumPy iterator if necessary\n ds = dataset if inspect.isgenerator(dataset) else tfds.as_numpy(dataset)\n\n for x, y in tqdm.tqdm(ds):\n # Sample from probabilistic model\n mean, uncertainty = estimator(x)\n # Cache predictions\n y_true.append(y)\n y_pred.append(mean)\n y_uncertainty.append(uncertainty)\n\n # Use vectorized NumPy containers\n y_true = np.concatenate(y_true).flatten()\n y_pred = np.concatenate(y_pred).flatten()\n y_uncertainty = np.concatenate(y_uncertainty).flatten()\n fractions = np.asarray([0.5, 0.6, 0.7, 0.8, 0.9, 1.0])\n\n # Metrics for evaluation\n metrics = zip([\"accuracy\", \"auc\"], cls.metrics())\n\n return {\n metric: cls._evaluate_metric(\n y_true,\n y_pred,\n y_uncertainty,\n fractions,\n lambda y_true, y_pred: metric_fn(y_true, y_pred).numpy(),\n name,\n ) for (metric, metric_fn) in metrics\n }\n\n @staticmethod\n def _evaluate_metric(\n y_true: np.ndarray,\n y_pred: np.ndarray,\n y_uncertainty: np.ndarray,\n fractions: Sequence[float],\n metric_fn: Callable[[np.ndarray, np.ndarray], float],\n name=None,\n ) -> pd.DataFrame:\n \"\"\"Evaluate model predictive distribution on `metric_fn` at data retain\n `fractions`.\n\n Args:\n y_true: `numpy.ndarray`, the ground truth labels, with shape [N].\n y_pred: `numpy.ndarray`, the model predictions, with shape [N].\n y_uncertainty: `numpy.ndarray`, the model uncertainties,\n with shape [N].\n fractions: `iterable`, the percentages of data to retain for\n calculating `metric_fn`.\n metric_fn: `lambda(y_true, y_pred) -> float`, a metric\n function that provides a score given ground truths\n and predictions.\n name: (optional) `str`, the name of the method.\n\n Returns:\n A `pandas.DataFrame` with columns [\"retained_data\", \"mean\", \"std\"],\n that summarizes the scores at different data retained fractions.\n \"\"\"\n\n N = y_true.shape[0]\n\n # Sorts indexes by ascending uncertainty\n I_uncertainties = np.argsort(y_uncertainty)\n\n # Score containers\n mean = np.empty_like(fractions)\n # TODO(filangel): do bootstrap sampling and estimate standard error\n std = np.zeros_like(fractions)\n\n for i, frac in enumerate(fractions):\n # Keep only the %-frac of lowest uncertainties\n I = np.zeros(N, dtype=bool)\n I[I_uncertainties[:int(N * frac)]] = True\n mean[i] = metric_fn(y_true[I], y_pred[I])\n\n # Store\n df = pd.DataFrame(dict(retained_data=fractions, mean=mean, std=std))\n df.name = name\n\n return df\n\n @property\n def datasets(self) -> tf.data.Dataset:\n \"\"\"Pointer to the processed datasets.\"\"\"\n return self.__ds\n\n @property\n def info(self) -> BenchmarkInfo:\n \"\"\"Text description of the benchmark.\"\"\"\n return BenchmarkInfo(description=\"\", urls=\"\", setup=\"\", citation=\"\")\n\n @property\n def level(self) -> Level:\n \"\"\"The downstream task level.\"\"\"\n return self.__level\n\n @staticmethod\n def loss() -> tfk.losses.Loss:\n \"\"\"Loss used for training binary classifiers.\"\"\"\n return tfk.losses.BinaryCrossentropy()\n\n @staticmethod\n def metrics() -> tfk.metrics.Metric:\n \"\"\"Evaluation metrics used for monitoring training.\"\"\"\n return [tfk.metrics.BinaryAccuracy(), tfk.metrics.AUC()]\n\n @staticmethod\n def class_weight() -> Sequence[float]:\n \"\"\"Class weights used for rebalancing the dataset, by skewing the `loss`\n accordingly.\"\"\"\n return [1.0, 4.0]\n\n @classmethod\n def load(\n cls,\n level: Union[Text, Level] = \"realworld\",\n batch_size: int = 64,\n data_dir: Optional[Text] = None,\n as_numpy: bool = False,\n ) -> DataSplits:\n \"\"\"Loads the datasets for the benchmark.\n\n Args:\n level: `Level` or `str, downstream task level.\n batch_size: (optional) `int`, number of datapoints\n per mini-batch.\n data_dir: (optional) `str`, path to parent data directory.\n as_numpy: (optional) `bool`, if True returns python generators\n with `numpy.ndarray` outputs.\n\n Returns:\n A namedtuple with properties:\n * train: `tf.data.Dataset`, train dataset.\n * validation: `tf.data.Dataset`, validation dataset.\n * test: `tf.data.Dataset`, test dataset.\n \"\"\"\n import tensorflow_datasets as tfds\n from .tfds_adapter import DiabeticRetinopathyDiagnosis\n\n # Fetch datasets\n try:\n ds_train, ds_validation, ds_test = DiabeticRetinopathyDiagnosis(\n data_dir=data_dir or DATA_DIR,\n config=level).as_dataset(split=[\"train\", \"validation\", \"test\"],\n shuffle_files=True,\n batch_size=batch_size)\n except AssertionError as ae:\n raise AssertionError(\n str(ae) +\n \" Run DiabeticRetinopathyDiagnosisBecnhmark.download_and_prepare()\"\n \" first and then retry.\")\n\n # Parse task level\n level = level if isinstance(level, Level) else Level.from_str(level)\n # Dataset tranformations\n transforms_train, transforms_eval = cls._preprocessors()\n # Apply transformations\n ds_train = ds_train.map(transforms_train,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n ds_validation = ds_validation.map(\n transforms_eval, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n ds_test = ds_test.map(transforms_eval,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n # Prefetches datasets to memory\n ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)\n ds_validation = ds_validation.prefetch(tf.data.experimental.AUTOTUNE)\n ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE)\n\n if as_numpy:\n # Convert to NumPy iterators\n ds_train = tfds.as_numpy(ds_train)\n ds_validation = tfds.as_numpy(ds_validation)\n ds_test = tfds.as_numpy(ds_test)\n\n return DataSplits(ds_train, ds_validation, ds_test)\n\n @classmethod\n def download_and_prepare(cls, levels=None) -> None:\n \"\"\"Downloads dataset from Kaggle, extracts zip files and processes it using\n `tensorflow_datasets`.\n\n Args:\n levels: (optional) `iterable` of `str`, specifies which\n levels from {'medium', 'realworld'} to prepare,\n if None it prepares all the levels.\n\n Raises:\n OSError: if `~/.kaggle/kaggle.json` is not set up.\n \"\"\"\n # Disable GPU for data download, extraction and preparation\n import os\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n cls._download()\n # cls._extract()\n #cls._prepare(levels)\n\n @staticmethod\n def _download() -> None:\n \"\"\"Downloads data from Kaggle using `tensorflow_datasets`.\n\n Raises:\n OSError: if `~/.kaggle/kaggle.json` is not set up.\n \"\"\"\n import subprocess as sp\n import tensorflow_datasets as tfds\n\n # Append `/home/$USER/.local/bin` to path\n os.environ[\"PATH\"] += \":/home/{}/.local/bin/\".format(os.environ[\"USER\"])\n\n # Download all files from Kaggle\n drd = tfds.download.kaggle.KaggleCompetitionDownloader(\n \"diabetic-retinopathy-detection\")\n try:\n for dfile in drd.competition_files:\n drd.download_file(dfile,\n output_dir=_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR)\n except sp.CalledProcessError as cpe:\n raise OSError(\n str(cpe) + \".\" +\n \" Make sure you have ~/.kaggle/kaggle.json setup, fetched from the Kaggle website\"\n \" https://www.kaggle.com//account -> 'Create New API Key'.\"\n \" Also accept the dataset license by going to\"\n \" https://www.kaggle.com/c/diabetic-retinopathy-detection/rules\"\n \" and look for the button 'I Understand and Accept' (make sure when reloading the\"\n \" page that the button does not pop up again).\")\n\n @staticmethod\n def _extract() -> None:\n \"\"\"Extracts zip files downloaded from Kaggle.\"\"\"\n import glob\n import tqdm\n import zipfile\n import tempfile\n\n # Extract train and test original images\n for split in [\"train\", \"test\"]:\n # Extract \".zip.00*\"\" files to \"\"\n with tempfile.NamedTemporaryFile() as tmp:\n # Concatenate \".zip.00*\" to \".zip\"\n for fname in tqdm.tqdm(\n sorted(\n glob.glob(\n os.path.join(_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR,\n \"{split}.zip.00*\".format(split=split))))):\n # Unzip \".zip\" to \"\"\n with open(fname, \"rb\") as ztmp:\n tmp.write(ztmp.read())\n with zipfile.ZipFile(tmp) as zfile:\n for image in tqdm.tqdm(iterable=zfile.namelist(),\n total=len(zfile.namelist())):\n zfile.extract(member=image,\n path=_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR)\n # Delete \".zip.00*\" files\n for splitzip in os.listdir(_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR):\n if \"{split}.zip.00\".format(split=split) in splitzip:\n os.remove(\n os.path.join(_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR, splitzip))\n\n # Extract \"sample.zip\", \"trainLabels.csv.zip\"\n for fname in [\"sample\", \"trainLabels.csv\"]:\n zfname = os.path.join(_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR,\n \"{fname}.zip\".format(fname=fname))\n with zipfile.ZipFile(zfname) as zfile:\n zfile.extractall(_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR)\n os.remove(zfname)\n\n @staticmethod\n def _prepare(levels=None) -> None:\n \"\"\"Generates the TFRecord objects for medium and realworld experiments.\"\"\"\n import multiprocessing\n from absl import logging\n from .tfds_adapter import DiabeticRetinopathyDiagnosis\n # Hangle each level individually\n for level in levels or [\"medium\", \"realworld\"]:\n dtask = DiabeticRetinopathyDiagnosis(data_dir=DATA_DIR, config=level)\n logging.debug(\"=== Preparing TFRecords for {} ===\".format(level))\n dtask.download_and_prepare()\n\n @classmethod\n def _preprocessors(cls) -> Tuple[transforms.Transform, transforms.Transform]:\n \"\"\"Applies transformations to the raw data.\"\"\"\n import tensorflow_datasets as tfds\n\n # Transformation hyperparameters\n mean = np.asarray([0.42606387, 0.29752496, 0.21309826])\n stddev = np.asarray([0.27662534, 0.20280295, 0.1687619])\n\n class Parse(transforms.Transform):\n \"\"\"Parses datapoints from raw `tf.data.Dataset`.\"\"\"\n\n def __call__(self, x, y=None):\n \"\"\"Returns `as_supervised` tuple.\"\"\"\n return x[\"image\"], x[\"label\"]\n\n class CastX(transforms.Transform):\n \"\"\"Casts image to `dtype`.\"\"\"\n\n def __init__(self, dtype):\n \"\"\"Constructs a type caster.\"\"\"\n self.dtype = dtype\n\n def __call__(self, x, y):\n \"\"\"Returns casted image (to `dtype`) and its (unchanged) label as\n tuple.\"\"\"\n return tf.cast(x, self.dtype), y\n\n class To01X(transforms.Transform):\n \"\"\"Rescales image to [min, max]=[0, 1].\"\"\"\n\n def __call__(self, x, y):\n \"\"\"Returns rescaled image and its (unchanged) label as tuple.\"\"\"\n return x / 255.0, y\n\n # Get augmentation schemes\n [augmentation_config,\n no_augmentation_config] = cls._ImageDataGenerator_config()\n\n # Transformations for train dataset\n transforms_train = transforms.Compose([\n Parse(),\n CastX(tf.float32),\n To01X(),\n transforms.Normalize(mean, stddev),\n # TODO(filangel): hangle batch with ImageDataGenerator\n # transforms.RandomAugment(**augmentation_config),\n ])\n\n # Transformations for validation/test dataset\n transforms_eval = transforms.Compose([\n Parse(),\n CastX(tf.float32),\n To01X(),\n transforms.Normalize(mean, stddev),\n # TODO(filangel): hangle batch with ImageDataGenerator\n # transforms.RandomAugment(**no_augmentation_config),\n ])\n\n return transforms_train, transforms_eval\n\n @staticmethod\n def _ImageDataGenerator_config():\n \"\"\"Returns the configs for the\n `tensorflow.keras.preprocessing.image.ImageDataGenerator`, used for the\n random augmentation of the dataset, following the implementation of\n https://github.com/chleibig/disease-detection/blob/f3401b26aa9b832ff77afe93\n e3faa342f7d088e5/scripts/inspect_data_augmentation.py.\"\"\"\n augmentation_config = dict(\n featurewise_center=False,\n samplewise_center=False,\n featurewise_std_normalization=False,\n samplewise_std_normalization=False,\n zca_whitening=False,\n rotation_range=180.0,\n width_shift_range=0.05,\n height_shift_range=0.05,\n shear_range=0.,\n zoom_range=0.10,\n channel_shift_range=0.,\n fill_mode=\"constant\",\n cval=0.,\n horizontal_flip=True,\n vertical_flip=True,\n data_format=\"channels_last\",\n )\n no_augmentation_config = dict(\n featurewise_center=False,\n samplewise_center=False,\n featurewise_std_normalization=False,\n samplewise_std_normalization=False,\n zca_whitening=False,\n rotation_range=0.0,\n width_shift_range=0.0,\n height_shift_range=0.0,\n shear_range=0.,\n zoom_range=0.0,\n channel_shift_range=0.,\n fill_mode=\"nearest\",\n cval=0.,\n horizontal_flip=False,\n vertical_flip=False,\n data_format=\"channels_last\",\n )\n return augmentation_config, no_augmentation_config\n"},"apis":{"kind":"string","value":"[((1435, 1514), 'os.path.join', 'os.path.join', (['DATA_DIR', '\"\"\"downloads\"\"\"', '\"\"\"manual\"\"\"', '\"\"\"diabetic_retinopathy_diagnosis\"\"\"'], {}), \"(DATA_DIR, 'downloads', 'manual', 'diabetic_retinopathy_diagnosis')\\n\", (1447, 1514), False, 'import os\\n'), ((3842, 3855), 'tqdm.tqdm', 'tqdm.tqdm', (['ds'], {}), '(ds)\\n', (3851, 3855), False, 'import tqdm\\n'), ((4258, 4300), 'numpy.asarray', 'np.asarray', (['[0.5, 0.6, 0.7, 0.8, 0.9, 1.0]'], {}), '([0.5, 0.6, 0.7, 0.8, 0.9, 1.0])\\n', (4268, 4300), True, 'import numpy as np\\n'), ((5816, 5841), 'numpy.argsort', 'np.argsort', (['y_uncertainty'], {}), '(y_uncertainty)\\n', (5826, 5841), True, 'import numpy as np\\n'), ((5877, 5901), 'numpy.empty_like', 'np.empty_like', (['fractions'], {}), '(fractions)\\n', (5890, 5901), True, 'import numpy as np\\n'), ((5984, 6008), 'numpy.zeros_like', 'np.zeros_like', (['fractions'], {}), '(fractions)\\n', (5997, 6008), True, 'import numpy as np\\n'), ((10740, 10827), 'tensorflow_datasets.download.kaggle.KaggleCompetitionDownloader', 'tfds.download.kaggle.KaggleCompetitionDownloader', (['\"\"\"diabetic-retinopathy-detection\"\"\"'], {}), \"(\\n 'diabetic-retinopathy-detection')\\n\", (10788, 10827), True, 'import tensorflow_datasets as tfds\\n'), ((13982, 14030), 'numpy.asarray', 'np.asarray', (['[0.42606387, 0.29752496, 0.21309826]'], {}), '([0.42606387, 0.29752496, 0.21309826])\\n', (13992, 14030), True, 'import numpy as np\\n'), ((14044, 14091), 'numpy.asarray', 'np.asarray', (['[0.27662534, 0.20280295, 0.1687619]'], {}), '([0.27662534, 0.20280295, 0.1687619])\\n', (14054, 14091), True, 'import numpy as np\\n'), ((3768, 3796), 'inspect.isgenerator', 'inspect.isgenerator', (['dataset'], {}), '(dataset)\\n', (3787, 3796), False, 'import inspect\\n'), ((3802, 3824), 'tensorflow_datasets.as_numpy', 'tfds.as_numpy', (['dataset'], {}), '(dataset)\\n', (3815, 3824), True, 'import tensorflow_datasets as tfds\\n'), ((6114, 6137), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'bool'}), '(N, dtype=bool)\\n', (6122, 6137), True, 'import numpy as np\\n'), ((9526, 9549), 'tensorflow_datasets.as_numpy', 'tfds.as_numpy', (['ds_train'], {}), '(ds_train)\\n', (9539, 9549), True, 'import tensorflow_datasets as tfds\\n'), ((9572, 9600), 'tensorflow_datasets.as_numpy', 'tfds.as_numpy', (['ds_validation'], {}), '(ds_validation)\\n', (9585, 9600), True, 'import tensorflow_datasets as tfds\\n'), ((9617, 9639), 'tensorflow_datasets.as_numpy', 'tfds.as_numpy', (['ds_test'], {}), '(ds_test)\\n', (9630, 9639), True, 'import tensorflow_datasets as tfds\\n'), ((12643, 12695), 'os.listdir', 'os.listdir', (['_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR'], {}), '(_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR)\\n', (12653, 12695), False, 'import os\\n'), ((13209, 13226), 'os.remove', 'os.remove', (['zfname'], {}), '(zfname)\\n', (13218, 13226), False, 'import os\\n'), ((4103, 4125), 'numpy.concatenate', 'np.concatenate', (['y_true'], {}), '(y_true)\\n', (4117, 4125), True, 'import numpy as np\\n'), ((4149, 4171), 'numpy.concatenate', 'np.concatenate', (['y_pred'], {}), '(y_pred)\\n', (4163, 4171), True, 'import numpy as np\\n'), ((4202, 4231), 'numpy.concatenate', 'np.concatenate', (['y_uncertainty'], {}), '(y_uncertainty)\\n', (4216, 4231), True, 'import numpy as np\\n'), ((11855, 11884), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\\n', (11882, 11884), False, 'import tempfile\\n'), ((13102, 13125), 'zipfile.ZipFile', 'zipfile.ZipFile', (['zfname'], {}), '(zfname)\\n', (13117, 13125), False, 'import zipfile\\n'), ((2520, 2642), 'absl.logging.info', 'logging.info', (['\"\"\"Data not found, `DiabeticRetinopathyDiagnosisBecnhmark.download_and_prepare()` is now running...\"\"\"'], {}), \"(\\n 'Data not found, `DiabeticRetinopathyDiagnosisBecnhmark.download_and_prepare()` is now running...'\\n )\\n\", (2532, 2642), False, 'from absl import logging\\n'), ((12315, 12335), 'zipfile.ZipFile', 'zipfile.ZipFile', (['tmp'], {}), '(tmp)\\n', (12330, 12335), False, 'import zipfile\\n'), ((14628, 14650), 'tensorflow.cast', 'tf.cast', (['x', 'self.dtype'], {}), '(x, self.dtype)\\n', (14635, 14650), True, 'import tensorflow as tf\\n'), ((12793, 12857), 'os.path.join', 'os.path.join', (['_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR', 'splitzip'], {}), '(_DIABETIC_RETINOPATHY_DIAGNOSIS_DATA_DIR, splitzip)\\n', (12805, 12857), False, 'import os\\n')]"}}},{"rowIdx":8430,"cells":{"repo_name":{"kind":"string","value":"agustinhenze/mibs.snmplabs.com"},"repo_path":{"kind":"string","value":"pysnmp-with-texts/CXConsoleDriver-MIB.py"},"repo_head_hexsha":{"kind":"string","value":"1fc5c07860542b89212f4c8ab807057d9a9206c7"},"content":{"kind":"string","value":"#\n# PySNMP MIB module CXConsoleDriver-MIB (http://snmplabs.com/pysmi)\n# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXConsoleDriver-MIB\n# Produced by pysmi-0.3.4 at Wed May 1 12:32:28 2019\n# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4\n# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) \n#\nInteger, OctetString, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"Integer\", \"OctetString\", \"ObjectIdentifier\")\nNamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\")\nValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueSizeConstraint\", \"ValueRangeConstraint\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ConstraintsUnion\")\ncxConsoleDriver, = mibBuilder.importSymbols(\"CXProduct-SMI\", \"cxConsoleDriver\")\nNotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\")\nCounter64, Gauge32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, Integer32, ModuleIdentity, NotificationType, ObjectIdentity, MibIdentifier, Counter32, iso, Bits = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Counter64\", \"Gauge32\", \"TimeTicks\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"IpAddress\", \"Unsigned32\", \"Integer32\", \"ModuleIdentity\", \"NotificationType\", \"ObjectIdentity\", \"MibIdentifier\", \"Counter32\", \"iso\", \"Bits\")\nTextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\")\ncxCdBaudRate = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 1), Integer32().clone(9600)).setMaxAccess(\"readwrite\")\nif mibBuilder.loadTexts: cxCdBaudRate.setStatus('mandatory')\nif mibBuilder.loadTexts: cxCdBaudRate.setDescription('Determines the baud rate of the console port. The setting of this object is dynamic. The console port immediately implements the option you enter. Options: 9600 19200 38400 115200 Default Value: 9600 Configuration Changed: operative')\ncxCdCharSize = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(7, 8)).clone(8)).setMaxAccess(\"readwrite\")\nif mibBuilder.loadTexts: cxCdCharSize.setStatus('mandatory')\nif mibBuilder.loadTexts: cxCdCharSize.setDescription('Determines how many bits constitute a character for the console port. Options: none - the value is fixed at 8 Default Value: 8 Configuration Changed: none ')\ncxCdParity = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues((\"noParity\", 1), (\"evenParity\", 2), (\"oddParity\", 3))).clone('noParity')).setMaxAccess(\"readwrite\")\nif mibBuilder.loadTexts: cxCdParity.setStatus('mandatory')\nif mibBuilder.loadTexts: cxCdParity.setDescription('Determines the parity scheme the CPU uses to validate the characters it receives through the console port. Options: none - the value is fixed at noParity Default Value: noParity Configuration Changed: none ')\ncxCdStopBit = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)).clone(1)).setMaxAccess(\"readwrite\")\nif mibBuilder.loadTexts: cxCdStopBit.setStatus('mandatory')\nif mibBuilder.loadTexts: cxCdStopBit.setDescription('Determines how many stop bits are at the end of each character the console port receives. Options: none - the value is fixed at 1 Default Value: 1 Configuration Changed: none ')\ncxCdProtocol = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues((\"localConsole\", 1), (\"ppp\", 2))).clone('localConsole')).setMaxAccess(\"readwrite\")\nif mibBuilder.loadTexts: cxCdProtocol.setStatus('mandatory')\nif mibBuilder.loadTexts: cxCdProtocol.setDescription('Determines the protocol (configuration method) for the console port. The setting of this object is dynamic. The console port immediately implements the option you enter. However, if you change the protocol you are currently using to configure the port your connection will be lost. Options: localConsole (1): you use this protocol when you attach a TTY terminal directly to the console port. This protocol requires you to use command line configuration. You also must enter a password to gain access to the configuration tables. You can define the password using the object uiPassword of the CXUserInterface Table. ppp (2): you use this protocol when you are configuring via a windows-based application such as HP/OV (Hewlett Packard-OpenView). Default Value: ppp (2) Configuration Changed: operative')\nmibBuilder.exportSymbols(\"CXConsoleDriver-MIB\", cxCdParity=cxCdParity, cxCdProtocol=cxCdProtocol, cxCdBaudRate=cxCdBaudRate, cxCdStopBit=cxCdStopBit, cxCdCharSize=cxCdCharSize)\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8431,"cells":{"repo_name":{"kind":"string","value":"Lifeistrange/WeiboSpider"},"repo_path":{"kind":"string","value":"db/redis_db.py"},"repo_head_hexsha":{"kind":"string","value":"8aa3465487ef64bb6e9bb4bd503f182a1b38c292"},"content":{"kind":"string","value":"# coding:utf-8\nimport datetime\nimport json\nimport re\n\nimport redis\nfrom config.conf import get_redis_args\n\nredis_args = get_redis_args()\n\n\nclass Cookies(object):\n rd_con = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'),\n password=redis_args.get('password'), db=redis_args.get('cookies'))\n\n rd_con_broker = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'),\n password=redis_args.get('password'), db=redis_args.get('broker'))\n\n @classmethod\n def store_cookies(cls, name, cookies):\n pickled_cookies = json.dumps(\n {'cookies': cookies, 'loginTime': datetime.datetime.now().timestamp()})\n cls.rd_con.hset('account', name, pickled_cookies)\n cls.rd_con.lpush('account_queue', name)\n\n @classmethod\n def fetch_cookies(cls):\n for i in range(cls.rd_con.llen('account_queue')):\n name = cls.rd_con.rpop('account_queue').decode('utf-8')\n if name:\n j_account = cls.rd_con.hget('account', name).decode('utf-8')\n if j_account:\n cls.rd_con.lpush('account_queue', name) # 当账号不存在时,这个name也会清除,并取下一个name\n account = json.loads(j_account)\n login_time = datetime.datetime.fromtimestamp(account['loginTime'])\n if datetime.datetime.now() - login_time > datetime.timedelta(hours=20):\n cls.rd_con.hdel('account', name)\n continue # 丢弃这个过期账号,account_queue会在下次访问的时候被清除,这里不清除是因为分布式的关系\n return name, account['cookies']\n else:\n return None\n\n @classmethod\n def delete_cookies(cls, name):\n cls.rd_con.hdel('account', name)\n return True\n\n @classmethod\n def check_login_task(cls):\n if cls.rd_con_broker.llen('login_queue') > 0:\n cls.rd_con_broker.delete('login_queue')\n\n\nclass Urls(object):\n rd_con = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'),\n password=redis_args.get('password'), db=redis_args.get('urls'))\n\n @classmethod\n def store_crawl_url(cls, url, result):\n cls.rd_con.set(url, result)\n\n\nclass IdNames(object):\n rd_con = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'),\n password=redis_args.get('password'), db=redis_args.get('id_name'))\n\n @classmethod\n def store_id_name(cls, user_name, user_id):\n cls.rd_con.set(user_name, user_id)\n\n @classmethod\n def fetch_uid_by_name(cls, user_name):\n user_id = cls.rd_con.get(user_name)\n if user_id:\n return user_id.decode('utf-8')\n return ''\n"},"apis":{"kind":"string","value":"[((120, 136), 'config.conf.get_redis_args', 'get_redis_args', ([], {}), '()\\n', (134, 136), False, 'from config.conf import get_redis_args\\n'), ((1261, 1282), 'json.loads', 'json.loads', (['j_account'], {}), '(j_account)\\n', (1271, 1282), False, 'import json\\n'), ((1316, 1369), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', ([\"account['loginTime']\"], {}), \"(account['loginTime'])\\n\", (1347, 1369), False, 'import datetime\\n'), ((695, 718), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\\n', (716, 718), False, 'import datetime\\n'), ((1432, 1460), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(20)'}), '(hours=20)\\n', (1450, 1460), False, 'import datetime\\n'), ((1393, 1416), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\\n', (1414, 1416), False, 'import datetime\\n')]"}}},{"rowIdx":8432,"cells":{"repo_name":{"kind":"string","value":"vEpiphyte/vivisect"},"repo_path":{"kind":"string","value":"vivisect/storage/mpfile.py"},"repo_head_hexsha":{"kind":"string","value":"14947a53c6781175f0aa83d49cc16c524a2e23a3"},"content":{"kind":"string","value":"import base64\nimport logging\n\nimport msgpack\n\nlogger = logging.getLogger(__name__)\n\nloadargs = {'use_list': False, 'raw': False}\nif msgpack.version < (1, 0, 0):\n loadargs['encoding'] = 'utf-8'\nelse:\n loadargs['strict_map_key'] = False\n\nVSIG = b'MSGVIV'.ljust(8, b'\\x00')\n\n\ndef vivEventsAppendFile(filename, events):\n with open(filename, 'ab') as f:\n for event in events:\n if event[0] == 20:\n mape = base64.b64encode(event[1][3])\n event = (event[0], (event[1][0], event[1][1], event[1][2], mape))\n msgpack.pack(event, f, use_bin_type=False)\n\n\ndef saveWorkspaceChanges(vw, filename):\n events = vw.exportWorkspaceChanges()\n vivEventsAppendFile(filename, events)\n\n\ndef vivEventsToFile(filename, events):\n with open(filename, 'wb') as f:\n msgpack.pack(VSIG, f, use_bin_type=False)\n for event in events:\n if event[0] == 20:\n mape = base64.b64encode(event[1][3])\n event = (event[0], (event[1][0], event[1][1], event[1][2], mape))\n msgpack.pack(event, f, use_bin_type=False)\n\n\ndef saveWorkspace(vw, filename):\n events = vw.exportWorkspace()\n vivEventsToFile(filename, events)\n\n\ndef vivEventsFromFile(filename):\n events = []\n with open(filename, 'rb') as f:\n unpacker = msgpack.Unpacker(f, **loadargs)\n siggy = next(unpacker)\n if siggy.encode('utf-8') != VSIG:\n logger.warning('Invalid file signature of %s', str(siggy))\n return\n for event in unpacker:\n if event[0] == 20:\n mape = base64.b64decode(event[1][3])\n event = (event[0], (event[1][0], event[1][1], event[1][2], mape))\n events.append(event)\n return events\n\n\ndef loadWorkspace(vw, filename):\n events = vivEventsFromFile(filename)\n vw.importWorkspace(events)\n"},"apis":{"kind":"string","value":"[((55, 82), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\\n', (72, 82), False, 'import logging\\n'), ((818, 859), 'msgpack.pack', 'msgpack.pack', (['VSIG', 'f'], {'use_bin_type': '(False)'}), '(VSIG, f, use_bin_type=False)\\n', (830, 859), False, 'import msgpack\\n'), ((1323, 1354), 'msgpack.Unpacker', 'msgpack.Unpacker', (['f'], {}), '(f, **loadargs)\\n', (1339, 1354), False, 'import msgpack\\n'), ((565, 607), 'msgpack.pack', 'msgpack.pack', (['event', 'f'], {'use_bin_type': '(False)'}), '(event, f, use_bin_type=False)\\n', (577, 607), False, 'import msgpack\\n'), ((1067, 1109), 'msgpack.pack', 'msgpack.pack', (['event', 'f'], {'use_bin_type': '(False)'}), '(event, f, use_bin_type=False)\\n', (1079, 1109), False, 'import msgpack\\n'), ((441, 470), 'base64.b64encode', 'base64.b64encode', (['event[1][3]'], {}), '(event[1][3])\\n', (457, 470), False, 'import base64\\n'), ((943, 972), 'base64.b64encode', 'base64.b64encode', (['event[1][3]'], {}), '(event[1][3])\\n', (959, 972), False, 'import base64\\n'), ((1603, 1632), 'base64.b64decode', 'base64.b64decode', (['event[1][3]'], {}), '(event[1][3])\\n', (1619, 1632), False, 'import base64\\n')]"}}},{"rowIdx":8433,"cells":{"repo_name":{"kind":"string","value":"mathiasose/pytest-pgsql"},"repo_path":{"kind":"string","value":"pytest_pgsql/plugin.py"},"repo_head_hexsha":{"kind":"string","value":"5e076db146699c3b683b49e4a31323c4c23054de"},"content":{"kind":"string","value":"\"\"\"This forms the core of the pytest plugin.\"\"\"\n\nimport pytest\nimport testing.postgresql\n\nfrom pytest_pgsql import database\nfrom pytest_pgsql import ext\n\n\ndef pytest_addoption(parser):\n \"\"\"Add configuration options for pytest_pgsql.\"\"\"\n parser.addoption(\n '--pg-extensions', action='store', default='',\n help=\"A comma-separated list of PostgreSQL extensions to install at \"\n \"the beginning of the session for use by all tests. Example: \"\n \"--pg-extensions=uuid-ossp,pg_tgrm,pgcrypto\")\n\n parser.addoption(\n '--pg-work-mem', type=int, default=32,\n help='Set the value of the `work_mem` setting, in megabytes. '\n '`pytest_pgsql` defaults to 32. Adjusting this up or down can '\n 'help performance; see the Postgres documentation for more details.')\n\n parser.addoption(\n '--pg-conf-opt', action='append',\n help='Add a key=value line that will be appended to postgresql.conf')\n\n\n@pytest.fixture(scope='session')\ndef database_uri(request):\n \"\"\"A fixture giving the connection URI of the session-wide test database.\"\"\"\n # Note: due to the nature of the variable configs, the command line options\n # must be tested manually.\n\n work_mem = request.config.getoption('--pg-work-mem')\n if work_mem < 0: # pragma: no cover\n pytest.exit('ERROR: --pg-work-mem value must be >= 0. Got: %d' % work_mem)\n return\n elif work_mem == 0: # pragma: no cover\n # Disable memory tweak and use the server default.\n work_mem_setting = ''\n else:\n # User wants to change the working memory setting.\n work_mem_setting = '-c work_mem=%dMB ' % work_mem\n\n conf_opts = request.config.getoption('--pg-conf-opt')\n if conf_opts:\n conf_opts_string = ' -c ' + ' -c '.join(conf_opts)\n else:\n conf_opts_string = ''\n\n # pylint: disable=bad-continuation,deprecated-method\n with testing.postgresql.Postgresql(\n postgres_args='-c TimeZone=UTC '\n '-c fsync=off '\n '-c synchronous_commit=off '\n '-c full_page_writes=off '\n + work_mem_setting +\n '-c checkpoint_timeout=30min '\n '-c bgwriter_delay=10000ms'\n + conf_opts_string) as pgdb:\n yield pgdb.url()\n\n\n#: A SQLAlchemy engine shared by the transacted and non-transacted database fixtures.\n#:\n#: .. seealso:: `pytest_pgsql.ext.create_engine_fixture`\n# pylint: disable=invalid-name\npg_engine = ext.create_engine_fixture('pg_engine', scope='session')\n# pylint: enable=invalid-name\n\n\n@pytest.fixture(scope='session')\ndef database_snapshot(pg_engine):\n \"\"\"Create one database snapshot for the session.\n\n The database will be restored to this state after each test.\n\n .. note ::\n\n This is an implementation detail and should not be used directly except\n by derived fixtures.\n \"\"\"\n return database.create_database_snapshot(pg_engine)\n\n\n# pylint: disable=invalid-name\n\n#: Create a test database instance and cleans up after each test finishes.\n#:\n#: You should prefer the `transacted_postgresql_db` fixture unless your test\n#: cannot be run in a single transaction. The `transacted_postgresql_db` fixture\n#: leads to faster tests since it doesn't tear down the entire database between\n#: each test.\npostgresql_db = \\\n database.PostgreSQLTestDB.create_fixture('postgresql_db')\n\n\n#: Create a test database instance that rolls back the current transaction after\n#: each test finishes, verifying its integrity before returning.\n#:\n#: Read the warning in the main documentation page before using this fixture.\ntransacted_postgresql_db = \\\n database.TransactedPostgreSQLTestDB.create_fixture('transacted_postgresql_db')\n\n# pylint: enable=invalid-name\n"},"apis":{"kind":"string","value":"[((976, 1007), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '\"\"\"session\"\"\"'}), \"(scope='session')\\n\", (990, 1007), False, 'import pytest\\n'), ((2552, 2607), 'pytest_pgsql.ext.create_engine_fixture', 'ext.create_engine_fixture', (['\"\"\"pg_engine\"\"\"'], {'scope': '\"\"\"session\"\"\"'}), \"('pg_engine', scope='session')\\n\", (2577, 2607), False, 'from pytest_pgsql import ext\\n'), ((2641, 2672), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '\"\"\"session\"\"\"'}), \"(scope='session')\\n\", (2655, 2672), False, 'import pytest\\n'), ((3402, 3459), 'pytest_pgsql.database.PostgreSQLTestDB.create_fixture', 'database.PostgreSQLTestDB.create_fixture', (['\"\"\"postgresql_db\"\"\"'], {}), \"('postgresql_db')\\n\", (3442, 3459), False, 'from pytest_pgsql import database\\n'), ((3722, 3800), 'pytest_pgsql.database.TransactedPostgreSQLTestDB.create_fixture', 'database.TransactedPostgreSQLTestDB.create_fixture', (['\"\"\"transacted_postgresql_db\"\"\"'], {}), \"('transacted_postgresql_db')\\n\", (3772, 3800), False, 'from pytest_pgsql import database\\n'), ((2971, 3015), 'pytest_pgsql.database.create_database_snapshot', 'database.create_database_snapshot', (['pg_engine'], {}), '(pg_engine)\\n', (3004, 3015), False, 'from pytest_pgsql import database\\n'), ((1336, 1410), 'pytest.exit', 'pytest.exit', ([\"('ERROR: --pg-work-mem value must be >= 0. Got: %d' % work_mem)\"], {}), \"('ERROR: --pg-work-mem value must be >= 0. Got: %d' % work_mem)\\n\", (1347, 1410), False, 'import pytest\\n')]"}}},{"rowIdx":8434,"cells":{"repo_name":{"kind":"string","value":"abrahamneben/orbcomm_beam_mapping"},"repo_path":{"kind":"string","value":"power_data_to_sat_passes/date_utils.py"},"repo_head_hexsha":{"kind":"string","value":"71b3e7d6e4214db0a6f4e68ebeeb7d7f846f5004"},"content":{"kind":"string","value":"# written by abraham on aug 24\n\n\ndef dyear2date(dyear):\n\n\tyear = int(dyear)\n\n\tmonth_lengths = [31,28,31,30,31,30,31,31,30,31,30,31]\n\tdays_before_months = [0,31,59,90,120,151,181,212,243,273,304,334]\n\n\tdays_into_year_f = (dyear-year)*365\n\tdays_into_year_i = int(days_into_year_f)\n\n\tfor i in range(12):\n\t\tif days_before_months[i] < days_into_year_f < (days_before_months[i]+month_lengths[i]):\n\t\t\tmonth = i+1\n\t\t\tbreak\n\n\tdate = days_into_year_i - days_before_months[month-1]\n\thours_f = (days_into_year_f-days_into_year_i)*24\n\thours_i = int(hours_f)\n\tminutes_f = (hours_f-hours_i)*60\n\tminutes_i = int(minutes_f)\n\tseconds_i = int((minutes_f-minutes_i)*60)\n\n\treturn \"%02d/%02d/%d %02d:%02d:%02d\" % (month,date,year,hours_i,minutes_i,seconds_i)\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8435,"cells":{"repo_name":{"kind":"string","value":"sourcery-ai-bot/personal-expenses-accounting"},"repo_path":{"kind":"string","value":"app/base/count_lines.py"},"repo_head_hexsha":{"kind":"string","value":"55e76744a06fd502d119f57427cd7a0bfaf68fe1"},"content":{"kind":"string","value":"import glob\nfrom os import walk\n\nexclude_folders = [\n 'node_modules',\n 'ios',\n 'android',\n '__pycache__'\n]\n\nexclude_files = [\n 'json',\n 'txt',\n 'traineddata',\n 'lstmf',\n 'yml',\n 'md'\n 'log',\n 'env',\n 'gitignore',\n 'dockerignore'\n]\n\n# get all files in directory\ndirr = '/home/viktor/Documents/personal-expenses-accounting/app/services/web_service/'\nfolders = glob.glob(dirr + '/**/', recursive=True)\n\n# only app related directories\ndirectories = []\nfor folder in folders:\n current_folder = folder.split('/')[-2]\n if current_folder not in exclude_folders:\n files = glob.glob(folder + '*')\n print(files)\n directories.append(folder)\n\n\n# num_lines = sum(1 for line in open('myfile.txt'))\n"},"apis":{"kind":"string","value":"[((400, 440), 'glob.glob', 'glob.glob', ([\"(dirr + '/**/')\"], {'recursive': '(True)'}), \"(dirr + '/**/', recursive=True)\\n\", (409, 440), False, 'import glob\\n'), ((618, 641), 'glob.glob', 'glob.glob', ([\"(folder + '*')\"], {}), \"(folder + '*')\\n\", (627, 641), False, 'import glob\\n')]"}}},{"rowIdx":8436,"cells":{"repo_name":{"kind":"string","value":"rgurevych/python_for_testers"},"repo_path":{"kind":"string","value":"data/contacts.py"},"repo_head_hexsha":{"kind":"string","value":"04023a5d6ea480f7828aa56e8a4094b744e05721"},"content":{"kind":"string","value":"\nfrom models.contact import Contact\n\ntestdata = [Contact(first_name=\"Firstname\", last_name=\"Lastname\", mobile_phone=\"+12345678\",\n work_phone=\"12345\", home_phone=\"67890\", fax=\"55443322\", email_1=\"email_1@email.com\",\n email_2=\"email_2@email.com\", email_3=\"email_3@email.com\",\n address=\"Street, 15 \\n 12345 New-York\")]\n"},"apis":{"kind":"string","value":"[((49, 328), 'models.contact.Contact', 'Contact', ([], {'first_name': '\"\"\"Firstname\"\"\"', 'last_name': '\"\"\"Lastname\"\"\"', 'mobile_phone': '\"\"\"+12345678\"\"\"', 'work_phone': '\"\"\"12345\"\"\"', 'home_phone': '\"\"\"67890\"\"\"', 'fax': '\"\"\"55443322\"\"\"', 'email_1': '\"\"\"email_1@email.com\"\"\"', 'email_2': '\"\"\"email_2@email.com\"\"\"', 'email_3': '\"\"\"email_3@email.com\"\"\"', 'address': '\"\"\"Street, 15 \\n 12345 New-York\"\"\"'}), '(first_name=\\'Firstname\\', last_name=\\'Lastname\\', mobile_phone=\\n \\'+12345678\\', work_phone=\\'12345\\', home_phone=\\'67890\\', fax=\\'55443322\\',\\n email_1=\\'email_1@email.com\\', email_2=\\'email_2@email.com\\', email_3=\\n \\'email_3@email.com\\', address=\"\"\"Street, 15 \\n 12345 New-York\"\"\")\\n', (56, 328), False, 'from models.contact import Contact\\n')]"}}},{"rowIdx":8437,"cells":{"repo_name":{"kind":"string","value":"nobuto-m/charm-helpers"},"repo_path":{"kind":"string","value":"charmhelpers/contrib/charmsupport/nrpe.py"},"repo_head_hexsha":{"kind":"string","value":"4cffc05ace43234d34b040cccdde3460f68cb673"},"content":{"kind":"string","value":"# Copyright 2014-2015 Canonical Limited.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Compatibility with the nrpe-external-master charm\"\"\"\n# Copyright 2012 Canonical Ltd.\n#\n# Authors:\n# Matthew Wedgwood \n\nimport subprocess\nimport pwd\nimport grp\nimport os\nimport glob\nimport shutil\nimport re\nimport shlex\nimport yaml\n\nfrom charmhelpers.core.hookenv import (\n config,\n hook_name,\n local_unit,\n log,\n relation_get,\n relation_ids,\n relation_set,\n relations_of_type,\n)\n\nfrom charmhelpers.core.host import service\nfrom charmhelpers.core import host\n\n# This module adds compatibility with the nrpe-external-master and plain nrpe\n# subordinate charms. To use it in your charm:\n#\n# 1. Update metadata.yaml\n#\n# provides:\n# (...)\n# nrpe-external-master:\n# interface: nrpe-external-master\n# scope: container\n#\n# and/or\n#\n# provides:\n# (...)\n# local-monitors:\n# interface: local-monitors\n# scope: container\n\n#\n# 2. Add the following to config.yaml\n#\n# nagios_context:\n# default: \"juju\"\n# type: string\n# description: |\n# Used by the nrpe subordinate charms.\n# A string that will be prepended to instance name to set the host name\n# in nagios. So for instance the hostname would be something like:\n# juju-myservice-0\n# If you're running multiple environments with the same services in them\n# this allows you to differentiate between them.\n# nagios_servicegroups:\n# default: \"\"\n# type: string\n# description: |\n# A comma-separated list of nagios servicegroups.\n# If left empty, the nagios_context will be used as the servicegroup\n#\n# 3. Add custom checks (Nagios plugins) to files/nrpe-external-master\n#\n# 4. Update your hooks.py with something like this:\n#\n# from charmsupport.nrpe import NRPE\n# (...)\n# def update_nrpe_config():\n# nrpe_compat = NRPE()\n# nrpe_compat.add_check(\n# shortname = \"myservice\",\n# description = \"Check MyService\",\n# check_cmd = \"check_http -w 2 -c 10 http://localhost\"\n# )\n# nrpe_compat.add_check(\n# \"myservice_other\",\n# \"Check for widget failures\",\n# check_cmd = \"/srv/myapp/scripts/widget_check\"\n# )\n# nrpe_compat.write()\n#\n# def config_changed():\n# (...)\n# update_nrpe_config()\n#\n# def nrpe_external_master_relation_changed():\n# update_nrpe_config()\n#\n# def local_monitors_relation_changed():\n# update_nrpe_config()\n#\n# 4.a If your charm is a subordinate charm set primary=False\n#\n# from charmsupport.nrpe import NRPE\n# (...)\n# def update_nrpe_config():\n# nrpe_compat = NRPE(primary=False)\n#\n# 5. ln -s hooks.py nrpe-external-master-relation-changed\n# ln -s hooks.py local-monitors-relation-changed\n\n\nclass CheckException(Exception):\n pass\n\n\nclass Check(object):\n shortname_re = '[A-Za-z0-9-_.@]+$'\n service_template = (\"\"\"\n#---------------------------------------------------\n# This file is Juju managed\n#---------------------------------------------------\ndefine service {{\n use active-service\n host_name {nagios_hostname}\n service_description {nagios_hostname}[{shortname}] \"\"\"\n \"\"\"{description}\n check_command check_nrpe!{command}\n servicegroups {nagios_servicegroup}\n}}\n\"\"\")\n\n def __init__(self, shortname, description, check_cmd):\n super(Check, self).__init__()\n # XXX: could be better to calculate this from the service name\n if not re.match(self.shortname_re, shortname):\n raise CheckException(\"shortname must match {}\".format(\n Check.shortname_re))\n self.shortname = shortname\n self.command = \"check_{}\".format(shortname)\n # Note: a set of invalid characters is defined by the\n # Nagios server config\n # The default is: illegal_object_name_chars=`~!$%^&*\"|'<>?,()=\n self.description = description\n self.check_cmd = self._locate_cmd(check_cmd)\n\n def _get_check_filename(self):\n return os.path.join(NRPE.nrpe_confdir, '{}.cfg'.format(self.command))\n\n def _get_service_filename(self, hostname):\n return os.path.join(NRPE.nagios_exportdir,\n 'service__{}_{}.cfg'.format(hostname, self.command))\n\n def _locate_cmd(self, check_cmd):\n search_path = (\n '/usr/lib/nagios/plugins',\n '/usr/local/lib/nagios/plugins',\n )\n parts = shlex.split(check_cmd)\n for path in search_path:\n if os.path.exists(os.path.join(path, parts[0])):\n command = os.path.join(path, parts[0])\n if len(parts) > 1:\n command += \" \" + \" \".join(parts[1:])\n return command\n log('Check command not found: {}'.format(parts[0]))\n return ''\n\n def _remove_service_files(self):\n if not os.path.exists(NRPE.nagios_exportdir):\n return\n for f in os.listdir(NRPE.nagios_exportdir):\n if f.endswith('_{}.cfg'.format(self.command)):\n os.remove(os.path.join(NRPE.nagios_exportdir, f))\n\n def remove(self, hostname):\n nrpe_check_file = self._get_check_filename()\n if os.path.exists(nrpe_check_file):\n os.remove(nrpe_check_file)\n self._remove_service_files()\n\n def write(self, nagios_context, hostname, nagios_servicegroups):\n nrpe_check_file = self._get_check_filename()\n with open(nrpe_check_file, 'w') as nrpe_check_config:\n nrpe_check_config.write(\"# check {}\\n\".format(self.shortname))\n if nagios_servicegroups:\n nrpe_check_config.write(\n \"# The following header was added automatically by juju\\n\")\n nrpe_check_config.write(\n \"# Modifying it will affect nagios monitoring and alerting\\n\")\n nrpe_check_config.write(\n \"# servicegroups: {}\\n\".format(nagios_servicegroups))\n nrpe_check_config.write(\"command[{}]={}\\n\".format(\n self.command, self.check_cmd))\n\n if not os.path.exists(NRPE.nagios_exportdir):\n log('Not writing service config as {} is not accessible'.format(\n NRPE.nagios_exportdir))\n else:\n self.write_service_config(nagios_context, hostname,\n nagios_servicegroups)\n\n def write_service_config(self, nagios_context, hostname,\n nagios_servicegroups):\n self._remove_service_files()\n\n templ_vars = {\n 'nagios_hostname': hostname,\n 'nagios_servicegroup': nagios_servicegroups,\n 'description': self.description,\n 'shortname': self.shortname,\n 'command': self.command,\n }\n nrpe_service_text = Check.service_template.format(**templ_vars)\n nrpe_service_file = self._get_service_filename(hostname)\n with open(nrpe_service_file, 'w') as nrpe_service_config:\n nrpe_service_config.write(str(nrpe_service_text))\n\n def run(self):\n subprocess.call(self.check_cmd)\n\n\nclass NRPE(object):\n nagios_logdir = '/var/log/nagios'\n nagios_exportdir = '/var/lib/nagios/export'\n nrpe_confdir = '/etc/nagios/nrpe.d'\n homedir = '/var/lib/nagios' # home dir provided by nagios-nrpe-server\n\n def __init__(self, hostname=None, primary=True):\n super(NRPE, self).__init__()\n self.config = config()\n self.primary = primary\n self.nagios_context = self.config['nagios_context']\n if 'nagios_servicegroups' in self.config and self.config['nagios_servicegroups']:\n self.nagios_servicegroups = self.config['nagios_servicegroups']\n else:\n self.nagios_servicegroups = self.nagios_context\n self.unit_name = local_unit().replace('/', '-')\n if hostname:\n self.hostname = hostname\n else:\n nagios_hostname = get_nagios_hostname()\n if nagios_hostname:\n self.hostname = nagios_hostname\n else:\n self.hostname = \"{}-{}\".format(self.nagios_context, self.unit_name)\n self.checks = []\n # Iff in an nrpe-external-master relation hook, set primary status\n relation = relation_ids('nrpe-external-master')\n if relation:\n log(\"Setting charm primary status {}\".format(primary))\n for rid in relation:\n relation_set(relation_id=rid, relation_settings={'primary': self.primary})\n self.remove_check_queue = set()\n\n def add_check(self, *args, **kwargs):\n shortname = None\n if kwargs.get('shortname') is None:\n if len(args) > 0:\n shortname = args[0]\n else:\n shortname = kwargs['shortname']\n\n self.checks.append(Check(*args, **kwargs))\n try:\n self.remove_check_queue.remove(shortname)\n except KeyError:\n pass\n\n def remove_check(self, *args, **kwargs):\n if kwargs.get('shortname') is None:\n raise ValueError('shortname of check must be specified')\n\n # Use sensible defaults if they're not specified - these are not\n # actually used during removal, but they're required for constructing\n # the Check object; check_disk is chosen because it's part of the\n # nagios-plugins-basic package.\n if kwargs.get('check_cmd') is None:\n kwargs['check_cmd'] = 'check_disk'\n if kwargs.get('description') is None:\n kwargs['description'] = ''\n\n check = Check(*args, **kwargs)\n check.remove(self.hostname)\n self.remove_check_queue.add(kwargs['shortname'])\n\n def write(self):\n try:\n nagios_uid = pwd.getpwnam('nagios').pw_uid\n nagios_gid = grp.getgrnam('nagios').gr_gid\n except Exception:\n log(\"Nagios user not set up, nrpe checks not updated\")\n return\n\n if not os.path.exists(NRPE.nagios_logdir):\n os.mkdir(NRPE.nagios_logdir)\n os.chown(NRPE.nagios_logdir, nagios_uid, nagios_gid)\n\n nrpe_monitors = {}\n monitors = {\"monitors\": {\"remote\": {\"nrpe\": nrpe_monitors}}}\n for nrpecheck in self.checks:\n nrpecheck.write(self.nagios_context, self.hostname,\n self.nagios_servicegroups)\n nrpe_monitors[nrpecheck.shortname] = {\n \"command\": nrpecheck.command,\n }\n\n # update-status hooks are configured to firing every 5 minutes by\n # default. When nagios-nrpe-server is restarted, the nagios server\n # reports checks failing causing unnecessary alerts. Let's not restart\n # on update-status hooks.\n if not hook_name() == 'update-status':\n service('restart', 'nagios-nrpe-server')\n\n monitor_ids = relation_ids(\"local-monitors\") + \\\n relation_ids(\"nrpe-external-master\")\n for rid in monitor_ids:\n reldata = relation_get(unit=local_unit(), rid=rid)\n if 'monitors' in reldata:\n # update the existing set of monitors with the new data\n old_monitors = yaml.safe_load(reldata['monitors'])\n old_nrpe_monitors = old_monitors['monitors']['remote']['nrpe']\n # remove keys that are in the remove_check_queue\n old_nrpe_monitors = {k: v for k, v in old_nrpe_monitors.items()\n if k not in self.remove_check_queue}\n # update/add nrpe_monitors\n old_nrpe_monitors.update(nrpe_monitors)\n old_monitors['monitors']['remote']['nrpe'] = old_nrpe_monitors\n # write back to the relation\n relation_set(relation_id=rid, monitors=yaml.dump(old_monitors))\n else:\n # write a brand new set of monitors, as no existing ones.\n relation_set(relation_id=rid, monitors=yaml.dump(monitors))\n\n self.remove_check_queue.clear()\n\n\ndef get_nagios_hostcontext(relation_name='nrpe-external-master'):\n \"\"\"\n Query relation with nrpe subordinate, return the nagios_host_context\n\n :param str relation_name: Name of relation nrpe sub joined to\n \"\"\"\n for rel in relations_of_type(relation_name):\n if 'nagios_host_context' in rel:\n return rel['nagios_host_context']\n\n\ndef get_nagios_hostname(relation_name='nrpe-external-master'):\n \"\"\"\n Query relation with nrpe subordinate, return the nagios_hostname\n\n :param str relation_name: Name of relation nrpe sub joined to\n \"\"\"\n for rel in relations_of_type(relation_name):\n if 'nagios_hostname' in rel:\n return rel['nagios_hostname']\n\n\ndef get_nagios_unit_name(relation_name='nrpe-external-master'):\n \"\"\"\n Return the nagios unit name prepended with host_context if needed\n\n :param str relation_name: Name of relation nrpe sub joined to\n \"\"\"\n host_context = get_nagios_hostcontext(relation_name)\n if host_context:\n unit = \"%s:%s\" % (host_context, local_unit())\n else:\n unit = local_unit()\n return unit\n\n\ndef add_init_service_checks(nrpe, services, unit_name, immediate_check=True):\n \"\"\"\n Add checks for each service in list\n\n :param NRPE nrpe: NRPE object to add check to\n :param list services: List of services to check\n :param str unit_name: Unit name to use in check description\n :param bool immediate_check: For sysv init, run the service check immediately\n \"\"\"\n for svc in services:\n # Don't add a check for these services from neutron-gateway\n if svc in ['ext-port', 'os-charm-phy-nic-mtu']:\n next\n\n upstart_init = '/etc/init/%s.conf' % svc\n sysv_init = '/etc/init.d/%s' % svc\n\n if host.init_is_systemd():\n nrpe.add_check(\n shortname=svc,\n description='process check {%s}' % unit_name,\n check_cmd='check_systemd.py %s' % svc\n )\n elif os.path.exists(upstart_init):\n nrpe.add_check(\n shortname=svc,\n description='process check {%s}' % unit_name,\n check_cmd='check_upstart_job %s' % svc\n )\n elif os.path.exists(sysv_init):\n cronpath = '/etc/cron.d/nagios-service-check-%s' % svc\n checkpath = '%s/service-check-%s.txt' % (nrpe.homedir, svc)\n croncmd = (\n '/usr/local/lib/nagios/plugins/check_exit_status.pl '\n '-e -s /etc/init.d/%s status' % svc\n )\n cron_file = '*/5 * * * * root %s > %s\\n' % (croncmd, checkpath)\n f = open(cronpath, 'w')\n f.write(cron_file)\n f.close()\n nrpe.add_check(\n shortname=svc,\n description='service check {%s}' % unit_name,\n check_cmd='check_status_file.py -f %s' % checkpath,\n )\n # if /var/lib/nagios doesn't exist open(checkpath, 'w') will fail\n # (LP: #1670223).\n if immediate_check and os.path.isdir(nrpe.homedir):\n f = open(checkpath, 'w')\n subprocess.call(\n croncmd.split(),\n stdout=f,\n stderr=subprocess.STDOUT\n )\n f.close()\n os.chmod(checkpath, 0o644)\n\n\ndef copy_nrpe_checks(nrpe_files_dir=None):\n \"\"\"\n Copy the nrpe checks into place\n\n \"\"\"\n NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins'\n if nrpe_files_dir is None:\n # determine if \"charmhelpers\" is in CHARMDIR or CHARMDIR/hooks\n for segment in ['.', 'hooks']:\n nrpe_files_dir = os.path.abspath(os.path.join(\n os.getenv('CHARM_DIR'),\n segment,\n 'charmhelpers',\n 'contrib',\n 'openstack',\n 'files'))\n if os.path.isdir(nrpe_files_dir):\n break\n else:\n raise RuntimeError(\"Couldn't find charmhelpers directory\")\n if not os.path.exists(NAGIOS_PLUGINS):\n os.makedirs(NAGIOS_PLUGINS)\n for fname in glob.glob(os.path.join(nrpe_files_dir, \"check_*\")):\n if os.path.isfile(fname):\n shutil.copy2(fname,\n os.path.join(NAGIOS_PLUGINS, os.path.basename(fname)))\n\n\ndef add_haproxy_checks(nrpe, unit_name):\n \"\"\"\n Add checks for each service in list\n\n :param NRPE nrpe: NRPE object to add check to\n :param str unit_name: Unit name to use in check description\n \"\"\"\n nrpe.add_check(\n shortname='haproxy_servers',\n description='Check HAProxy {%s}' % unit_name,\n check_cmd='check_haproxy.sh')\n nrpe.add_check(\n shortname='haproxy_queue',\n description='Check HAProxy queue depth {%s}' % unit_name,\n check_cmd='check_haproxy_queue_depth.sh')\n"},"apis":{"kind":"string","value":"[((12981, 13013), 'charmhelpers.core.hookenv.relations_of_type', 'relations_of_type', (['relation_name'], {}), '(relation_name)\\n', (12998, 13013), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((13334, 13366), 'charmhelpers.core.hookenv.relations_of_type', 'relations_of_type', (['relation_name'], {}), '(relation_name)\\n', (13351, 13366), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((5158, 5180), 'shlex.split', 'shlex.split', (['check_cmd'], {}), '(check_cmd)\\n', (5169, 5180), False, 'import shlex\\n'), ((5659, 5692), 'os.listdir', 'os.listdir', (['NRPE.nagios_exportdir'], {}), '(NRPE.nagios_exportdir)\\n', (5669, 5692), False, 'import os\\n'), ((5916, 5947), 'os.path.exists', 'os.path.exists', (['nrpe_check_file'], {}), '(nrpe_check_file)\\n', (5930, 5947), False, 'import os\\n'), ((7801, 7832), 'subprocess.call', 'subprocess.call', (['self.check_cmd'], {}), '(self.check_cmd)\\n', (7816, 7832), False, 'import subprocess\\n'), ((8169, 8177), 'charmhelpers.core.hookenv.config', 'config', ([], {}), '()\\n', (8175, 8177), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((8990, 9026), 'charmhelpers.core.hookenv.relation_ids', 'relation_ids', (['\"\"\"nrpe-external-master\"\"\"'], {}), \"('nrpe-external-master')\\n\", (9002, 9026), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((13823, 13835), 'charmhelpers.core.hookenv.local_unit', 'local_unit', ([], {}), '()\\n', (13833, 13835), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((14508, 14530), 'charmhelpers.core.host.init_is_systemd', 'host.init_is_systemd', ([], {}), '()\\n', (14528, 14530), False, 'from charmhelpers.core import host\\n'), ((16800, 16830), 'os.path.exists', 'os.path.exists', (['NAGIOS_PLUGINS'], {}), '(NAGIOS_PLUGINS)\\n', (16814, 16830), False, 'import os\\n'), ((16840, 16867), 'os.makedirs', 'os.makedirs', (['NAGIOS_PLUGINS'], {}), '(NAGIOS_PLUGINS)\\n', (16851, 16867), False, 'import os\\n'), ((16895, 16934), 'os.path.join', 'os.path.join', (['nrpe_files_dir', '\"\"\"check_*\"\"\"'], {}), \"(nrpe_files_dir, 'check_*')\\n\", (16907, 16934), False, 'import os\\n'), ((16948, 16969), 'os.path.isfile', 'os.path.isfile', (['fname'], {}), '(fname)\\n', (16962, 16969), False, 'import os\\n'), ((4204, 4242), 're.match', 're.match', (['self.shortname_re', 'shortname'], {}), '(self.shortname_re, shortname)\\n', (4212, 4242), False, 'import re\\n'), ((5584, 5621), 'os.path.exists', 'os.path.exists', (['NRPE.nagios_exportdir'], {}), '(NRPE.nagios_exportdir)\\n', (5598, 5621), False, 'import os\\n'), ((5961, 5987), 'os.remove', 'os.remove', (['nrpe_check_file'], {}), '(nrpe_check_file)\\n', (5970, 5987), False, 'import os\\n'), ((6808, 6845), 'os.path.exists', 'os.path.exists', (['NRPE.nagios_exportdir'], {}), '(NRPE.nagios_exportdir)\\n', (6822, 6845), False, 'import os\\n'), ((10683, 10717), 'os.path.exists', 'os.path.exists', (['NRPE.nagios_logdir'], {}), '(NRPE.nagios_logdir)\\n', (10697, 10717), False, 'import os\\n'), ((10731, 10759), 'os.mkdir', 'os.mkdir', (['NRPE.nagios_logdir'], {}), '(NRPE.nagios_logdir)\\n', (10739, 10759), False, 'import os\\n'), ((10772, 10824), 'os.chown', 'os.chown', (['NRPE.nagios_logdir', 'nagios_uid', 'nagios_gid'], {}), '(NRPE.nagios_logdir, nagios_uid, nagios_gid)\\n', (10780, 10824), False, 'import os\\n'), ((11512, 11552), 'charmhelpers.core.host.service', 'service', (['\"\"\"restart\"\"\"', '\"\"\"nagios-nrpe-server\"\"\"'], {}), \"('restart', 'nagios-nrpe-server')\\n\", (11519, 11552), False, 'from charmhelpers.core.host import service\\n'), ((11576, 11606), 'charmhelpers.core.hookenv.relation_ids', 'relation_ids', (['\"\"\"local-monitors\"\"\"'], {}), \"('local-monitors')\\n\", (11588, 11606), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((11623, 11659), 'charmhelpers.core.hookenv.relation_ids', 'relation_ids', (['\"\"\"nrpe-external-master\"\"\"'], {}), \"('nrpe-external-master')\\n\", (11635, 11659), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((14734, 14762), 'os.path.exists', 'os.path.exists', (['upstart_init'], {}), '(upstart_init)\\n', (14748, 14762), False, 'import os\\n'), ((16651, 16680), 'os.path.isdir', 'os.path.isdir', (['nrpe_files_dir'], {}), '(nrpe_files_dir)\\n', (16664, 16680), False, 'import os\\n'), ((5244, 5272), 'os.path.join', 'os.path.join', (['path', 'parts[0]'], {}), '(path, parts[0])\\n', (5256, 5272), False, 'import os\\n'), ((5301, 5329), 'os.path.join', 'os.path.join', (['path', 'parts[0]'], {}), '(path, parts[0])\\n', (5313, 5329), False, 'import os\\n'), ((8534, 8546), 'charmhelpers.core.hookenv.local_unit', 'local_unit', ([], {}), '()\\n', (8544, 8546), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((9164, 9238), 'charmhelpers.core.hookenv.relation_set', 'relation_set', ([], {'relation_id': 'rid', 'relation_settings': \"{'primary': self.primary}\"}), \"(relation_id=rid, relation_settings={'primary': self.primary})\\n\", (9176, 9238), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((10470, 10492), 'pwd.getpwnam', 'pwd.getpwnam', (['\"\"\"nagios\"\"\"'], {}), \"('nagios')\\n\", (10482, 10492), False, 'import pwd\\n'), ((10525, 10547), 'grp.getgrnam', 'grp.getgrnam', (['\"\"\"nagios\"\"\"'], {}), \"('nagios')\\n\", (10537, 10547), False, 'import grp\\n'), ((10593, 10647), 'charmhelpers.core.hookenv.log', 'log', (['\"\"\"Nagios user not set up, nrpe checks not updated\"\"\"'], {}), \"('Nagios user not set up, nrpe checks not updated')\\n\", (10596, 10647), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((11468, 11479), 'charmhelpers.core.hookenv.hook_name', 'hook_name', ([], {}), '()\\n', (11477, 11479), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((11896, 11931), 'yaml.safe_load', 'yaml.safe_load', ([\"reldata['monitors']\"], {}), \"(reldata['monitors'])\\n\", (11910, 11931), False, 'import yaml\\n'), ((13784, 13796), 'charmhelpers.core.hookenv.local_unit', 'local_unit', ([], {}), '()\\n', (13794, 13796), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((14967, 14992), 'os.path.exists', 'os.path.exists', (['sysv_init'], {}), '(sysv_init)\\n', (14981, 14992), False, 'import os\\n'), ((5779, 5817), 'os.path.join', 'os.path.join', (['NRPE.nagios_exportdir', 'f'], {}), '(NRPE.nagios_exportdir, f)\\n', (5791, 5817), False, 'import os\\n'), ((11732, 11744), 'charmhelpers.core.hookenv.local_unit', 'local_unit', ([], {}), '()\\n', (11742, 11744), False, 'from charmhelpers.core.hookenv import config, hook_name, local_unit, log, relation_get, relation_ids, relation_set, relations_of_type\\n'), ((16473, 16495), 'os.getenv', 'os.getenv', (['\"\"\"CHARM_DIR\"\"\"'], {}), \"('CHARM_DIR')\\n\", (16482, 16495), False, 'import os\\n'), ((17057, 17080), 'os.path.basename', 'os.path.basename', (['fname'], {}), '(fname)\\n', (17073, 17080), False, 'import os\\n'), ((12508, 12531), 'yaml.dump', 'yaml.dump', (['old_monitors'], {}), '(old_monitors)\\n', (12517, 12531), False, 'import yaml\\n'), ((12680, 12699), 'yaml.dump', 'yaml.dump', (['monitors'], {}), '(monitors)\\n', (12689, 12699), False, 'import yaml\\n'), ((15804, 15831), 'os.path.isdir', 'os.path.isdir', (['nrpe.homedir'], {}), '(nrpe.homedir)\\n', (15817, 15831), False, 'import os\\n'), ((16079, 16103), 'os.chmod', 'os.chmod', (['checkpath', '(420)'], {}), '(checkpath, 420)\\n', (16087, 16103), False, 'import os\\n')]"}}},{"rowIdx":8438,"cells":{"repo_name":{"kind":"string","value":"mintzer/pupillometry-rf-back"},"repo_path":{"kind":"string","value":"venv/Lib/site-packages/proglog/proglog.py"},"repo_head_hexsha":{"kind":"string","value":"cfa86fa984a49dce0123798f8de5b838c02e10d5"},"content":{"kind":"string","value":"\"\"\"Implements the generic progress logger class, and the ProgressBar class.\n\"\"\"\n\nfrom tqdm import tqdm, tqdm_notebook\nfrom collections import OrderedDict\nimport time\n\nSETTINGS = {\n 'notebook': False\n}\n\ndef notebook(turn='on'):\n SETTINGS['notebook'] = True if (turn == 'on') else False\n\ndef troncate_string(s, max_length=25):\n return s if (len(s) < max_length) else (s[:max_length] + \"...\")\n\nclass ProgressLogger:\n \"\"\"Generic class for progress loggers.\n\n A progress logger contains a \"state\" dictionnary.\n\n Parameters\n ----------\n\n init_state\n Dictionnary representing the initial state.\n \"\"\"\n\n def __init__(self, init_state=None):\n\n self.state = {}\n self.stored = {}\n self.logs = []\n self.log_indent = 0\n if init_state is not None:\n self.state.update(init_state)\n\n def log(self, message):\n self.logs.append((' ' * self.log_indent) + message)\n\n def dump_logs(self, filepath=None):\n if filepath is not None:\n with open(filepath, 'a') as f:\n f.write(\"\\n\".join(self.logs))\n else:\n return \"\\n\".join(self.logs)\n\n def callback(self, **kw):\n \"\"\"Execute something after the state has been updated by the given\n state elements.\n\n This default callback does nothing, overwrite it by subclassing\n \"\"\"\n pass\n\n def store(self, **kw):\n \"\"\"Store objects in the logger and trigger ``self.store_callback``.\n\n This works exactly like ``logger()``, but the later is meant for simple\n data objects (text, numbers) that will be sent over the network or\n written to a file. The ``store`` method expects rather large objects\n which are not necessarily serializable, and will be used eg to draw\n plots on the fly.\n \"\"\"\n self.stored.update(kw)\n self.store_callback(**kw)\n\n def store_callback(self, **kw):\n \"\"\"Execute something after the store has been updated by the given\n state elements.\n\n This default callback does nothing, overwrite it by subclassing\n \"\"\"\n pass\n\n def iter(self, **kw):\n \"\"\"Iterate through a list while updating the state.\n\n Examples\n --------\n\n >>> for username in logger.iter(user=['tom', 'tim', 'lea']:\n >>> # At every loop, logger.state['user'] is updated\n >>> print (username)\n\n \"\"\"\n for field, iterable in kw.items():\n for it in iterable:\n self(**{field: it})\n yield it\n\n\n\n\n def __call__(self, **kw):\n self.state.update(kw)\n self.callback(**kw)\n\nclass ProgressBarLogger(ProgressLogger):\n \"\"\"Generic class for progress loggers.\n\n A progress logger contains a \"state\" dictionnary\n\n Parameters\n ----------\n\n init_state\n Initial state of the logger\n\n bars\n Either None (will be initialized with no bar) or a list/tuple of bar\n names (``['main', 'sub']``) which will be initialized with index -1 and\n no total, or a dictionary (possibly ordered) of bars, of the form\n ``{bar_1: {title: 'bar1', index: 2, total:23}, bar_2: {...}}``\n\n ignored_bars\n Either None (newly met bars will be added) or a list of blacklisted bar\n names, or ``'all_others'`` to signify that all bar names not already in\n ``self.bars`` will be ignored.\n \"\"\"\n\n bar_indent = 2\n\n def __init__(self, init_state=None, bars=None, ignored_bars=None,\n logged_bars='all', min_time_interval=0, ignore_bars_under=0):\n ProgressLogger.__init__(self, init_state)\n if bars is None:\n bars = OrderedDict()\n elif isinstance(bars, (list, tuple)):\n bars = OrderedDict([\n (b, dict(title=b, index=-1, total=None, message=None,\n indent=0))\n for b in bars\n ])\n if isinstance(ignored_bars, (list, tuple)):\n ignored_bars = set(ignored_bars)\n self.ignored_bars = ignored_bars\n self.logged_bars = logged_bars\n self.state['bars'] = bars\n self.min_time_interval = min_time_interval\n self.ignore_bars_under = ignore_bars_under\n\n @property\n def bars(self):\n \"\"\"Return ``self.state['bars'].``\"\"\"\n return self.state['bars']\n\n def bar_is_ignored(self, bar):\n if self.ignored_bars is None:\n return False\n elif self.ignored_bars == 'all_others':\n return (bar not in self.bars)\n else:\n return bar in self.ignored_bars\n\n def bar_is_logged(self, bar):\n if (not self.logged_bars):\n return False\n elif self.logged_bars == 'all':\n return True\n else:\n return bar in self.logged_bars\n\n def iterable_is_too_short(self, iterable):\n length = len(iterable) if hasattr(iterable, '__len__') else None\n return (length is not None) and (length < self.ignore_bars_under)\n\n def iter_bar(self, bar_prefix='', **kw):\n \"\"\"Iterate through a list while updating a state bar.\n\n Examples\n --------\n >>> for username in logger.iter_bar(user=['tom', 'tim', 'lea']):\n >>> # At every loop, logger.state['bars']['user'] is updated\n >>> # to {index: i, total: 3, title:'user'}\n >>> print (username)\n\n \"\"\"\n if 'bar_message' in kw:\n bar_message = kw.pop('bar_message')\n else:\n bar_message = None\n bar, iterable = kw.popitem()\n\n if self.bar_is_ignored(bar) or self.iterable_is_too_short(iterable):\n return iterable\n bar = bar_prefix + bar\n if hasattr(iterable, '__len__'):\n self(**{bar + '__total': len(iterable)})\n\n def new_iterable():\n last_time = time.time()\n i = 0 # necessary in case the iterator is empty\n for i, it in enumerate(iterable):\n now_time = time.time()\n if (i == 0) or (now_time - last_time > self.min_time_interval):\n if bar_message is not None:\n self(**{bar + '__message': bar_message(it)})\n self(**{bar + '__index': i})\n last_time = now_time\n yield it\n\n if self.bars[bar]['index'] != i:\n self(**{bar + '__index': i})\n self(**{bar + '__index': i + 1})\n\n return new_iterable()\n\n def bars_callback(self, bar, attr, value, old_value=None):\n \"\"\"Execute a custom action after the progress bars are updated.\n\n Parameters\n ----------\n bar\n Name/ID of the bar to be modified.\n\n attr\n Attribute of the bar attribute to be modified\n\n value\n New value of the attribute\n\n old_value\n Previous value of this bar's attribute.\n\n This default callback does nothing, overwrite it by subclassing.\n \"\"\"\n pass\n\n def __call__(self, **kw):\n\n items = sorted(kw.items(), key=lambda kv: not kv[0].endswith('total'))\n\n for key, value in items:\n if '__' in key:\n bar, attr = key.split('__')\n if self.bar_is_ignored(bar):\n continue\n kw.pop(key)\n if bar not in self.bars:\n self.bars[bar] = dict(title=bar, index=-1,\n total=None, message=None)\n old_value = self.bars[bar][attr]\n\n if self.bar_is_logged(bar):\n new_bar = (attr == 'index') and (value < old_value)\n if (attr == 'total') or (new_bar):\n self.bars[bar]['indent'] = self.log_indent\n else:\n self.log_indent = self.bars[bar]['indent']\n self.log(\"[%s] %s: %s\" % (bar, attr, value))\n self.log_indent += self.bar_indent\n self.bars[bar][attr] = value\n self.bars_callback(bar, attr, value, old_value)\n self.state.update(kw)\n self.callback(**kw)\n\nclass TqdmProgressBarLogger(ProgressBarLogger):\n \"\"\"Tqdm-powered progress bar for console or Notebooks.\n\n Parameters\n ----------\n init_state\n Initial state of the logger\n\n bars\n Either None (will be initialized with no bar) or a list/tuple of bar\n names (``['main', 'sub']``) which will be initialized with index -1 and\n no total, or a dictionary (possibly ordered) of bars, of the form\n ``{bar_1: {title: 'bar1', index: 2, total:23}, bar_2: {...}}``\n\n ignored_bars\n Either None (newly met bars will be added) or a list of blacklisted bar\n names, or ``'all_others'`` to signify that all bar names not already in\n ``self.bars`` will be ignored.\n\n\n leave_bars\n\n notebook\n True will make the bars look nice (HTML) in the jupyter notebook. It is\n advised to leave to 'default' as the default can be globally set from\n inside a notebook with ``import proglog; proglog.notebook_mode()``.\n\n print_messages\n If True, every ``logger(message='something')`` will print a message in\n the console / notebook\n \"\"\"\n\n def __init__(self, init_state=None, bars=None, leave_bars=False,\n ignored_bars=None, logged_bars='all', notebook='default',\n print_messages=True, min_time_interval=0,\n ignore_bars_under=0):\n ProgressBarLogger.__init__(self, init_state=init_state, bars=bars,\n ignored_bars=ignored_bars,\n logged_bars=logged_bars,\n ignore_bars_under=ignore_bars_under,\n min_time_interval=min_time_interval)\n self.leave_bars = leave_bars\n self.tqdm_bars = OrderedDict([\n (bar, None)\n for bar in self.bars\n ])\n if notebook == 'default':\n notebook = SETTINGS['notebook']\n self.notebook = notebook\n self.print_messages = print_messages\n self.tqdm = (tqdm_notebook if self.notebook else tqdm)\n\n def new_tqdm_bar(self, bar):\n \"\"\"Create a new tqdm bar, possibly replacing an existing one.\"\"\"\n if (bar in self.tqdm_bars) and (self.tqdm_bars[bar] is not None):\n self.close_tqdm_bar(bar)\n infos = self.bars[bar]\n self.tqdm_bars[bar] = self.tqdm(\n total=infos['total'],\n desc=infos['title'],\n postfix=dict(now=troncate_string(str(infos['message']))),\n leave=self.leave_bars\n )\n def close_tqdm_bar(self, bar):\n \"\"\"Close and erase the tqdm bar\"\"\"\n self.tqdm_bars[bar].close()\n if not self.notebook:\n self.tqdm_bars[bar] = None\n\n def bars_callback(self, bar, attr, value, old_value):\n if (bar not in self.tqdm_bars) or (self.tqdm_bars[bar] is None):\n self.new_tqdm_bar(bar)\n if attr == 'index':\n if value >= old_value:\n total = self.bars[bar]['total']\n if total and (value >= total):\n self.close_tqdm_bar(bar)\n else:\n self.tqdm_bars[bar].update(value - old_value)\n else:\n self.new_tqdm_bar(bar)\n self.tqdm_bars[bar].update(value + 1)\n elif attr == 'message':\n self.tqdm_bars[bar].set_postfix(now=troncate_string(str(value)))\n self.tqdm_bars[bar].update(0)\n\n def callback(self, **kw):\n if self.print_messages and ('message' in kw) and kw['message']:\n if self.notebook:\n print(kw['message'])\n else:\n self.tqdm.write(kw['message'])\n\nclass RqWorkerProgressLogger:\n def __init__(self, job):\n self.job = job\n if 'progress_data' not in self.job.meta:\n self.job.meta['progress_data'] = {}\n self.job.save()\n\n def callback(self, **kw):\n self.job.meta['progress_data'] = self.state\n self.job.save()\n\nclass RqWorkerBarLogger(RqWorkerProgressLogger, ProgressBarLogger):\n\n def __init__(self, job, init_state=None, bars=None, ignored_bars=(),\n logged_bars='all', min_time_interval=0):\n RqWorkerProgressLogger.__init__(self, job)\n ProgressBarLogger.__init__(self, init_state=init_state, bars=bars,\n ignored_bars=ignored_bars,\n logged_bars=logged_bars,\n min_time_interval=min_time_interval)\n\nclass MuteProgressBarLogger(ProgressBarLogger):\n\n def bar_is_ignored(self, bar):\n return True\n\ndef default_bar_logger(logger, bars=None, ignored_bars=None, logged_bars='all',\n min_time_interval=0, ignore_bars_under=0):\n if logger == 'bar':\n return TqdmProgressBarLogger(\n bars=bars,\n ignored_bars=ignored_bars,\n logged_bars=logged_bars,\n min_time_interval=min_time_interval,\n ignore_bars_under=ignore_bars_under\n )\n elif logger is None:\n return MuteProgressBarLogger()\n else:\n return logger\n"},"apis":{"kind":"string","value":"[((9891, 9938), 'collections.OrderedDict', 'OrderedDict', (['[(bar, None) for bar in self.bars]'], {}), '([(bar, None) for bar in self.bars])\\n', (9902, 9938), False, 'from collections import OrderedDict\\n'), ((3666, 3679), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\\n', (3677, 3679), False, 'from collections import OrderedDict\\n'), ((5832, 5843), 'time.time', 'time.time', ([], {}), '()\\n', (5841, 5843), False, 'import time\\n'), ((5977, 5988), 'time.time', 'time.time', ([], {}), '()\\n', (5986, 5988), False, 'import time\\n')]"}}},{"rowIdx":8439,"cells":{"repo_name":{"kind":"string","value":"jorgepadilla19/gdsfactory"},"repo_path":{"kind":"string","value":"gdsfactory/tests/test_component_from_yaml_bezier.py"},"repo_head_hexsha":{"kind":"string","value":"68e1c18257a75d4418279851baea417c8899a165"},"content":{"kind":"string","value":"import gdsfactory as gf\nfrom gdsfactory.component import Component\n\nyaml = \"\"\"\nname:\n test_component_yaml_without_cell\n\ninstances:\n mmi:\n component: mmi1x2\n bend:\n component: bend_s\n\nconnections:\n bend,o1: mmi,o2\n\n\"\"\"\n\n\ndef test_component_from_yaml_without_cell() -> Component:\n \"\"\"bezier does not have cell\"\"\"\n c = gf.read.from_yaml(yaml)\n assert c.name == \"test_component_yaml_without_cell\", c.name\n assert len(c.get_dependencies()) == 2, len(c.get_dependencies())\n assert len(c.ports) == 0, len(c.ports)\n return c\n\n\nif __name__ == \"__main__\":\n c = test_component_from_yaml_without_cell()\n print(c.name)\n c.show()\n"},"apis":{"kind":"string","value":"[((344, 367), 'gdsfactory.read.from_yaml', 'gf.read.from_yaml', (['yaml'], {}), '(yaml)\\n', (361, 367), True, 'import gdsfactory as gf\\n')]"}}},{"rowIdx":8440,"cells":{"repo_name":{"kind":"string","value":"AdamBrianBright/cats-python"},"repo_path":{"kind":"string","value":"cats/types.py"},"repo_head_hexsha":{"kind":"string","value":"163cbde06c0d56520c217c0d66ddca34c7e0f63b"},"content":{"kind":"string","value":"from pathlib import Path\nfrom types import GeneratorType\nfrom typing import AsyncIterable, Iterable, TypeAlias\n\nimport ujson\n\nfrom cats.errors import MalformedHeadersError\n\ntry:\n from django.db.models import QuerySet, Model\nexcept ImportError:\n QuerySet = type('QuerySet', (list,), {})\n Model = type('Model', (list,), {})\n\n__all__ = [\n 'Bytes',\n 'BytesGen',\n 'BytesAsyncGen',\n 'BytesAnyGen',\n 'Byte',\n 'Json',\n 'File',\n 'List',\n 'Missing',\n 'MISSING',\n 'QuerySet',\n 'Model',\n 'T_Headers',\n 'Headers',\n]\n\nBytes: TypeAlias = bytes | bytearray | memoryview\nBytesGen: TypeAlias = Iterable[Bytes]\nBytesAsyncGen: TypeAlias = AsyncIterable[Bytes]\nBytesAnyGen: TypeAlias = BytesGen | BytesAsyncGen\n\nByte: TypeAlias = Bytes\nJson: TypeAlias = str | int | float | dict | list | bool | None\nFile: TypeAlias = Path | str\nList = list | tuple | set | GeneratorType | QuerySet\n\n\nclass Missing(str):\n \"\"\"\n Custom Missing type is required for Pydantic to work properly. IDK\n \"\"\"\n __slots__ = ()\n\n def __init__(self):\n super().__init__()\n\n def __eq__(self, other):\n return isinstance(other, Missing)\n\n def __bool__(self):\n return False\n\n\nMISSING = Missing()\n\n\nclass Headers(dict):\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n v = self._convert(*args, **kwargs)\n if (offset := v.get('offset', None)) and (not isinstance(offset, int) or offset < 0):\n raise MalformedHeadersError('Invalid offset header', headers=v)\n super().__init__(v)\n\n @classmethod\n def _key(cls, key: str) -> str:\n return key.replace(' ', '-').title()\n\n def __getitem__(self, item):\n return super().__getitem__(self._key(item))\n\n def __setitem__(self, key, value):\n return super().__setitem__(self._key(key), value)\n\n def __delitem__(self, key):\n return super().__delitem__(self._key(key))\n\n def __contains__(self, item):\n return super().__contains__(self._key(item))\n\n @classmethod\n def _convert(cls, *args, **kwargs):\n return {cls._key(k): v for k, v in dict(*args, **kwargs).items() if isinstance(k, str)}\n\n def update(self, *args, **kwargs) -> None:\n super().update(self._convert(*args, **kwargs))\n\n def encode(self) -> bytes:\n return ujson.dumps(self, ensure_ascii=False, escape_forward_slashes=False).encode('utf-8')\n\n @classmethod\n def decode(cls, headers: Bytes) -> 'Headers':\n try:\n headers = ujson.loads(headers)\n except ValueError: # + UnicodeDecodeError\n headers = None\n return cls(headers or {})\n\n\nT_Headers: TypeAlias = Headers | dict[str]\n"},"apis":{"kind":"string","value":"[((1471, 1528), 'cats.errors.MalformedHeadersError', 'MalformedHeadersError', (['\"\"\"Invalid offset header\"\"\"'], {'headers': 'v'}), \"('Invalid offset header', headers=v)\\n\", (1492, 1528), False, 'from cats.errors import MalformedHeadersError\\n'), ((2503, 2523), 'ujson.loads', 'ujson.loads', (['headers'], {}), '(headers)\\n', (2514, 2523), False, 'import ujson\\n'), ((2316, 2383), 'ujson.dumps', 'ujson.dumps', (['self'], {'ensure_ascii': '(False)', 'escape_forward_slashes': '(False)'}), '(self, ensure_ascii=False, escape_forward_slashes=False)\\n', (2327, 2383), False, 'import ujson\\n')]"}}},{"rowIdx":8441,"cells":{"repo_name":{"kind":"string","value":"MyCollege/raven"},"repo_path":{"kind":"string","value":"raven/utils/urlparse.py"},"repo_head_hexsha":{"kind":"string","value":"9447f3a55ae7703afe84c3493625e3c3fb700700"},"content":{"kind":"string","value":"from __future__ import absolute_import\n\ntry:\n import urlparse as _urlparse\nexcept ImportError:\n from urllib import parse as _urlparse\n \n\ndef register_scheme(scheme):\n for method in filter(lambda s: s.startswith('uses_'), dir(_urlparse)):\n uses = getattr(_urlparse, method)\n if scheme not in uses:\n uses.append(scheme)\n\n\nurlparse = _urlparse.urlparse\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8442,"cells":{"repo_name":{"kind":"string","value":"stjordanis/MONeT-1"},"repo_path":{"kind":"string","value":"setup.py"},"repo_head_hexsha":{"kind":"string","value":"98a5c7d149ca19c8c64069dbd8f27ce7f97bf3af"},"content":{"kind":"string","value":"import setuptools\n\nsetuptools.setup(\n name=\"monet_memory_optimized_training\",\n version=\"0.0.1\",\n description=\"Memory Optimized Network Training Framework\",\n url=\"https://github.com/philkr/lowrank_conv\",\n packages=setuptools.find_packages(include = ['monet', 'monet.*', 'models', 'checkmate', 'gist']),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n)\n"},"apis":{"kind":"string","value":"[((228, 317), 'setuptools.find_packages', 'setuptools.find_packages', ([], {'include': \"['monet', 'monet.*', 'models', 'checkmate', 'gist']\"}), \"(include=['monet', 'monet.*', 'models', 'checkmate',\\n 'gist'])\\n\", (252, 317), False, 'import setuptools\\n')]"}}},{"rowIdx":8443,"cells":{"repo_name":{"kind":"string","value":"Superomeg4/pyleecan"},"repo_path":{"kind":"string","value":"Tests/Methods/Machine/test_Magnet_Type_11_meth.py"},"repo_head_hexsha":{"kind":"string","value":"2b695b5f39e77475a07aa0ea89489fb0a9659337"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"\n@date Created on Thu Dec 18 13:56:33 2014\n@copyright (C) 2014-2015 EOMYS ENGINEERING.\n@author pierre_b\n\"\"\"\n\nfrom unittest import TestCase\n\nfrom ddt import ddt, data\n\nfrom pyleecan.Classes.Arc1 import Arc1\nfrom pyleecan.Classes.Segment import Segment\n\nfrom pyleecan.Classes.MagnetType11 import MagnetType11\nfrom pyleecan.Classes.LamSlotMag import LamSlotMag\n\nfrom pyleecan.Classes.SlotMPolar import SlotMPolar\nfrom numpy import pi, exp, angle, array\nfrom pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface\n\nMag11_test = list()\n# Internal Slot surface\nlam = LamSlotMag(is_internal=True, Rext=0.5)\nlam.slot = SlotMPolar(H0=0, W0=pi / 4, Zs=4)\nlam.slot.magnet = [MagnetType11(Hmag=1, Wmag=pi / 4)]\nMag11_test.append({\"test_obj\": lam, \"S_exp\": 0.78539616, \"Ao\": pi / 4, \"H_exp\": 1})\n\n# Internal Slot inset\nlam = LamSlotMag(is_internal=True, Rext=0.5)\nlam.slot = SlotMPolar(H0=40e-3, W0=pi / 4, Zs=4)\nlam.slot.magnet = [MagnetType11(Hmag=20e-3, Wmag=pi / 4)]\nMag11_test.append({\"test_obj\": lam, \"S_exp\": 7.3827e-3, \"Ao\": pi / 4, \"H_exp\": 20e-3})\n\n# Outward Slot inset\nlam = LamSlotMag(is_internal=False, Rext=0.1325)\nlam.slot = SlotMPolar(H0=5e-3, W0=pi / 10, Zs=8)\nlam.slot.magnet = [MagnetType11(Hmag=8e-3, Wmag=pi / 12)]\nMag11_test.append({\"test_obj\": lam, \"S_exp\": 2.09439e-6, \"Ao\": pi / 12, \"H_exp\": 8e-3})\n\n# For AlmostEqual\nDELTA = 1e-4\n\n\n@ddt\nclass test_Magnet_Type_11_meth(TestCase):\n \"\"\"unittest for MagnetType11 methods\n \"\"\"\n\n @data(*Mag11_test)\n def test_comp_surface(self, test_dict):\n \"\"\"Check that the computation of the surface is correct\n \"\"\"\n test_obj = test_dict[\"test_obj\"]\n result = test_obj.slot.magnet[0].comp_surface()\n\n a = result\n b = test_dict[\"S_exp\"]\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n self.assertAlmostEqual((a - b) / a, 0, delta=DELTA, msg=msg)\n\n # Compare numerical and analytical results\n b = comp_surface(test_obj.slot.magnet[0])\n msg = \"Analytical: \" + str(a) + \" Numerical \" + str(b)\n self.assertAlmostEqual((a - b) / a, 0, delta=DELTA, msg=msg)\n\n @data(*Mag11_test)\n def test_comp_height(self, test_dict):\n \"\"\"Check that the computation of the height is correct\n \"\"\"\n test_obj = test_dict[\"test_obj\"]\n result = test_obj.slot.magnet[0].comp_height()\n\n a = result\n b = test_dict[\"H_exp\"]\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n self.assertAlmostEqual((a - b) / a, 0, delta=DELTA, msg=msg)\n\n @data(*Mag11_test)\n def test_comp_angle_op(self, test_dict):\n \"\"\"Check that the computation of the opening angle is correct\n \"\"\"\n test_obj = test_dict[\"test_obj\"]\n result = test_obj.slot.magnet[0].comp_angle_opening()\n\n a = result\n b = test_dict[\"Ao\"]\n msg = \"Return \" + str(a) + \" expected \" + str(b)\n self.assertAlmostEqual((a - b) / a, 0, delta=DELTA, msg=msg)\n\n def test_build_geometry_out(self):\n \"\"\"check that curve_list is correct (outwards magnet)\"\"\"\n lam = LamSlotMag(\n Rint=40e-3,\n Rext=90e-3,\n is_internal=False,\n is_stator=False,\n L1=0.45,\n Nrvd=1,\n Wrvd=0.05,\n )\n magnet = [MagnetType11(Wmag=pi / 10, Hmag=0.2)]\n lam.slot = SlotMPolar(Zs=8, W0=pi / 10, H0=0.2, magnet=magnet)\n test_obj = lam.slot.magnet[0]\n Z1 = (40e-3 + 0.2) * exp(-1j * pi / 10 / 2)\n Z2 = (40e-3 + 0.2) * exp(1j * pi / 10 / 2)\n\n Z = abs(Z1)\n\n Z3 = (Z - 0.2) * exp(1j * angle(Z1))\n Z4 = (Z - 0.2) * exp(1j * angle(Z2))\n\n # # Creation of curve\n curve_list = list()\n curve_list.append(Segment(Z1, Z3))\n curve_list.append(Arc1(Z3, Z4, abs(Z3)))\n curve_list.append(Segment(Z4, Z2))\n curve_list.append(Arc1(Z2, Z1, -abs(Z2)))\n\n surface = test_obj.build_geometry()\n result = surface[0].get_lines()\n for i in range(0, len(result)):\n a = result[i].begin\n b = curve_list[i].begin\n self.assertAlmostEqual((a - b) / a, 0, delta=DELTA)\n\n a = result[i].end\n b = curve_list[i].end\n self.assertAlmostEqual((a - b) / a, 0, delta=DELTA)\n\n def test_build_geometry_in(self):\n \"\"\"check that curve_list is correct (inwards magnet)\"\"\"\n lam = LamSlotMag(\n Rint=40e-1,\n Rext=90e-1,\n is_internal=True,\n is_stator=False,\n L1=0.45,\n Nrvd=1,\n Wrvd=0.05,\n )\n magnet = [MagnetType11(Wmag=pi / 10, Hmag=0.2)]\n lam.slot = SlotMPolar(Zs=8, W0=pi / 10, H0=0.2, magnet=magnet)\n test_obj = lam.slot.magnet[0]\n Z1 = (90e-1 - 0.2) * exp(-1j * pi / 10 / 2)\n Z2 = (90e-1 - 0.2) * exp(1j * pi / 10 / 2)\n\n Z = abs(Z1)\n\n Z3 = (Z + 0.2) * exp(1j * angle(Z1))\n Z4 = (Z + 0.2) * exp(1j * angle(Z2))\n\n # # Creation of curve\n curve_list = list()\n curve_list.append(Segment(Z1, Z3))\n curve_list.append(Arc1(Z3, Z4, abs(Z3)))\n curve_list.append(Segment(Z4, Z2))\n curve_list.append(Arc1(Z2, Z1, -abs(Z2)))\n\n surface = test_obj.build_geometry()\n result = surface[0].get_lines()\n for i in range(0, len(result)):\n a = result[i].begin\n b = curve_list[i].begin\n self.assertAlmostEqual((a - b) / a, 0, delta=DELTA)\n\n a = result[i].end\n b = curve_list[i].end\n self.assertAlmostEqual((a - b) / a, 0, delta=DELTA)\n"},"apis":{"kind":"string","value":"[((598, 636), 'pyleecan.Classes.LamSlotMag.LamSlotMag', 'LamSlotMag', ([], {'is_internal': '(True)', 'Rext': '(0.5)'}), '(is_internal=True, Rext=0.5)\\n', (608, 636), False, 'from pyleecan.Classes.LamSlotMag import LamSlotMag\\n'), ((648, 681), 'pyleecan.Classes.SlotMPolar.SlotMPolar', 'SlotMPolar', ([], {'H0': '(0)', 'W0': '(pi / 4)', 'Zs': '(4)'}), '(H0=0, W0=pi / 4, Zs=4)\\n', (658, 681), False, 'from pyleecan.Classes.SlotMPolar import SlotMPolar\\n'), ((849, 887), 'pyleecan.Classes.LamSlotMag.LamSlotMag', 'LamSlotMag', ([], {'is_internal': '(True)', 'Rext': '(0.5)'}), '(is_internal=True, Rext=0.5)\\n', (859, 887), False, 'from pyleecan.Classes.LamSlotMag import LamSlotMag\\n'), ((899, 935), 'pyleecan.Classes.SlotMPolar.SlotMPolar', 'SlotMPolar', ([], {'H0': '(0.04)', 'W0': '(pi / 4)', 'Zs': '(4)'}), '(H0=0.04, W0=pi / 4, Zs=4)\\n', (909, 935), False, 'from pyleecan.Classes.SlotMPolar import SlotMPolar\\n'), ((1110, 1152), 'pyleecan.Classes.LamSlotMag.LamSlotMag', 'LamSlotMag', ([], {'is_internal': '(False)', 'Rext': '(0.1325)'}), '(is_internal=False, Rext=0.1325)\\n', (1120, 1152), False, 'from pyleecan.Classes.LamSlotMag import LamSlotMag\\n'), ((1164, 1202), 'pyleecan.Classes.SlotMPolar.SlotMPolar', 'SlotMPolar', ([], {'H0': '(0.005)', 'W0': '(pi / 10)', 'Zs': '(8)'}), '(H0=0.005, W0=pi / 10, Zs=8)\\n', (1174, 1202), False, 'from pyleecan.Classes.SlotMPolar import SlotMPolar\\n'), ((701, 734), 'pyleecan.Classes.MagnetType11.MagnetType11', 'MagnetType11', ([], {'Hmag': '(1)', 'Wmag': '(pi / 4)'}), '(Hmag=1, Wmag=pi / 4)\\n', (713, 734), False, 'from pyleecan.Classes.MagnetType11 import MagnetType11\\n'), ((956, 992), 'pyleecan.Classes.MagnetType11.MagnetType11', 'MagnetType11', ([], {'Hmag': '(0.02)', 'Wmag': '(pi / 4)'}), '(Hmag=0.02, Wmag=pi / 4)\\n', (968, 992), False, 'from pyleecan.Classes.MagnetType11 import MagnetType11\\n'), ((1221, 1259), 'pyleecan.Classes.MagnetType11.MagnetType11', 'MagnetType11', ([], {'Hmag': '(0.008)', 'Wmag': '(pi / 12)'}), '(Hmag=0.008, Wmag=pi / 12)\\n', (1233, 1259), False, 'from pyleecan.Classes.MagnetType11 import MagnetType11\\n'), ((1484, 1501), 'ddt.data', 'data', (['*Mag11_test'], {}), '(*Mag11_test)\\n', (1488, 1501), False, 'from ddt import ddt, data\\n'), ((2136, 2153), 'ddt.data', 'data', (['*Mag11_test'], {}), '(*Mag11_test)\\n', (2140, 2153), False, 'from ddt import ddt, data\\n'), ((2551, 2568), 'ddt.data', 'data', (['*Mag11_test'], {}), '(*Mag11_test)\\n', (2555, 2568), False, 'from ddt import ddt, data\\n'), ((1960, 1997), 'pyleecan.Methods.Machine.Magnet.comp_surface.comp_surface', 'comp_surface', (['test_obj.slot.magnet[0]'], {}), '(test_obj.slot.magnet[0])\\n', (1972, 1997), False, 'from pyleecan.Methods.Machine.Magnet.comp_surface import comp_surface\\n'), ((3092, 3193), 'pyleecan.Classes.LamSlotMag.LamSlotMag', 'LamSlotMag', ([], {'Rint': '(0.04)', 'Rext': '(0.09)', 'is_internal': '(False)', 'is_stator': '(False)', 'L1': '(0.45)', 'Nrvd': '(1)', 'Wrvd': '(0.05)'}), '(Rint=0.04, Rext=0.09, is_internal=False, is_stator=False, L1=\\n 0.45, Nrvd=1, Wrvd=0.05)\\n', (3102, 3193), False, 'from pyleecan.Classes.LamSlotMag import LamSlotMag\\n'), ((3361, 3412), 'pyleecan.Classes.SlotMPolar.SlotMPolar', 'SlotMPolar', ([], {'Zs': '(8)', 'W0': '(pi / 10)', 'H0': '(0.2)', 'magnet': 'magnet'}), '(Zs=8, W0=pi / 10, H0=0.2, magnet=magnet)\\n', (3371, 3412), False, 'from pyleecan.Classes.SlotMPolar import SlotMPolar\\n'), ((4413, 4510), 'pyleecan.Classes.LamSlotMag.LamSlotMag', 'LamSlotMag', ([], {'Rint': '(4.0)', 'Rext': '(9.0)', 'is_internal': '(True)', 'is_stator': '(False)', 'L1': '(0.45)', 'Nrvd': '(1)', 'Wrvd': '(0.05)'}), '(Rint=4.0, Rext=9.0, is_internal=True, is_stator=False, L1=0.45,\\n Nrvd=1, Wrvd=0.05)\\n', (4423, 4510), False, 'from pyleecan.Classes.LamSlotMag import LamSlotMag\\n'), ((4681, 4732), 'pyleecan.Classes.SlotMPolar.SlotMPolar', 'SlotMPolar', ([], {'Zs': '(8)', 'W0': '(pi / 10)', 'H0': '(0.2)', 'magnet': 'magnet'}), '(Zs=8, W0=pi / 10, H0=0.2, magnet=magnet)\\n', (4691, 4732), False, 'from pyleecan.Classes.SlotMPolar import SlotMPolar\\n'), ((3304, 3340), 'pyleecan.Classes.MagnetType11.MagnetType11', 'MagnetType11', ([], {'Wmag': '(pi / 10)', 'Hmag': '(0.2)'}), '(Wmag=pi / 10, Hmag=0.2)\\n', (3316, 3340), False, 'from pyleecan.Classes.MagnetType11 import MagnetType11\\n'), ((3480, 3504), 'numpy.exp', 'exp', (['(-1.0j * pi / 10 / 2)'], {}), '(-1.0j * pi / 10 / 2)\\n', (3483, 3504), False, 'from numpy import pi, exp, angle, array\\n'), ((3532, 3555), 'numpy.exp', 'exp', (['(1.0j * pi / 10 / 2)'], {}), '(1.0j * pi / 10 / 2)\\n', (3535, 3555), False, 'from numpy import pi, exp, angle, array\\n'), ((3751, 3766), 'pyleecan.Classes.Segment.Segment', 'Segment', (['Z1', 'Z3'], {}), '(Z1, Z3)\\n', (3758, 3766), False, 'from pyleecan.Classes.Segment import Segment\\n'), ((3843, 3858), 'pyleecan.Classes.Segment.Segment', 'Segment', (['Z4', 'Z2'], {}), '(Z4, Z2)\\n', (3850, 3858), False, 'from pyleecan.Classes.Segment import Segment\\n'), ((4624, 4660), 'pyleecan.Classes.MagnetType11.MagnetType11', 'MagnetType11', ([], {'Wmag': '(pi / 10)', 'Hmag': '(0.2)'}), '(Wmag=pi / 10, Hmag=0.2)\\n', (4636, 4660), False, 'from pyleecan.Classes.MagnetType11 import MagnetType11\\n'), ((4800, 4824), 'numpy.exp', 'exp', (['(-1.0j * pi / 10 / 2)'], {}), '(-1.0j * pi / 10 / 2)\\n', (4803, 4824), False, 'from numpy import pi, exp, angle, array\\n'), ((4852, 4875), 'numpy.exp', 'exp', (['(1.0j * pi / 10 / 2)'], {}), '(1.0j * pi / 10 / 2)\\n', (4855, 4875), False, 'from numpy import pi, exp, angle, array\\n'), ((5071, 5086), 'pyleecan.Classes.Segment.Segment', 'Segment', (['Z1', 'Z3'], {}), '(Z1, Z3)\\n', (5078, 5086), False, 'from pyleecan.Classes.Segment import Segment\\n'), ((5163, 5178), 'pyleecan.Classes.Segment.Segment', 'Segment', (['Z4', 'Z2'], {}), '(Z4, Z2)\\n', (5170, 5178), False, 'from pyleecan.Classes.Segment import Segment\\n'), ((3610, 3619), 'numpy.angle', 'angle', (['Z1'], {}), '(Z1)\\n', (3615, 3619), False, 'from numpy import pi, exp, angle, array\\n'), ((3655, 3664), 'numpy.angle', 'angle', (['Z2'], {}), '(Z2)\\n', (3660, 3664), False, 'from numpy import pi, exp, angle, array\\n'), ((4930, 4939), 'numpy.angle', 'angle', (['Z1'], {}), '(Z1)\\n', (4935, 4939), False, 'from numpy import pi, exp, angle, array\\n'), ((4975, 4984), 'numpy.angle', 'angle', (['Z2'], {}), '(Z2)\\n', (4980, 4984), False, 'from numpy import pi, exp, angle, array\\n')]"}}},{"rowIdx":8444,"cells":{"repo_name":{"kind":"string","value":"arshadzahangirchowdhury/TomoEncoders"},"repo_path":{"kind":"string","value":"tomo_encoders/tasks/void_mapping.py"},"repo_head_hexsha":{"kind":"string","value":"9c2b15fd515d864079f198546821faee5d78df17"},"content":{"kind":"string","value":"#!/usr/bin/env python3 \n# -*- coding: utf-8 -*- \n\"\"\" \n\"\"\" \nfrom operator import mod\nfrom tomo_encoders.misc.voxel_processing import modified_autocontrast, TimerGPU\nfrom tomo_encoders.reconstruction.recon import recon_patches_3d\nimport cupy as cp\nimport numpy as np\nfrom skimage.filters import threshold_otsu\nfrom tomo_encoders import Grid\n\n\n\ndef get_values_cyl_mask(vol, mask_fac):\n \n vol_shape = vol.shape\n assert vol_shape[1] == vol_shape[2], \"must be a tomographic volume where shape y = shape x\"\n \n shape_yx = vol_shape[1]\n shape_z = vol_shape[0]\n rad = int(mask_fac*shape_yx/2)\n \n pts = cp.arange(-int(shape_yx//2), int(cp.ceil(shape_yx//2)))\n yy, xx = cp.meshgrid(pts, pts, indexing = 'ij')\n circ = (cp.sqrt(yy**2 + xx**2) < rad).astype(cp.uint8) # inside is positive\n circ = circ[cp.newaxis, ...]\n cyl = cp.repeat(circ, shape_z, axis = 0)\n return vol[cyl > 0]\n\n\ndef cylindrical_mask(out_vol, mask_fac, mask_val = 0):\n \n vol_shape = out_vol.shape\n assert vol_shape[1] == vol_shape[2], \"must be a tomographic volume where shape y = shape x\"\n \n shape_yx = vol_shape[1]\n shape_z = vol_shape[0]\n rad = int(mask_fac*shape_yx/2)\n \n pts = cp.arange(-int(shape_yx//2), int(cp.ceil(shape_yx//2)))\n yy, xx = cp.meshgrid(pts, pts, indexing = 'ij')\n circ = (cp.sqrt(yy**2 + xx**2) < rad).astype(cp.uint8) # inside is positive\n circ = circ[cp.newaxis, ...]\n cyl = cp.repeat(circ, shape_z, axis = 0)\n out_vol[cyl == 0] = mask_val\n \n return\n\n\ndef segment_otsu(vol, s = 0.05):\n '''segment volume with otsu'''\n timer = TimerGPU()\n timer.tic()\n tmp_values = vol[::4,::4,::4].get()\n # rec_min_max = modified_autocontrast(tmp_values, s = s, normalize_sampling_factor=1)\n thresh = cp.float32(threshold_otsu(tmp_values.reshape(-1)))\n vol = (vol < thresh).astype(cp.uint8)\n timer.toc(\"otsu thresholding\")\n return vol\n\ndef edge_map(Y):\n\n '''\n this algorithm was inspired by: https://github.com/tomochallenge/tomochallenge_utils/blob/master/foam_phantom_utils.py\n '''\n msk = cp.zeros_like(Y)\n tmp = Y[:-1]!=Y[1:]\n msk[:-1][tmp] = 1\n msk[1:][tmp] = 1\n tmp = Y[:,:-1]!=Y[:,1:]\n msk[:,:-1][tmp] = 1\n msk[:,1:][tmp] = 1\n tmp = Y[:,:,:-1]!=Y[:,:,1:]\n msk[:,:,:-1][tmp] = 1\n msk[:,:,1:][tmp] = 1\n return msk > 0\n\ndef guess_surface(V_bin, b, wd):\n \n # find patches on surface\n wdb = int(wd//b)\n p3d = Grid(V_bin.shape, width = wdb)\n \n x = p3d.extract(V_bin)\n is_surf = (np.std(x, axis = (1,2,3)) > 0.0)\n is_ones = (np.sum(x, axis = (1,2,3))/(wdb**3) == 1)\n is_zeros = (np.sum(x, axis = (1,2,3))/(wdb**3) == 0)\n \n p3d = p3d.rescale(b)\n p3d_surf = p3d.filter_by_condition(is_surf)\n p3d_ones = p3d.filter_by_condition(is_ones)\n p3d_zeros = p3d.filter_by_condition(is_zeros)\n eff = len(p3d_surf)*(wd**3)/np.prod(p3d_surf.vol_shape)\n print(f\"\\tSTAT: r value: {eff*100.0:.2f}\") \n return p3d_surf, p3d_ones, p3d_zeros\n\ndef process_patches(projs, theta, center, fe, p_surf, min_max, TIMEIT = False):\n\n # SCHEME 1: integrate reconstruction and segmention (segments data on gpu itself)\n # st_proc = cp.cuda.Event(); end_proc = cp.cuda.Event(); st_proc.record()\n # x_surf, p_surf = recon_patches_3d(projs, theta, center, p_surf, \\\n # apply_fbp = True, segmenter = fe, \\\n # segmenter_batch_size = 256)\n # end_proc.record(); end_proc.synchronize(); t_surf = cp.cuda.get_elapsed_time(st_proc,end_proc)\n \n \n # SCHEME 2: reconstruct and segment separately (copies rec data from gpu to cpu)\n st_rec = cp.cuda.Event(); end_rec = cp.cuda.Event(); st_rec.record()\n x_surf, p_surf = recon_patches_3d(projs, theta, center, p_surf, \\\n apply_fbp =True)\n end_rec.record(); end_rec.synchronize(); t_rec = cp.cuda.get_elapsed_time(st_rec,end_rec)\n st_seg = cp.cuda.Event(); end_seg = cp.cuda.Event(); st_seg.record()\n \n x_surf = np.clip(x_surf, *min_max)\n x_surf = fe.predict_patches(\"segmenter\", x_surf[...,np.newaxis], 256, None, min_max = min_max)[...,0]\n end_seg.record(); end_seg.synchronize(); t_seg = cp.cuda.get_elapsed_time(st_seg,end_seg)\n \n print(f'\\tTIME: local reconstruction - {t_rec/1000.0:.2f} secs') \n print(f'\\tTIME: local segmentation - {t_seg/1000.0:.2f} secs')\n print(f'\\tSTAT: total patches in neighborhood: {len(p_surf)}') \n if TIMEIT:\n return x_surf, p_surf, t_rec, t_seg\n else:\n return x_surf, p_surf\n \n \n \n\n"},"apis":{"kind":"string","value":"[((688, 724), 'cupy.meshgrid', 'cp.meshgrid', (['pts', 'pts'], {'indexing': '\"\"\"ij\"\"\"'}), \"(pts, pts, indexing='ij')\\n\", (699, 724), True, 'import cupy as cp\\n'), ((850, 882), 'cupy.repeat', 'cp.repeat', (['circ', 'shape_z'], {'axis': '(0)'}), '(circ, shape_z, axis=0)\\n', (859, 882), True, 'import cupy as cp\\n'), ((1276, 1312), 'cupy.meshgrid', 'cp.meshgrid', (['pts', 'pts'], {'indexing': '\"\"\"ij\"\"\"'}), \"(pts, pts, indexing='ij')\\n\", (1287, 1312), True, 'import cupy as cp\\n'), ((1438, 1470), 'cupy.repeat', 'cp.repeat', (['circ', 'shape_z'], {'axis': '(0)'}), '(circ, shape_z, axis=0)\\n', (1447, 1470), True, 'import cupy as cp\\n'), ((1604, 1614), 'tomo_encoders.misc.voxel_processing.TimerGPU', 'TimerGPU', ([], {}), '()\\n', (1612, 1614), False, 'from tomo_encoders.misc.voxel_processing import modified_autocontrast, TimerGPU\\n'), ((2085, 2101), 'cupy.zeros_like', 'cp.zeros_like', (['Y'], {}), '(Y)\\n', (2098, 2101), True, 'import cupy as cp\\n'), ((2446, 2474), 'tomo_encoders.Grid', 'Grid', (['V_bin.shape'], {'width': 'wdb'}), '(V_bin.shape, width=wdb)\\n', (2450, 2474), False, 'from tomo_encoders import Grid\\n'), ((3673, 3688), 'cupy.cuda.Event', 'cp.cuda.Event', ([], {}), '()\\n', (3686, 3688), True, 'import cupy as cp\\n'), ((3700, 3715), 'cupy.cuda.Event', 'cp.cuda.Event', ([], {}), '()\\n', (3713, 3715), True, 'import cupy as cp\\n'), ((3754, 3816), 'tomo_encoders.reconstruction.recon.recon_patches_3d', 'recon_patches_3d', (['projs', 'theta', 'center', 'p_surf'], {'apply_fbp': '(True)'}), '(projs, theta, center, p_surf, apply_fbp=True)\\n', (3770, 3816), False, 'from tomo_encoders.reconstruction.recon import recon_patches_3d\\n'), ((3911, 3952), 'cupy.cuda.get_elapsed_time', 'cp.cuda.get_elapsed_time', (['st_rec', 'end_rec'], {}), '(st_rec, end_rec)\\n', (3935, 3952), True, 'import cupy as cp\\n'), ((3965, 3980), 'cupy.cuda.Event', 'cp.cuda.Event', ([], {}), '()\\n', (3978, 3980), True, 'import cupy as cp\\n'), ((3992, 4007), 'cupy.cuda.Event', 'cp.cuda.Event', ([], {}), '()\\n', (4005, 4007), True, 'import cupy as cp\\n'), ((4043, 4068), 'numpy.clip', 'np.clip', (['x_surf', '*min_max'], {}), '(x_surf, *min_max)\\n', (4050, 4068), True, 'import numpy as np\\n'), ((4228, 4269), 'cupy.cuda.get_elapsed_time', 'cp.cuda.get_elapsed_time', (['st_seg', 'end_seg'], {}), '(st_seg, end_seg)\\n', (4252, 4269), True, 'import cupy as cp\\n'), ((2524, 2549), 'numpy.std', 'np.std', (['x'], {'axis': '(1, 2, 3)'}), '(x, axis=(1, 2, 3))\\n', (2530, 2549), True, 'import numpy as np\\n'), ((2878, 2905), 'numpy.prod', 'np.prod', (['p3d_surf.vol_shape'], {}), '(p3d_surf.vol_shape)\\n', (2885, 2905), True, 'import numpy as np\\n'), ((652, 674), 'cupy.ceil', 'cp.ceil', (['(shape_yx // 2)'], {}), '(shape_yx // 2)\\n', (659, 674), True, 'import cupy as cp\\n'), ((1240, 1262), 'cupy.ceil', 'cp.ceil', (['(shape_yx // 2)'], {}), '(shape_yx // 2)\\n', (1247, 1262), True, 'import cupy as cp\\n'), ((2572, 2597), 'numpy.sum', 'np.sum', (['x'], {'axis': '(1, 2, 3)'}), '(x, axis=(1, 2, 3))\\n', (2578, 2597), True, 'import numpy as np\\n'), ((2629, 2654), 'numpy.sum', 'np.sum', (['x'], {'axis': '(1, 2, 3)'}), '(x, axis=(1, 2, 3))\\n', (2635, 2654), True, 'import numpy as np\\n'), ((739, 765), 'cupy.sqrt', 'cp.sqrt', (['(yy ** 2 + xx ** 2)'], {}), '(yy ** 2 + xx ** 2)\\n', (746, 765), True, 'import cupy as cp\\n'), ((1327, 1353), 'cupy.sqrt', 'cp.sqrt', (['(yy ** 2 + xx ** 2)'], {}), '(yy ** 2 + xx ** 2)\\n', (1334, 1353), True, 'import cupy as cp\\n')]"}}},{"rowIdx":8445,"cells":{"repo_name":{"kind":"string","value":"roundium/handypackages"},"repo_path":{"kind":"string","value":"handypackages/subscribe/migrations/0001_initial.py"},"repo_head_hexsha":{"kind":"string","value":"b8a0e4952644144b31168f9a4ac8e743933d87c7"},"content":{"kind":"string","value":"# Generated by Django 2.2.1 on 2019-06-22 11:03\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='SubscribeModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('email', models.EmailField(db_index=True, max_length=255, unique=True, verbose_name='Email')),\n ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='Subscribe Time')),\n ],\n options={\n 'verbose_name': 'Subscribe Email',\n 'verbose_name_plural': 'Subscribe Emails',\n 'abstract': False,\n },\n ),\n ]\n"},"apis":{"kind":"string","value":"[((310, 403), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '\"\"\"ID\"\"\"'}), \"(auto_created=True, primary_key=True, serialize=False,\\n verbose_name='ID')\\n\", (326, 403), False, 'from django.db import migrations, models\\n'), ((428, 516), 'django.db.models.EmailField', 'models.EmailField', ([], {'db_index': '(True)', 'max_length': '(255)', 'unique': '(True)', 'verbose_name': '\"\"\"Email\"\"\"'}), \"(db_index=True, max_length=255, unique=True, verbose_name=\\n 'Email')\\n\", (445, 516), False, 'from django.db import migrations, models\\n'), ((546, 616), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'verbose_name': '\"\"\"Subscribe Time\"\"\"'}), \"(auto_now_add=True, verbose_name='Subscribe Time')\\n\", (566, 616), False, 'from django.db import migrations, models\\n')]"}}},{"rowIdx":8446,"cells":{"repo_name":{"kind":"string","value":"lwh2015/TuShare"},"repo_path":{"kind":"string","value":"TuShare/view/sh_margins.py"},"repo_head_hexsha":{"kind":"string","value":"f244e05e5cf208e18e6237d3b81f71f0d3c1394a"},"content":{"kind":"string","value":"# -*- coding: UTF-8 -*-\nimport json\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport tushare as ts\nfrom .publiceClass import DateEncoder\n\n@csrf_exempt\ndef sh_margins(request):\n try:\n start = request.POST.get('start','')#选填\n end = request.POST.get('end','')#选填\n data = ts.sh_margins(start,end)\n res = {'columns':[\n '信用交易日期',\n '本日融资余额(元)',\n '本日融资买入额(元)',\n '本日融券余量',\n '本日融券余量金额(元)',\n '本日融券卖出量',\n '本日融资融券余额(元)'\n ],'data':json.loads(json.dumps(data.values,cls=DateEncoder))}\n except(BaseException):\n return HttpResponse(BaseException)\n else:\n\n return HttpResponse(json.dumps(res),content_type=\"application/json\")\n\n"},"apis":{"kind":"string","value":"[((341, 366), 'tushare.sh_margins', 'ts.sh_margins', (['start', 'end'], {}), '(start, end)\\n', (354, 366), True, 'import tushare as ts\\n'), ((676, 703), 'django.http.HttpResponse', 'HttpResponse', (['BaseException'], {}), '(BaseException)\\n', (688, 703), False, 'from django.http import HttpResponse\\n'), ((743, 758), 'json.dumps', 'json.dumps', (['res'], {}), '(res)\\n', (753, 758), False, 'import json\\n'), ((592, 632), 'json.dumps', 'json.dumps', (['data.values'], {'cls': 'DateEncoder'}), '(data.values, cls=DateEncoder)\\n', (602, 632), False, 'import json\\n')]"}}},{"rowIdx":8447,"cells":{"repo_name":{"kind":"string","value":"robertob45/learning-python"},"repo_path":{"kind":"string","value":"intermediate/classes/camera.py"},"repo_head_hexsha":{"kind":"string","value":"7407f7d9e513792150eb2b65ebc644b5f8632c56"},"content":{"kind":"string","value":"class Camera:\n \"\"\"docstring for .\"\"\"\n def __init__(self, brand, sensor, lens, battery):\n self.brand = brand\n self.sensor = sensor\n self.lens = lens\n self.battery = battery\n\n def __str__(self):\n return self.brand + ' ' + self.sensor + ' ' + self.lens + ' ' + self.battery\n\n def focus(self):\n print('Focusing using', self.lens, '...')\n print('')\n\n def frame(self):\n print('Move until your subject is in the desired position')\n print('.')\n print('.')\n print('.')\n\n def flash(self, flash_use):\n if flash_use == 's':\n print('Shooting with flash...')\n else:\n print('Shooting without flash...')\n print('')\n\n def format(self, save_format):\n if save_format == 'jpg':\n print('Saving in: ' + save_format)\n elif save_format == 'raw':\n print('Saving in: ' + save_format)\n else:\n print('No valid format to save')\n\n def take_picture(self, save_format, flash_use):\n print('Say cheese!')\n self.focus()\n self.frame()\n self.flash(flash_use)\n self.format(save_format)\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8448,"cells":{"repo_name":{"kind":"string","value":"didindinn/database-as-a-service"},"repo_path":{"kind":"string","value":"dbaas/tsuru/tests/test_service_add.py"},"repo_head_hexsha":{"kind":"string","value":"747de31ff8546f7874ddd654af860e130afd17a0"},"content":{"kind":"string","value":"from mock import patch, MagicMock\n\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase\nfrom django.core.urlresolvers import reverse\nfrom django.utils.datastructures import MultiValueDictKeyError\n\nfrom account.models import Role, Team, Organization\nfrom physical.tests.factory import EnvironmentFactory, PlanFactory\nfrom physical.models import Plan\n\n\nclass ValidationTestCase(TestCase):\n \"\"\"HTTP test cases for the tsuru Service Add. This class focuses on\n validations of POST\n \"\"\"\n USERNAME = \"fake_user\"\n PASSWORD = \"123456\"\n\n def setUp(self):\n self.role = Role.objects.get_or_create(name=\"fake_role\")[0]\n self.organization = Organization.objects.get_or_create(\n name='fake_organization'\n )[0]\n self.team = Team.objects.get_or_create(\n name=\"fake_team\", role=self.role,\n organization=self.organization)[0]\n self.superuser = User.objects.create_superuser(\n self.USERNAME,\n email=\"{}@admin.com\".format(self.USERNAME),\n password=self.PASSWORD\n )\n self.team.users.add(self.superuser)\n self.client.login(username=self.USERNAME, password=self.PASSWORD)\n self.env = 'dev'\n self.environment = EnvironmentFactory.create(name=self.env)\n self.url = reverse('tsuru:service-add', args=(self.env,))\n self.name = 'fake_database'\n self.user = '{}@admin.com'.format(self.USERNAME)\n self.description = 'fake desc'\n self.plan = PlanFactory(name='fake_plan', provider=Plan.CLOUDSTACK)\n self.plan.environments.add(self.environment)\n self.plan_name = 'fake-plan-dev'\n\n def tearDown(self):\n self.client.logout()\n\n def _assert_resp(self, resp, msg):\n self.assertEqual(resp.status_code, 400)\n self.assertEqual(resp.content, msg)\n\n def test_name_not_in_payload(self):\n with self.assertRaises(MultiValueDictKeyError):\n self.client.post(self.url, {})\n\n def test_user_not_in_payload(self):\n with self.assertRaises(MultiValueDictKeyError):\n self.client.post(\n self.url,\n {'name': self.name}\n )\n\n def test_team_not_in_payload(self):\n with self.assertRaises(MultiValueDictKeyError):\n self.client.post(\n self.url,\n {'name': self.name, 'user': self.user}\n )\n\n def test_description_fail(self):\n resp = self.client.post(\n self.url,\n {'name': self.name, 'user': self.user, 'team': self.team}\n )\n self._assert_resp(resp, '\"A description must be provided.\"')\n\n def test_name_fail(self):\n resp = self.client.post(\n self.url,\n {\n 'name': '99invalid-name',\n 'user': self.user,\n 'description': self.description,\n 'team': self.team\n }\n )\n self._assert_resp(\n resp,\n '\"Your database name must match /^[a-z][a-z0-9_]+$/ .\"'\n )\n\n @patch('tsuru.views.Database.objects.get', new=MagicMock())\n def test_database_found(self):\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': self.user,\n 'description': self.description,\n 'team': self.team\n }\n )\n self._assert_resp(\n resp,\n '\"There is already a database called fake_database in dev.\"'\n )\n\n @patch(\n 'tsuru.views.database_name_evironment_constraint',\n new=MagicMock(return_value=True)\n )\n def test_already_exist_database_with_name(self):\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': self.user,\n 'description': self.description,\n 'team': self.team\n }\n )\n self._assert_resp(\n resp,\n '\"fake_database already exists in env dev!\"'\n )\n\n def test_user_not_found(self):\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': 'another_user@not_found.com',\n 'description': self.description,\n 'team': self.team\n }\n )\n self._assert_resp(\n resp,\n '\"User does not exist.\"'\n )\n\n def test_team_not_found(self):\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': 'another_user@not_found.com',\n 'description': self.description,\n 'team': 'team_not_found'\n }\n )\n self._assert_resp(\n resp,\n '\"User does not exist.\"'\n )\n\n def test_env_not_found(self):\n self.url = self.url.replace(\n '/{}/'.format(self.env),\n '/env_not_found/'\n )\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': self.user,\n 'description': self.description,\n 'team': self.team.name\n }\n )\n self._assert_resp(\n resp,\n '\"Environment does not exist.\"'\n )\n\n @patch(\n 'tsuru.views.Team.count_databases_in_use',\n new=MagicMock(return_value=99)\n )\n def test_allocation_limit(self):\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': self.user,\n 'description': self.description,\n 'team': self.team.name\n }\n )\n self._assert_resp(\n resp,\n ('\"The database alocation limit of 2 has been exceeded for the '\n 'selected team: fake_team\"')\n )\n\n def test_plan_not_on_payload(self):\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': self.user,\n 'description': self.description,\n 'team': self.team.name\n }\n )\n self._assert_resp(\n resp,\n '\"Plan was not found\"'\n )\n\n def test_plan_not_found(self):\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': self.user,\n 'description': self.description,\n 'team': self.team.name,\n 'plan': 'not found'\n }\n )\n self._assert_resp(\n resp,\n '\"Plan was not found\"'\n )\n\n @patch('notification.tasks.TaskRegister.create_task', new=MagicMock())\n @patch('notification.tasks.create_database_with_retry')\n def test_call_database_create(self, create_database_mock):\n resp = self.client.post(\n self.url,\n {\n 'name': self.name,\n 'user': self.user,\n 'description': self.description,\n 'team': self.team.name,\n 'plan': self.plan_name\n }\n )\n\n self.assertTrue(create_database_mock.called)\n self.assertEqual(resp.status_code, 201)\n"},"apis":{"kind":"string","value":"[((6821, 6875), 'mock.patch', 'patch', (['\"\"\"notification.tasks.create_database_with_retry\"\"\"'], {}), \"('notification.tasks.create_database_with_retry')\\n\", (6826, 6875), False, 'from mock import patch, MagicMock\\n'), ((1268, 1308), 'physical.tests.factory.EnvironmentFactory.create', 'EnvironmentFactory.create', ([], {'name': 'self.env'}), '(name=self.env)\\n', (1293, 1308), False, 'from physical.tests.factory import EnvironmentFactory, PlanFactory\\n'), ((1328, 1374), 'django.core.urlresolvers.reverse', 'reverse', (['\"\"\"tsuru:service-add\"\"\"'], {'args': '(self.env,)'}), \"('tsuru:service-add', args=(self.env,))\\n\", (1335, 1374), False, 'from django.core.urlresolvers import reverse\\n'), ((1527, 1582), 'physical.tests.factory.PlanFactory', 'PlanFactory', ([], {'name': '\"\"\"fake_plan\"\"\"', 'provider': 'Plan.CLOUDSTACK'}), \"(name='fake_plan', provider=Plan.CLOUDSTACK)\\n\", (1538, 1582), False, 'from physical.tests.factory import EnvironmentFactory, PlanFactory\\n'), ((611, 655), 'account.models.Role.objects.get_or_create', 'Role.objects.get_or_create', ([], {'name': '\"\"\"fake_role\"\"\"'}), \"(name='fake_role')\\n\", (637, 655), False, 'from account.models import Role, Team, Organization\\n'), ((687, 747), 'account.models.Organization.objects.get_or_create', 'Organization.objects.get_or_create', ([], {'name': '\"\"\"fake_organization\"\"\"'}), \"(name='fake_organization')\\n\", (721, 747), False, 'from account.models import Role, Team, Organization\\n'), ((793, 890), 'account.models.Team.objects.get_or_create', 'Team.objects.get_or_create', ([], {'name': '\"\"\"fake_team\"\"\"', 'role': 'self.role', 'organization': 'self.organization'}), \"(name='fake_team', role=self.role, organization=\\n self.organization)\\n\", (819, 890), False, 'from account.models import Role, Team, Organization\\n'), ((3129, 3140), 'mock.MagicMock', 'MagicMock', ([], {}), '()\\n', (3138, 3140), False, 'from mock import patch, MagicMock\\n'), ((3635, 3663), 'mock.MagicMock', 'MagicMock', ([], {'return_value': '(True)'}), '(return_value=True)\\n', (3644, 3663), False, 'from mock import patch, MagicMock\\n'), ((5449, 5475), 'mock.MagicMock', 'MagicMock', ([], {'return_value': '(99)'}), '(return_value=99)\\n', (5458, 5475), False, 'from mock import patch, MagicMock\\n'), ((6803, 6814), 'mock.MagicMock', 'MagicMock', ([], {}), '()\\n', (6812, 6814), False, 'from mock import patch, MagicMock\\n')]"}}},{"rowIdx":8449,"cells":{"repo_name":{"kind":"string","value":"Muhammet-Yildiz/Ecommerce_Website-HepsiOrada"},"repo_path":{"kind":"string","value":"Main/migrations/0072_auto_20210506_0016.py"},"repo_head_hexsha":{"kind":"string","value":"91935014ccc37e0ea57c8cbd2c4891941dcbb917"},"content":{"kind":"string","value":"# Generated by Django 3.1.4 on 2021-05-05 21:16\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Main', '0071_auto_20210506_0004'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='product',\n name='chooseColor',\n ),\n migrations.RemoveField(\n model_name='product',\n name='chooseSize',\n ),\n ]\n"},"apis":{"kind":"string","value":"[((224, 288), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '\"\"\"product\"\"\"', 'name': '\"\"\"chooseColor\"\"\"'}), \"(model_name='product', name='chooseColor')\\n\", (246, 288), False, 'from django.db import migrations\\n'), ((333, 396), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '\"\"\"product\"\"\"', 'name': '\"\"\"chooseSize\"\"\"'}), \"(model_name='product', name='chooseSize')\\n\", (355, 396), False, 'from django.db import migrations\\n')]"}}},{"rowIdx":8450,"cells":{"repo_name":{"kind":"string","value":"zweed4u/dailycodingproblem"},"repo_path":{"kind":"string","value":"1.py"},"repo_head_hexsha":{"kind":"string","value":"6e40eaad347e283f86a11adeff01c6426211a0be"},"content":{"kind":"string","value":"#!/usr/bin/python3\n\"\"\"\nGood morning! Here's your coding interview problem for today.\n\nThis problem was recently asked by Google.\n\nGiven a list of numbers and a number k, return whether any two numbers from the list add up to k.\n\nFor example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.\n\nBonus: Can you do this in one pass?\n\"\"\"\n\ndef func(l, k):\n sums = []\n for index, element in enumerate(l):\n print(f'Current element: {element}')\n if index == 0:\n # first element - need another\n print()\n continue\n for num in range(index):\n print(f'Appending {l[index]} + {l[num]}')\n sums.append(l[num] + l[index])\n print()\n print(sums)\n return k in sums\n\nprint(func([10, 15, 3, 7], 17))\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8451,"cells":{"repo_name":{"kind":"string","value":"ow-gryphon/gryphon"},"repo_path":{"kind":"string","value":"gryphon/data/template_scaffolding/template/setup.py"},"repo_head_hexsha":{"kind":"string","value":"0b34f2f61a50af46b9d1ec1d3c15d53cf4055dd5"},"content":{"kind":"string","value":"import json\nimport setuptools\n\nwith open(\"template/README.md\", \"r\") as fh:\n long_description = fh.read()\n\nwith open('requirements.txt') as fr:\n requirements = fr.read().strip().split('\\n')\n\nwith open('metadata.json') as fr:\n metadata = json.load(fr)\n\nsetuptools.setup(\n name=\"\", # Name of the repository\n version=\"0.0.1\",\n author=metadata.get(\"author\", \"\"),\n author_email=metadata.get(\"author_email\", \"\"),\n description=metadata.get(\"description\", \"\"),\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"\", # Repository URL or externally maintained page\n packages=setuptools.find_packages(),\n python_requires='>=3.6',\n install_requires=requirements,\n)\n"},"apis":{"kind":"string","value":"[((245, 258), 'json.load', 'json.load', (['fr'], {}), '(fr)\\n', (254, 258), False, 'import json\\n'), ((640, 666), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\\n', (664, 666), False, 'import setuptools\\n')]"}}},{"rowIdx":8452,"cells":{"repo_name":{"kind":"string","value":"Mhaiyang/iccv"},"repo_path":{"kind":"string","value":"train_base3.py"},"repo_head_hexsha":{"kind":"string","value":"04a8ee52c2323d7ff5cdf03c0be1466e8180d2eb"},"content":{"kind":"string","value":"\"\"\"\n @Time : 201/21/19 10:41\n @Author : TaylorMei\n @Email : mhy845879017@gmail.com\n \n @Project : iccv\n @File : train_base3.py\n @Function:\n \n\"\"\"\nimport datetime\nimport os\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom torch.backends import cudnn\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom tensorboardX import SummaryWriter\nfrom tqdm import tqdm\n\nimport joint_transforms\nfrom config import msd_training_root\nfrom config import backbone_path\nfrom dataset import ImageFolder\nfrom misc import AvgMeter, check_mkdir\nfrom model.base3 import BASE3\n\nimport loss as L\n\ncudnn.benchmark = True\n\ndevice_ids = [2]\n\nckpt_path = './ckpt'\nexp_name = 'BASE3'\n\nargs = {\n 'epoch_num': 100,\n 'train_batch_size': 14,\n 'last_epoch': 0,\n 'lr': 5e-3,\n 'lr_decay': 0.9,\n 'weight_decay': 5e-4,\n 'momentum': 0.9,\n 'snapshot': '',\n 'scale': 384,\n 'save_point': [60, 80, 90],\n 'add_graph': True,\n 'poly_train': True,\n 'optimizer': 'SGD'\n}\n\n# Path.\ncheck_mkdir(ckpt_path)\ncheck_mkdir(os.path.join(ckpt_path, exp_name))\nvis_path = os.path.join(ckpt_path, exp_name, 'log')\ncheck_mkdir(vis_path)\nlog_path = os.path.join(ckpt_path, exp_name, str(datetime.datetime.now()) + '.txt')\nwriter = SummaryWriter(log_dir=vis_path, comment=exp_name)\n\n# Transform Data.\njoint_transform = joint_transforms.Compose([\n joint_transforms.RandomRotate(),\n joint_transforms.Resize((args['scale'], args['scale']))\n])\nimg_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # maybe can optimized.\n])\ntarget_transform = transforms.ToTensor()\n\n# Prepare Data Set.\ntrain_set = ImageFolder(msd_training_root, joint_transform, img_transform, target_transform)\nprint(\"Train set: {}\".format(train_set.__len__()))\ntrain_loader = DataLoader(train_set, batch_size=args['train_batch_size'], num_workers=0, shuffle=True)\n\n\ndef main():\n print(args)\n print(exp_name)\n\n net = BASE3(backbone_path).cuda(device_ids[0]).train()\n if args['add_graph']:\n writer.add_graph(net, input_to_model=torch.rand(\n args['train_batch_size'], 3, args['scale'], args['scale']).cuda(device_ids[0]))\n\n if args['optimizer'] == 'Adam':\n print(\"Adam\")\n optimizer = optim.Adam([\n {'params': [param for name, param in net.named_parameters() if name[-4:] == 'bias'],\n 'lr': 2 * args['lr']},\n {'params': [param for name, param in net.named_parameters() if name[-4:] != 'bias'],\n 'lr': 1 * args['lr'], 'weight_decay': args['weight_decay']}\n ])\n else:\n print(\"SGD\")\n optimizer = optim.SGD([\n {'params': [param for name, param in net.named_parameters() if name[-4:] == 'bias'],\n 'lr': 2 * args['lr']},\n {'params': [param for name, param in net.named_parameters() if name[-4:] != 'bias'],\n 'lr': 1 * args['lr'], 'weight_decay': args['weight_decay']}\n ], momentum=args['momentum'])\n\n if len(args['snapshot']) > 0:\n print('Training Resumes From \\'%s\\'' % args['snapshot'])\n net.load_state_dict(torch.load(os.path.join(ckpt_path, exp_name, args['snapshot'] + '.pth')))\n\n net = nn.DataParallel(net, device_ids=device_ids)\n print(\"Using {} GPU(s) to Train.\".format(len(device_ids)))\n\n open(log_path, 'w').write(str(args) + '\\n\\n')\n train(net, optimizer)\n writer.close()\n\n\ndef train(net, optimizer):\n curr_iter = 1\n\n for epoch in range(args['last_epoch'] + 1, args['last_epoch'] + 1 + args['epoch_num']):\n loss_4_record, loss_3_record, loss_2_record, loss_1_record, \\\n loss_f_record, loss_record = AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter()\n\n train_iterator = tqdm(train_loader, total=len(train_loader))\n for data in train_iterator:\n if args['poly_train']:\n base_lr = args['lr'] * (1 - float(curr_iter) / (args['epoch_num'] * len(train_loader))) ** args[\n 'lr_decay']\n optimizer.param_groups[0]['lr'] = 2 * base_lr\n optimizer.param_groups[1]['lr'] = 1 * base_lr\n\n inputs, labels = data\n batch_size = inputs.size(0)\n inputs = Variable(inputs).cuda(device_ids[0])\n labels = Variable(labels).cuda(device_ids[0])\n\n optimizer.zero_grad()\n\n predict_4, predict_3, predict_2, predict_1, predict_f = net(inputs)\n\n loss_4 = L.lovasz_hinge(predict_4, labels)\n loss_3 = L.lovasz_hinge(predict_3, labels)\n loss_2 = L.lovasz_hinge(predict_2, labels)\n loss_1 = L.lovasz_hinge(predict_1, labels)\n loss_f = L.lovasz_hinge(predict_f, labels)\n\n loss = loss_4 + loss_3 + loss_2 + loss_1 + loss_f\n\n loss.backward()\n\n optimizer.step()\n\n loss_record.update(loss.data, batch_size)\n loss_4_record.update(loss_4.data, batch_size)\n loss_3_record.update(loss_3.data, batch_size)\n loss_2_record.update(loss_2.data, batch_size)\n loss_1_record.update(loss_1.data, batch_size)\n loss_f_record.update(loss_f.data, batch_size)\n\n if curr_iter % 50 == 0:\n writer.add_scalar('loss', loss, curr_iter)\n writer.add_scalar('loss_4', loss_4, curr_iter)\n writer.add_scalar('loss_3', loss_3, curr_iter)\n writer.add_scalar('loss_2', loss_2, curr_iter)\n writer.add_scalar('loss_1', loss_1, curr_iter)\n writer.add_scalar('loss_f', loss_f, curr_iter)\n\n log = '[%3d], [%6d], [%.6f], [%.5f], [L4: %.5f], [L3: %.5f], [L2: %.5f], [L1: %.5f], [Lf: %.5f]' % \\\n (epoch, curr_iter, base_lr, loss_record.avg, loss_4_record.avg, loss_3_record.avg, loss_2_record.avg,\n loss_1_record.avg, loss_f_record.avg)\n train_iterator.set_description(log)\n open(log_path, 'a').write(log + '\\n')\n\n curr_iter += 1\n\n if epoch in args['save_point']:\n net.cpu()\n torch.save(net.module.state_dict(), os.path.join(ckpt_path, exp_name, '%d.pth' % epoch))\n net.cuda(device_ids[0])\n\n if epoch >= args['epoch_num']:\n net.cpu()\n torch.save(net.module.state_dict(), os.path.join(ckpt_path, exp_name, '%d.pth' % epoch))\n print(\"Optimization Have Done!\")\n return\n\n\nif __name__ == '__main__':\n main()\n"},"apis":{"kind":"string","value":"[((1056, 1078), 'misc.check_mkdir', 'check_mkdir', (['ckpt_path'], {}), '(ckpt_path)\\n', (1067, 1078), False, 'from misc import AvgMeter, check_mkdir\\n'), ((1137, 1177), 'os.path.join', 'os.path.join', (['ckpt_path', 'exp_name', '\"\"\"log\"\"\"'], {}), \"(ckpt_path, exp_name, 'log')\\n\", (1149, 1177), False, 'import os\\n'), ((1178, 1199), 'misc.check_mkdir', 'check_mkdir', (['vis_path'], {}), '(vis_path)\\n', (1189, 1199), False, 'from misc import AvgMeter, check_mkdir\\n'), ((1293, 1342), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {'log_dir': 'vis_path', 'comment': 'exp_name'}), '(log_dir=vis_path, comment=exp_name)\\n', (1306, 1342), False, 'from tensorboardX import SummaryWriter\\n'), ((1688, 1709), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\\n', (1707, 1709), False, 'from torchvision import transforms\\n'), ((1743, 1828), 'dataset.ImageFolder', 'ImageFolder', (['msd_training_root', 'joint_transform', 'img_transform', 'target_transform'], {}), '(msd_training_root, joint_transform, img_transform, target_transform\\n )\\n', (1754, 1828), False, 'from dataset import ImageFolder\\n'), ((1890, 1981), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batch_size': \"args['train_batch_size']\", 'num_workers': '(0)', 'shuffle': '(True)'}), \"(train_set, batch_size=args['train_batch_size'], num_workers=0,\\n shuffle=True)\\n\", (1900, 1981), False, 'from torch.utils.data import DataLoader\\n'), ((1091, 1124), 'os.path.join', 'os.path.join', (['ckpt_path', 'exp_name'], {}), '(ckpt_path, exp_name)\\n', (1103, 1124), False, 'import os\\n'), ((3282, 3325), 'torch.nn.DataParallel', 'nn.DataParallel', (['net'], {'device_ids': 'device_ids'}), '(net, device_ids=device_ids)\\n', (3297, 3325), False, 'from torch import nn\\n'), ((1411, 1442), 'joint_transforms.RandomRotate', 'joint_transforms.RandomRotate', ([], {}), '()\\n', (1440, 1442), False, 'import joint_transforms\\n'), ((1448, 1503), 'joint_transforms.Resize', 'joint_transforms.Resize', ([\"(args['scale'], args['scale'])\"], {}), \"((args['scale'], args['scale']))\\n\", (1471, 1503), False, 'import joint_transforms\\n'), ((1548, 1569), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\\n', (1567, 1569), False, 'from torchvision import transforms\\n'), ((1575, 1641), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\\n', (1595, 1641), False, 'from torchvision import transforms\\n'), ((1249, 1272), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\\n', (1270, 1272), False, 'import datetime\\n'), ((3732, 3742), 'misc.AvgMeter', 'AvgMeter', ([], {}), '()\\n', (3740, 3742), False, 'from misc import AvgMeter, check_mkdir\\n'), ((3744, 3754), 'misc.AvgMeter', 'AvgMeter', ([], {}), '()\\n', (3752, 3754), False, 'from misc import AvgMeter, check_mkdir\\n'), ((3756, 3766), 'misc.AvgMeter', 'AvgMeter', ([], {}), '()\\n', (3764, 3766), False, 'from misc import AvgMeter, check_mkdir\\n'), ((3768, 3778), 'misc.AvgMeter', 'AvgMeter', ([], {}), '()\\n', (3776, 3778), False, 'from misc import AvgMeter, check_mkdir\\n'), ((3780, 3790), 'misc.AvgMeter', 'AvgMeter', ([], {}), '()\\n', (3788, 3790), False, 'from misc import AvgMeter, check_mkdir\\n'), ((3792, 3802), 'misc.AvgMeter', 'AvgMeter', ([], {}), '()\\n', (3800, 3802), False, 'from misc import AvgMeter, check_mkdir\\n'), ((4542, 4575), 'loss.lovasz_hinge', 'L.lovasz_hinge', (['predict_4', 'labels'], {}), '(predict_4, labels)\\n', (4556, 4575), True, 'import loss as L\\n'), ((4597, 4630), 'loss.lovasz_hinge', 'L.lovasz_hinge', (['predict_3', 'labels'], {}), '(predict_3, labels)\\n', (4611, 4630), True, 'import loss as L\\n'), ((4652, 4685), 'loss.lovasz_hinge', 'L.lovasz_hinge', (['predict_2', 'labels'], {}), '(predict_2, labels)\\n', (4666, 4685), True, 'import loss as L\\n'), ((4707, 4740), 'loss.lovasz_hinge', 'L.lovasz_hinge', (['predict_1', 'labels'], {}), '(predict_1, labels)\\n', (4721, 4740), True, 'import loss as L\\n'), ((4762, 4795), 'loss.lovasz_hinge', 'L.lovasz_hinge', (['predict_f', 'labels'], {}), '(predict_f, labels)\\n', (4776, 4795), True, 'import loss as L\\n'), ((3208, 3268), 'os.path.join', 'os.path.join', (['ckpt_path', 'exp_name', \"(args['snapshot'] + '.pth')\"], {}), \"(ckpt_path, exp_name, args['snapshot'] + '.pth')\\n\", (3220, 3268), False, 'import os\\n'), ((6202, 6253), 'os.path.join', 'os.path.join', (['ckpt_path', 'exp_name', \"('%d.pth' % epoch)\"], {}), \"(ckpt_path, exp_name, '%d.pth' % epoch)\\n\", (6214, 6253), False, 'import os\\n'), ((6401, 6452), 'os.path.join', 'os.path.join', (['ckpt_path', 'exp_name', \"('%d.pth' % epoch)\"], {}), \"(ckpt_path, exp_name, '%d.pth' % epoch)\\n\", (6413, 6452), False, 'import os\\n'), ((2039, 2059), 'model.base3.BASE3', 'BASE3', (['backbone_path'], {}), '(backbone_path)\\n', (2044, 2059), False, 'from model.base3 import BASE3\\n'), ((4309, 4325), 'torch.autograd.Variable', 'Variable', (['inputs'], {}), '(inputs)\\n', (4317, 4325), False, 'from torch.autograd import Variable\\n'), ((4367, 4383), 'torch.autograd.Variable', 'Variable', (['labels'], {}), '(labels)\\n', (4375, 4383), False, 'from torch.autograd import Variable\\n'), ((2159, 2228), 'torch.rand', 'torch.rand', ([\"args['train_batch_size']\", '(3)', \"args['scale']\", \"args['scale']\"], {}), \"(args['train_batch_size'], 3, args['scale'], args['scale'])\\n\", (2169, 2228), False, 'import torch\\n')]"}}},{"rowIdx":8453,"cells":{"repo_name":{"kind":"string","value":"uwase-diane/min_pitch"},"repo_path":{"kind":"string","value":"tests/test_comment.py"},"repo_head_hexsha":{"kind":"string","value":"514ab5da150244e900fd51b6563173a905ef4f29"},"content":{"kind":"string","value":"import unittest\nfrom app.models import Comment, Pitch\nfrom app import db\n\nclass TestPitchComment(unittest.TestCase):\n\n def setUp(self):\n self.new_pitch = Pitch(post = \"doit\", category='Quotes')\n self.new_comment = Comment(comment = \"good comment\", pitch=self.new_pitch)\n \n def test_instance(self):\n self.assertTrue(isinstance(self.new_comment,Comment))\n\n\n def test_check_instance_variables(self):\n self.assertEquals(self.new_comment.comment,\"good comment\")\n self.assertEquals(self.new_comment.pitch,self.new_pitch, 'do it')"},"apis":{"kind":"string","value":"[((164, 201), 'app.models.Pitch', 'Pitch', ([], {'post': '\"\"\"doit\"\"\"', 'category': '\"\"\"Quotes\"\"\"'}), \"(post='doit', category='Quotes')\\n\", (169, 201), False, 'from app.models import Comment, Pitch\\n'), ((231, 284), 'app.models.Comment', 'Comment', ([], {'comment': '\"\"\"good comment\"\"\"', 'pitch': 'self.new_pitch'}), \"(comment='good comment', pitch=self.new_pitch)\\n\", (238, 284), False, 'from app.models import Comment, Pitch\\n')]"}}},{"rowIdx":8454,"cells":{"repo_name":{"kind":"string","value":"itteamforslp/safelife_project"},"repo_path":{"kind":"string","value":"teacher/views.py"},"repo_head_hexsha":{"kind":"string","value":"53af23dec0d19acf7227a43a16d7aedad443e90d"},"content":{"kind":"string","value":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.template import loader\nfrom django.db import connection\nfrom django.http import HttpResponseRedirect\nimport datetime\nfrom django.http import JsonResponse\nfrom administrator.models import Course, CourseTeacher, CourseStudent, Student\nfrom django.core.exceptions import PermissionDenied\n\n\ndef teacher_only(function):\n #\"\"\"Limit view to teacher only.\"\"\"\n def _inner(request, *args, **kwargs):\n if not request.user.is_staff == False | request.user.is_superuser:\n raise PermissionDenied \n return function(request, *args, **kwargs)\n return _inner\n\n@login_required(login_url = '/users')\n@teacher_only\ndef home(request):\n current_user = request.user.id\n teacher_current_courses = Course.objects.select_related().raw('SELECT * '\n 'FROM course_teachers as CT, courses as C '\n 'WHERE CT.teachers_id = %s AND C.course_id = CT.course_id AND C.is_complete = 0 ', [current_user])\n\n currentdate = datetime.datetime.today().strftime('%Y-%m-%d')\n\n with connection.cursor() as cursor:\n cursor.execute('SELECT CL.course_id, CL.date '\n 'FROM classes as CL, course_teachers as CT '\n 'WHERE CT.teachers_id = %s AND CL.date >= %s '\n 'AND CT.course_id = CL.course_id '\n 'GROUP BY CL.course_id ', [current_user, currentdate])\n \n next_class_date = cursor.fetchall()\n \n with connection.cursor() as cursor:\n cursor.execute('SELECT CS.course_id, COUNT(CS.students_id) '\n 'FROM course_teachers as CT, course_students as CS '\n 'WHERE CT.teachers_id = %s AND CT.course_id = CS.course_id '\n 'GROUP BY CS.course_id ', [current_user])\n teacher_student_count = cursor.fetchall()\n\n with connection.cursor() as cursor:\n cursor.execute('SELECT C.course_id, C.notes '\n 'FROM course_teachers as CT, courses as C '\n 'WHERE CT.teachers_id = %s AND C.course_id = CT.course_id '\n 'GROUP BY CT.course_id ', [current_user])\n teacher_course_notes = cursor.fetchall()\n \n\n template = loader.get_template('teacher/dashboard.html')\n context = {\n 'teacher_current_courses': teacher_current_courses,\n 'teacher_student_count': teacher_student_count,\n 'next_class_date': next_class_date,\n 'teacher_course_notes': teacher_course_notes\n }\n \n # Render the template to the user\n return HttpResponse(template.render(context, request))\n\n@csrf_exempt\ndef update_course_notes(request):\n # Get the student name that was passed from the web page\n courseNotes = request.POST.get('courseNotes')\n courseId = request.POST.get('courseId')\n # Create a cursor to execute raw SQL queries.\n with connection.cursor() as cursor:\n cursor.execute('UPDATE courses '\n 'SET notes = %s '\n 'WHERE course_id = %s', [courseNotes, courseId])\n\n # Render the response to the user\n \n"},"apis":{"kind":"string","value":"[((776, 810), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '\"\"\"/users\"\"\"'}), \"(login_url='/users')\\n\", (790, 810), False, 'from django.contrib.auth.decorators import login_required\\n'), ((2666, 2711), 'django.template.loader.get_template', 'loader.get_template', (['\"\"\"teacher/dashboard.html\"\"\"'], {}), \"('teacher/dashboard.html')\\n\", (2685, 2711), False, 'from django.template import loader\\n'), ((1306, 1325), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\\n', (1323, 1325), False, 'from django.db import connection\\n'), ((1789, 1808), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\\n', (1806, 1808), False, 'from django.db import connection\\n'), ((2197, 2216), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\\n', (2214, 2216), False, 'from django.db import connection\\n'), ((3355, 3374), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\\n', (3372, 3374), False, 'from django.db import connection\\n'), ((919, 950), 'administrator.models.Course.objects.select_related', 'Course.objects.select_related', ([], {}), '()\\n', (948, 950), False, 'from administrator.models import Course, CourseTeacher, CourseStudent, Student\\n'), ((1245, 1270), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\\n', (1268, 1270), False, 'import datetime\\n')]"}}},{"rowIdx":8455,"cells":{"repo_name":{"kind":"string","value":"botstory/bot-story"},"repo_path":{"kind":"string","value":"botstory/middlewares/text/text_test.py"},"repo_head_hexsha":{"kind":"string","value":"9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3"},"content":{"kind":"string","value":"import logging\nimport pytest\nimport re\nfrom . import text\nfrom ... import matchers\nfrom ...utils import answer, SimpleTrigger\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.asyncio\nasync def test_should_run_story_on_equal_message():\n trigger = SimpleTrigger()\n\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on('hi there!')\n def one_story():\n @story.part()\n def then(ctx):\n trigger.passed()\n\n await talk.pure_text('hi there!')\n\n assert trigger.is_triggered\n\n\n@pytest.mark.asyncio\nasync def test_should_not_run_story_on_non_equal_message():\n trigger = SimpleTrigger()\n\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on('hi there!')\n def one_story():\n @story.part()\n def then(ctx):\n trigger.passed()\n\n await talk.pure_text('buy!')\n\n assert not trigger.is_triggered\n\n\n@pytest.mark.asyncio\nasync def test_should_catch_any_text_message():\n trigger = SimpleTrigger()\n\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on(text.Any())\n def one_story():\n @story.part()\n def then(ctx):\n trigger.passed()\n\n await talk.pure_text('hi there!')\n\n assert trigger.is_triggered\n\n\n@pytest.mark.asyncio\nasync def test_should_ignore_any_non_text_message():\n trigger = SimpleTrigger()\n\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on(text.Any())\n def one_story():\n @story.part()\n def then(ctx):\n trigger.passed()\n\n await talk.location('some where')\n\n assert not trigger.is_triggered\n\n\ndef test_serialize_text_any():\n m_old = text.Any()\n m_new = matchers.deserialize(matchers.serialize(m_old))\n assert isinstance(m_new, text.Any)\n\n\n@pytest.mark.asyncio\nasync def test_should_catch_equal_text_message():\n trigger_hi_there = SimpleTrigger()\n trigger_see_you = SimpleTrigger()\n\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on(text.Equal('hi there!'))\n def first_story():\n @story.part()\n def then(ctx):\n trigger_hi_there.passed()\n\n @story.on(text.Equal('see you!'))\n def second_story():\n @story.part()\n def then(ctx):\n trigger_see_you.passed()\n\n await talk.pure_text('see you!')\n\n assert not trigger_hi_there.is_triggered\n assert trigger_see_you.is_triggered\n\n\ndef test_equal_handle_should_create_right_type():\n assert isinstance(text.Equal.handle(''), text.Equal)\n\n\ndef test_serialize_text_equal():\n m_old = text.Equal('hats off')\n m_new = matchers.deserialize(matchers.serialize(m_old))\n assert isinstance(m_new, text.Equal)\n assert m_new.test_string == 'hats off'\n\n\n@pytest.mark.asyncio\nasync def test_should_catch_equal_text_message_case_in_sensitive():\n trigger_hi_there = SimpleTrigger()\n trigger_see_you = SimpleTrigger()\n\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on(text.EqualCaseIgnore('hi there!'))\n def first_story():\n @story.part()\n def then(ctx):\n trigger_hi_there.passed()\n\n @story.on(text.EqualCaseIgnore('see you!'))\n def second_story():\n @story.part()\n def then(ctx):\n trigger_see_you.passed()\n\n await talk.pure_text('See You!')\n\n assert not trigger_hi_there.is_triggered\n assert trigger_see_you.is_triggered\n\n\ndef test_serialize_text_equal_case_ignore():\n m_old = text.EqualCaseIgnore('hats off')\n m_new = matchers.deserialize(matchers.serialize(m_old))\n assert isinstance(m_new, text.EqualCaseIgnore)\n assert m_new.test_string == 'hats off'\n\n\n@pytest.mark.asyncio\nasync def test_should_catch_text_message_that_match_regex():\n trigger_buy = SimpleTrigger()\n trigger_sell = SimpleTrigger()\n\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on(text.Match('buy (.*)btc'))\n def one_story():\n @story.part()\n def then(ctx):\n trigger_buy.receive(text.get_text(ctx)['matches'][0])\n\n @story.on(text.Match('sell (.*)btc'))\n def another_story():\n @story.part()\n def then(ctx):\n trigger_sell.receive(text.get_text(ctx)['matches'][0])\n\n await talk.pure_text('buy 700btc')\n await talk.pure_text('sell 600btc')\n\n assert trigger_buy.result() == '700'\n assert trigger_sell.result() == '600'\n\n\n@pytest.mark.asyncio\nasync def test_should_catch_text_message_that_match_regex_with_flags():\n trigger_destination = SimpleTrigger()\n\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on(text.Match('going to (.*)', re.IGNORECASE))\n def one_story():\n @story.part()\n def then(ctx):\n logger.debug('ctx')\n logger.debug(ctx)\n trigger_destination.receive(text.get_text(ctx)['matches'][0])\n\n await talk.pure_text('Going to Pripyat')\n\n assert trigger_destination.result() == 'Pripyat'\n\n\n@pytest.mark.asyncio\nasync def test_should_not_fail_on_empty_message():\n with answer.Talk() as talk:\n story = talk.story\n\n @story.on(text.Match('going to (.*)', re.IGNORECASE))\n def one_story():\n @story.part()\n def then(ctx):\n pass\n\n await talk.ask(None)\n\n\ndef test_serialize_text_match():\n m_old = text.Match('hello (.*)', re.IGNORECASE)\n m_new = matchers.deserialize(matchers.serialize(m_old))\n assert isinstance(m_new, text.Match)\n assert m_new.matcher.match('Hello Piter!')\n\n\ndef test_text_qual_should_handle_text():\n assert isinstance(matchers.get_validator('just pure text'), text.Equal)\n"},"apis":{"kind":"string","value":"[((136, 163), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\\n', (153, 163), False, 'import logging\\n')]"}}},{"rowIdx":8456,"cells":{"repo_name":{"kind":"string","value":"xqt/pwb"},"repo_path":{"kind":"string","value":"pywikibot/site/_datasite.py"},"repo_head_hexsha":{"kind":"string","value":"9a4fe27138f32952e533256195849d05855df0b0"},"content":{"kind":"string","value":"\"\"\"Objects representing API interface to Wikibase site.\"\"\"\n#\n# (C) Pywikibot team, 2012-2022\n#\n# Distributed under the terms of the MIT license.\n#\nimport datetime\nimport json\nimport uuid\nfrom contextlib import suppress\nfrom typing import Optional\nfrom warnings import warn\n\nimport pywikibot\nfrom pywikibot.data import api\nfrom pywikibot.exceptions import (\n APIError,\n EntityTypeUnknownError,\n IsRedirectPageError,\n NoPageError,\n NoWikibaseEntityError,\n)\nfrom pywikibot.site._apisite import APISite\nfrom pywikibot.site._decorators import need_extension, need_right, need_version\nfrom pywikibot.tools import itergroup, merge_unique_dicts, remove_last_args\n\n\n__all__ = ('DataSite', )\n\n\nclass DataSite(APISite):\n\n \"\"\"Wikibase data capable site.\"\"\"\n\n def __init__(self, *args, **kwargs) -> None:\n \"\"\"Initializer.\"\"\"\n super().__init__(*args, **kwargs)\n self._item_namespace = None\n self._property_namespace = None\n self._type_to_class = {\n 'item': pywikibot.ItemPage,\n 'property': pywikibot.PropertyPage,\n 'mediainfo': pywikibot.MediaInfo,\n 'lexeme': pywikibot.LexemePage,\n 'form': pywikibot.LexemeForm,\n 'sense': pywikibot.LexemeSense,\n }\n\n def _cache_entity_namespaces(self) -> None:\n \"\"\"Find namespaces for each known wikibase entity type.\"\"\"\n self._entity_namespaces = {}\n for entity_type in self._type_to_class:\n for namespace in self.namespaces.values():\n if not hasattr(namespace, 'defaultcontentmodel'):\n continue\n\n content_model = namespace.defaultcontentmodel\n if content_model == ('wikibase-' + entity_type):\n self._entity_namespaces[entity_type] = namespace\n break\n\n def get_namespace_for_entity_type(self, entity_type):\n \"\"\"\n Return namespace for given entity type.\n\n :return: corresponding namespace\n :rtype: Namespace\n \"\"\"\n if not hasattr(self, '_entity_namespaces'):\n self._cache_entity_namespaces()\n if entity_type in self._entity_namespaces:\n return self._entity_namespaces[entity_type]\n raise EntityTypeUnknownError(\n '{!r} does not support entity type \"{}\" '\n \"or it doesn't have its own namespace\"\n .format(self, entity_type))\n\n @property\n def item_namespace(self):\n \"\"\"\n Return namespace for items.\n\n :return: item namespace\n :rtype: Namespace\n \"\"\"\n if self._item_namespace is None:\n self._item_namespace = self.get_namespace_for_entity_type('item')\n return self._item_namespace\n\n @property\n def property_namespace(self):\n \"\"\"\n Return namespace for properties.\n\n :return: property namespace\n :rtype: Namespace\n \"\"\"\n if self._property_namespace is None:\n self._property_namespace = self.get_namespace_for_entity_type(\n 'property')\n return self._property_namespace\n\n def get_entity_for_entity_id(self, entity_id):\n \"\"\"\n Return a new instance for given entity id.\n\n :raises pywikibot.exceptions.NoWikibaseEntityError: there is no entity\n with the id\n :return: a WikibaseEntity subclass\n :rtype: WikibaseEntity\n \"\"\"\n for cls in self._type_to_class.values():\n if cls.is_valid_id(entity_id):\n return cls(self, entity_id)\n\n entity = pywikibot.page.WikibaseEntity(self, entity_id)\n raise NoWikibaseEntityError(entity)\n\n @property\n @need_version('1.28-wmf.3')\n def sparql_endpoint(self):\n \"\"\"\n Return the sparql endpoint url, if any has been set.\n\n :return: sparql endpoint url\n :rtype: str|None\n \"\"\"\n return self.siteinfo['general'].get('wikibase-sparql')\n\n @property\n @need_version('1.28-wmf.23')\n def concept_base_uri(self):\n \"\"\"\n Return the base uri for concepts/entities.\n\n :return: concept base uri\n :rtype: str\n \"\"\"\n return self.siteinfo['general']['wikibase-conceptbaseuri']\n\n def geo_shape_repository(self):\n \"\"\"Return Site object for the geo-shapes repository e.g. commons.\"\"\"\n url = self.siteinfo['general'].get('wikibase-geoshapestoragebaseurl')\n if url:\n return pywikibot.Site(url=url, user=self.username())\n\n return None\n\n def tabular_data_repository(self):\n \"\"\"Return Site object for the tabular-datas repository e.g. commons.\"\"\"\n url = self.siteinfo['general'].get(\n 'wikibase-tabulardatastoragebaseurl')\n if url:\n return pywikibot.Site(url=url, user=self.username())\n\n return None\n\n def loadcontent(self, identification, *props):\n \"\"\"\n Fetch the current content of a Wikibase item.\n\n This is called loadcontent since\n wbgetentities does not support fetching old\n revisions. Eventually this will get replaced by\n an actual loadrevisions.\n\n :param identification: Parameters used to identify the page(s)\n :type identification: dict\n :param props: the optional properties to fetch.\n \"\"\"\n params = merge_unique_dicts(identification, action='wbgetentities',\n # TODO: When props is empty it results in\n # an empty string ('&props=') but it should\n # result in a missing entry.\n props=props if props else False)\n req = self.simple_request(**params)\n data = req.submit()\n if 'success' not in data:\n raise APIError(data['errors'], '')\n return data['entities']\n\n def preload_entities(self, pagelist, groupsize: int = 50):\n \"\"\"\n Yield subclasses of WikibaseEntity's with content prefilled.\n\n Note that pages will be iterated in a different order\n than in the underlying pagelist.\n\n :param pagelist: an iterable that yields either WikibaseEntity objects,\n or Page objects linked to an ItemPage.\n :param groupsize: how many pages to query at a time\n \"\"\"\n if not hasattr(self, '_entity_namespaces'):\n self._cache_entity_namespaces()\n for sublist in itergroup(pagelist, groupsize):\n req = {'ids': [], 'titles': [], 'sites': []}\n for p in sublist:\n if isinstance(p, pywikibot.page.WikibaseEntity):\n ident = p._defined_by()\n for key in ident:\n req[key].append(ident[key])\n else:\n if p.site == self and p.namespace() in (\n self._entity_namespaces.values()):\n req['ids'].append(p.title(with_ns=False))\n else:\n assert p.site.has_data_repository, \\\n 'Site must have a data repository'\n req['sites'].append(p.site.dbName())\n req['titles'].append(p._link._text)\n\n req = self.simple_request(action='wbgetentities', **req)\n data = req.submit()\n for entity in data['entities']:\n if 'missing' in data['entities'][entity]:\n continue\n cls = self._type_to_class[data['entities'][entity]['type']]\n page = cls(self, entity)\n # No api call is made because item._content is given\n page._content = data['entities'][entity]\n with suppress(IsRedirectPageError):\n page.get() # cannot provide get_redirect=True (T145971)\n yield page\n\n def getPropertyType(self, prop):\n \"\"\"\n Obtain the type of a property.\n\n This is used specifically because we can cache\n the value for a much longer time (near infinite).\n \"\"\"\n params = {'action': 'wbgetentities', 'ids': prop.getID(),\n 'props': 'datatype'}\n expiry = datetime.timedelta(days=365 * 100)\n # Store it for 100 years\n req = self._request(expiry=expiry, parameters=params)\n data = req.submit()\n\n # the IDs returned from the API can be upper or lowercase, depending\n # on the version. See bug T55894 for more information.\n try:\n dtype = data['entities'][prop.getID()]['datatype']\n except KeyError:\n dtype = data['entities'][prop.getID().lower()]['datatype']\n\n return dtype\n\n @need_right('edit')\n def editEntity(self, entity, data, bot: bool = True, **kwargs):\n \"\"\"\n Edit entity.\n\n Note: This method is unable to create entities other than 'item'\n if dict with API parameters was passed to 'entity' parameter.\n\n :param entity: Page to edit, or dict with API parameters\n to use for entity identification\n :type entity: WikibaseEntity or dict\n :param data: data updates\n :type data: dict\n :param bot: Whether to mark the edit as a bot edit\n :return: New entity data\n :rtype: dict\n \"\"\"\n # this changes the reference to a new object\n data = dict(data)\n if isinstance(entity, pywikibot.page.WikibaseEntity):\n params = entity._defined_by(singular=True)\n if 'id' in params and params['id'] == '-1':\n del params['id']\n if not params:\n params['new'] = entity.entity_type\n data_for_new_entity = entity.get_data_for_new_entity()\n data.update(data_for_new_entity)\n else:\n if 'id' in entity and entity['id'] == '-1':\n del entity['id']\n params = dict(entity)\n if not params: # If no identification was provided\n params['new'] = 'item'\n\n params['action'] = 'wbeditentity'\n if bot:\n params['bot'] = 1\n if 'baserevid' in kwargs and kwargs['baserevid']:\n params['baserevid'] = kwargs['baserevid']\n params['token'] = self.tokens['edit']\n\n for arg in kwargs:\n if arg in ['clear', 'summary']:\n params[arg] = kwargs[arg]\n elif arg != 'baserevid':\n warn('Unknown wbeditentity parameter {} ignored'.format(arg),\n UserWarning, 2)\n\n params['data'] = json.dumps(data)\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('edit')\n def addClaim(self, entity, claim, bot: bool = True, summary=None) -> None:\n \"\"\"\n Add a claim.\n\n :param entity: Entity to modify\n :type entity: WikibaseEntity\n :param claim: Claim to be added\n :type claim: pywikibot.Claim\n :param bot: Whether to mark the edit as a bot edit\n :param summary: Edit summary\n :type summary: str\n \"\"\"\n claim.snak = entity.getID() + '$' + str(uuid.uuid4())\n params = {'action': 'wbsetclaim',\n 'claim': json.dumps(claim.toJSON()),\n 'baserevid': entity.latest_revision_id,\n 'summary': summary,\n 'token': self.tokens['edit'],\n 'bot': bot,\n }\n req = self.simple_request(**params)\n data = req.submit()\n # Update the item\n if claim.getID() in entity.claims:\n entity.claims[claim.getID()].append(claim)\n else:\n entity.claims[claim.getID()] = [claim]\n entity.latest_revision_id = data['pageinfo']['lastrevid']\n\n @need_right('edit')\n def changeClaimTarget(self, claim, snaktype: str = 'value',\n bot: bool = True, summary=None):\n \"\"\"\n Set the claim target to the value of the provided claim target.\n\n :param claim: The source of the claim target value\n :type claim: pywikibot.Claim\n :param snaktype: An optional snaktype ('value', 'novalue' or\n 'somevalue'). Default: 'value'\n :param bot: Whether to mark the edit as a bot edit\n :param summary: Edit summary\n :type summary: str\n \"\"\"\n if claim.isReference or claim.isQualifier:\n raise NotImplementedError\n if not claim.snak:\n # We need to already have the snak value\n raise NoPageError(claim)\n params = {'action': 'wbsetclaimvalue', 'claim': claim.snak,\n 'snaktype': snaktype, 'summary': summary, 'bot': bot,\n 'token': self.tokens['edit']}\n\n if snaktype == 'value':\n params['value'] = json.dumps(claim._formatValue())\n\n params['baserevid'] = claim.on_item.latest_revision_id\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('edit')\n def save_claim(self, claim, summary=None, bot: bool = True):\n \"\"\"\n Save the whole claim to the wikibase site.\n\n :param claim: The claim to save\n :type claim: pywikibot.Claim\n :param bot: Whether to mark the edit as a bot edit\n :param summary: Edit summary\n :type summary: str\n \"\"\"\n if claim.isReference or claim.isQualifier:\n raise NotImplementedError\n if not claim.snak:\n # We need to already have the snak value\n raise NoPageError(claim)\n params = {'action': 'wbsetclaim',\n 'claim': json.dumps(claim.toJSON()),\n 'token': self.tokens['edit'],\n 'baserevid': claim.on_item.latest_revision_id,\n 'summary': summary,\n 'bot': bot,\n }\n\n req = self.simple_request(**params)\n data = req.submit()\n claim.on_item.latest_revision_id = data['pageinfo']['lastrevid']\n return data\n\n @need_right('edit')\n @remove_last_args(['baserevid']) # since 7.0.0\n def editSource(self, claim, source,\n new: bool = False,\n bot: bool = True,\n summary: Optional[str] = None):\n \"\"\"Create/Edit a source.\n\n .. versionchanged:: 7.0\n deprecated `baserevid` parameter was removed\n\n :param claim: A Claim object to add the source to\n :type claim: pywikibot.Claim\n :param source: A Claim object to be used as a source\n :type source: pywikibot.Claim\n :param new: Whether to create a new one if the \"source\" already exists\n :param bot: Whether to mark the edit as a bot edit\n :param summary: Edit summary\n \"\"\"\n if claim.isReference or claim.isQualifier:\n raise ValueError('The claim cannot have a source.')\n params = {'action': 'wbsetreference', 'statement': claim.snak,\n 'baserevid': claim.on_item.latest_revision_id,\n 'summary': summary, 'bot': bot, 'token': self.tokens['edit']}\n\n # build up the snak\n if isinstance(source, list):\n sources = source\n else:\n sources = [source]\n\n snak = {}\n for sourceclaim in sources:\n datavalue = sourceclaim._formatDataValue()\n valuesnaks = snak.get(sourceclaim.getID(), [])\n valuesnaks.append({\n 'snaktype': 'value',\n 'property': sourceclaim.getID(),\n 'datavalue': datavalue,\n })\n\n snak[sourceclaim.getID()] = valuesnaks\n # set the hash if the source should be changed.\n # if present, all claims of one source have the same hash\n if not new and hasattr(sourceclaim, 'hash'):\n params['reference'] = sourceclaim.hash\n params['snaks'] = json.dumps(snak)\n\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('edit')\n @remove_last_args(['baserevid']) # since 7.0.0\n def editQualifier(self, claim, qualifier,\n new: bool = False,\n bot: bool = True,\n summary: Optional[str] = None):\n \"\"\"Create/Edit a qualifier.\n\n .. versionchanged:: 7.0\n deprecated `baserevid` parameter was removed\n\n :param claim: A Claim object to add the qualifier to\n :type claim: pywikibot.Claim\n :param qualifier: A Claim object to be used as a qualifier\n :type qualifier: pywikibot.Claim\n :param new: Whether to create a new one if the \"qualifier\"\n already exists\n :param bot: Whether to mark the edit as a bot edit\n :param summary: Edit summary\n \"\"\"\n if claim.isReference or claim.isQualifier:\n raise ValueError('The claim cannot have a qualifier.')\n params = {'action': 'wbsetqualifier', 'claim': claim.snak,\n 'baserevid': claim.on_item.latest_revision_id,\n 'summary': summary, 'bot': bot}\n\n if (not new and hasattr(qualifier, 'hash')\n and qualifier.hash is not None):\n params['snakhash'] = qualifier.hash\n params['token'] = self.tokens['edit']\n # build up the snak\n if qualifier.getSnakType() == 'value':\n params['value'] = json.dumps(qualifier._formatValue())\n params['snaktype'] = qualifier.getSnakType()\n params['property'] = qualifier.getID()\n\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('edit')\n @remove_last_args(['baserevid']) # since 7.0.0\n def removeClaims(self, claims,\n bot: bool = True,\n summary: Optional[str] = None):\n \"\"\"Remove claims.\n\n .. versionchanged:: 7.0\n deprecated `baserevid` parameter was removed\n\n :param claims: Claims to be removed\n :type claims: List[pywikibot.Claim]\n :param bot: Whether to mark the edit as a bot edit\n :type bot: bool\n :param summary: Edit summary\n :type summary: str\n \"\"\"\n # Check on_item for all additional claims\n items = {claim.on_item for claim in claims if claim.on_item}\n assert len(items) == 1\n baserevid = items.pop().latest_revision_id\n\n params = {\n 'action': 'wbremoveclaims', 'baserevid': baserevid,\n 'summary': summary,\n 'bot': bot,\n 'claim': '|'.join(claim.snak for claim in claims),\n 'token': self.tokens['edit'],\n }\n\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('edit')\n @remove_last_args(['baserevid']) # since 7.0.0\n def removeSources(self, claim, sources,\n bot: bool = True,\n summary: Optional[str] = None):\n \"\"\"Remove sources.\n\n .. versionchanged:: 7.0\n deprecated `baserevid` parameter was removed\n\n :param claim: A Claim object to remove the sources from\n :type claim: pywikibot.Claim\n :param sources: A list of Claim objects that are sources\n :type sources: list\n :param bot: Whether to mark the edit as a bot edit\n :param summary: Edit summary\n \"\"\"\n params = {\n 'action': 'wbremovereferences',\n 'baserevid': claim.on_item.latest_revision_id,\n 'summary': summary, 'bot': bot,\n 'statement': claim.snak,\n 'references': '|'.join(source.hash for source in sources),\n 'token': self.tokens['edit'],\n }\n\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('edit')\n @remove_last_args(['baserevid']) # since 7.0.0\n def remove_qualifiers(self, claim, qualifiers,\n bot: bool = True,\n summary: Optional[str] = None):\n \"\"\"Remove qualifiers.\n\n .. versionchanged:: 7.0\n deprecated `baserevid` parameter was removed\n\n :param claim: A Claim object to remove the qualifier from\n :type claim: pywikibot.Claim\n :param qualifiers: Claim objects currently used as a qualifiers\n :type qualifiers: List[pywikibot.Claim]\n :param bot: Whether to mark the edit as a bot edit\n :param summary: Edit summary\n \"\"\"\n params = {\n 'action': 'wbremovequalifiers',\n 'claim': claim.snak,\n 'baserevid': claim.on_item.latest_revision_id,\n 'summary': summary,\n 'bot': bot,\n 'qualifiers': [qualifier.hash for qualifier in qualifiers],\n 'token': self.tokens['edit']\n }\n\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('edit')\n def linkTitles(self, page1, page2, bot: bool = True):\n \"\"\"\n Link two pages together.\n\n :param page1: First page to link\n :type page1: pywikibot.Page\n :param page2: Second page to link\n :type page2: pywikibot.Page\n :param bot: Whether to mark the edit as a bot edit\n :return: dict API output\n :rtype: dict\n \"\"\"\n params = {\n 'action': 'wblinktitles',\n 'tosite': page1.site.dbName(),\n 'totitle': page1.title(),\n 'fromsite': page2.site.dbName(),\n 'fromtitle': page2.title(),\n 'token': self.tokens['edit']\n }\n if bot:\n params['bot'] = 1\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('item-merge')\n def mergeItems(self, from_item, to_item, ignore_conflicts=None,\n summary=None, bot: bool = True):\n \"\"\"\n Merge two items together.\n\n :param from_item: Item to merge from\n :type from_item: pywikibot.ItemPage\n :param to_item: Item to merge into\n :type to_item: pywikibot.ItemPage\n :param ignore_conflicts: Which type of conflicts\n ('description', 'sitelink', and 'statement')\n should be ignored\n :type ignore_conflicts: list of str\n :param summary: Edit summary\n :type summary: str\n :param bot: Whether to mark the edit as a bot edit\n :return: dict API output\n :rtype: dict\n \"\"\"\n params = {\n 'action': 'wbmergeitems',\n 'fromid': from_item.getID(),\n 'toid': to_item.getID(),\n 'ignoreconflicts': ignore_conflicts,\n 'token': self.tokens['edit'],\n 'summary': summary,\n }\n if bot:\n params['bot'] = 1\n req = self.simple_request(**params)\n return req.submit()\n\n @need_right('item-merge')\n @need_extension('WikibaseLexeme')\n def mergeLexemes(self, from_lexeme, to_lexeme, summary=None, *,\n bot: bool = True) -> dict:\n \"\"\"\n Merge two lexemes together.\n\n :param from_lexeme: Lexeme to merge from\n :type from_lexeme: pywikibot.LexemePage\n :param to_lexeme: Lexeme to merge into\n :type to_lexeme: pywikibot.LexemePage\n :param summary: Edit summary\n :type summary: str\n :keyword bot: Whether to mark the edit as a bot edit\n :return: dict API output\n \"\"\"\n params = {\n 'action': 'wblmergelexemes',\n 'source': from_lexeme.getID(),\n 'target': to_lexeme.getID(),\n 'token': self.tokens['edit'],\n 'summary': summary,\n }\n if bot:\n params['bot'] = 1\n req = self.simple_request(**params)\n data = req.submit()\n return data\n\n @need_right('item-redirect')\n def set_redirect_target(self, from_item, to_item, bot: bool = True):\n \"\"\"\n Make a redirect to another item.\n\n :param to_item: title of target item.\n :type to_item: pywikibot.ItemPage\n :param from_item: Title of the item to be redirected.\n :type from_item: pywikibot.ItemPage\n :param bot: Whether to mark the edit as a bot edit\n \"\"\"\n params = {\n 'action': 'wbcreateredirect',\n 'from': from_item.getID(),\n 'to': to_item.getID(),\n 'token': self.tokens['edit'],\n 'bot': bot,\n }\n req = self.simple_request(**params)\n return req.submit()\n\n def search_entities(self, search: str, language: str,\n total: Optional[int] = None, **kwargs):\n \"\"\"\n Search for pages or properties that contain the given text.\n\n :param search: Text to find.\n :param language: Language to search in.\n :param total: Maximum number of pages to retrieve in total, or\n None in case of no limit.\n :return: 'search' list from API output.\n :rtype: Generator\n \"\"\"\n lang_codes = self._paraminfo.parameter('wbsearchentities',\n 'language')['type']\n if language not in lang_codes:\n raise ValueError('Data site used does not support provided '\n 'language.')\n\n if 'site' in kwargs:\n if kwargs['site'].sitename != self.sitename:\n raise ValueError('The site given in the kwargs is different.')\n\n warn('search_entities should not get a site via kwargs.',\n UserWarning, 2)\n del kwargs['site']\n\n parameters = dict(search=search, language=language, **kwargs)\n gen = self._generator(api.APIGenerator,\n type_arg='wbsearchentities',\n data_name='search',\n total=total, parameters=parameters)\n return gen\n\n @need_right('edit')\n def _wbset_action(self, itemdef, action: str, action_data,\n **kwargs) -> dict:\n \"\"\"\n Execute wbset{action} on a Wikibase entity.\n\n Supported actions are:\n wbsetaliases, wbsetdescription, wbsetlabel and wbsetsitelink\n\n :param itemdef: Entity to modify or create\n :type itemdef: str, WikibaseEntity or Page connected to such item\n :param action: wbset{action} to perform:\n 'wbsetaliases', 'wbsetdescription', 'wbsetlabel', 'wbsetsitelink'\n :param action_data: data to be used in API request, see API help\n :type action_data: SiteLink or dict\n wbsetaliases:\n dict shall have the following structure:\n {'language': value (str),\n 'add': list of language codes (str),\n 'remove': list of language codes (str),\n 'set' list of language codes (str)\n }\n 'add' and 'remove' are alternative to 'set'\n wbsetdescription and wbsetlabel:\n dict shall have keys 'language', 'value'\n wbsetsitelink:\n dict shall have keys 'linksite', 'linktitle' and\n optionally 'badges'\n :keyword bot: Whether to mark the edit as a bot edit, default is True\n :type bot: bool\n :keyword tags: Change tags to apply with the edit\n :type tags: list of str\n :return: query result\n :raises AssertionError, TypeError\n \"\"\"\n def format_sitelink(sitelink):\n \"\"\"Convert SiteLink to a dict accepted by wbsetsitelink API.\"\"\"\n if isinstance(sitelink, pywikibot.page.SiteLink):\n _dict = {\n 'linksite': sitelink._sitekey,\n 'linktitle': sitelink._rawtitle,\n 'badges': '|'.join([b.title() for b in sitelink.badges]),\n }\n else:\n _dict = sitelink\n\n return _dict\n\n def prepare_data(action, data):\n \"\"\"Prepare data as expected by API.\"\"\"\n if action == 'wbsetaliases':\n res = data\n keys = set(res)\n assert keys < {'language', 'add', 'remove', 'set'}\n assert 'language' in keys\n assert ({'add', 'remove', 'set'} & keys)\n assert ({'add', 'set'} >= keys)\n assert ({'remove', 'set'} >= keys)\n elif action in ('wbsetlabel', 'wbsetdescription'):\n res = data\n keys = set(res)\n assert keys == {'language', 'value'}\n elif action == 'wbsetsitelink':\n res = format_sitelink(data)\n keys = set(res)\n assert keys >= {'linksite'}\n assert keys <= {'linksite', 'linktitle', 'badges'}\n else:\n raise ValueError('Something has gone wrong ...')\n\n return res\n\n # Supported actions\n assert action in ('wbsetaliases', 'wbsetdescription',\n 'wbsetlabel', 'wbsetsitelink'), \\\n 'action {} not supported.'.format(action)\n\n # prefer ID over (site, title)\n if isinstance(itemdef, str):\n itemdef = self.get_entity_for_entity_id(itemdef)\n elif isinstance(itemdef, pywikibot.Page):\n itemdef = pywikibot.ItemPage.fromPage(itemdef, lazy_load=True)\n elif not isinstance(itemdef, pywikibot.page.WikibaseEntity):\n raise TypeError('itemdef shall be str, WikibaseEntity or Page')\n\n params = itemdef._defined_by(singular=True)\n # TODO: support 'new'\n baserevid = kwargs.pop(\n 'baserevid',\n itemdef.latest_revision_id if 'id' in params else 0\n )\n params.update(\n {'baserevid': baserevid,\n 'action': action,\n 'token': self.tokens['edit'],\n 'bot': kwargs.pop('bot', True),\n })\n params.update(prepare_data(action, action_data))\n\n for arg in kwargs:\n if arg in ['summary', 'tags']:\n params[arg] = kwargs[arg]\n else:\n warn('Unknown parameter {} for action {}, ignored'\n .format(arg, action), UserWarning, 2)\n\n req = self.simple_request(**params)\n data = req.submit()\n return data\n\n def wbsetaliases(self, itemdef, aliases, **kwargs):\n \"\"\"\n Set aliases for a single Wikibase entity.\n\n See self._wbset_action() for parameters\n \"\"\"\n return self._wbset_action(itemdef, 'wbsetaliases', aliases, **kwargs)\n\n def wbsetdescription(self, itemdef, description, **kwargs):\n \"\"\"\n Set description for a single Wikibase entity.\n\n See self._wbset_action()\n \"\"\"\n return self._wbset_action(itemdef, 'wbsetdescription', description,\n **kwargs)\n\n def wbsetlabel(self, itemdef, label, **kwargs):\n \"\"\"\n Set label for a single Wikibase entity.\n\n See self._wbset_action() for parameters\n \"\"\"\n return self._wbset_action(itemdef, 'wbsetlabel', label, **kwargs)\n\n def wbsetsitelink(self, itemdef, sitelink, **kwargs):\n \"\"\"\n Set, remove or modify a sitelink on a Wikibase item.\n\n See self._wbset_action() for parameters\n \"\"\"\n return self._wbset_action(itemdef, 'wbsetsitelink', sitelink, **kwargs)\n\n @need_right('edit')\n @need_extension('WikibaseLexeme')\n def add_form(self, lexeme, form, *, bot: bool = True,\n baserevid=None) -> dict:\n \"\"\"\n Add a form.\n\n :param lexeme: Lexeme to modify\n :type lexeme: pywikibot.LexemePage\n :param form: Form to be added\n :type form: pywikibot.LexemeForm\n :keyword bot: Whether to mark the edit as a bot edit\n :keyword baserevid: Base revision id override, used to detect\n conflicts.\n :type baserevid: long\n \"\"\"\n params = {\n 'action': 'wbladdform',\n 'lexemeId': lexeme.getID(),\n 'data': json.dumps(form.toJSON()),\n 'bot': bot,\n 'token': self.tokens['edit'],\n }\n if baserevid:\n params['baserevid'] = baserevid\n req = self.simple_request(**params)\n data = req.submit()\n return data\n\n @need_right('edit')\n @need_extension('WikibaseLexeme')\n def remove_form(self, form, *, bot: bool = True, baserevid=None) -> dict:\n \"\"\"\n Remove a form.\n\n :param form: Form to be removed\n :type form: pywikibot.LexemeForm\n :keyword bot: Whether to mark the edit as a bot edit\n :keyword baserevid: Base revision id override, used to detect\n conflicts.\n :type baserevid: long\n \"\"\"\n params = {\n 'action': 'wblremoveform',\n 'id': form.getID(),\n 'bot': bot,\n 'token': self.tokens['edit'],\n }\n if baserevid:\n params['baserevid'] = baserevid\n req = self.simple_request(**params)\n data = req.submit()\n return data\n\n @need_right('edit')\n @need_extension('WikibaseLexeme')\n def edit_form_elements(self, form, data, *, bot: bool = True,\n baserevid=None) -> dict:\n \"\"\"\n Edit lexeme form elements.\n\n :param form: Form\n :type form: pywikibot.LexemeForm\n :param data: data updates\n :type data: dict\n :keyword bot: Whether to mark the edit as a bot edit\n :keyword baserevid: Base revision id override, used to detect\n conflicts.\n :type baserevid: long\n :return: New form data\n \"\"\"\n params = {\n 'action': 'wbleditformelements',\n 'formId': form.getID(),\n 'data': json.dumps(data),\n 'bot': bot,\n 'token': self.tokens['edit'],\n }\n if baserevid:\n params['baserevid'] = baserevid\n req = self.simple_request(**params)\n data = req.submit()\n return data\n"},"apis":{"kind":"string","value":"[((3677, 3703), 'pywikibot.site._decorators.need_version', 'need_version', (['\"\"\"1.28-wmf.3\"\"\"'], {}), \"('1.28-wmf.3')\\n\", (3689, 3703), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((3966, 3993), 'pywikibot.site._decorators.need_version', 'need_version', (['\"\"\"1.28-wmf.23\"\"\"'], {}), \"('1.28-wmf.23')\\n\", (3978, 3993), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((8716, 8734), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (8726, 8734), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((10677, 10695), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (10687, 10695), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((11784, 11802), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (11794, 11802), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((12986, 13004), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (12996, 13004), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((14022, 14040), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (14032, 14040), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((14046, 14077), 'pywikibot.tools.remove_last_args', 'remove_last_args', ([\"['baserevid']\"], {}), \"(['baserevid'])\\n\", (14062, 14077), False, 'from pywikibot.tools import itergroup, merge_unique_dicts, remove_last_args\\n'), ((15992, 16010), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (16002, 16010), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((16016, 16047), 'pywikibot.tools.remove_last_args', 'remove_last_args', ([\"['baserevid']\"], {}), \"(['baserevid'])\\n\", (16032, 16047), False, 'from pywikibot.tools import itergroup, merge_unique_dicts, remove_last_args\\n'), ((17594, 17612), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (17604, 17612), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((17618, 17649), 'pywikibot.tools.remove_last_args', 'remove_last_args', ([\"['baserevid']\"], {}), \"(['baserevid'])\\n\", (17634, 17649), False, 'from pywikibot.tools import itergroup, merge_unique_dicts, remove_last_args\\n'), ((18690, 18708), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (18700, 18708), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((18714, 18745), 'pywikibot.tools.remove_last_args', 'remove_last_args', ([\"['baserevid']\"], {}), \"(['baserevid'])\\n\", (18730, 18745), False, 'from pywikibot.tools import itergroup, merge_unique_dicts, remove_last_args\\n'), ((19723, 19741), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (19733, 19741), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((19747, 19778), 'pywikibot.tools.remove_last_args', 'remove_last_args', ([\"['baserevid']\"], {}), \"(['baserevid'])\\n\", (19763, 19778), False, 'from pywikibot.tools import itergroup, merge_unique_dicts, remove_last_args\\n'), ((20811, 20829), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (20821, 20829), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((21612, 21636), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"item-merge\"\"\"'], {}), \"('item-merge')\\n\", (21622, 21636), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((22747, 22771), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"item-merge\"\"\"'], {}), \"('item-merge')\\n\", (22757, 22771), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((22777, 22809), 'pywikibot.site._decorators.need_extension', 'need_extension', (['\"\"\"WikibaseLexeme\"\"\"'], {}), \"('WikibaseLexeme')\\n\", (22791, 22809), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((23707, 23734), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"item-redirect\"\"\"'], {}), \"('item-redirect')\\n\", (23717, 23734), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((25802, 25820), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (25812, 25820), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((31299, 31317), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (31309, 31317), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((31323, 31355), 'pywikibot.site._decorators.need_extension', 'need_extension', (['\"\"\"WikibaseLexeme\"\"\"'], {}), \"('WikibaseLexeme')\\n\", (31337, 31355), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((32229, 32247), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (32239, 32247), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((32253, 32285), 'pywikibot.site._decorators.need_extension', 'need_extension', (['\"\"\"WikibaseLexeme\"\"\"'], {}), \"('WikibaseLexeme')\\n\", (32267, 32285), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((33007, 33025), 'pywikibot.site._decorators.need_right', 'need_right', (['\"\"\"edit\"\"\"'], {}), \"('edit')\\n\", (33017, 33025), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((33031, 33063), 'pywikibot.site._decorators.need_extension', 'need_extension', (['\"\"\"WikibaseLexeme\"\"\"'], {}), \"('WikibaseLexeme')\\n\", (33045, 33063), False, 'from pywikibot.site._decorators import need_extension, need_right, need_version\\n'), ((3566, 3612), 'pywikibot.page.WikibaseEntity', 'pywikibot.page.WikibaseEntity', (['self', 'entity_id'], {}), '(self, entity_id)\\n', (3595, 3612), False, 'import pywikibot\\n'), ((3627, 3656), 'pywikibot.exceptions.NoWikibaseEntityError', 'NoWikibaseEntityError', (['entity'], {}), '(entity)\\n', (3648, 3656), False, 'from pywikibot.exceptions import APIError, EntityTypeUnknownError, IsRedirectPageError, NoPageError, NoWikibaseEntityError\\n'), ((5326, 5421), 'pywikibot.tools.merge_unique_dicts', 'merge_unique_dicts', (['identification'], {'action': '\"\"\"wbgetentities\"\"\"', 'props': '(props if props else False)'}), \"(identification, action='wbgetentities', props=props if\\n props else False)\\n\", (5344, 5421), False, 'from pywikibot.tools import itergroup, merge_unique_dicts, remove_last_args\\n'), ((6447, 6477), 'pywikibot.tools.itergroup', 'itergroup', (['pagelist', 'groupsize'], {}), '(pagelist, groupsize)\\n', (6456, 6477), False, 'from pywikibot.tools import itergroup, merge_unique_dicts, remove_last_args\\n'), ((8217, 8251), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(365 * 100)'}), '(days=365 * 100)\\n', (8235, 8251), False, 'import datetime\\n'), ((10582, 10598), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\\n', (10592, 10598), False, 'import json\\n'), ((15896, 15912), 'json.dumps', 'json.dumps', (['snak'], {}), '(snak)\\n', (15906, 15912), False, 'import json\\n'), ((5801, 5829), 'pywikibot.exceptions.APIError', 'APIError', ([\"data['errors']\", '\"\"\"\"\"\"'], {}), \"(data['errors'], '')\\n\", (5809, 5829), False, 'from pywikibot.exceptions import APIError, EntityTypeUnknownError, IsRedirectPageError, NoPageError, NoWikibaseEntityError\\n'), ((12541, 12559), 'pywikibot.exceptions.NoPageError', 'NoPageError', (['claim'], {}), '(claim)\\n', (12552, 12559), False, 'from pywikibot.exceptions import APIError, EntityTypeUnknownError, IsRedirectPageError, NoPageError, NoWikibaseEntityError\\n'), ((13533, 13551), 'pywikibot.exceptions.NoPageError', 'NoPageError', (['claim'], {}), '(claim)\\n', (13544, 13551), False, 'from pywikibot.exceptions import APIError, EntityTypeUnknownError, IsRedirectPageError, NoPageError, NoWikibaseEntityError\\n'), ((25361, 25434), 'warnings.warn', 'warn', (['\"\"\"search_entities should not get a site via kwargs.\"\"\"', 'UserWarning', '(2)'], {}), \"('search_entities should not get a site via kwargs.', UserWarning, 2)\\n\", (25365, 25434), False, 'from warnings import warn\\n'), ((33703, 33719), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\\n', (33713, 33719), False, 'import json\\n'), ((11146, 11158), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\\n', (11156, 11158), False, 'import uuid\\n'), ((29203, 29255), 'pywikibot.ItemPage.fromPage', 'pywikibot.ItemPage.fromPage', (['itemdef'], {'lazy_load': '(True)'}), '(itemdef, lazy_load=True)\\n', (29230, 29255), False, 'import pywikibot\\n'), ((7745, 7774), 'contextlib.suppress', 'suppress', (['IsRedirectPageError'], {}), '(IsRedirectPageError)\\n', (7753, 7774), False, 'from contextlib import suppress\\n')]"}}},{"rowIdx":8457,"cells":{"repo_name":{"kind":"string","value":"MisaelVillaverde/fourier-calculator"},"repo_path":{"kind":"string","value":"app.py"},"repo_head_hexsha":{"kind":"string","value":"fd50cd292e333c1a9d75e93962a0aaa0985ecef9"},"content":{"kind":"string","value":"from flask import Flask\nfrom flask import render_template, request \nfrom flask import jsonify\nimport requests\nimport json\napp = Flask(__name__)\n\n\n@app.route(\"/symbo\",methods=['POST'])\ndef symbo():\n #import pdb; pdb.set_trace()\n session = requests.session()\n token = session.get(\"https://es.symbolab.com/solver/step-by-step/x%5E%7B2%7D?or=input\").cookies.get_dict()[\"sy2.pub.token\"]\n query = request.json[\"expression\"]\n #response = json.loads(session.get(f\"https://es.symbolab.com/pub_api/steps?subscribed=true&origin=input&language=es&query=%5Cint+tcos%5Cleft(nt%5Cright)dt+&referer=https%3A%2F%2Fes.symbolab.com%2Fsolver%2Fstep-by-step%2F%255Cint_%257B%2520%257Dtcos%255Cleft(nt%255Cright)dt%2520%3For%3Dinput&plotRequest=PlotOptional&page=step-by-step\",headers={\n response = json.loads(session.get(f\"https://es.symbolab.com/pub_api/steps?subscribed=true&origin=input&language=es&query={query}\",headers={\n \"x-requested-with\":\"XMLHttpRequest\",\n \"authorization\":f\"Bearer {token}\"\n }).content)\n return {\n \"dym\":response[\"dym\"],\n \"solutions\":response[\"solutions\"]\n }\n\n@app.route('/')\ndef hello():\n return render_template('index.html')\n\napp.run(debug=True)"},"apis":{"kind":"string","value":"[((128, 143), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\\n', (133, 143), False, 'from flask import Flask\\n'), ((244, 262), 'requests.session', 'requests.session', ([], {}), '()\\n', (260, 262), False, 'import requests\\n'), ((1160, 1189), 'flask.render_template', 'render_template', (['\"\"\"index.html\"\"\"'], {}), \"('index.html')\\n\", (1175, 1189), False, 'from flask import render_template, request\\n')]"}}},{"rowIdx":8458,"cells":{"repo_name":{"kind":"string","value":"kalona/Spark-The-Definitive-Guide"},"repo_path":{"kind":"string","value":"my_code/Chapter_2.py"},"repo_head_hexsha":{"kind":"string","value":"0b495c4710b2030aa59d5a7f4053ee0a8345d0d8"},"content":{"kind":"string","value":"from pyspark.sql import SparkSession\n\n# spark = SparkSession.builder.master(\"local[*]\").getOrCreate()\n\nspark = SparkSession.builder.getOrCreate()\n\nfile_path = \"C:\\home_work\\local_github\\Spark-The-Definitive-Guide\\data\\/flight-data\\csv\\/2015-summary.csv\"\n\n# COMMAND ----------\n\n\n# COMMAND ----------\n\nflightData2015 = spark\\\n .read\\\n .option(\"inferSchema\", \"true\")\\\n .option(\"header\", \"true\")\\\n .csv(\"./data/flight-data/csv/2015-summary.csv\")\n\n# COMMAND ----------\n\nflightData2015.createOrReplaceTempView(\"flight_data_2015\")\n\n\n# COMMAND ----------\n\nsqlWay = spark.sql(\"\"\"\nSELECT DEST_COUNTRY_NAME, count(1)\nFROM flight_data_2015\nGROUP BY DEST_COUNTRY_NAME\n\"\"\")\n\ndataFrameWay = flightData2015\\\n .groupBy(\"DEST_COUNTRY_NAME\")\\\n .count()\n\nsqlWay.explain()\ndataFrameWay.explain()\n\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import max, col\n#\nflightData2015.select(max(col(\"count\"))).show(1)\n\n\n# COMMAND ----------\n\nmaxSql = spark.sql(\"\"\"\nSELECT DEST_COUNTRY_NAME, sum(count) as destination_total\nFROM flight_data_2015\nGROUP BY DEST_COUNTRY_NAME\nORDER BY sum(count) DESC\nLIMIT 5\n\"\"\")\n\nmaxSql.show()\n\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import desc\n\nflightData2015\\\n .groupBy(\"DEST_COUNTRY_NAME\")\\\n .sum(\"count\")\\\n .withColumnRenamed(\"sum(count)\", \"destination_total\")\\\n .sort(desc(\"destination_total\"))\\\n .limit(5)\\\n .show()\n\n\n# COMMAND ----------\n\nflightData2015\\\n .groupBy(\"DEST_COUNTRY_NAME\")\\\n .sum(\"count\")\\\n .withColumnRenamed(\"sum(count)\", \"destination_total\")\\\n .sort(desc(\"destination_total\"))\\\n .limit(5)\\\n .explain()\n\n\n# COMMAND ----------\n"},"apis":{"kind":"string","value":"[((111, 145), 'pyspark.sql.SparkSession.builder.getOrCreate', 'SparkSession.builder.getOrCreate', ([], {}), '()\\n', (143, 145), False, 'from pyspark.sql import SparkSession\\n'), ((876, 888), 'pyspark.sql.functions.col', 'col', (['\"\"\"count\"\"\"'], {}), \"('count')\\n\", (879, 888), False, 'from pyspark.sql.functions import max, col\\n'), ((1301, 1326), 'pyspark.sql.functions.desc', 'desc', (['\"\"\"destination_total\"\"\"'], {}), \"('destination_total')\\n\", (1305, 1326), False, 'from pyspark.sql.functions import desc\\n'), ((1507, 1532), 'pyspark.sql.functions.desc', 'desc', (['\"\"\"destination_total\"\"\"'], {}), \"('destination_total')\\n\", (1511, 1532), False, 'from pyspark.sql.functions import desc\\n')]"}}},{"rowIdx":8459,"cells":{"repo_name":{"kind":"string","value":"ContinuumIO/intake-postgres"},"repo_path":{"kind":"string","value":"tests/test_intake_postgres.py"},"repo_head_hexsha":{"kind":"string","value":"fda7f7b2b6255544ea7ffd365a4ac8b2655fd226"},"content":{"kind":"string","value":"import os\nimport pickle\nimport pytest\nimport pandas as pd\nfrom shapely import wkt\n\nfrom intake_postgres import PostgresSource\nfrom intake import open_catalog\nfrom .util import verify_datasource_interface\n\n\nTEST_DATA_DIR = 'tests'\nTEST_DATA = [\n ('sample1', 'sample1.csv'),\n ('sample2_1', 'sample2_1.csv'),\n ('sample2_2', 'sample2_2.csv'),\n]\nTEST_GIS_DATA = [\n ('points', 'sample_points.psql'),\n ('multipoints', 'sample_multipoints.psql'),\n ('lines', 'sample_lines.psql'),\n ('multilines', 'sample_multilines.psql'),\n ('polygons', 'sample_polygons.psql'),\n ('multipolygons', 'sample_multipolygons.psql'),\n # ('triangles', 'sample_triangles.psql'),\n]\nTEST_TEMPLATE_DATA = [\n 'jinja2_params_with_env',\n]\n\n\n@pytest.fixture(scope='module')\ndef engine():\n \"\"\"Start docker container for PostgreSQL database, yield a tuple (engine,\n metadata), and cleanup connection afterward.\"\"\"\n from .util import start_postgres, stop_postgres\n from sqlalchemy import create_engine\n stop_postgres(let_fail=True)\n local_port = start_postgres()\n\n uri = 'postgresql://postgres@localhost:{}/postgres'.format(local_port)\n engine = create_engine(uri)\n for table_name, csv_fname in TEST_DATA:\n csv_fpath = os.path.join(TEST_DATA_DIR, csv_fname)\n df = pd.read_csv(csv_fpath)\n df.to_sql(table_name, engine, index=False)\n for table_name, psql_fname in TEST_GIS_DATA:\n psql_fpath = os.path.join(TEST_DATA_DIR, psql_fname)\n with engine.connect() as conn:\n with open(psql_fpath, 'r') as fp:\n cmds = fp.read().strip().split(';')\n for cmd in cmds:\n if cmd.strip():\n conn.execute(' '.join(cmd.split()))\n\n try:\n yield engine\n finally:\n stop_postgres()\n\n\n@pytest.mark.parametrize('table_name,_', TEST_DATA)\ndef test_open(engine, table_name, _):\n d = PostgresSource(str(engine.url), 'select * from '+table_name)\n assert d.container == 'dataframe'\n assert d.description is None\n verify_datasource_interface(d)\n\n\n@pytest.mark.parametrize('table_name,csv_fpath', TEST_DATA)\ndef test_discover(engine, table_name, csv_fpath):\n expected_df = pd.read_csv(os.path.join(TEST_DATA_DIR, csv_fpath))\n source = PostgresSource(str(engine.url), 'select * from '+table_name)\n info = source.discover()\n dt = {k: str(v) for k, v in expected_df.dtypes.to_dict().items()}\n assert info['dtype'] == dt\n assert info['shape'] == (None, 3)\n assert info['npartitions'] == 1\n\n\n@pytest.mark.parametrize('table_name,csv_fpath', TEST_DATA)\ndef test_read(engine, table_name, csv_fpath):\n expected_df = pd.read_csv(os.path.join(TEST_DATA_DIR, csv_fpath))\n source = PostgresSource(str(engine.url), 'select * from '+table_name)\n df = source.read()\n assert expected_df.equals(df)\n\n\n@pytest.mark.parametrize('table_name,csv_fpath', TEST_DATA)\ndef test_discover_after_read(engine, table_name, csv_fpath):\n \"\"\"Assert that after reading the dataframe, discover() shows more accurate\n information.\n \"\"\"\n expected_df = pd.read_csv(os.path.join(TEST_DATA_DIR, csv_fpath))\n source = PostgresSource(str(engine.url), 'select * from '+table_name)\n info = source.discover()\n dt = {k: str(v) for k, v in expected_df.dtypes.to_dict().items()}\n assert info['dtype'] == dt\n assert info['shape'] == (None, 3)\n assert info['npartitions'] == 1\n\n df = source.read()\n assert expected_df.equals(df)\n\n info = source.discover()\n assert info['dtype'] == dt\n assert info['shape'] == (4, 3)\n assert info['npartitions'] == 1\n\n assert expected_df.equals(df)\n\n\n@pytest.mark.parametrize('table_name,csv_fpath', TEST_DATA)\ndef test_close(engine, table_name, csv_fpath):\n expected_df = pd.read_csv(os.path.join(TEST_DATA_DIR, csv_fpath))\n source = PostgresSource(str(engine.url), 'select * from '+table_name)\n\n source.close()\n # Can reopen after close\n df = source.read()\n\n assert expected_df.equals(df)\n\n\n@pytest.mark.parametrize('table_name,csv_fpath', TEST_DATA)\ndef test_pickle(engine, table_name, csv_fpath):\n source = PostgresSource(str(engine.url), 'select * from '+table_name)\n\n pickled_source = pickle.dumps(source)\n source_clone = pickle.loads(pickled_source)\n\n expected_df = source.read()\n df = source_clone.read()\n\n assert expected_df.equals(df)\n\n\n@pytest.mark.parametrize('table_name,_1', TEST_DATA)\ndef test_catalog(engine, table_name, _1):\n catalog_fpath = os.path.join(TEST_DATA_DIR, 'catalog1.yml')\n\n catalog = open_catalog(catalog_fpath)\n ds_name = table_name.rsplit('_idx', 1)[0]\n src = catalog[ds_name]\n pgsrc = src.get()\n pgsrc._uri = str(engine.url)\n\n assert src.describe()['container'] == 'dataframe'\n assert src.describe_open()['plugin'] == 'postgres'\n assert src.describe_open()['args']['sql_expr'][:6] in ('select', 'SELECT')\n\n metadata = pgsrc.discover()\n assert metadata['npartitions'] == 1\n\n expected_df = pd.read_sql_query(pgsrc._sql_expr, engine)\n df = pgsrc.read()\n assert expected_df.equals(df)\n\n pgsrc.close()\n\n\ndef test_catalog_join(engine):\n catalog_fpath = os.path.join(TEST_DATA_DIR, 'catalog1.yml')\n\n catalog = open_catalog(catalog_fpath)\n ds_name = 'sample2'\n src = catalog[ds_name]\n pgsrc = src.get()\n pgsrc._uri = str(engine.url)\n\n assert src.describe()['container'] == 'dataframe'\n assert src.describe_open()['plugin'] == 'postgres'\n assert src.describe_open()['args']['sql_expr'][:6] in ('select', 'SELECT')\n\n metadata = pgsrc.discover()\n assert metadata['npartitions'] == 1\n\n expected_df = pd.read_sql_query(pgsrc._sql_expr, engine)\n df = pgsrc.read()\n assert expected_df.equals(df)\n\n pgsrc.close()\n\n\n@pytest.mark.parametrize('table_name,_1', TEST_GIS_DATA)\ndef test_postgis_data(engine, table_name, _1):\n from sqlalchemy import MetaData\n catalog_fpath = os.path.join(TEST_DATA_DIR, 'catalog1.yml')\n\n catalog = open_catalog(catalog_fpath)\n ds_name = table_name\n src = catalog[ds_name]\n pgsrc = src.get()\n pgsrc._uri = str(engine.url)\n\n assert src.describe()['container'] == 'dataframe'\n assert src.describe_open()['plugin'] == 'postgres'\n assert src.describe_open()['args']['sql_expr'][:6] in ('select', 'SELECT')\n\n metadata = pgsrc.discover()\n assert metadata['npartitions'] == 1\n\n meta = MetaData()\n meta.reflect(bind=engine)\n col_exprs = ['ST_AsText({0}) as {0}'.format(col.name)\n for col in meta.tables[table_name].columns]\n _query = pgsrc._sql_expr.replace('*', ', '.join(col_exprs))\n expected_df = pd.read_sql_query(_query, engine).applymap(\n lambda geom: str(wkt.loads(geom))\n )\n df = pgsrc.read().applymap(lambda geom: str(wkt.loads(geom)))\n assert expected_df.equals(df)\n\n pgsrc.close()\n\n\n@pytest.mark.parametrize('ds_name', TEST_TEMPLATE_DATA)\ndef test_jinja2(engine, ds_name):\n catalog_fpath = os.path.join(TEST_DATA_DIR, 'catalog1.yml')\n\n catalog = open_catalog(catalog_fpath)\n src = catalog[ds_name]\n pgsrc = src.get()\n pgsrc._uri = str(engine.url)\n\n assert src.describe()['container'] == 'dataframe'\n assert src.describe_open()['plugin'] == 'postgres'\n assert src.describe_open()['args']['sql_expr'][:6] in ('select', 'SELECT')\n\n metadata = pgsrc.discover()\n assert metadata['npartitions'] == 1\n\n expected_df = pd.read_sql_query(pgsrc._sql_expr, engine)\n df = pgsrc.read()\n assert expected_df.equals(df)\n\n pgsrc.close()\n"},"apis":{"kind":"string","value":"[((736, 766), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '\"\"\"module\"\"\"'}), \"(scope='module')\\n\", (750, 766), False, 'import pytest\\n'), ((1804, 1854), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"table_name,_\"\"\"', 'TEST_DATA'], {}), \"('table_name,_', TEST_DATA)\\n\", (1827, 1854), False, 'import pytest\\n'), ((2071, 2129), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"table_name,csv_fpath\"\"\"', 'TEST_DATA'], {}), \"('table_name,csv_fpath', TEST_DATA)\\n\", (2094, 2129), False, 'import pytest\\n'), ((2531, 2589), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"table_name,csv_fpath\"\"\"', 'TEST_DATA'], {}), \"('table_name,csv_fpath', TEST_DATA)\\n\", (2554, 2589), False, 'import pytest\\n'), ((2840, 2898), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"table_name,csv_fpath\"\"\"', 'TEST_DATA'], {}), \"('table_name,csv_fpath', TEST_DATA)\\n\", (2863, 2898), False, 'import pytest\\n'), ((3640, 3698), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"table_name,csv_fpath\"\"\"', 'TEST_DATA'], {}), \"('table_name,csv_fpath', TEST_DATA)\\n\", (3663, 3698), False, 'import pytest\\n'), ((4000, 4058), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"table_name,csv_fpath\"\"\"', 'TEST_DATA'], {}), \"('table_name,csv_fpath', TEST_DATA)\\n\", (4023, 4058), False, 'import pytest\\n'), ((4372, 4423), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"table_name,_1\"\"\"', 'TEST_DATA'], {}), \"('table_name,_1', TEST_DATA)\\n\", (4395, 4423), False, 'import pytest\\n'), ((5748, 5803), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"table_name,_1\"\"\"', 'TEST_GIS_DATA'], {}), \"('table_name,_1', TEST_GIS_DATA)\\n\", (5771, 5803), False, 'import pytest\\n'), ((6831, 6885), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['\"\"\"ds_name\"\"\"', 'TEST_TEMPLATE_DATA'], {}), \"('ds_name', TEST_TEMPLATE_DATA)\\n\", (6854, 6885), False, 'import pytest\\n'), ((1160, 1178), 'sqlalchemy.create_engine', 'create_engine', (['uri'], {}), '(uri)\\n', (1173, 1178), False, 'from sqlalchemy import create_engine\\n'), ((4203, 4223), 'pickle.dumps', 'pickle.dumps', (['source'], {}), '(source)\\n', (4215, 4223), False, 'import pickle\\n'), ((4243, 4271), 'pickle.loads', 'pickle.loads', (['pickled_source'], {}), '(pickled_source)\\n', (4255, 4271), False, 'import pickle\\n'), ((4486, 4529), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', '\"\"\"catalog1.yml\"\"\"'], {}), \"(TEST_DATA_DIR, 'catalog1.yml')\\n\", (4498, 4529), False, 'import os\\n'), ((4545, 4572), 'intake.open_catalog', 'open_catalog', (['catalog_fpath'], {}), '(catalog_fpath)\\n', (4557, 4572), False, 'from intake import open_catalog\\n'), ((4982, 5024), 'pandas.read_sql_query', 'pd.read_sql_query', (['pgsrc._sql_expr', 'engine'], {}), '(pgsrc._sql_expr, engine)\\n', (4999, 5024), True, 'import pandas as pd\\n'), ((5153, 5196), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', '\"\"\"catalog1.yml\"\"\"'], {}), \"(TEST_DATA_DIR, 'catalog1.yml')\\n\", (5165, 5196), False, 'import os\\n'), ((5212, 5239), 'intake.open_catalog', 'open_catalog', (['catalog_fpath'], {}), '(catalog_fpath)\\n', (5224, 5239), False, 'from intake import open_catalog\\n'), ((5627, 5669), 'pandas.read_sql_query', 'pd.read_sql_query', (['pgsrc._sql_expr', 'engine'], {}), '(pgsrc._sql_expr, engine)\\n', (5644, 5669), True, 'import pandas as pd\\n'), ((5907, 5950), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', '\"\"\"catalog1.yml\"\"\"'], {}), \"(TEST_DATA_DIR, 'catalog1.yml')\\n\", (5919, 5950), False, 'import os\\n'), ((5966, 5993), 'intake.open_catalog', 'open_catalog', (['catalog_fpath'], {}), '(catalog_fpath)\\n', (5978, 5993), False, 'from intake import open_catalog\\n'), ((6375, 6385), 'sqlalchemy.MetaData', 'MetaData', ([], {}), '()\\n', (6383, 6385), False, 'from sqlalchemy import MetaData\\n'), ((6940, 6983), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', '\"\"\"catalog1.yml\"\"\"'], {}), \"(TEST_DATA_DIR, 'catalog1.yml')\\n\", (6952, 6983), False, 'import os\\n'), ((6999, 7026), 'intake.open_catalog', 'open_catalog', (['catalog_fpath'], {}), '(catalog_fpath)\\n', (7011, 7026), False, 'from intake import open_catalog\\n'), ((7390, 7432), 'pandas.read_sql_query', 'pd.read_sql_query', (['pgsrc._sql_expr', 'engine'], {}), '(pgsrc._sql_expr, engine)\\n', (7407, 7432), True, 'import pandas as pd\\n'), ((1243, 1281), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', 'csv_fname'], {}), '(TEST_DATA_DIR, csv_fname)\\n', (1255, 1281), False, 'import os\\n'), ((1295, 1317), 'pandas.read_csv', 'pd.read_csv', (['csv_fpath'], {}), '(csv_fpath)\\n', (1306, 1317), True, 'import pandas as pd\\n'), ((1439, 1478), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', 'psql_fname'], {}), '(TEST_DATA_DIR, psql_fname)\\n', (1451, 1478), False, 'import os\\n'), ((2210, 2248), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', 'csv_fpath'], {}), '(TEST_DATA_DIR, csv_fpath)\\n', (2222, 2248), False, 'import os\\n'), ((2666, 2704), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', 'csv_fpath'], {}), '(TEST_DATA_DIR, csv_fpath)\\n', (2678, 2704), False, 'import os\\n'), ((3094, 3132), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', 'csv_fpath'], {}), '(TEST_DATA_DIR, csv_fpath)\\n', (3106, 3132), False, 'import os\\n'), ((3776, 3814), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', 'csv_fpath'], {}), '(TEST_DATA_DIR, csv_fpath)\\n', (3788, 3814), False, 'import os\\n'), ((6617, 6650), 'pandas.read_sql_query', 'pd.read_sql_query', (['_query', 'engine'], {}), '(_query, engine)\\n', (6634, 6650), True, 'import pandas as pd\\n'), ((6686, 6701), 'shapely.wkt.loads', 'wkt.loads', (['geom'], {}), '(geom)\\n', (6695, 6701), False, 'from shapely import wkt\\n'), ((6757, 6772), 'shapely.wkt.loads', 'wkt.loads', (['geom'], {}), '(geom)\\n', (6766, 6772), False, 'from shapely import wkt\\n')]"}}},{"rowIdx":8460,"cells":{"repo_name":{"kind":"string","value":"dks1018/CoffeeShopCoding"},"repo_path":{"kind":"string","value":"Module_3/testImage.py"},"repo_head_hexsha":{"kind":"string","value":"13ac1700673c86c601eb2758570920620a956e4c"},"content":{"kind":"string","value":"# file = open('C:\\\\Users\\\\dks10\\\\OneDrive\\\\Desktop\\\\Projects\\\\Code\\\\Python\\\\PythonCrypto\\\\Module_3\\\\eye.png', 'rb')\nfile = open('encrypt_eye.png', 'rb')\nimage = file.read()\nfile.close()\n\nimage = bytearray(image)\n\nkey = 48\n\nfor index, value in enumerate(image):\n image[index] = value^key\n\nfile = open('2eye.png','wb')\nfile.write(image)\n\nfile.close()"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8461,"cells":{"repo_name":{"kind":"string","value":"Aircoookie/LedFx"},"repo_path":{"kind":"string","value":"ledfxcontroller/effects/temporal.py"},"repo_head_hexsha":{"kind":"string","value":"95628fc237497dd89aaf30fdbf88f780f3330166"},"content":{"kind":"string","value":"import time\nimport logging\nfrom ledfxcontroller.effects import Effect\nfrom threading import Thread\nimport voluptuous as vol\n\n_LOGGER = logging.getLogger(__name__)\nDEFAULT_RATE = 1.0 / 60.0\n\n@Effect.no_registration\nclass TemporalEffect(Effect):\n _thread_active = False\n _thread = None\n\n CONFIG_SCHEMA = vol.Schema({\n vol.Required('speed', default = 1.0): float\n })\n\n def thread_function(self):\n\n while self._thread_active:\n startTime = time.time()\n\n # Treat the return value of the effect loop as a speed modifier\n # such that effects that are nartually faster or slower can have\n # a consistent feel.\n sleepInterval = self.effect_loop()\n if sleepInterval is None:\n sleepInterval = 1.0\n sleepInterval = sleepInterval * DEFAULT_RATE\n\n # Calculate the time to sleep accounting for potential heavy\n # frame assembly operations\n timeToSleep = (sleepInterval / self._config['speed']) - (time.time() - startTime)\n if timeToSleep > 0:\n time.sleep(timeToSleep)\n\n def effect_loop(self):\n \"\"\"\n Triggered periodically based on the effect speed and \n any additional effect modifiers\n \"\"\"\n pass\n\n def activate(self, pixel_count):\n super().activate(pixel_count)\n\n self._thread_active = True\n self._thread = Thread(target = self.thread_function)\n self._thread.start()\n\n def deactivate(self):\n if self._thread_active:\n self._thread_active = False\n self._thread.join()\n self._thread = None\n \n super().deactivate()\n"},"apis":{"kind":"string","value":"[((135, 162), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\\n', (152, 162), False, 'import logging\\n'), ((1434, 1469), 'threading.Thread', 'Thread', ([], {'target': 'self.thread_function'}), '(target=self.thread_function)\\n', (1440, 1469), False, 'from threading import Thread\\n'), ((332, 366), 'voluptuous.Required', 'vol.Required', (['\"\"\"speed\"\"\"'], {'default': '(1.0)'}), \"('speed', default=1.0)\\n\", (344, 366), True, 'import voluptuous as vol\\n'), ((475, 486), 'time.time', 'time.time', ([], {}), '()\\n', (484, 486), False, 'import time\\n'), ((1108, 1131), 'time.sleep', 'time.sleep', (['timeToSleep'], {}), '(timeToSleep)\\n', (1118, 1131), False, 'import time\\n'), ((1035, 1046), 'time.time', 'time.time', ([], {}), '()\\n', (1044, 1046), False, 'import time\\n')]"}}},{"rowIdx":8462,"cells":{"repo_name":{"kind":"string","value":"Surferlul/csc-python-solutions"},"repo_path":{"kind":"string","value":"07/c/3 - Square Census.py"},"repo_head_hexsha":{"kind":"string","value":"bea99e5e1e344d17fb2cb29d8bcbc6b108e24cee"},"content":{"kind":"string","value":"n=int(input())\nc = 1\nwhile c**2 < n:\n print(c**2)\n c += 1\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8463,"cells":{"repo_name":{"kind":"string","value":"LuChang-CS/sherbet"},"repo_path":{"kind":"string","value":"utils.py"},"repo_head_hexsha":{"kind":"string","value":"d1061aca108eab8e0ccbd2202460e25261fdf1d5"},"content":{"kind":"string","value":"import numpy as np\n\n\nclass DataGenerator:\n def __init__(self, inputs, shuffle=True, batch_size=32):\n assert len(inputs) > 0\n self.inputs = inputs\n self.idx = np.arange(len(inputs[0]))\n self.shuffle = shuffle\n self.batch_size = batch_size\n self.on_epoch_end()\n\n def data_length(self):\n return len(self.idx)\n\n def __len__(self):\n n = self.data_length()\n len_ = n // self.batch_size\n return len_ if n % self.batch_size == 0 else len_ + 1\n\n def __getitem__(self, index):\n start = index * self.batch_size\n end = start + self.batch_size\n index = self.idx[start:end]\n data = []\n for x in self.inputs:\n data.append(x[index])\n return data\n\n def on_epoch_end(self):\n if self.shuffle:\n np.random.shuffle(self.idx)\n\n def set_batch_size(self, batch_size):\n self.batch_size = batch_size\n\n\ndef lr_decay(total_epoch, init_lr, split_val):\n lr_map = [init_lr] * total_epoch\n if len(split_val) > 0:\n assert split_val[0][0] > 1\n assert split_val[-1][0] <= total_epoch\n current_split_index = 0\n current_lr = init_lr\n next_epoch, next_lr = split_val[current_split_index]\n for i in range(total_epoch):\n if i < next_epoch - 1:\n lr_map[i] = current_lr\n else:\n current_lr = next_lr\n lr_map[i] = current_lr\n current_split_index += 1\n if current_split_index >= len(split_val):\n next_epoch = total_epoch + 1\n else:\n next_epoch, next_lr = split_val[current_split_index]\n\n def lr_schedule_fn(epoch, lr):\n return lr_map[epoch]\n\n return lr_schedule_fn\n"},"apis":{"kind":"string","value":"[((831, 858), 'numpy.random.shuffle', 'np.random.shuffle', (['self.idx'], {}), '(self.idx)\\n', (848, 858), True, 'import numpy as np\\n')]"}}},{"rowIdx":8464,"cells":{"repo_name":{"kind":"string","value":"sudhanshu55/Speech_to_Image"},"repo_path":{"kind":"string","value":"Version1_STI.py"},"repo_head_hexsha":{"kind":"string","value":"7a047725b3167cfcb7a68004b3c35b2ece75fde4"},"content":{"kind":"string","value":"from nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords\nimport speech_recognition as sr\nimport nltk\nfrom google_images_download import google_images_download \nresponse = google_images_download.googleimagesdownload()\nr = sr.Recognizer()\nwith sr.Microphone() as source:\n print(\"Say something!\")\n audio = r.listen(source)\n \ndata = r.recognize_google(audio).encode(\"utf-8\")\nprint (data)\nstopWords = set(stopwords.words('english'))\nwords = word_tokenize(data)\nwordsFiltered = []\n\nfor w in words:\n if w not in stopWords:\n wordsFiltered.append(w)\n \ninto_string = str(wordsFiltered)\nprint(into_string)\narguments = {\"keywords\":into_string,\"limit\":2,\"print_urls\":True} #creating list of arguments\nresponse.download(arguments) #passing the arguments to the function"},"apis":{"kind":"string","value":"[((203, 248), 'google_images_download.google_images_download.googleimagesdownload', 'google_images_download.googleimagesdownload', ([], {}), '()\\n', (246, 248), False, 'from google_images_download import google_images_download\\n'), ((253, 268), 'speech_recognition.Recognizer', 'sr.Recognizer', ([], {}), '()\\n', (266, 268), True, 'import speech_recognition as sr\\n'), ((477, 496), 'nltk.tokenize.word_tokenize', 'word_tokenize', (['data'], {}), '(data)\\n', (490, 496), False, 'from nltk.tokenize import sent_tokenize, word_tokenize\\n'), ((274, 289), 'speech_recognition.Microphone', 'sr.Microphone', ([], {}), '()\\n', (287, 289), True, 'import speech_recognition as sr\\n'), ((441, 467), 'nltk.corpus.stopwords.words', 'stopwords.words', (['\"\"\"english\"\"\"'], {}), \"('english')\\n\", (456, 467), False, 'from nltk.corpus import stopwords\\n')]"}}},{"rowIdx":8465,"cells":{"repo_name":{"kind":"string","value":"jonathanlloyd/scratchstack-httpserver"},"repo_path":{"kind":"string","value":"src/models.py"},"repo_head_hexsha":{"kind":"string","value":"72f9bb5b1673b132786d94c017dbf2d370886b79"},"content":{"kind":"string","value":"from dataclasses import dataclass\n\n@dataclass\nclass Request:\n method: str\n path: str\n headers: dict\n body: bytes\n\n@dataclass\nclass Response:\n status_code: int\n reason_phrase: str\n headers: dict\n body: bytes\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8466,"cells":{"repo_name":{"kind":"string","value":"EdwardZX/hoomd-blue"},"repo_path":{"kind":"string","value":"hoomd/communicator.py"},"repo_head_hexsha":{"kind":"string","value":"c87ac3f136534e8a80359a2faceeb730f445da21"},"content":{"kind":"string","value":"# Copyright (c) 2009-2021 The Regents of the University of Michigan\n# This file is part of the HOOMD-blue project, released under the BSD 3-Clause\n# License.\n\n\"\"\"MPI communicator.\"\"\"\n\nfrom hoomd import _hoomd\nimport hoomd\n\nimport contextlib\n\n\nclass Communicator(object):\n \"\"\"MPI communicator.\n\n Args:\n mpi_comm: Accepts an mpi4py communicator. Use this argument to perform\n many independent hoomd simulations where you communicate between those\n simulations using mpi4py.\n ranks_per_partition (int): (MPI) Number of ranks to include in a\n partition.\n\n `Communicator` initialize MPI communications for a `hoomd.Simulation`. To\n use MPI, launch your Python script with an MPI launcher (e.g. ``mpirun`` or\n ``mpiexec``). By default, `Communicator` uses all ranks provided by the\n launcher ``num_launch_ranks`` for a single `hoomd.Simulation` object which\n decomposes the state onto that many domains.\n\n Set ``ranks_per_partition`` to an integer to partition launched ranks into\n ``num_launch_ranks / ranks_per_partition`` communicators, each with their\n own `partition` index. Use this to perform many simulations in parallel, for\n example by using `partition` as an index into an array of state points to\n execute.\n \"\"\"\n\n def __init__(self, mpi_comm=None, ranks_per_partition=None):\n\n # check ranks_per_partition\n if ranks_per_partition is not None:\n if not hoomd.version.mpi_enabled:\n raise RuntimeError(\n \"The ranks_per_partition option is only available in MPI.\\n\"\n )\n\n mpi_available = hoomd.version.mpi_enabled\n\n self.cpp_mpi_conf = None\n\n # create the specified configuration\n if mpi_comm is None:\n self.cpp_mpi_conf = _hoomd.MPIConfiguration()\n else:\n if not mpi_available:\n raise RuntimeError(\"mpi_comm is not supported in serial builds\")\n\n handled = False\n\n # pass in pointer to MPI_Comm object provided by mpi4py\n try:\n import mpi4py\n if isinstance(mpi_comm, mpi4py.MPI.Comm):\n addr = mpi4py.MPI._addressof(mpi_comm)\n self.cpp_mpi_conf = \\\n _hoomd.MPIConfiguration._make_mpi_conf_mpi_comm(addr)\n handled = True\n except ImportError:\n # silently ignore when mpi4py is missing\n pass\n\n # undocumented case: handle plain integers as pointers to MPI_Comm\n # objects\n if not handled and isinstance(mpi_comm, int):\n self.cpp_mpi_conf = \\\n _hoomd.MPIConfiguration._make_mpi_conf_mpi_comm(mpi_comm)\n handled = True\n\n if not handled:\n raise RuntimeError(\n \"Invalid mpi_comm object: {}\".format(mpi_comm))\n\n if ranks_per_partition is not None:\n # check validity\n if (self.cpp_mpi_conf.getNRanksGlobal() % ranks_per_partition):\n raise RuntimeError('Total number of ranks is not a multiple of '\n 'ranks_per_partition.')\n\n # split the communicator into partitions\n self.cpp_mpi_conf.splitPartitions(ranks_per_partition)\n\n @property\n def num_ranks(self):\n \"\"\"int: The number of ranks in this partition.\n\n When initialized with ``ranks_per_partition=None``, `num_ranks` is equal\n to the ``num_launch_ranks`` set by the MPI launcher. When using\n partitions, `num_ranks` is equal to ``ranks_per_partition``.\n\n Note:\n Returns 1 in builds with ENABLE_MPI=off.\n \"\"\"\n if hoomd.version.mpi_enabled:\n return self.cpp_mpi_conf.getNRanks()\n else:\n return 1\n\n @property\n def rank(self):\n \"\"\"int: The current rank within the partition.\n\n Note:\n Returns 0 in builds with ENABLE_MPI=off.\n \"\"\"\n if hoomd.version.mpi_enabled:\n return self.cpp_mpi_conf.getRank()\n else:\n return 0\n\n @property\n def num_partitions(self):\n \"\"\"int: The number of partitions in this execution.\n\n Create partitions with the ``ranks_per_partition`` argument on\n initialization. Then, the number of partitions is\n ``num_launch_ranks / ranks_per_partition``.\n\n Note:\n Returns 1 in builds with ENABLE_MPI=off.\n \"\"\"\n if hoomd.version.mpi_enabled:\n return self.cpp_mpi_conf.getNPartitions()\n else:\n return 1\n\n @property\n def partition(self):\n \"\"\"int: The current partition.\n\n Note:\n Returns 0 in builds with ENABLE_MPI=off.\n \"\"\"\n if hoomd.version.mpi_enabled:\n return self.cpp_mpi_conf.getPartition()\n else:\n return 0\n\n def barrier_all(self):\n \"\"\"Perform a MPI barrier synchronization across all ranks.\n\n Note:\n Does nothing in builds with ENABLE_MPI=off.\n \"\"\"\n if hoomd.version.mpi_enabled:\n _hoomd.mpi_barrier_world()\n\n def barrier(self):\n \"\"\"Perform a barrier synchronization across all ranks in the partition.\n\n Note:\n Does nothing in builds with ENABLE_MPI=off.\n \"\"\"\n if hoomd.version.mpi_enabled:\n self.cpp_mpi_conf.barrier()\n\n @contextlib.contextmanager\n def localize_abort(self):\n \"\"\"Localize MPI_Abort to this partition.\n\n HOOMD calls ``MPI_Abort`` to tear down all running MPI processes\n whenever there is an uncaught exception. By default, this will abort the\n entire MPI execution. When using partitions, an uncaught exception on\n one partition will therefore abort all of them.\n\n Use the return value of :py:meth:`localize_abort()` as a context manager\n to tell HOOMD that all operations within the context will use only\n that MPI communicator so that an uncaught exception in one partition\n will only abort that partition and leave the others running.\n \"\"\"\n global _current_communicator\n prev = _current_communicator\n\n _current_communicator = self\n yield None\n _current_communicator = prev\n\n\n# store the \"current\" communicator to be used for MPI_Abort calls. This defaults\n# to the world communicator, but users can opt in to a more specific\n# communicator using the Device.localize_abort context manager\n_current_communicator = Communicator()\n"},"apis":{"kind":"string","value":"[((1818, 1843), 'hoomd._hoomd.MPIConfiguration', '_hoomd.MPIConfiguration', ([], {}), '()\\n', (1841, 1843), False, 'from hoomd import _hoomd\\n'), ((5167, 5193), 'hoomd._hoomd.mpi_barrier_world', '_hoomd.mpi_barrier_world', ([], {}), '()\\n', (5191, 5193), False, 'from hoomd import _hoomd\\n'), ((2718, 2775), 'hoomd._hoomd.MPIConfiguration._make_mpi_conf_mpi_comm', '_hoomd.MPIConfiguration._make_mpi_conf_mpi_comm', (['mpi_comm'], {}), '(mpi_comm)\\n', (2765, 2775), False, 'from hoomd import _hoomd\\n'), ((2203, 2234), 'mpi4py.MPI._addressof', 'mpi4py.MPI._addressof', (['mpi_comm'], {}), '(mpi_comm)\\n', (2224, 2234), False, 'import mpi4py\\n'), ((2301, 2354), 'hoomd._hoomd.MPIConfiguration._make_mpi_conf_mpi_comm', '_hoomd.MPIConfiguration._make_mpi_conf_mpi_comm', (['addr'], {}), '(addr)\\n', (2348, 2354), False, 'from hoomd import _hoomd\\n')]"}}},{"rowIdx":8467,"cells":{"repo_name":{"kind":"string","value":"dominc8/affinity-propagation"},"repo_path":{"kind":"string","value":"src/affinity-propagation/generate_data.py"},"repo_head_hexsha":{"kind":"string","value":"b91b18b52eb68a7eafaadf0ceac39fe10955dcf2"},"content":{"kind":"string","value":"from config import DataGeneratorCfg\nfrom sklearn.datasets.samples_generator import make_blobs\nimport numpy as np\n\ndef generate():\n data, true_labels = make_blobs(n_samples=DataGeneratorCfg.n_samples, centers=DataGeneratorCfg.centers, cluster_std=DataGeneratorCfg.cluster_std, random_state=DataGeneratorCfg.random_state)\n print(\"Generating new data!\")\n np.savetxt(\"data/data.txt\", data)\n np.savetxt(\"data/true_labels.txt\", true_labels)\n return data\n\n"},"apis":{"kind":"string","value":"[((154, 332), 'sklearn.datasets.samples_generator.make_blobs', 'make_blobs', ([], {'n_samples': 'DataGeneratorCfg.n_samples', 'centers': 'DataGeneratorCfg.centers', 'cluster_std': 'DataGeneratorCfg.cluster_std', 'random_state': 'DataGeneratorCfg.random_state'}), '(n_samples=DataGeneratorCfg.n_samples, centers=DataGeneratorCfg.\\n centers, cluster_std=DataGeneratorCfg.cluster_std, random_state=\\n DataGeneratorCfg.random_state)\\n', (164, 332), False, 'from sklearn.datasets.samples_generator import make_blobs\\n'), ((361, 394), 'numpy.savetxt', 'np.savetxt', (['\"\"\"data/data.txt\"\"\"', 'data'], {}), \"('data/data.txt', data)\\n\", (371, 394), True, 'import numpy as np\\n'), ((399, 446), 'numpy.savetxt', 'np.savetxt', (['\"\"\"data/true_labels.txt\"\"\"', 'true_labels'], {}), \"('data/true_labels.txt', true_labels)\\n\", (409, 446), True, 'import numpy as np\\n')]"}}},{"rowIdx":8468,"cells":{"repo_name":{"kind":"string","value":"roch1990/peon"},"repo_path":{"kind":"string","value":"peon/tests/test_project/test_file/test_function_def/test_functions/test_reflection_at_line.py"},"repo_head_hexsha":{"kind":"string","value":"0e9e40956c05138c0820fe380b354fdd1fe95e01"},"content":{"kind":"string","value":"import _ast\n\nfrom peon.src.project.file.function_def.function import FunctionLint\n\n\nclass ReflectionAtLineFixture:\n empty_node = _ast.Pass\n is_instance_at_first_lvl = _ast.FunctionDef(id='isinstance', lineno=1)\n type_at_first_lvl = _ast.FunctionDef(id='type', lineno=1)\n is_instance_at_second_lvl = _ast.FunctionDef(body=[_ast.Expr(id='isinstance', lineno=2)], lineno=1)\n type_at_second_lvl = _ast.FunctionDef(body=[_ast.Expr(id='type', lineno=2)], lineno=1)\n\n\ndef test_empty_node():\n assert FunctionLint(\n definition=ReflectionAtLineFixture.empty_node,\n ).reflection_at_line() == tuple()\n\n\ndef test_is_instance_at_first_lvl():\n assert FunctionLint(\n definition=ReflectionAtLineFixture.is_instance_at_first_lvl,\n ).reflection_at_line() == (1,)\n\n\ndef test_type_at_first_lvl():\n assert FunctionLint(\n definition=ReflectionAtLineFixture.type_at_first_lvl,\n ).reflection_at_line() == (1,)\n\n\ndef test_is_instance_at_second_lvl():\n assert FunctionLint(\n definition=ReflectionAtLineFixture.is_instance_at_second_lvl,\n ).reflection_at_line() == (2,)\n\n\ndef test_type_at_second_lvl():\n assert FunctionLint(\n definition=ReflectionAtLineFixture.type_at_second_lvl,\n ).reflection_at_line() == (2,)\n"},"apis":{"kind":"string","value":"[((173, 216), '_ast.FunctionDef', '_ast.FunctionDef', ([], {'id': '\"\"\"isinstance\"\"\"', 'lineno': '(1)'}), \"(id='isinstance', lineno=1)\\n\", (189, 216), False, 'import _ast\\n'), ((241, 278), '_ast.FunctionDef', '_ast.FunctionDef', ([], {'id': '\"\"\"type\"\"\"', 'lineno': '(1)'}), \"(id='type', lineno=1)\\n\", (257, 278), False, 'import _ast\\n'), ((334, 370), '_ast.Expr', '_ast.Expr', ([], {'id': '\"\"\"isinstance\"\"\"', 'lineno': '(2)'}), \"(id='isinstance', lineno=2)\\n\", (343, 370), False, 'import _ast\\n'), ((431, 461), '_ast.Expr', '_ast.Expr', ([], {'id': '\"\"\"type\"\"\"', 'lineno': '(2)'}), \"(id='type', lineno=2)\\n\", (440, 461), False, 'import _ast\\n'), ((510, 569), 'peon.src.project.file.function_def.function.FunctionLint', 'FunctionLint', ([], {'definition': 'ReflectionAtLineFixture.empty_node'}), '(definition=ReflectionAtLineFixture.empty_node)\\n', (522, 569), False, 'from peon.src.project.file.function_def.function import FunctionLint\\n'), ((667, 740), 'peon.src.project.file.function_def.function.FunctionLint', 'FunctionLint', ([], {'definition': 'ReflectionAtLineFixture.is_instance_at_first_lvl'}), '(definition=ReflectionAtLineFixture.is_instance_at_first_lvl)\\n', (679, 740), False, 'from peon.src.project.file.function_def.function import FunctionLint\\n'), ((828, 894), 'peon.src.project.file.function_def.function.FunctionLint', 'FunctionLint', ([], {'definition': 'ReflectionAtLineFixture.type_at_first_lvl'}), '(definition=ReflectionAtLineFixture.type_at_first_lvl)\\n', (840, 894), False, 'from peon.src.project.file.function_def.function import FunctionLint\\n'), ((990, 1064), 'peon.src.project.file.function_def.function.FunctionLint', 'FunctionLint', ([], {'definition': 'ReflectionAtLineFixture.is_instance_at_second_lvl'}), '(definition=ReflectionAtLineFixture.is_instance_at_second_lvl)\\n', (1002, 1064), False, 'from peon.src.project.file.function_def.function import FunctionLint\\n'), ((1153, 1220), 'peon.src.project.file.function_def.function.FunctionLint', 'FunctionLint', ([], {'definition': 'ReflectionAtLineFixture.type_at_second_lvl'}), '(definition=ReflectionAtLineFixture.type_at_second_lvl)\\n', (1165, 1220), False, 'from peon.src.project.file.function_def.function import FunctionLint\\n')]"}}},{"rowIdx":8469,"cells":{"repo_name":{"kind":"string","value":"Nama/A.T.S.P.-Website"},"repo_path":{"kind":"string","value":"db2_funcs.py"},"repo_head_hexsha":{"kind":"string","value":"658db78da1b12c01ef9ead2dc44d1ecd97b178d8"},"content":{"kind":"string","value":"###############################################################################\n# #\n'''Website Database-connection-related features''' #\n# #\n###############################################################################\n\n\nimport cymysql\n\nfrom conf import website_db\nfrom time import gmtime\nfrom time import strftime\n\ndb_host = website_db.ip\ndb_port = website_db.port\ndb = website_db.db\ndb_user = website_db.user\ndb_pw = website_db.pw\n\n\n###############################################################################\n# #\n'''Databse-connect and close''' #\n# #\n###############################################################################\n\n\ndef db_con():\n conn = cymysql.connect(host=db_host, port=db_port, user=db_user, passwd=db_pw, db=db)\n cur = conn.cursor()\n return conn, cur\n\n\ndef db_close(conn, cur):\n cur.close()\n conn.close()\n\n\n###############################################################################\n# #\n'''Donation-Page data''' #\n# #\n###############################################################################\n\n\ndef donate_save(nick):\n conn, cur = db_con()\n time = strftime('%Y.%m.%d - %H:%M:%S', gmtime())\n cur.execute('INSERT INTO `donate` (`time`, `user`) VALUES (%s, %s)', (time, nick))\n conn.commit()\n db_close(conn, cur)\n\n\ndef donate_read():\n conn, cur = db_con()\n cur.execute('SELECT * FROM `donate` ORDER BY `time` DESC LIMIT 20')\n nicks = list()\n for r in cur.fetchall():\n nicks.append([r[0], r[1]])\n\n db_close(conn, cur)\n return nicks\n\n\n###############################################################################\n# #\n'''Short-URL data''' #\n# #\n###############################################################################\n\n\ndef shorturl_save(surl, url):\n conn, cur = db_con()\n cur.execute('INSERT INTO `shorturls` (`surl`, `url`) VALUES (%s, %s)', (surl, url))\n conn.commit()\n db_close(conn, cur)\n\n\ndef shorturl_read():\n conn, cur = db_con()\n cur.execute('SELECT * FROM `shorturls`')\n urls = list()\n for r in cur.fetchall():\n urls.append([r[0], r[0], r[1]])\n\n db_close(conn, cur)\n return urls\n\n\n###############################################################################\n# #\n'''Old Worlds''' #\n# #\n###############################################################################\n\n\ndef get_old_worlds(item):\n conn, cur = db_con()\n sql = 'SELECT * FROM `oldworlds` ORDER BY `date` DESC LIMIT {0}, {1}'.format(item, 20)\n cur.execute(sql)\n worlds = cur.fetchall()\n\n db_close(conn, cur)\n return worlds\n\n\n###############################################################################\n# #\n'''Server Backup-Size in Dash''' #\n# #\n###############################################################################\n\n\ndef backup_size():\n conn, cur = db_con()\n dbtshock = []\n tserver = []\n htdocs = []\n cur.execute('SELECT * FROM `backups`')\n for r in cur.fetchall():\n if r[1] == 'db':\n dbtshock.append([r[0] * 1000, r[2]])\n elif r[1] == 'tserver':\n tserver.append([r[0] * 1000, r[2]])\n elif r[1] == 'htdocs':\n htdocs.append([r[0] * 1000, r[2]])\n\n db_close(conn, cur)\n return (dbtshock, tserver, htdocs)\n"},"apis":{"kind":"string","value":"[((1043, 1121), 'cymysql.connect', 'cymysql.connect', ([], {'host': 'db_host', 'port': 'db_port', 'user': 'db_user', 'passwd': 'db_pw', 'db': 'db'}), '(host=db_host, port=db_port, user=db_user, passwd=db_pw, db=db)\\n', (1058, 1121), False, 'import cymysql\\n'), ((1722, 1730), 'time.gmtime', 'gmtime', ([], {}), '()\\n', (1728, 1730), False, 'from time import gmtime\\n')]"}}},{"rowIdx":8470,"cells":{"repo_name":{"kind":"string","value":"rgschmitz1/tcss702"},"repo_path":{"kind":"string","value":"nlp/handler.py"},"repo_head_hexsha":{"kind":"string","value":"b0fdd7b6107401dc297b467c9e63773dfb8fd487"},"content":{"kind":"string","value":"from minio import Minio\nimport json\nimport os\nfrom .Inspector import Inspector\nfrom .topic_model import topic_model\n\n#def handle(event):\ndef handle(event, context):\n with open(\"/var/openfaas/secrets/minio-access-key\") as f:\n access_key = f.read()\n with open(\"/var/openfaas/secrets/minio-secret-key\") as f:\n secret_key = f.read()\n\n mc = Minio(os.environ['minio_hostname'],\n access_key=access_key,\n secret_key=secret_key,\n secure=False)\n\n tm = topic_model(mc)\n\n # Collect data\n inspector = Inspector()\n inspector.inspectAll()\n # Add custom message and finish the function\n# if \"startWallClock\" in event:\n# inspector.addAttribute(\"startWallClock\", event['startWallClock'])\n\n body = json.loads(event.body)\n print(body['fn'], flush=True)\n\n fn = {\"p\": tm.preprocess,\n \"t\": tm.train,\n \"q\": tm.query}\n\n fn[body['fn']]()\n\n inspector.inspectAllDeltas()\n # Include functionName\n inspector.addAttribute(\"functionName\", fn[body['fn']].__name__)\n\n iret = inspector.finish()\n ret = {\n \"status\": 200,\n \"body\": iret\n }\n return ret\n"},"apis":{"kind":"string","value":"[((359, 459), 'minio.Minio', 'Minio', ([\"os.environ['minio_hostname']\"], {'access_key': 'access_key', 'secret_key': 'secret_key', 'secure': '(False)'}), \"(os.environ['minio_hostname'], access_key=access_key, secret_key=\\n secret_key, secure=False)\\n\", (364, 459), False, 'from minio import Minio\\n'), ((772, 794), 'json.loads', 'json.loads', (['event.body'], {}), '(event.body)\\n', (782, 794), False, 'import json\\n')]"}}},{"rowIdx":8471,"cells":{"repo_name":{"kind":"string","value":"jmangs/prometheus-pve-exporter"},"repo_path":{"kind":"string","value":"src/pve_exporter/cli.py"},"repo_head_hexsha":{"kind":"string","value":"2947a1247d854791114eb5ed348a250739540708"},"content":{"kind":"string","value":"\"\"\"\nProxmox VE exporter for the Prometheus monitoring system.\n\"\"\"\n\nimport sys\nfrom argparse import ArgumentParser\nfrom pve_exporter.http import start_http_server\n\ndef main(args=None):\n \"\"\"\n Main entry point.\n \"\"\"\n\n parser = ArgumentParser()\n parser.add_argument('config', nargs='?', default='pve.yml',\n help='Path to configuration file (pve.yml)')\n parser.add_argument('port', nargs='?', type=int, default='9221',\n help='Port on which the exporter is listening (9221)')\n parser.add_argument('address', nargs='?', default='',\n help='Address to which the exporter will bind')\n\n params = parser.parse_args(args if args is None else sys.argv[1:])\n\n start_http_server(params.config, params.port, params.address)\n"},"apis":{"kind":"string","value":"[((236, 252), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\\n', (250, 252), False, 'from argparse import ArgumentParser\\n'), ((741, 802), 'pve_exporter.http.start_http_server', 'start_http_server', (['params.config', 'params.port', 'params.address'], {}), '(params.config, params.port, params.address)\\n', (758, 802), False, 'from pve_exporter.http import start_http_server\\n')]"}}},{"rowIdx":8472,"cells":{"repo_name":{"kind":"string","value":"vinodkahuja/augur"},"repo_path":{"kind":"string","value":"workers/repo_info_worker/repo_info_worker.py"},"repo_head_hexsha":{"kind":"string","value":"a7688af262c2f971767962d4a20110daf4b1179a"},"content":{"kind":"string","value":"#SPDX-License-Identifier: MIT\nimport logging, os, sys, time, requests, json\nfrom datetime import datetime\nfrom multiprocessing import Process, Queue\nimport pandas as pd\nimport sqlalchemy as s\nfrom workers.worker_base import Worker\n\n# NOTE: This worker primarily inserts rows into the REPO_INFO table, which serves the primary purposes of \n# 1. Displaying discrete metadata like \"number of forks\" and how they change over time \n# 2. Validating other workers, like those related to pull requests, issues, and commits. Our totals should be at or very near the totals in the repo_info table.\n\n# This table also updates the REPO table in 2 cases: \n# 1. Recognizing when a repository is a forked repository by updating the \"forked_from\" field and \n# 2. Recognizing when a repository is archived, and recording the data we observed the change in status. \n\nclass RepoInfoWorker(Worker):\n def __init__(self, config={}):\n\n worker_type = \"repo_info_worker\"\n \n # Define what this worker can be given and know how to interpret\n given = [['github_url']]\n models = ['repo_info']\n\n # Define the tables needed to insert, update, or delete on\n data_tables = ['repo_info', 'repo']\n operations_tables = ['worker_history', 'worker_job']\n\n # Run the general worker initialization\n super().__init__(worker_type, config, given, models, data_tables, operations_tables)\n\n # Define data collection info\n self.tool_source = 'Repo Info Worker'\n self.tool_version = '1.0.0'\n self.data_source = 'GitHub API'\n\n def repo_info_model(self, task, repo_id):\n\n github_url = task['given']['github_url']\n\n self.logger.info(\"Beginning filling the repo_info model for repo: \" + github_url + \"\\n\")\n\n owner, repo = self.get_owner_repo(github_url)\n\n url = 'https://api.github.com/graphql'\n\n query = \"\"\"\n {\n repository(owner:\"%s\", name:\"%s\"){\n updatedAt\n hasIssuesEnabled\n issues(states:OPEN) {\n totalCount\n }\n hasWikiEnabled\n forkCount\n defaultBranchRef {\n name\n }\n watchers {\n totalCount\n }\n id\n licenseInfo {\n name\n url\n }\n stargazers {\n totalCount\n }\n codeOfConduct {\n name\n url\n }\n issue_count: issues {\n totalCount\n }\n issues_closed: issues(states:CLOSED) {\n totalCount\n }\n pr_count: pullRequests {\n totalCount\n }\n pr_open: pullRequests(states: OPEN) {\n totalCount\n }\n pr_closed: pullRequests(states: CLOSED) {\n totalCount\n }\n pr_merged: pullRequests(states: MERGED) {\n totalCount\n }\n ref(qualifiedName: \"master\") {\n target {\n ... on Commit {\n history(first: 0){\n totalCount\n }\n }\n }\n }\n }\n }\n \"\"\" % (owner, repo)\n\n # Hit the graphql endpoint and retry 3 times in case of failure\n num_attempts = 0\n success = False\n data = None\n while num_attempts < 3:\n self.logger.info(\"Hitting endpoint: {} ...\\n\".format(url))\n r = requests.post(url, json={'query': query}, headers=self.headers)\n self.update_gh_rate_limit(r)\n\n try:\n data = r.json()\n except:\n data = json.loads(json.dumps(r.text))\n\n if 'errors' in data:\n self.logger.info(\"Error!: {}\".format(data['errors']))\n if data['errors'][0]['message'] == 'API rate limit exceeded':\n self.update_gh_rate_limit(r)\n continue\n\n if 'data' in data:\n success = True\n data = data['data']['repository']\n break\n else:\n self.logger.info(\"Request returned a non-data dict: {}\\n\".format(data))\n if data['message'] == 'Not Found':\n self.logger.info(\"Github repo was not found or does not exist for endpoint: {}\\n\".format(url))\n break\n if data['message'] == 'You have triggered an abuse detection mechanism. Please wait a few minutes before you try again.':\n self.update_gh_rate_limit(r, temporarily_disable=True)\n continue\n if data['message'] == 'Bad credentials':\n self.update_gh_rate_limit(r, bad_credentials=True)\n continue\n num_attempts += 1\n if not success:\n self.logger.error('Cannot hit endpoint after 3 attempts. \\\"Completing\\\" task.\\n')\n self.register_task_completion(self.task, repo_id, 'repo_info')\n return\n\n # Just checking that the data is accessible (would not be if repo no longer exists)\n try:\n data['updatedAt']\n except Exception as e:\n self.logger.error('Cannot access repo_info data: {}\\nError: {}. \\\"Completing\\\" task.'.format(data, e))\n self.register_task_completion(self.task, repo_id, 'repo_info')\n return\n\n # Get committers count info that requires seperate endpoint\n committers_count = self.query_committers_count(owner, repo)\n\n # Put all data together in format of the table\n self.logger.info(f'Inserting repo info for repo with id:{repo_id}, owner:{owner}, name:{repo}\\n')\n rep_inf = {\n 'repo_id': repo_id,\n 'last_updated': data['updatedAt'] if 'updatedAt' in data else None,\n 'issues_enabled': data['hasIssuesEnabled'] if 'hasIssuesEnabled' in data else None,\n 'open_issues': data['issues']['totalCount'] if data['issues'] else None,\n 'pull_requests_enabled': None,\n 'wiki_enabled': data['hasWikiEnabled'] if 'hasWikiEnabled' in data else None,\n 'pages_enabled': None,\n 'fork_count': data['forkCount'] if 'forkCount' in data else None,\n 'default_branch': data['defaultBranchRef']['name'] if data['defaultBranchRef'] else None,\n 'watchers_count': data['watchers']['totalCount'] if data['watchers'] else None,\n 'UUID': None,\n 'license': data['licenseInfo']['name'] if data['licenseInfo'] else None,\n 'stars_count': data['stargazers']['totalCount'] if data['stargazers'] else None,\n 'committers_count': committers_count,\n 'issue_contributors_count': None,\n 'changelog_file': None,\n 'contributing_file': None,\n 'license_file': data['licenseInfo']['url'] if data['licenseInfo'] else None,\n 'code_of_conduct_file': data['codeOfConduct']['url'] if data['codeOfConduct'] else None,\n 'security_issue_file': None,\n 'security_audit_file': None,\n 'status': None,\n 'keywords': None,\n 'commit_count': data['ref']['target']['history']['totalCount'] if data['ref'] else None,\n 'issues_count': data['issue_count']['totalCount'] if data['issue_count'] else None,\n 'issues_closed': data['issues_closed']['totalCount'] if data['issues_closed'] else None,\n 'pull_request_count': data['pr_count']['totalCount'] if data['pr_count'] else None,\n 'pull_requests_open': data['pr_open']['totalCount'] if data['pr_open'] else None,\n 'pull_requests_closed': data['pr_closed']['totalCount'] if data['pr_closed'] else None,\n 'pull_requests_merged': data['pr_merged']['totalCount'] if data['pr_merged'] else None,\n 'tool_source': self.tool_source,\n 'tool_version': self.tool_version,\n 'data_source': self.data_source\n }\n\n result = self.db.execute(self.repo_info_table.insert().values(rep_inf))\n self.logger.info(f\"Primary Key inserted into repo_info table: {result.inserted_primary_key}\\n\")\n self.results_counter += 1\n\n # Note that the addition of information about where a repository may be forked from, and whether a repository is archived, updates the `repo` table, not the `repo_info` table.\n forked = self.is_forked(owner, repo)\n archived = self.is_archived(owner, repo)\n archived_date_collected = None\n if archived is not False:\n archived_date_collected = archived\n archived = 1\n else:\n archived = 0\n\n rep_additional_data = {\n 'forked_from': forked,\n 'repo_archived': archived,\n 'repo_archived_date_collected': archived_date_collected\n }\n result = self.db.execute(self.repo_table.update().where(\n self.repo_table.c.repo_id==repo_id).values(rep_additional_data))\n\n self.logger.info(f\"Inserted info for {owner}/{repo}\\n\")\n\n # Register this task as completed\n self.register_task_completion(self.task, repo_id, \"repo_info\")\n\n def query_committers_count(self, owner, repo):\n self.logger.info('Querying committers count\\n')\n url = f'https://api.github.com/repos/{owner}/{repo}/contributors?per_page=100'\n committers = 0\n\n try:\n while True:\n r = requests.get(url, headers=self.headers)\n self.update_gh_rate_limit(r)\n committers += len(r.json())\n\n if 'next' not in r.links:\n break\n else:\n url = r.links['next']['url']\n except Exception:\n self.logger.exception('An error occured while querying contributor count\\n')\n\n return committers\n\n def is_forked(self, owner, repo): #/repos/:owner/:repo parent\n self.logger.info('Querying parent info to verify if the repo is forked\\n')\n url = f'https://api.github.com/repos/{owner}/{repo}'\n\n r = requests.get(url, headers=self.headers)\n self.update_gh_rate_limit(r)\n\n data = self.get_repo_data(url, r)\n\n if 'fork' in data:\n if 'parent' in data:\n return data['parent']['full_name']\n return 'Parent not available'\n\n return False\n\n def is_archived(self, owner, repo):\n self.logger.info('Querying committers count\\n')\n url = f'https://api.github.com/repos/{owner}/{repo}'\n\n r = requests.get(url, headers=self.headers)\n self.update_gh_rate_limit(r)\n\n data = self.get_repo_data(url, r)\n\n if 'archived' in data:\n if data['archived']:\n if 'updated_at' in data:\n return data['updated_at']\n return 'Date not available'\n return False\n\n return False\n\n def get_repo_data(self, url, response):\n success = False\n try:\n data = response.json()\n except:\n data = json.loads(json.dumps(response.text))\n\n if 'errors' in data:\n self.logger.info(\"Error!: {}\".format(data['errors']))\n if data['errors'][0]['message'] == 'API rate limit exceeded':\n self.update_gh_rate_limit(response)\n\n if 'id' in data:\n success = True\n else:\n self.logger.info(\"Request returned a non-data dict: {}\\n\".format(data))\n if data['message'] == 'Not Found':\n self.logger.info(\"Github repo was not found or does not exist for endpoint: {}\\n\".format(url))\n if data['message'] == 'You have triggered an abuse detection mechanism. Please wait a few minutes before you try again.':\n self.update_gh_rate_limit(r, temporarily_disable=True)\n if data['message'] == 'Bad credentials':\n self.update_gh_rate_limit(r, bad_credentials=True)\n if not success:\n self.register_task_failure(self.task, repo_id, \"Failed to hit endpoint: {}\".format(url))\n\n return data\n"},"apis":{"kind":"string","value":"[((10670, 10709), 'requests.get', 'requests.get', (['url'], {'headers': 'self.headers'}), '(url, headers=self.headers)\\n', (10682, 10709), False, 'import logging, os, sys, time, requests, json\\n'), ((11137, 11176), 'requests.get', 'requests.get', (['url'], {'headers': 'self.headers'}), '(url, headers=self.headers)\\n', (11149, 11176), False, 'import logging, os, sys, time, requests, json\\n'), ((4041, 4104), 'requests.post', 'requests.post', (['url'], {'json': \"{'query': query}\", 'headers': 'self.headers'}), \"(url, json={'query': query}, headers=self.headers)\\n\", (4054, 4104), False, 'import logging, os, sys, time, requests, json\\n'), ((10035, 10074), 'requests.get', 'requests.get', (['url'], {'headers': 'self.headers'}), '(url, headers=self.headers)\\n', (10047, 10074), False, 'import logging, os, sys, time, requests, json\\n'), ((11663, 11688), 'json.dumps', 'json.dumps', (['response.text'], {}), '(response.text)\\n', (11673, 11688), False, 'import logging, os, sys, time, requests, json\\n'), ((4250, 4268), 'json.dumps', 'json.dumps', (['r.text'], {}), '(r.text)\\n', (4260, 4268), False, 'import logging, os, sys, time, requests, json\\n')]"}}},{"rowIdx":8473,"cells":{"repo_name":{"kind":"string","value":"victor-estrade/SystGradDescent"},"repo_path":{"kind":"string","value":"benchmark/my_argparser.py"},"repo_head_hexsha":{"kind":"string","value":"822e7094290301ec47a99433381a8d6406798aff"},"content":{"kind":"string","value":"# coding: utf-8\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport argparse\n\n\ndef parse_args_tolerance():\n parser = argparse.ArgumentParser(description='just for tolerance')\n parser.add_argument(\"--tolerance\", type=float,\n default=0.1, help=\"tolerance value for Minuit migrad and simplex minimization\")\n args, _ = parser.parse_known_args()\n return args.tolerance\n\ndef GB_parse_args(main_description=\"Training launcher\"):\n parser = argparse.ArgumentParser(description=main_description)\n\n parser.add_argument(\"--verbose\", \"-v\", type=int, choices=[0, 1, 2],\n default=0, help=\"increase output verbosity\")\n\n parser.add_argument(\"--start-cv\", type=int,\n default=0, help=\"start of i_cv for range(start, end)\")\n parser.add_argument(\"--end-cv\", type=int,\n default=30, help=\"end of i_cv for range(start, end)\")\n parser.add_argument(\"--tolerance\", type=float,\n default=0.1, help=\"tolerance value for Minuit migrad and simplex minimization\")\n parser.add_argument('--load-run', help='load saved runs. Do not run the models',\n action='store_true')\n parser.add_argument('--estimate-only', help='Turns off conditional estimation for V_stat and V_syst',\n action='store_true')\n parser.add_argument('--conditional-only', help='Turns off common estimation',\n action='store_true')\n\n # MODEL HYPER PARAMETERS\n parser.add_argument('--n-estimators', help='number of estimators',\n default=100, type=int)\n\n parser.add_argument('--max-depth', help='maximum depth of trees',\n default=3, type=int)\n\n parser.add_argument('--learning-rate', '--lr', help='learning rate',\n default=1e-1, type=float)\n\n # OTHER\n parser.add_argument('--no-cuda', '--no-gpu', help='flag to use or not the gpu',\n action='store_false', dest='cuda')\n parser.add_argument('--retrain', help='flag to force retraining',\n action='store_true')\n parser.add_argument('--skip-minuit', help='flag to skip minuit NLL minization',\n action='store_true')\n\n args = parser.parse_args()\n return args\n\n\ndef REG_parse_args(main_description=\"Training launcher\"):\n parser = argparse.ArgumentParser(description=main_description)\n\n parser.add_argument(\"--verbose\", \"-v\", type=int, choices=[0, 1, 2],\n default=0, help=\"increase output verbosity\")\n\n parser.add_argument(\"--start-cv\", type=int,\n default=0, help=\"start of i_cv for range(start, end)\")\n parser.add_argument(\"--end-cv\", type=int,\n default=30, help=\"end of i_cv for range(start, end)\")\n parser.add_argument(\"--tolerance\", type=float,\n default=0.1, help=\"tolerance value for Minuit migrad and simplex minimization\")\n parser.add_argument('--load-run', help='load saved runs. Do not run the models',\n action='store_true')\n parser.add_argument('--estimate-only', help='Turns off conditional estimation for V_stat and V_syst',\n action='store_true')\n parser.add_argument('--conditional-only', help='Turns off common estimation',\n action='store_true')\n\n # MODEL HYPER PARAMETERS\n parser.add_argument('--learning-rate', '--lr', help='learning rate',\n default=1e-4, type=float)\n\n parser.add_argument('--beta1', help='beta 1 for Adam',\n default=0.5, type=float)\n parser.add_argument('--beta2', help='beta 2 for Adam',\n default=0.9, type=float)\n parser.add_argument('--weight-decay', help='weight decay for SGD',\n default=0.0, type=float)\n\n parser.add_argument('--optimizer', help='optimizer name', dest='optimizer_name',\n default='Adam', type=str, choices=('Adam', 'SGD', 'ADAM', 'sgd', 'adam'))\n\n parser.add_argument('--n-unit', help='Number of units in layers. Controls NN width.',\n default=200, type=int)\n\n parser.add_argument('--sample-size', help='data sample size',\n default=1000, type=int)\n\n parser.add_argument('--batch-size', help='mini-batch size',\n default=20, type=int)\n\n parser.add_argument('--n-steps', help='number of update steps',\n default=1000, type=int)\n\n # OTHER\n parser.add_argument('--no-cuda', '--no-gpu', help='flag to use or not the gpu',\n action='store_false', dest='cuda')\n parser.add_argument('--retrain', help='flag to force retraining',\n action='store_true')\n\n args = parser.parse_args()\n return args\n\n\n\ndef INFERNO_parse_args(main_description=\"Training launcher\"):\n parser = argparse.ArgumentParser(description=main_description)\n\n parser.add_argument(\"--verbose\", \"-v\", type=int, choices=[0, 1, 2],\n default=0, help=\"increase output verbosity\")\n\n parser.add_argument(\"--start-cv\", type=int,\n default=0, help=\"start of i_cv for range(start, end)\")\n parser.add_argument(\"--end-cv\", type=int,\n default=30, help=\"end of i_cv for range(start, end)\")\n parser.add_argument(\"--tolerance\", type=float,\n default=0.1, help=\"tolerance value for Minuit migrad and simplex minimization\")\n parser.add_argument('--load-run', help='load saved runs. Do not run the models',\n action='store_true')\n parser.add_argument('--estimate-only', help='Turns off conditional estimation for V_stat and V_syst',\n action='store_true')\n parser.add_argument('--conditional-only', help='Turns off common estimation',\n action='store_true')\n\n # MODEL HYPER PARAMETERS\n parser.add_argument('--learning-rate', '--lr', help='learning rate',\n default=1e-3, type=float)\n parser.add_argument('--temperature', help='control initial softmax steepness',\n default=1.0, type=float)\n\n parser.add_argument('--beta1', help='beta 1 for Adam',\n default=0.5, type=float)\n parser.add_argument('--beta2', help='beta 2 for Adam',\n default=0.9, type=float)\n parser.add_argument('--weight-decay', help='weight decay for SGD',\n default=0.0, type=float)\n\n parser.add_argument('--optimizer', help='optimizer name', dest='optimizer_name',\n default='Adam', type=str, choices=('Adam', 'SGD', 'ADAM', 'sgd', 'adam'))\n\n parser.add_argument('--n-unit', help='Number of units in layers. Controls NN width.',\n default=200, type=int)\n\n parser.add_argument('--n-bins', help='number of output bins',\n default=10, type=int)\n\n parser.add_argument('--sample-size', help='data sample size',\n default=1000, type=int)\n\n parser.add_argument('--batch-size', help='mini-batch size',\n default=20, type=int)\n\n parser.add_argument('--n-steps', help='number of update steps',\n default=1000, type=int)\n\n # OTHER\n parser.add_argument('--no-cuda', '--no-gpu', help='flag to use or not the gpu',\n action='store_false', dest='cuda')\n parser.add_argument('--retrain', help='flag to force retraining',\n action='store_true')\n\n args = parser.parse_args()\n return args\n\n\n\ndef NET_parse_args(main_description=\"Training launcher\"):\n parser = argparse.ArgumentParser(description=main_description)\n\n parser.add_argument(\"--verbose\", \"-v\", type=int, choices=[0, 1, 2],\n default=0, help=\"increase output verbosity\")\n\n parser.add_argument(\"--start-cv\", type=int,\n default=0, help=\"start of i_cv for range(start, end)\")\n parser.add_argument(\"--end-cv\", type=int,\n default=30, help=\"end of i_cv for range(start, end)\")\n parser.add_argument(\"--tolerance\", type=float,\n default=0.1, help=\"tolerance value for Minuit migrad and simplex minimization\")\n parser.add_argument('--load-run', help='load saved runs. Do not run the models',\n action='store_true')\n parser.add_argument('--estimate-only', help='Turns off conditional estimation for V_stat and V_syst',\n action='store_true')\n parser.add_argument('--conditional-only', help='Turns off common estimation',\n action='store_true')\n\n # MODEL HYPER PARAMETERS\n parser.add_argument('--learning-rate', '--lr', help='learning rate',\n default=1e-3, type=float)\n\n parser.add_argument('--beta1', help='beta 1 for Adam',\n default=0.9, type=float)\n parser.add_argument('--beta2', help='beta 2 for Adam',\n default=0.999, type=float)\n parser.add_argument('--weight-decay', help='weight decay for SGD',\n default=0.0, type=float)\n\n parser.add_argument('--optimizer', help='optimizer name', dest='optimizer_name',\n default='Adam', type=str, choices=('Adam', 'SGD', 'ADAM', 'sgd', 'adam'))\n\n parser.add_argument('--n-unit', help='Number of units in layers. Controls NN width.',\n default=200, type=int)\n\n parser.add_argument('--sample-size', help='data sample size',\n default=1000, type=int)\n\n parser.add_argument('--batch-size', help='mini-batch size',\n default=1000, type=int)\n\n parser.add_argument('--n-steps', help='number of update steps',\n default=1000, type=int)\n\n # OTHER\n parser.add_argument('--no-cuda', '--no-gpu', help='flag to use or not the gpu',\n action='store_false', dest='cuda')\n parser.add_argument('--retrain', help='flag to force retraining',\n action='store_true')\n\n args = parser.parse_args()\n return args\n\ndef TP_parse_args(main_description=\"Training launcher\"):\n parser = argparse.ArgumentParser(description=main_description)\n\n parser.add_argument(\"--verbose\", \"-v\", type=int, choices=[0, 1, 2],\n default=0, help=\"increase output verbosity\")\n\n parser.add_argument(\"--start-cv\", type=int,\n default=0, help=\"start of i_cv for range(start, end)\")\n parser.add_argument(\"--end-cv\", type=int,\n default=30, help=\"end of i_cv for range(start, end)\")\n parser.add_argument(\"--tolerance\", type=float,\n default=0.1, help=\"tolerance value for Minuit migrad and simplex minimization\")\n parser.add_argument('--load-run', help='load saved runs. Do not run the models',\n action='store_true')\n parser.add_argument('--estimate-only', help='Turns off conditional estimation for V_stat and V_syst',\n action='store_true')\n parser.add_argument('--conditional-only', help='Turns off common estimation',\n action='store_true')\n\n # MODEL HYPER PARAMETERS\n parser.add_argument('--learning-rate', '--lr', help='learning rate',\n default=1e-3, type=float)\n parser.add_argument('--trade-off', help='trade-off between classic loss and adversarial loss',\n default=1.0, type=float)\n\n parser.add_argument('--beta1', help='beta 1 for Adam',\n default=0.9, type=float)\n parser.add_argument('--beta2', help='beta 2 for Adam',\n default=0.999, type=float)\n parser.add_argument('--weight-decay', help='weight decay for SGD',\n default=0.0, type=float)\n\n parser.add_argument('--optimizer', help='optimizer name', dest='optimizer_name',\n default='Adam', type=str, choices=('Adam', 'SGD', 'ADAM', 'sgd', 'adam'))\n\n parser.add_argument('--n-unit', help='Number of units in layers. Controls NN width.',\n default=200, type=int)\n\n parser.add_argument('--sample-size', help='data sample size',\n default=1000, type=int)\n\n parser.add_argument('--batch-size', help='mini-batch size',\n default=1000, type=int)\n\n parser.add_argument('--n-steps', help='number of update steps',\n default=1000, type=int)\n\n # OTHER\n parser.add_argument('--no-cuda', '--no-gpu', help='flag to use or not the gpu',\n action='store_false', dest='cuda')\n parser.add_argument('--retrain', help='flag to force retraining',\n action='store_true')\n\n args = parser.parse_args()\n return args\n\n\n\ndef PIVOT_parse_args(main_description=\"Training launcher\"):\n parser = argparse.ArgumentParser(description=main_description)\n\n parser.add_argument(\"--verbose\", \"-v\", type=int, choices=[0, 1, 2],\n default=0, help=\"increase output verbosity\")\n\n parser.add_argument(\"--start-cv\", type=int,\n default=0, help=\"start of i_cv for range(start, end)\")\n parser.add_argument(\"--end-cv\", type=int,\n default=30, help=\"end of i_cv for range(start, end)\")\n parser.add_argument(\"--tolerance\", type=float,\n default=0.1, help=\"tolerance value for Minuit migrad and simplex minimization\")\n parser.add_argument('--load-run', help='load saved runs. Do not run the models',\n action='store_true')\n parser.add_argument('--estimate-only', help='Turns off conditional estimation for V_stat and V_syst',\n action='store_true')\n parser.add_argument('--conditional-only', help='Turns off common estimation',\n action='store_true')\n\n # MODEL HYPER PARAMETERS\n parser.add_argument('--learning-rate', '--lr', help='learning rate',\n default=1e-3, type=float)\n parser.add_argument('--trade-off', help='trade-off between classic loss and adversarial loss',\n default=1.0, type=float)\n\n parser.add_argument('--beta1', help='beta 1 for Adam',\n default=0.9, type=float)\n parser.add_argument('--beta2', help='beta 2 for Adam',\n default=0.999, type=float)\n parser.add_argument('--weight-decay', help='weight decay for SGD',\n default=0.0, type=float)\n\n parser.add_argument('--optimizer', help='optimizer name', dest='optimizer_name',\n default='Adam', type=str, choices=('Adam', 'SGD', 'ADAM', 'sgd', 'adam'))\n\n parser.add_argument('--n-unit', help='Number of units in layers. Controls NN width.',\n default=200, type=int)\n\n parser.add_argument('--sample-size', help='data sample size',\n default=1000, type=int)\n\n parser.add_argument('--batch-size', help='mini-batch size',\n default=1000, type=int)\n\n parser.add_argument('--n-steps', help='number of update steps',\n default=1000, type=int)\n parser.add_argument('--n-net-pre-training-steps', help='number of update steps for pretraining the classifier',\n default=1000, type=int)\n parser.add_argument('--n-adv-pre-training-steps', help='number of update steps for pretraining the adversarial',\n default=1000, type=int)\n parser.add_argument('--n-recovery-steps', help='number of update steps for adversarial recovery',\n default=1, type=int)\n\n # OTHER\n parser.add_argument('--no-cuda', '--no-gpu', help='flag to use or not the gpu',\n action='store_false', dest='cuda')\n parser.add_argument('--retrain', help='flag to force retraining',\n action='store_true')\n\n args = parser.parse_args()\n return args\n\n\ndef FF_parse_args(main_description=\"Training launcher\"):\n parser = argparse.ArgumentParser(description=main_description)\n\n parser.add_argument(\"--verbose\", \"-v\", type=int, choices=[0, 1, 2],\n default=0, help=\"increase output verbosity\")\n\n parser.add_argument(\"--start-cv\", type=int,\n default=0, help=\"start of i_cv for range(start, end)\")\n parser.add_argument(\"--end-cv\", type=int,\n default=30, help=\"end of i_cv for range(start, end)\")\n parser.add_argument(\"--tolerance\", type=float,\n default=0.1, help=\"tolerance value for Minuit migrad and simplex minimization\")\n parser.add_argument('--load-run', help='load saved runs. Do not run the models',\n action='store_true')\n parser.add_argument('--estimate-only', help='Turns off conditional estimation for V_stat and V_syst',\n action='store_true')\n parser.add_argument('--conditional-only', help='Turns off common estimation',\n action='store_true')\n\n # MODEL HYPER PARAMETERS\n parser.add_argument('--feature-id', help='feature index to filter on',\n default=0, type=int)\n\n # OTHER\n parser.add_argument('--no-cuda', '--no-gpu', help='flag to use or not the gpu',\n action='store_false', dest='cuda')\n parser.add_argument('--retrain', help='flag to force retraining',\n action='store_true')\n parser.add_argument('--skip-minuit', help='flag to skip minuit NLL minization',\n action='store_true')\n\n args = parser.parse_args()\n return args\n"},"apis":{"kind":"string","value":"[((225, 282), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '\"\"\"just for tolerance\"\"\"'}), \"(description='just for tolerance')\\n\", (248, 282), False, 'import argparse\\n'), ((575, 628), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'main_description'}), '(description=main_description)\\n', (598, 628), False, 'import argparse\\n'), ((2495, 2548), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'main_description'}), '(description=main_description)\\n', (2518, 2548), False, 'import argparse\\n'), ((5058, 5111), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'main_description'}), '(description=main_description)\\n', (5081, 5111), False, 'import argparse\\n'), ((7862, 7915), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'main_description'}), '(description=main_description)\\n', (7885, 7915), False, 'import argparse\\n'), ((10422, 10475), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'main_description'}), '(description=main_description)\\n', (10445, 10475), False, 'import argparse\\n'), ((13135, 13188), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'main_description'}), '(description=main_description)\\n', (13158, 13188), False, 'import argparse\\n'), ((16320, 16373), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'main_description'}), '(description=main_description)\\n', (16343, 16373), False, 'import argparse\\n')]"}}},{"rowIdx":8474,"cells":{"repo_name":{"kind":"string","value":"SarthakJariwala/Shockley-Queisser-Calculator"},"repo_path":{"kind":"string","value":"src/main/python/main.py"},"repo_head_hexsha":{"kind":"string","value":"5f9cfd4c97b8141e8b4ee8d15fa5f3cccfe25b7e"},"content":{"kind":"string","value":"from fbs_runtime.application_context.PyQt5 import ApplicationContext, cached_property\nfrom fbs_runtime.platform import is_windows, is_mac\n# system imports\nimport sys\n\n# module imports \nfrom PyQt5 import uic, QtWidgets\nfrom PyQt5.QtWidgets import QMessageBox\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport scipy.constants as constants\nfrom scipy.integrate import simps, quad\nfrom scipy.interpolate import splrep, splint\nfrom scipy.optimize import fmin\n\nclass AppContext(ApplicationContext):\n def run(self):\n self.main_window.show()\n return self.app.exec_()\n \n def get_design(self):\n qtCreatorFile = self.get_resource(\"SQ_GUI.ui\")\n return qtCreatorFile\n \n def get_file(self):\n astmg_file = self.get_resource(\"ASTMG173.csv\")\n return astmg_file\n\n @cached_property\n def main_window(self):\n return MainWindow(self.get_design(), self.get_file())\nif is_windows():\n matplotlib.use('Qt5Agg')\nelif is_mac():\n matplotlib.use('macosx')\n\nclass MainWindow(QtWidgets.QMainWindow): \n \n def __init__(self, uiFile, astmg173_file):\n super(MainWindow, self).__init__()\n\n #Create Main Window\n self.ui = uic.loadUi(uiFile, self)\n #self.ui = WindowTemplate()\n #self.ui.setupUi(self)\n\n #Connect PushButtons to Functions etc\n self.ui.CalcualteSQ_pushButton.clicked.connect(self.calculate_SQ)\n self.ui.load_pushButton.clicked.connect(self.load_SMARTS_spectrum)\n self.ui.save_pushButton.clicked.connect(self.save_bandgap_array)\n\n #start app with checked \"plot j-v curve\"\n self.ui.plot_checkBox.setChecked(True)\n\n self.astmg173_file = astmg173_file\n self.out_array = None\n \n self.show()\n \n def load_SMARTS_spectrum(self):\n filename = QtWidgets.QFileDialog.getOpenFileName(self)\n try:\n self.SMARTS = np.genfromtxt(filename[0], skip_header=1)\n self.ui.load_checkBox.setChecked(False)\n except Exception as e:\n QMessageBox.information(\n self, None, \n str(e), QMessageBox.Ok\n )\n\n\n\n def calculate_SQ(self):\n h = constants.physical_constants['Planck constant'][0] # units of J*s\n h_ev = constants.physical_constants['Planck constant in eV s'][0]\n c_nm = (constants.physical_constants['speed of light in vacuum'][0]) * 1e9\n c = (constants.physical_constants['speed of light in vacuum'][0])\n \n e_charge = constants.physical_constants['elementary charge'][0] \n kb_ev = constants.physical_constants['Boltzmann constant in eV/K'][0]\n\n \"\"\"User settings\"\"\"\n Tcell = self.ui.temp_spinBox.value() #temperature of solar cell in degrees K\n bandgap = self.ui.bandgap_doubleSpinBox.value() #enter bandgap in eV\n\n #self.ui.textBrowser.append(str('Tcell = %.3f' %(Tcell)))\n\n plot_jv = self.ui.plot_checkBox.isChecked() #'True' if you want to plot the SQ JV curve for \"bandgap\"\n\n\n plot_bandgap_array = self.ui.calc_SQ_array_checkBox.isChecked() #'True' if you want to plot SQ parameters for an array of bandgaps \n # starting from \"mbandgap_array_min\" to \"bandgap_array_max\" \n # with number of points \"num_points_bandgap_array\"\n # (see below)\n \n #'False' if you just want SQ data for one bandgap (faster)\n\n bandgap_array_min = self.ui.bandgap_min_doubleSpinBox.value() #in eV\n bandgap_array_max = self.ui.bandgap_max_doubleSpinBox.value() # in eV\n num_points_bandgap_array = self.ui.no_points_spinBox.value()\n\n\n \"\"\"Programming below\"\"\"\n bandgap_array = np.linspace(bandgap_array_min, bandgap_array_max, num_points_bandgap_array)\n #First convert AM1.5 spectrum from W/m^2/nm to W/m^2/ev\n \n if self.ui.load_checkBox.isChecked():\n astmg173 = np.loadtxt(self.astmg173_file, delimiter = ',', skiprows = 2)\n am15_wav = np.copy(astmg173[:,0]) #AM1.5 wavelength axis in nm\n am15 = np.copy(astmg173[:,2]) #AM1.5 in units of W/m^2/nm = J/s*m^2/nm\n else:\n try:\n astmg173 = self.SMARTS\n\n am15_wav = np.copy(astmg173[:,0]) #AM1.5 wavelength axis in nm\n\n am15 = np.copy(astmg173[:,1]) #AM1.5 in units of W/m^2/nm = J/s*m^2/nm\n except:\n QMessageBox.information(\n self, None, \n \"No valid spectrum file found!\\n\\n\"+\n \"Load a valid file or check the 'Use ASTMG173'box\"\n )\n return\n\n total_power_nm = simps(am15, x = am15_wav) #Integrate over nm to check that total power density = 1000 W/m^2\n\n\n am15_ev = h_ev * (c_nm) / (am15_wav )\n am15_wats_ev = am15 * (h_ev * c_nm/ ((am15_ev) ** 2.0))\n\n am15_ev_flip = am15_ev[::-1] \n am15_wats_ev_flip = am15_wats_ev[::-1]\n\n\n total_power_ev = simps(am15_wats_ev_flip, x = am15_ev_flip) #Integrate over eV to check that total power density = 1000 W/m^2\n\n\n am15_photons_ev = am15_wats_ev_flip / (am15_ev_flip * e_charge)\n\n am15_photons_nm = am15 / (am15_ev * e_charge)\n\n total_photonflux_ev = simps(am15_photons_ev, x = am15_ev_flip)\n\n\n total_photonflux_nm = simps(am15_photons_nm , x = am15_wav)\n\n\n total_photonflux_ev_splrep = splrep(am15_ev_flip, am15_photons_ev)\n\n emin = am15_ev_flip[0]\n emax = am15_ev_flip[len(am15_ev_flip) - 1]\n\n def solar_photons_above_gap(Egap): #units of photons / sec *m^2\n return splint(Egap, emax,total_photonflux_ev_splrep) \n \n\n def RR0(Egap):\n integrand = lambda eV : eV ** 2.0 / (np.exp(eV / (kb_ev * Tcell)) - 1)\n integral = quad(integrand, Egap, emax, full_output=1)[0]\n return ((2.0 * np.pi / ((c ** 2.0) * (h_ev ** 3.0)))) * integral\n \n def current_density(V, Egap): #to get from units of amps / m^2 to mA/ cm^2 ---multiply by 1000 to convert to mA ---- multiply by (0.01 ^2) to convert to cm^2\n cur_dens = e_charge * (solar_photons_above_gap(Egap) - RR0(Egap) * np.exp( V / (kb_ev * Tcell))) \n return cur_dens * 1000 * (0.01 ** 2.0)\n def JSC(Egap): \n return current_density(0, Egap) \n \n def VOC(Egap):\n return (kb_ev * Tcell) * np.log(solar_photons_above_gap(Egap) / RR0(Egap))\n\n \n def fmax(func_to_maximize, initial_guess=0):\n \"\"\"return the x that maximizes func_to_maximize(x)\"\"\"\n func_to_minimize = lambda x : -func_to_maximize(x)\n return fmin(func_to_minimize, initial_guess, disp=False)[0] \n\n def V_mpp_Jmpp_maxpower_maxeff_ff(Egap):\n\n vmpp = fmax(lambda V : V * current_density(V, Egap)) \n jmpp = current_density(vmpp, Egap)\n \n maxpower = vmpp * jmpp\n max_eff = maxpower / (total_power_ev * 1000 * (0.01 ** 2.0))\n jsc_return = JSC(Egap)\n voc_return = VOC(Egap)\n ff = maxpower / (jsc_return * voc_return) \n return [vmpp, jmpp, maxpower, max_eff, ff, jsc_return, voc_return]\n\n\n maxpcemeta = V_mpp_Jmpp_maxpower_maxeff_ff(bandgap)\n\n self.ui.textBrowser.append(str('For Bandgap = %.3f eV, TCell = %.3f K:\\nJSC = %.3f mA/cm^2\\nVOC = %.3f V\\nFF = %.3f\\nPCE = %.3f' % (bandgap, Tcell, maxpcemeta[5], maxpcemeta[6],maxpcemeta[4], maxpcemeta[3] * 100)))\n\n if plot_bandgap_array == True:\n \n pce_array = np.empty_like(bandgap_array)\n ff_array = np.empty_like(bandgap_array)\n voc_array = np.empty_like(bandgap_array)\n jsc_array = np.empty_like(bandgap_array)\n for i in range(len(bandgap_array)):\n metadata = V_mpp_Jmpp_maxpower_maxeff_ff(bandgap_array[i])\n pce_array[i] = metadata[3] \n ff_array[i] = metadata[4]\n voc_array[i] = metadata[6]\n jsc_array[i] = metadata[5]\n \n self.out_array = np.array((bandgap_array,pce_array,ff_array, voc_array,jsc_array)).T\n \n plt.figure(figsize=(5,4))\n plt.title('Cell Temperature = %.2f K' %(Tcell))\n plt.xlim(bandgap_array[0], bandgap_array[len(bandgap_array) - 1])\n plt.ylabel('PCE (%)')\n plt.xlabel('Bandgap (eV)')\n plt.plot(bandgap_array, pce_array * 100)\n plt.tight_layout()\n plt.show()\n\n plt.figure(figsize=(5,4))\n plt.title('Cell Temperature = %.2f K' %(Tcell))\n plt.ylim(0, 1)\n plt.xlim(bandgap_array[0], bandgap_array[len(bandgap_array) - 1])\n plt.ylabel('Fill Factor')\n plt.xlabel('Bandgap (eV)')\n plt.plot(bandgap_array, ff_array)\n plt.tight_layout()\n plt.show()\n\n plt.figure(figsize=(5,4))\n plt.title('Cell Temperature = %.2f K' %(Tcell))\n plt.xlim(bandgap_array[0], bandgap_array[len(bandgap_array) - 1])\n plt.ylabel('Jsc (mA/cm$^2$)')\n plt.xlabel('Bandgap (eV)')\n plt.plot(bandgap_array, jsc_array)\n plt.tight_layout()\n plt.show()\n\n plt.figure(figsize=(5,4))\n plt.title('Cell Temperature = %.2f K' %(Tcell))\n plt.xlim(bandgap_array[0], bandgap_array[len(bandgap_array) - 1])\n plt.ylabel('Voc (V)')\n plt.xlabel('Bandgap (eV)')\n plt.plot(bandgap_array, voc_array, label = 'S-Q Voc')\n plt.plot(bandgap_array, bandgap_array, '--', label = 'Bandgap')\n plt.legend(loc = 'best')\n plt.tight_layout()\n plt.show()\n\n self.ui.textBrowser.append('--')\n\n else:\n self.ui.textBrowser.append('--')\n\n\n def JV_curve(Egap):\n volt_array = np.linspace(0, VOC(Egap), 200)\n j_array = np.empty_like(volt_array)\n for i in range(len(volt_array)):\n j_array[i] = current_density(volt_array[i], Egap)\n return [volt_array, j_array]\n\n\n if plot_jv == True:\n jv_meta = JV_curve(bandgap)\n v_array = jv_meta[0]\n jv_array = jv_meta[1]\n\n plt.figure(figsize=(5,4))\n plt.ylabel('Current Density (mA/cm$^2$)')\n plt.xlabel('Voltage (V)')\n plt.plot(v_array, -jv_array)\n plt.title('J-V Curve for '+str(self.ui.bandgap_doubleSpinBox.value())+'eV')\n plt.tight_layout()\n plt.show()\n self.ui.textBrowser.append('--')\n else:\n self.ui.textBrowser.append('--')\n \n def save_bandgap_array(self):\n if self.out_array is None:\n self.ui.textBrowser.append(\"Calculate SQ limit before saving file!\")\n else:\n filename = QtWidgets.QFileDialog.getSaveFileName(self)\n np.savetxt(filename[0]+\".txt\", self.out_array, delimiter='\\t', header=\"Bandgap, PCE, FillFactor, Voc, Jsc\")\n\n#def run():\n# win = MainWindow()\n# QtGui.QApplication.instance().exec_()\n# return win\n\n#run()\n\nif __name__ == '__main__':\n appctxt = AppContext() # 1. Instantiate ApplicationContext\n exit_code = appctxt.run()\n sys.exit(exit_code) # 2. Invoke appctxt.app.exec_()"},"apis":{"kind":"string","value":"[((941, 953), 'fbs_runtime.platform.is_windows', 'is_windows', ([], {}), '()\\n', (951, 953), False, 'from fbs_runtime.platform import is_windows, is_mac\\n'), ((959, 983), 'matplotlib.use', 'matplotlib.use', (['\"\"\"Qt5Agg\"\"\"'], {}), \"('Qt5Agg')\\n\", (973, 983), False, 'import matplotlib\\n'), ((989, 997), 'fbs_runtime.platform.is_mac', 'is_mac', ([], {}), '()\\n', (995, 997), False, 'from fbs_runtime.platform import is_windows, is_mac\\n'), ((11431, 11450), 'sys.exit', 'sys.exit', (['exit_code'], {}), '(exit_code)\\n', (11439, 11450), False, 'import sys\\n'), ((1003, 1027), 'matplotlib.use', 'matplotlib.use', (['\"\"\"macosx\"\"\"'], {}), \"('macosx')\\n\", (1017, 1027), False, 'import matplotlib\\n'), ((1214, 1238), 'PyQt5.uic.loadUi', 'uic.loadUi', (['uiFile', 'self'], {}), '(uiFile, self)\\n', (1224, 1238), False, 'from PyQt5 import uic, QtWidgets\\n'), ((1835, 1878), 'PyQt5.QtWidgets.QFileDialog.getOpenFileName', 'QtWidgets.QFileDialog.getOpenFileName', (['self'], {}), '(self)\\n', (1872, 1878), False, 'from PyQt5 import uic, QtWidgets\\n'), ((3815, 3890), 'numpy.linspace', 'np.linspace', (['bandgap_array_min', 'bandgap_array_max', 'num_points_bandgap_array'], {}), '(bandgap_array_min, bandgap_array_max, num_points_bandgap_array)\\n', (3826, 3890), True, 'import numpy as np\\n'), ((4780, 4803), 'scipy.integrate.simps', 'simps', (['am15'], {'x': 'am15_wav'}), '(am15, x=am15_wav)\\n', (4785, 4803), False, 'from scipy.integrate import simps, quad\\n'), ((5097, 5137), 'scipy.integrate.simps', 'simps', (['am15_wats_ev_flip'], {'x': 'am15_ev_flip'}), '(am15_wats_ev_flip, x=am15_ev_flip)\\n', (5102, 5137), False, 'from scipy.integrate import simps, quad\\n'), ((5367, 5405), 'scipy.integrate.simps', 'simps', (['am15_photons_ev'], {'x': 'am15_ev_flip'}), '(am15_photons_ev, x=am15_ev_flip)\\n', (5372, 5405), False, 'from scipy.integrate import simps, quad\\n'), ((5440, 5474), 'scipy.integrate.simps', 'simps', (['am15_photons_nm'], {'x': 'am15_wav'}), '(am15_photons_nm, x=am15_wav)\\n', (5445, 5474), False, 'from scipy.integrate import simps, quad\\n'), ((5517, 5554), 'scipy.interpolate.splrep', 'splrep', (['am15_ev_flip', 'am15_photons_ev'], {}), '(am15_ev_flip, am15_photons_ev)\\n', (5523, 5554), False, 'from scipy.interpolate import splrep, splint\\n'), ((1918, 1959), 'numpy.genfromtxt', 'np.genfromtxt', (['filename[0]'], {'skip_header': '(1)'}), '(filename[0], skip_header=1)\\n', (1931, 1959), True, 'import numpy as np\\n'), ((4033, 4090), 'numpy.loadtxt', 'np.loadtxt', (['self.astmg173_file'], {'delimiter': '\"\"\",\"\"\"', 'skiprows': '(2)'}), \"(self.astmg173_file, delimiter=',', skiprows=2)\\n\", (4043, 4090), True, 'import numpy as np\\n'), ((4118, 4143), 'numpy.copy', 'np.copy', (['astmg173[:, (0)]'], {}), '(astmg173[:, (0)])\\n', (4125, 4143), True, 'import numpy as np\\n'), ((4189, 4214), 'numpy.copy', 'np.copy', (['astmg173[:, (2)]'], {}), '(astmg173[:, (2)])\\n', (4196, 4214), True, 'import numpy as np\\n'), ((5730, 5776), 'scipy.interpolate.splint', 'splint', (['Egap', 'emax', 'total_photonflux_ev_splrep'], {}), '(Egap, emax, total_photonflux_ev_splrep)\\n', (5736, 5776), False, 'from scipy.interpolate import splrep, splint\\n'), ((7715, 7743), 'numpy.empty_like', 'np.empty_like', (['bandgap_array'], {}), '(bandgap_array)\\n', (7728, 7743), True, 'import numpy as np\\n'), ((7767, 7795), 'numpy.empty_like', 'np.empty_like', (['bandgap_array'], {}), '(bandgap_array)\\n', (7780, 7795), True, 'import numpy as np\\n'), ((7820, 7848), 'numpy.empty_like', 'np.empty_like', (['bandgap_array'], {}), '(bandgap_array)\\n', (7833, 7848), True, 'import numpy as np\\n'), ((7873, 7901), 'numpy.empty_like', 'np.empty_like', (['bandgap_array'], {}), '(bandgap_array)\\n', (7886, 7901), True, 'import numpy as np\\n'), ((8332, 8358), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\\n', (8342, 8358), True, 'import matplotlib.pyplot as plt\\n'), ((8370, 8416), 'matplotlib.pyplot.title', 'plt.title', ([\"('Cell Temperature = %.2f K' % Tcell)\"], {}), \"('Cell Temperature = %.2f K' % Tcell)\\n\", (8379, 8416), True, 'import matplotlib.pyplot as plt\\n'), ((8508, 8529), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['\"\"\"PCE (%)\"\"\"'], {}), \"('PCE (%)')\\n\", (8518, 8529), True, 'import matplotlib.pyplot as plt\\n'), ((8542, 8568), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['\"\"\"Bandgap (eV)\"\"\"'], {}), \"('Bandgap (eV)')\\n\", (8552, 8568), True, 'import matplotlib.pyplot as plt\\n'), ((8581, 8621), 'matplotlib.pyplot.plot', 'plt.plot', (['bandgap_array', '(pce_array * 100)'], {}), '(bandgap_array, pce_array * 100)\\n', (8589, 8621), True, 'import matplotlib.pyplot as plt\\n'), ((8634, 8652), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\\n', (8650, 8652), True, 'import matplotlib.pyplot as plt\\n'), ((8665, 8675), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\\n', (8673, 8675), True, 'import matplotlib.pyplot as plt\\n'), ((8689, 8715), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\\n', (8699, 8715), True, 'import matplotlib.pyplot as plt\\n'), ((8727, 8773), 'matplotlib.pyplot.title', 'plt.title', ([\"('Cell Temperature = %.2f K' % Tcell)\"], {}), \"('Cell Temperature = %.2f K' % Tcell)\\n\", (8736, 8773), True, 'import matplotlib.pyplot as plt\\n'), ((8787, 8801), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\\n', (8795, 8801), True, 'import matplotlib.pyplot as plt\\n'), ((8892, 8917), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['\"\"\"Fill Factor\"\"\"'], {}), \"('Fill Factor')\\n\", (8902, 8917), True, 'import matplotlib.pyplot as plt\\n'), ((8930, 8956), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['\"\"\"Bandgap (eV)\"\"\"'], {}), \"('Bandgap (eV)')\\n\", (8940, 8956), True, 'import matplotlib.pyplot as plt\\n'), ((8969, 9002), 'matplotlib.pyplot.plot', 'plt.plot', (['bandgap_array', 'ff_array'], {}), '(bandgap_array, ff_array)\\n', (8977, 9002), True, 'import matplotlib.pyplot as plt\\n'), ((9015, 9033), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\\n', (9031, 9033), True, 'import matplotlib.pyplot as plt\\n'), ((9046, 9056), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\\n', (9054, 9056), True, 'import matplotlib.pyplot as plt\\n'), ((9070, 9096), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\\n', (9080, 9096), True, 'import matplotlib.pyplot as plt\\n'), ((9108, 9154), 'matplotlib.pyplot.title', 'plt.title', ([\"('Cell Temperature = %.2f K' % Tcell)\"], {}), \"('Cell Temperature = %.2f K' % Tcell)\\n\", (9117, 9154), True, 'import matplotlib.pyplot as plt\\n'), ((9246, 9275), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['\"\"\"Jsc (mA/cm$^2$)\"\"\"'], {}), \"('Jsc (mA/cm$^2$)')\\n\", (9256, 9275), True, 'import matplotlib.pyplot as plt\\n'), ((9288, 9314), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['\"\"\"Bandgap (eV)\"\"\"'], {}), \"('Bandgap (eV)')\\n\", (9298, 9314), True, 'import matplotlib.pyplot as plt\\n'), ((9327, 9361), 'matplotlib.pyplot.plot', 'plt.plot', (['bandgap_array', 'jsc_array'], {}), '(bandgap_array, jsc_array)\\n', (9335, 9361), True, 'import matplotlib.pyplot as plt\\n'), ((9374, 9392), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\\n', (9390, 9392), True, 'import matplotlib.pyplot as plt\\n'), ((9405, 9415), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\\n', (9413, 9415), True, 'import matplotlib.pyplot as plt\\n'), ((9429, 9455), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\\n', (9439, 9455), True, 'import matplotlib.pyplot as plt\\n'), ((9467, 9513), 'matplotlib.pyplot.title', 'plt.title', ([\"('Cell Temperature = %.2f K' % Tcell)\"], {}), \"('Cell Temperature = %.2f K' % Tcell)\\n\", (9476, 9513), True, 'import matplotlib.pyplot as plt\\n'), ((9605, 9626), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['\"\"\"Voc (V)\"\"\"'], {}), \"('Voc (V)')\\n\", (9615, 9626), True, 'import matplotlib.pyplot as plt\\n'), ((9639, 9665), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['\"\"\"Bandgap (eV)\"\"\"'], {}), \"('Bandgap (eV)')\\n\", (9649, 9665), True, 'import matplotlib.pyplot as plt\\n'), ((9678, 9729), 'matplotlib.pyplot.plot', 'plt.plot', (['bandgap_array', 'voc_array'], {'label': '\"\"\"S-Q Voc\"\"\"'}), \"(bandgap_array, voc_array, label='S-Q Voc')\\n\", (9686, 9729), True, 'import matplotlib.pyplot as plt\\n'), ((9744, 9805), 'matplotlib.pyplot.plot', 'plt.plot', (['bandgap_array', 'bandgap_array', '\"\"\"--\"\"\"'], {'label': '\"\"\"Bandgap\"\"\"'}), \"(bandgap_array, bandgap_array, '--', label='Bandgap')\\n\", (9752, 9805), True, 'import matplotlib.pyplot as plt\\n'), ((9820, 9842), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '\"\"\"best\"\"\"'}), \"(loc='best')\\n\", (9830, 9842), True, 'import matplotlib.pyplot as plt\\n'), ((9857, 9875), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\\n', (9873, 9875), True, 'import matplotlib.pyplot as plt\\n'), ((9888, 9898), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\\n', (9896, 9898), True, 'import matplotlib.pyplot as plt\\n'), ((10113, 10138), 'numpy.empty_like', 'np.empty_like', (['volt_array'], {}), '(volt_array)\\n', (10126, 10138), True, 'import numpy as np\\n'), ((10441, 10467), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\\n', (10451, 10467), True, 'import matplotlib.pyplot as plt\\n'), ((10479, 10520), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['\"\"\"Current Density (mA/cm$^2$)\"\"\"'], {}), \"('Current Density (mA/cm$^2$)')\\n\", (10489, 10520), True, 'import matplotlib.pyplot as plt\\n'), ((10533, 10558), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['\"\"\"Voltage (V)\"\"\"'], {}), \"('Voltage (V)')\\n\", (10543, 10558), True, 'import matplotlib.pyplot as plt\\n'), ((10571, 10599), 'matplotlib.pyplot.plot', 'plt.plot', (['v_array', '(-jv_array)'], {}), '(v_array, -jv_array)\\n', (10579, 10599), True, 'import matplotlib.pyplot as plt\\n'), ((10700, 10718), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\\n', (10716, 10718), True, 'import matplotlib.pyplot as plt\\n'), ((10731, 10741), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\\n', (10739, 10741), True, 'import matplotlib.pyplot as plt\\n'), ((11038, 11081), 'PyQt5.QtWidgets.QFileDialog.getSaveFileName', 'QtWidgets.QFileDialog.getSaveFileName', (['self'], {}), '(self)\\n', (11075, 11081), False, 'from PyQt5 import uic, QtWidgets\\n'), ((11094, 11208), 'numpy.savetxt', 'np.savetxt', ([\"(filename[0] + '.txt')\", 'self.out_array'], {'delimiter': '\"\"\"\\t\"\"\"', 'header': '\"\"\"Bandgap, PCE, FillFactor, Voc, Jsc\"\"\"'}), \"(filename[0] + '.txt', self.out_array, delimiter='\\\\t', header=\\n 'Bandgap, PCE, FillFactor, Voc, Jsc')\\n\", (11104, 11208), True, 'import numpy as np\\n'), ((4351, 4376), 'numpy.copy', 'np.copy', (['astmg173[:, (0)]'], {}), '(astmg173[:, (0)])\\n', (4358, 4376), True, 'import numpy as np\\n'), ((4427, 4452), 'numpy.copy', 'np.copy', (['astmg173[:, (1)]'], {}), '(astmg173[:, (1)])\\n', (4434, 4452), True, 'import numpy as np\\n'), ((5920, 5962), 'scipy.integrate.quad', 'quad', (['integrand', 'Egap', 'emax'], {'full_output': '(1)'}), '(integrand, Egap, emax, full_output=1)\\n', (5924, 5962), False, 'from scipy.integrate import simps, quad\\n'), ((6798, 6847), 'scipy.optimize.fmin', 'fmin', (['func_to_minimize', 'initial_guess'], {'disp': '(False)'}), '(func_to_minimize, initial_guess, disp=False)\\n', (6802, 6847), False, 'from scipy.optimize import fmin\\n'), ((8239, 8307), 'numpy.array', 'np.array', (['(bandgap_array, pce_array, ff_array, voc_array, jsc_array)'], {}), '((bandgap_array, pce_array, ff_array, voc_array, jsc_array))\\n', (8247, 8307), True, 'import numpy as np\\n'), ((4527, 4656), 'PyQt5.QtWidgets.QMessageBox.information', 'QMessageBox.information', (['self', 'None', '(\\'No valid spectrum file found!\\\\n\\\\n\\' +\\n \"Load a valid file or check the \\'Use ASTMG173\\'box\")'], {}), '(self, None, \\'No valid spectrum file found!\\\\n\\\\n\\' +\\n \"Load a valid file or check the \\'Use ASTMG173\\'box\")\\n', (4550, 4656), False, 'from PyQt5.QtWidgets import QMessageBox\\n'), ((5863, 5891), 'numpy.exp', 'np.exp', (['(eV / (kb_ev * Tcell))'], {}), '(eV / (kb_ev * Tcell))\\n', (5869, 5891), True, 'import numpy as np\\n'), ((6306, 6333), 'numpy.exp', 'np.exp', (['(V / (kb_ev * Tcell))'], {}), '(V / (kb_ev * Tcell))\\n', (6312, 6333), True, 'import numpy as np\\n')]"}}},{"rowIdx":8475,"cells":{"repo_name":{"kind":"string","value":"tov101/HelpUs"},"repo_path":{"kind":"string","value":"helpus/core.py"},"repo_head_hexsha":{"kind":"string","value":"6b53d9651cf45c191774be2f70b70b130251d2a6"},"content":{"kind":"string","value":"import io\nimport logging\nimport os\nimport sys\n\nfrom PyQt5 import QtGui, QtCore, QtWidgets\nfrom helpus import icon_file_path\nfrom helpus import __version__\n\nLOGGER = logging.getLogger('HelpUs')\nLOGGER.setLevel(logging.DEBUG)\n\n\nclass XStream(QtCore.QObject):\n _stdout = None\n _stderr = None\n messageWritten = QtCore.pyqtSignal(str)\n\n @staticmethod\n def flush():\n pass\n\n @staticmethod\n def fileno():\n return -1\n\n def write(self, msg):\n if not self.signalsBlocked():\n self.messageWritten.emit(msg)\n\n @staticmethod\n def stdout():\n if not XStream._stdout:\n XStream._stdout = XStream()\n sys.stdout = XStream._stdout\n return XStream._stdout\n\n @staticmethod\n def stderr():\n if not XStream._stderr:\n XStream._stderr = XStream()\n sys.stderr = XStream._stderr\n return XStream._stderr\n\n\nclass MyBreakPoint(QtWidgets.QDialog):\n _stdout = None\n _stderr = None\n messageWritten = QtCore.pyqtSignal(str)\n\n HOOK_HEADER = '(Pdb) '\n HOOK_INTERACT = '>>> '\n HOOK_LINE_BREAK = '... '\n HOOKS = [HOOK_HEADER, HOOK_INTERACT]\n\n BUTTONS = [\n 'Continue',\n 'Next',\n 'Step',\n 'Where',\n 'Up',\n 'Down'\n ]\n\n def __init__(self, parent=None):\n super().__init__()\n\n if not parent:\n self.parentWidget = QtWidgets.QMainWindow()\n else:\n self.parentWidget = parent\n\n # Change Window Modality, otherwise parentWidget won't let you use this widget\n if self.parentWidget.windowModality() == QtCore.Qt.WindowModality.ApplicationModal:\n self.parentWidget.hide()\n self.parentWidget.setWindowModality(QtCore.Qt.WindowModality.NonModal)\n self.parentWidget.showNormal()\n\n # Set Icon\n if icon_file_path and os.path.exists(icon_file_path):\n self.setWindowIcon(QtGui.QIcon(icon_file_path))\n\n # Set Flags\n self.setWindowFlags(\n QtCore.Qt.WindowSystemMenuHint |\n QtCore.Qt.WindowTitleHint |\n QtCore.Qt.WindowCloseButtonHint\n )\n\n # Resize\n self.resize(513, 300)\n\n # Create Layout\n self.main_layout = QtWidgets.QHBoxLayout()\n self.setLayout(self.main_layout)\n self.setWindowTitle(\"HelpUs {}\".format(__version__))\n\n # Create Content Layouts\n self.ConsoleLayout = QtWidgets.QVBoxLayout()\n self.ButtonsLayout = QtWidgets.QVBoxLayout()\n self.main_layout.addLayout(self.ButtonsLayout)\n self.main_layout.addLayout(self.ConsoleLayout)\n\n # Create OutputConsole\n self.console = QtWidgets.QTextEdit(parent)\n self.console.insertPlainText = self.__insert_plain_text\n self.console.keyPressEvent = self.__key_press_event\n self.ConsoleLayout.addWidget(self.console)\n\n # Create buttons\n for button_text in self.BUTTONS:\n # Create Button Name\n button_name = 'button_%s' % button_text.lower()\n setattr(self, button_name, QtWidgets.QPushButton(button_text))\n getattr(self, button_name).clicked.connect(self.__push_button)\n\n # Add Button to Widget\n self.ButtonsLayout.addWidget(getattr(self, button_name))\n\n # Init Buffer\n self.buffer = io.StringIO()\n self.__set_enable_gui(False)\n self.showNormal()\n\n def __set_enable_gui(self, state=True):\n \"\"\"\n\n :param state:\n :return:\n \"\"\"\n self.console.setEnabled(state)\n for button_text in self.BUTTONS:\n # Get Button Name\n button_name = 'button_%s' % button_text.lower()\n getattr(self, button_name).setEnabled(state)\n if state:\n self.console.setFocus()\n\n def redirect_outerr_stream(self):\n \"\"\"\n\n :return:\n \"\"\"\n # Link Stream Output\n XStream.stdout().messageWritten.connect(self.console.insertPlainText)\n XStream.stderr().messageWritten.connect(self.console.insertPlainText)\n\n def readline(self):\n \"\"\"\n\n :return:\n \"\"\"\n if not self.console.isEnabled():\n self.__set_enable_gui(True)\n # Reset Buffer\n self.__reset_buffer()\n # Check Position\n while self.buffer.tell() == 0:\n QtCore.QCoreApplication.processEvents()\n value = self.buffer.getvalue()\n return value\n\n def __key_press_event(self, event):\n \"\"\"\n\n :param event:\n :return:\n \"\"\"\n # Get Last Line\n document = self.console.document()\n line_index = document.lineCount()\n raw_last_line = document.findBlockByLineNumber(line_index - 1).text()\n\n text = ''\n current_hook = ''\n # Exclude first 6 chars: (Pdb)\\s\n if raw_last_line:\n for hook in self.HOOKS:\n if raw_last_line.startswith(hook):\n current_hook = hook\n text = raw_last_line[len(hook):]\n break\n else:\n text = raw_last_line\n\n # Get Cursor position\n line_from_zero = line_index - 1\n current_cursor_line = self.console.textCursor().blockNumber()\n current_cursor_column = self.console.textCursor().columnNumber()\n\n # If Enter was pressed -> Process Expression\n if event.key() == QtCore.Qt.Key.Key_Return and text:\n # Consider Custom Clear Screen Command\n if text == 'cls':\n self.__clear_screen(raw_last_line)\n return\n\n # Replace Line Break with Enter\n if self.HOOK_LINE_BREAK == text:\n text = '\\r\\n'\n elif self.HOOK_LINE_BREAK in text:\n # Replace Line Break with tab\n text = text.replace(self.HOOK_LINE_BREAK, '\\t')\n current_hook = self.HOOK_LINE_BREAK\n\n self.__reset_buffer()\n self.buffer.write(text)\n self.__set_enable_gui(False)\n\n # If User want to delete something and there is no value in buffer -> Reject\n if event.key() == QtCore.Qt.Key.Key_Backspace or event.key() == QtCore.Qt.Key.Key_Delete:\n if current_cursor_line != line_from_zero or current_cursor_column <= len(current_hook):\n return\n\n if event.key() == QtCore.Qt.Key.Key_Home and current_cursor_line == line_from_zero:\n if text:\n temp_cursor = self.console.textCursor()\n temp_cursor.movePosition(\n QtGui.QTextCursor.MoveOperation.StartOfLine,\n QtGui.QTextCursor.MoveMode.MoveAnchor\n )\n temp_cursor.movePosition(\n QtGui.QTextCursor.MoveOperation.Right,\n QtGui.QTextCursor.MoveMode.MoveAnchor,\n len(current_hook)\n )\n self.console.setTextCursor(temp_cursor)\n return\n\n # Set Console Text to Black\n self.console.setTextColor(QtCore.Qt.GlobalColor.black)\n # Execute default method\n QtWidgets.QTextEdit.keyPressEvent(self.console, event)\n\n def __push_button(self):\n # Read text from Button and use it as pdb keyword\n button_scope = self.sender().text().lower()\n self.__reset_buffer()\n self.buffer.write(button_scope)\n self.__set_enable_gui(False)\n\n def __reset_buffer(self):\n if isinstance(self.buffer, io.StringIO):\n # Clear Buffer\n self.buffer.truncate(0)\n self.buffer.seek(0)\n else:\n self.buffer = io.StringIO()\n\n def __insert_plain_text(self, message):\n # Do some stylistics\n if message.startswith(self.HOOK_HEADER):\n self.console.setTextColor(QtCore.Qt.GlobalColor.magenta)\n QtWidgets.QTextEdit.insertPlainText(self.console, message)\n return\n elif message.startswith(self.HOOK_INTERACT):\n self.console.setTextColor(QtCore.Qt.GlobalColor.darkMagenta)\n QtWidgets.QTextEdit.insertPlainText(self.console, message)\n return\n\n if message.startswith('***'):\n self.console.setTextColor(QtCore.Qt.GlobalColor.red)\n\n QtWidgets.QTextEdit.insertPlainText(self.console, message)\n # AutoScroll\n self.console.verticalScrollBar().setValue(self.console.verticalScrollBar().maximum())\n\n def __clear_screen(self, text):\n current_hook = text\n for hook in self.HOOKS:\n if hook in current_hook:\n current_hook = hook\n break\n self.console.clear()\n self.console.insertPlainText(current_hook)\n\n\ndef get_qtconsole_object():\n if isinstance(sys.stdin, MyBreakPoint):\n return sys.stdin.console\n else:\n return MyBreakPoint.console\n\n\ndef setup_breakpoint_hook(parent, method, redirect_streams=False):\n def __method(*args, **kwargs):\n breakpoint()\n return method(*args, **kwargs)\n\n if not isinstance(sys.stdin, MyBreakPoint):\n sys.stdin = MyBreakPoint(parent)\n else:\n # Restore Streams\n sys.stdin = sys.__stdin__\n sys.stdout = sys.__stdout__\n sys.stderr = sys.__stderr__\n raise Exception(\n \"Multiple Instances are not allowed. Can be possible, but I'm to lazy to go deep with development.\"\n )\n\n if redirect_streams:\n sys.stdin.redirect_outerr_stream()\n return __method\n\n\nif __name__ == '__main__':\n p = QtWidgets.QApplication(sys.argv)\n LOGGER.error('Ceva')\n\n LOGGER.error = setup_breakpoint_hook(None, LOGGER.error, redirect_streams=True)\n # LOGGER.error = setup_breakpoint_hook(None, LOGGER.error, redirect_streams=True)\n\n x = 90\n LOGGER.error('Altceva')\n\n print(x)\n"},"apis":{"kind":"string","value":"[((165, 192), 'logging.getLogger', 'logging.getLogger', (['\"\"\"HelpUs\"\"\"'], {}), \"('HelpUs')\\n\", (182, 192), False, 'import logging\\n'), ((316, 338), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['str'], {}), '(str)\\n', (333, 338), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((1012, 1034), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['str'], {}), '(str)\\n', (1029, 1034), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((9549, 9581), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\\n', (9571, 9581), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((2253, 2276), 'PyQt5.QtWidgets.QHBoxLayout', 'QtWidgets.QHBoxLayout', ([], {}), '()\\n', (2274, 2276), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((2442, 2465), 'PyQt5.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\\n', (2463, 2465), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((2495, 2518), 'PyQt5.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\\n', (2516, 2518), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((2684, 2711), 'PyQt5.QtWidgets.QTextEdit', 'QtWidgets.QTextEdit', (['parent'], {}), '(parent)\\n', (2703, 2711), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((3347, 3360), 'io.StringIO', 'io.StringIO', ([], {}), '()\\n', (3358, 3360), False, 'import io\\n'), ((7139, 7193), 'PyQt5.QtWidgets.QTextEdit.keyPressEvent', 'QtWidgets.QTextEdit.keyPressEvent', (['self.console', 'event'], {}), '(self.console, event)\\n', (7172, 7193), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((8281, 8339), 'PyQt5.QtWidgets.QTextEdit.insertPlainText', 'QtWidgets.QTextEdit.insertPlainText', (['self.console', 'message'], {}), '(self.console, message)\\n', (8316, 8339), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((9457, 9491), 'sys.stdin.redirect_outerr_stream', 'sys.stdin.redirect_outerr_stream', ([], {}), '()\\n', (9489, 9491), False, 'import sys\\n'), ((1402, 1425), 'PyQt5.QtWidgets.QMainWindow', 'QtWidgets.QMainWindow', ([], {}), '()\\n', (1423, 1425), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((1872, 1902), 'os.path.exists', 'os.path.exists', (['icon_file_path'], {}), '(icon_file_path)\\n', (1886, 1902), False, 'import os\\n'), ((4357, 4396), 'PyQt5.QtCore.QCoreApplication.processEvents', 'QtCore.QCoreApplication.processEvents', ([], {}), '()\\n', (4394, 4396), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((7656, 7669), 'io.StringIO', 'io.StringIO', ([], {}), '()\\n', (7667, 7669), False, 'import io\\n'), ((7874, 7932), 'PyQt5.QtWidgets.QTextEdit.insertPlainText', 'QtWidgets.QTextEdit.insertPlainText', (['self.console', 'message'], {}), '(self.console, message)\\n', (7909, 7932), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((1935, 1962), 'PyQt5.QtGui.QIcon', 'QtGui.QIcon', (['icon_file_path'], {}), '(icon_file_path)\\n', (1946, 1962), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((3086, 3120), 'PyQt5.QtWidgets.QPushButton', 'QtWidgets.QPushButton', (['button_text'], {}), '(button_text)\\n', (3107, 3120), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n'), ((8090, 8148), 'PyQt5.QtWidgets.QTextEdit.insertPlainText', 'QtWidgets.QTextEdit.insertPlainText', (['self.console', 'message'], {}), '(self.console, message)\\n', (8125, 8148), False, 'from PyQt5 import QtGui, QtCore, QtWidgets\\n')]"}}},{"rowIdx":8476,"cells":{"repo_name":{"kind":"string","value":"newgene/biothings.api"},"repo_path":{"kind":"string","value":"biothings/hub/dataindex/indexer_schedule.py"},"repo_head_hexsha":{"kind":"string","value":"e3278695ac15a55fe420aa49c464946f81ec019d"},"content":{"kind":"string","value":"import math\n\n\nclass Schedule():\n\n def __init__(self, total, batch_size):\n self._batch_size = batch_size\n self._state = \"\"\n\n self.total = total\n self.scheduled = 0\n self.finished = 0\n\n @property\n def _batch(self):\n return math.ceil(self.scheduled / self._batch_size)\n\n @property\n def _batches(self):\n return math.ceil(self.total / self._batch_size)\n\n @property\n def _percentage(self):\n _percentage = self.scheduled / self.total * 100\n return \"%.1f%%\" % _percentage\n\n def suffix(self, string):\n return \" \".join((\n string,\n \"#%d/%d %s\" %\n (\n self._batch,\n self._batches,\n self._percentage\n )\n ))\n\n def completed(self):\n if self.finished != self.total:\n raise ValueError(self.finished, self.total)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.scheduled >= self.total:\n self._state = \"pending, waiting for completion,\"\n raise StopIteration()\n self.scheduled += self._batch_size\n if self.scheduled > self.total:\n self.scheduled = self.total\n self._state = self.suffix(\"running, on batch\") + \",\"\n return self._batch\n\n def __str__(self):\n return \" \".join(f\"\"\"\n = self.total else self._state}\n total={self.total} scheduled={self.scheduled} finished={self.finished}>\n \"\"\".split())\n\ndef test_01():\n schedule = Schedule(100, 10)\n for batch in schedule:\n print(batch)\n print(schedule)\n\ndef test_02():\n schedule = Schedule(25, 10)\n for batch in schedule:\n print(batch)\n print(schedule)\n print(schedule.suffix(\"Task\"))\n\ndef test_03():\n schedule = Schedule(0, 10)\n for batch in schedule:\n print(batch)\n print(schedule)\n print(schedule.suffix(\"Task\"))\n\ndef test_04():\n schedule = Schedule(1, 10)\n for batch in schedule:\n print(batch)\n print(schedule)\n print(schedule.suffix(\"Task\"))\n\n\nif __name__ == \"__main__\":\n test_02()\n"},"apis":{"kind":"string","value":"[((272, 316), 'math.ceil', 'math.ceil', (['(self.scheduled / self._batch_size)'], {}), '(self.scheduled / self._batch_size)\\n', (281, 316), False, 'import math\\n'), ((371, 411), 'math.ceil', 'math.ceil', (['(self.total / self._batch_size)'], {}), '(self.total / self._batch_size)\\n', (380, 411), False, 'import math\\n')]"}}},{"rowIdx":8477,"cells":{"repo_name":{"kind":"string","value":"voBits/ccxt"},"repo_path":{"kind":"string","value":"examples/py/async-basic.py"},"repo_head_hexsha":{"kind":"string","value":"edd2dd92053bd06232769a63465a43912b21eda0"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\nimport asyncio\nimport os\nimport sys\n\nroot = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nsys.path.append(root + '/python')\n\nimport ccxt.async as ccxt # noqa: E402\n\n\nasync def test_gdax():\n gdax = ccxt.gdax()\n markets = await gdax.load_markets()\n await gdax.close()\n return markets\n\nif __name__ == '__main__':\n print(asyncio.get_event_loop().run_until_complete(test_gdax()))\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8478,"cells":{"repo_name":{"kind":"string","value":"bennettdc/MCEdit-Unified"},"repo_path":{"kind":"string","value":"pymclevel/test/__init__.py"},"repo_head_hexsha":{"kind":"string","value":"90abfb170c65b877ac67193e717fa3a3ded635dd"},"content":{"kind":"string","value":"__author__ = 'Rio'\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8479,"cells":{"repo_name":{"kind":"string","value":"ethz-asl/modular_semantic_segmentation"},"repo_path":{"kind":"string","value":"xview/datasets/wrapper.py"},"repo_head_hexsha":{"kind":"string","value":"7c950f24df11540a7ddae4ff806d5b31934a3210"},"content":{"kind":"string","value":"from abc import ABCMeta, abstractmethod\n\n\nclass DataWrapper:\n \"\"\"Interface for access to datasets.\"\"\"\n\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def next(self):\n \"\"\"Returns next minibatch for training.\"\"\"\n return NotImplementedError\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8480,"cells":{"repo_name":{"kind":"string","value":"jrbourbeau/partd"},"repo_path":{"kind":"string","value":"partd/core.py"},"repo_head_hexsha":{"kind":"string","value":"74016a296a760de9c7a0e0d4b012a3478c9a0831"},"content":{"kind":"string","value":"from __future__ import absolute_import\n\nimport os\nimport shutil\nimport locket\nimport string\nfrom toolz import memoize\nfrom contextlib import contextmanager\nfrom .utils import nested_get, flatten\n\n\n\n# http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python\nvalid_chars = \"-_.() \" + string.ascii_letters + string.digits + os.path.sep\n\n\ndef escape_filename(fn):\n \"\"\" Escape text so that it is a valid filename\n\n >>> escape_filename('Foo!bar?')\n 'Foobar'\n\n \"\"\"\n return ''.join(filter(valid_chars.__contains__, fn))\n\n\ndef filename(path, key):\n return os.path.join(path, escape_filename(token(key)))\n\n\ndef token(key):\n \"\"\"\n\n >>> token('hello')\n 'hello'\n >>> token(('hello', 'world')) # doctest: +SKIP\n 'hello/world'\n \"\"\"\n if isinstance(key, str):\n return key\n elif isinstance(key, tuple):\n return os.path.join(*map(token, key))\n else:\n return str(key)\n\n\nclass Interface(object):\n def __init__(self):\n self._iset_seen = set()\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n self._iset_seen = set()\n\n def iset(self, key, value, **kwargs):\n if key in self._iset_seen:\n return\n else:\n self._iset(key, value, **kwargs)\n self._iset_seen.add(key)\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.drop()\n\n def iget(self, key):\n return self._get([key], lock=False)[0]\n\n def get(self, keys, **kwargs):\n if not isinstance(keys, list):\n return self.get([keys], **kwargs)[0]\n elif any(isinstance(key, list) for key in keys): # nested case\n flatkeys = list(flatten(keys))\n result = self.get(flatkeys, **kwargs)\n return nested_get(keys, dict(zip(flatkeys, result)))\n else:\n return self._get(keys, **kwargs)\n\n def delete(self, keys, **kwargs):\n if not isinstance(keys, list):\n return self._delete([keys], **kwargs)\n else:\n return self._delete(keys, **kwargs)\n\n def pop(self, keys, **kwargs):\n with self.partd.lock:\n result = self.partd.get(keys, lock=False)\n self.partd.delete(keys, lock=False)\n return result\n\n"},"apis":{"kind":"string","value":"[]"}}},{"rowIdx":8481,"cells":{"repo_name":{"kind":"string","value":"VITA-Group/Adv-SS-Pretraining"},"repo_path":{"kind":"string","value":"pretraining/model_ensemble.py"},"repo_head_hexsha":{"kind":"string","value":"4ffbebea582f858ec6165f082f52ded1fc9b817d"},"content":{"kind":"string","value":"'''\r\nmodel ensemble for cifar10 // input size(32,32)\r\n'''\r\n\r\n\r\nimport torch\r\nimport torchvision\r\n\r\nimport copy\r\nimport torch.nn as nn\r\nfrom resnetv2 import ResNet50 as resnet50v2\r\n\r\n\r\ndef split_resnet50(model):\r\n return nn.Sequential(\r\n model.conv1,\r\n model.layer1,\r\n model.layer2,\r\n model.layer3\r\n )\r\n\r\n\r\nclass PretrainEnsembleModel(nn.Module):\r\n\r\n def __init__(self):\r\n\r\n super(PretrainEnsembleModel, self).__init__()\r\n\r\n self.blocks = split_resnet50(resnet50v2())\r\n self.layer4_rotation = resnet50v2().layer4 \r\n self.layer4_jigsaw = resnet50v2().layer4\r\n\r\n self.fc_rotation = nn.Linear(2048, 4)\r\n self.fc_jigsaw = nn.Linear(2048, 31)\r\n\r\n self.avgpool1 = nn.AdaptiveAvgPool2d((1,1))\r\n self.avgpool2 = nn.AdaptiveAvgPool2d((1,1))\r\n self.avgpool3 = nn.AdaptiveAvgPool2d((1,1))\r\n\r\n\r\n def _Normal(self,x):\r\n mean=torch.Tensor([0.485, 0.456, 0.406])\r\n mean=mean[None,:,None,None].cuda()\r\n std = torch.Tensor([0.229, 0.224, 0.225])\r\n std = std[None,:,None,None].cuda()\r\n return x.sub(mean).div(std)\r\n\r\n def forward(self, x):\r\n\r\n feature_map = self.blocks(self._Normal(x))\r\n\r\n return feature_map\r\n"},"apis":{"kind":"string","value":"[((224, 292), 'torch.nn.Sequential', 'nn.Sequential', (['model.conv1', 'model.layer1', 'model.layer2', 'model.layer3'], {}), '(model.conv1, model.layer1, model.layer2, model.layer3)\\n', (237, 292), True, 'import torch.nn as nn\\n'), ((652, 670), 'torch.nn.Linear', 'nn.Linear', (['(2048)', '(4)'], {}), '(2048, 4)\\n', (661, 670), True, 'import torch.nn as nn\\n'), ((697, 716), 'torch.nn.Linear', 'nn.Linear', (['(2048)', '(31)'], {}), '(2048, 31)\\n', (706, 716), True, 'import torch.nn as nn\\n'), ((744, 772), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\\n', (764, 772), True, 'import torch.nn as nn\\n'), ((797, 825), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\\n', (817, 825), True, 'import torch.nn as nn\\n'), ((850, 878), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\\n', (870, 878), True, 'import torch.nn as nn\\n'), ((922, 957), 'torch.Tensor', 'torch.Tensor', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\\n', (934, 957), False, 'import torch\\n'), ((1017, 1052), 'torch.Tensor', 'torch.Tensor', (['[0.229, 0.224, 0.225]'], {}), '([0.229, 0.224, 0.225])\\n', (1029, 1052), False, 'import torch\\n'), ((505, 517), 'resnetv2.ResNet50', 'resnet50v2', ([], {}), '()\\n', (515, 517), True, 'from resnetv2 import ResNet50 as resnet50v2\\n'), ((551, 563), 'resnetv2.ResNet50', 'resnet50v2', ([], {}), '()\\n', (561, 563), True, 'from resnetv2 import ResNet50 as resnet50v2\\n'), ((602, 614), 'resnetv2.ResNet50', 'resnet50v2', ([], {}), '()\\n', (612, 614), True, 'from resnetv2 import ResNet50 as resnet50v2\\n')]"}}},{"rowIdx":8482,"cells":{"repo_name":{"kind":"string","value":"glciampaglia/HoaxyBots"},"repo_path":{"kind":"string","value":"scripts/ccdf.py"},"repo_head_hexsha":{"kind":"string","value":"db8d2b7d9927d5d4d94ded125f9785590dace906"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\" Function that implement Complement the Complementary Cumulative\nDistribution Function (CCDF).\n\"\"\"\n#\n# written by Chengcheng Shao \n\nimport numpy as np\nimport pandas as pd\n\n\ndef ccdf(s):\n \"\"\"\n Parameters:\n `s`, series, the values of s should be variable to be handled\n Return:\n a new series `s`, index of s will be X axis (number), value of s\n will be Y axis (probability)\n \"\"\"\n s = s.copy()\n s = s.sort_values(ascending=True, inplace=False)\n s.reset_index(drop=True, inplace=True)\n n = len(s)\n s.drop_duplicates(keep='first', inplace=True)\n X = s.values\n Y = [n - i for i in s.index]\n\n return pd.Series(data=Y, index=X) / n\n\n\ndef sum_cdf(s):\n s = s.copy()\n s = s.value_counts()\n s = s.sort_index(ascending=True)\n cumulative = []\n for i in range(len(s)):\n s0 = s.iloc[:i + 1]\n cumulative.append(np.inner(s0.index, s0.values))\n s = pd.Series(cumulative, index=s.index)\n return s / s.max()\n\n\ndef sum_ccdf(s):\n \"\"\"\n Parameters:\n `s`, series, the values of s should be variable to be handled\n Return:\n a news series `s`, index of s will be X axis (number), values\n will be Y axis (sum(X>=x))\n \"\"\"\n s = s.copy()\n s = s.value_counts()\n s = s.sort_index(ascending=True)\n cumulative = []\n for i in range(len(s)):\n s1 = s.iloc[i:]\n cumulative.append(np.inner(s1.index, s1.values))\n return pd.Series(cumulative, index=s.index)\n"},"apis":{"kind":"string","value":"[((965, 1001), 'pandas.Series', 'pd.Series', (['cumulative'], {'index': 's.index'}), '(cumulative, index=s.index)\\n', (974, 1001), True, 'import pandas as pd\\n'), ((1482, 1518), 'pandas.Series', 'pd.Series', (['cumulative'], {'index': 's.index'}), '(cumulative, index=s.index)\\n', (1491, 1518), True, 'import pandas as pd\\n'), ((696, 722), 'pandas.Series', 'pd.Series', ([], {'data': 'Y', 'index': 'X'}), '(data=Y, index=X)\\n', (705, 722), True, 'import pandas as pd\\n'), ((926, 955), 'numpy.inner', 'np.inner', (['s0.index', 's0.values'], {}), '(s0.index, s0.values)\\n', (934, 955), True, 'import numpy as np\\n'), ((1440, 1469), 'numpy.inner', 'np.inner', (['s1.index', 's1.values'], {}), '(s1.index, s1.values)\\n', (1448, 1469), True, 'import numpy as np\\n')]"}}},{"rowIdx":8483,"cells":{"repo_name":{"kind":"string","value":"eliracho37/lifelines"},"repo_path":{"kind":"string","value":"lifelines/fitters/kaplan_meier_fitter.py"},"repo_head_hexsha":{"kind":"string","value":"b1c6c2732d1ccfc2ae08f7178371d0f95ae3027b"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport numpy as np\nimport pandas as pd\n\nfrom lifelines.fitters import UnivariateFitter\nfrom lifelines.utils import _preprocess_inputs, _additive_estimate, StatError, inv_normal_cdf,\\\n median_survival_times\nfrom lifelines.plotting import plot_loglogs\n\n\nclass KaplanMeierFitter(UnivariateFitter):\n\n \"\"\"\n Class for fitting the Kaplan-Meier estimate for the survival function.\n\n KaplanMeierFitter( alpha=0.95)\n\n alpha: The alpha value associated with the confidence intervals.\n\n \"\"\"\n\n def fit(self, durations, event_observed=None, timeline=None, entry=None, label='KM_estimate',\n alpha=None, left_censorship=False, ci_labels=None):\n \"\"\"\n Parameters:\n duration: an array, or pd.Series, of length n -- duration subject was observed for\n timeline: return the best estimate at the values in timelines (postively increasing)\n event_observed: an array, or pd.Series, of length n -- True if the the death was observed, False if the event\n was lost (right-censored). Defaults all True if event_observed==None\n entry: an array, or pd.Series, of length n -- relative time when a subject entered the study. This is\n useful for left-truncated (not left-censored) observations. If None, all members of the population\n were born at time 0.\n label: a string to name the column of the estimate.\n alpha: the alpha value in the confidence intervals. Overrides the initializing\n alpha for this call to fit only.\n left_censorship: True if durations and event_observed refer to left censorship events. Default False\n ci_labels: add custom column names to the generated confidence intervals\n as a length-2 list: [, ]. Default: