ngram
listlengths
0
67.8k
[ "{ \"url\": repository.url, \"branch\": \"master\" }}) # If it hasn't happened after 30", "table according to it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\",", "frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None: time.sleep(0.5) while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if", "part # of the 'trackedbranches' table according to it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\"))", "\"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0],", "= time.time() + 30 finished = False while not finished and time.time() <", "handled for some reason, that check won't be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={", "hasn't happened after 30 seconds, something must be wrong. deadline = time.time() +", "mail: break logger.error(\"Administrator message: %s\\n > %s\" % (mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise", "logger.error(\"Administrator message: %s\\n > %s\" % (mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise testing.TestFailure else:", "is None: time.sleep(0.5) while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail: break", "frontend.operation(\"addrepository\", data={ \"name\": \"a\" * 65, \"path\": \"validpath2\" }, expect={ \"status\": \"failure\", \"code\":", "}) frontend.operation(\"addrepository\", data={ \"name\": \"a\" * 65, \"path\": \"validpath2\" }, expect={ \"status\": \"failure\",", "if it was 200. if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None: time.sleep(0.5) while True:", "fetched, and # if it's already handled for some reason, that check won't", "rows aren't actually part # of the 'trackedbranches' table according to it. rows", "# repository in the system. frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"),", "not finished: logger.error(\"Repository main branch ('refs/heads/master') not fetched after 30 seconds.\") raise testing.TestFailure", "# if it's already handled for some reason, that check won't be reliable.", "expected_string, inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string", "aren't actually part # of the 'trackedbranches' table according to it. rows =", "\"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\") with frontend.signin(): # Check that", "False while not finished and time.time() < deadline: # The frontend.page() function returns", "Check that /repositories still loads correctly now that there's a # repository in", "actually part # of the 'trackedbranches' table according to it. rows = document.findAll(\"tr\",", "instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\",", "If it hasn't happened after 30 seconds, something must be wrong. deadline =", "correctly now that there's a # repository in the system. frontend.page( \"repositories\", expect={", "\"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\")", "document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would like", "= False while not finished and time.time() < deadline: # The frontend.page() function", "}}) # If it hasn't happened after 30 seconds, something must be wrong.", "already handled for some reason, that check won't be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\",", "if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else: string = cells[0].string if string", "Check that this URL isn't handled already. We're using it later to detect", "that check won't be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\": \"critic\",", "if string is None: string = \"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0],", "len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0],", "\"path\": \"critic\", \"remote\": { \"url\": repository.url, \"branch\": \"master\" }}) # If it hasn't", "check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\",", "string = cells[0].string if string is None: string = \"\" testing.expect.check(expected_string, string) check_cell(rows[0],", "attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\",", "after 30 seconds.\") raise testing.TestFailure # Check that /repositories still loads correctly now", "finished = False while not finished and time.time() < deadline: # The frontend.page()", "repository has been created and the tracked branch fetched, and # if it's", "\"url\": repository.url, \"branch\": \"master\" }}) # If it hasn't happened after 30 seconds,", "it's already handled for some reason, that check won't be reliable. frontend.page(\"critic/master\", expected_http_status=404)", "deadline: # The frontend.page() function returns None if the HTTP status was #", "\"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\")", "'tables[0].findAll()' here, but BeautifulSoup apparently # doesn't parse nested tables correctly, so these", "\"validpath2\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\":", "testing.TestFailure else: finished = True if not finished: logger.error(\"Repository main branch ('refs/heads/master') not", "= rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would like to use 'tables[0].findAll()' here, but", "according to it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\")", "if it's already handled for some reason, that check won't be reliable. frontend.page(\"critic/master\",", "these rows aren't actually part # of the 'trackedbranches' table according to it.", "* 65, \"path\": \"validpath2\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={", "check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1],", "branch fetched, and # if it's already handled for some reason, that check", "\"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\", data={ \"name\": \"a\" * 65, \"path\":", "\"users\", \"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\",", "detect # that the repository has been created and the tracked branch fetched,", "\"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables", "len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else: string = cells[0].string if", "check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\", \"master\")", "= True if not finished: logger.error(\"Repository main branch ('refs/heads/master') not fetched after 30", "deadline = time.time() + 30 finished = False while not finished and time.time()", "= mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail: break logger.error(\"Administrator message: %s\\n > %s\" %", "inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url)", "finished: logger.error(\"Repository main branch ('refs/heads/master') not fetched after 30 seconds.\") raise testing.TestFailure #", "True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail: break logger.error(\"Administrator message: %s\\n >", "u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\", data={ \"name\": \"a\" * 65, \"path\": \"validpath2\" },", "# Would like to use 'tables[0].findAll()' here, but BeautifulSoup apparently # doesn't parse", "= \"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0],", "check won't be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\": \"critic\", \"remote\":", "\"path\": \"validpath2\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\": \"\",", "string = cells[0].findAll(\"i\")[0].string else: string = cells[0].string if string is None: string =", "testing.expect.check(1, len(rows)) def check_cell(row, class_name, expected_string, inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells))", "def check_cell(row, class_name, expected_string, inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type:", "# of the 'trackedbranches' table according to it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2,", "reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\": \"critic\", \"remote\": { \"url\": repository.url,", "URL isn't handled already. We're using it later to detect # that the", "testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would like to use", "'trackedbranches' table according to it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\",", "attrs=testing.expect.with_class(\"repository\")) testing.expect.check(1, len(rows)) def check_cell(row, class_name, expected_string, inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1,", "frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\": \"critic\", \"remote\": { \"url\": repository.url, \"branch\":", "and # if it's already handled for some reason, that check won't be", "We're using it later to detect # that the repository has been created", "time.time() + 30 finished = False while not finished and time.time() < deadline:", "data={ \"name\": \"a\" * 65, \"path\": \"validpath2\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\"", "to detect # that the repository has been created and the tracked branch", "isn't handled already. We're using it later to detect # that the repository", "if not finished: logger.error(\"Repository main branch ('refs/heads/master') not fetched after 30 seconds.\") raise", "the HTTP status was # 404, and a BeautifulSoup object if it was", "testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\", data={ \"name\": \"a\" * 65, \"path\": \"validpath2\"", "len(rows)) def check_cell(row, class_name, expected_string, inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if", "created and the tracked branch fetched, and # if it's already handled for", "break logger.error(\"Administrator message: %s\\n > %s\" % (mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise testing.TestFailure", "\"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\"))", "nested tables correctly, so these rows aren't actually part # of the 'trackedbranches'", "check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\")", "correctly, so these rows aren't actually part # of the 'trackedbranches' table according", "it hasn't happened after 30 seconds, something must be wrong. deadline = time.time()", "None if the HTTP status was # 404, and a BeautifulSoup object if", "and time.time() < deadline: # The frontend.page() function returns None if the HTTP", "fetched after 30 seconds.\") raise testing.TestFailure # Check that /repositories still loads correctly", "BeautifulSoup apparently # doesn't parse nested tables correctly, so these rows aren't actually", "already. We're using it later to detect # that the repository has been", "# that the repository has been created and the tracked branch fetched, and", "frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\": \"critic\", \"remote\": { \"url\": repository.url, \"branch\": \"master\" }})", "for some reason, that check won't be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\":", "message: %s\\n > %s\" % (mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise testing.TestFailure else: finished", "('refs/heads/master') not fetched after 30 seconds.\") raise testing.TestFailure # Check that /repositories still", "that the repository has been created and the tracked branch fetched, and #", "a # repository in the system. frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0,", "repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\") with frontend.signin(): #", "using it later to detect # that the repository has been created and", "frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\", data={", "expected_http_status=[200, 404]) is None: time.sleep(0.5) while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not", "\"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows))", "it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\",", "\"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables))", "\"\\n > \".join(mail.lines))) raise testing.TestFailure else: finished = True if not finished: logger.error(\"Repository", "None: string = \"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" %", "and the tracked branch fetched, and # if it's already handled for some", "raise testing.TestFailure else: finished = True if not finished: logger.error(\"Repository main branch ('refs/heads/master')", "200. if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None: time.sleep(0.5) while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log:", "= cells[0].findAll(\"i\")[0].string else: string = cells[0].string if string is None: string = \"\"", "been created and the tracked branch fetched, and # if it's already handled", "string is None: string = \"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\",", "check_cell(rows[0], \"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\"))", "}, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\": \"validpath1\"", "expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\": \"validpath1\" },", "it was 200. if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None: time.sleep(0.5) while True: mail", "inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else: string = cells[0].string if string is", "parse nested tables correctly, so these rows aren't actually part # of the", "testing.expect.check(1, len(tables)) # Would like to use 'tables[0].findAll()' here, but BeautifulSoup apparently #", "of the 'trackedbranches' table according to it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows))", "function returns None if the HTTP status was # 404, and a BeautifulSoup", "rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url)", "the tracked branch fetched, and # if it's already handled for some reason,", "\"a\" * 65, \"path\": \"validpath2\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\",", "string = \"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname)", "testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\", data={ \"name\": \"a\" * 65,", "apparently # doesn't parse nested tables correctly, so these rows aren't actually part", "> %s\" % (mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise testing.TestFailure else: finished = True", "something must be wrong. deadline = time.time() + 30 finished = False while", "tables correctly, so these rows aren't actually part # of the 'trackedbranches' table", "testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else: string = cells[0].string", "handled already. We're using it later to detect # that the repository has", "\"critic\", \"path\": \"critic\", \"remote\": { \"url\": repository.url, \"branch\": \"master\" }}) # If it", "+ 30 finished = False while not finished and time.time() < deadline: #", "check_cell(rows[1], \"users\", \"\") with frontend.signin(): # Check that this URL isn't handled already.", "\"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1],", "= document.findAll(\"tr\", attrs=testing.expect.with_class(\"repository\")) testing.expect.check(1, len(rows)) def check_cell(row, class_name, expected_string, inline_element_type=None): cells = row.findAll(\"td\",", "that there's a # repository in the system. frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"),", "main branch ('refs/heads/master') not fetched after 30 seconds.\") raise testing.TestFailure # Check that", "mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail: break logger.error(\"Administrator message: %s\\n > %s\"", "time.time() < deadline: # The frontend.page() function returns None if the HTTP status", "check_cell(row, class_name, expected_string, inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1,", "\"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\") with frontend.signin(): # Check that this", "% (mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise testing.TestFailure else: finished = True if not", "returns None if the HTTP status was # 404, and a BeautifulSoup object", "%s\\n > %s\" % (mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise testing.TestFailure else: finished =", "time def check_repository(document): rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"repository\")) testing.expect.check(1, len(rows)) def check_cell(row, class_name, expected_string,", "must be wrong. deadline = time.time() + 30 finished = False while not", "None: time.sleep(0.5) while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail: break logger.error(\"Administrator", "won't be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\": \"critic\", \"remote\": {", "len(tables)) # Would like to use 'tables[0].findAll()' here, but BeautifulSoup apparently # doesn't", "\"repository\": check_repository }) frontend.operation(\"addrepository\", data={ \"name\": \"a\" * 65, \"path\": \"validpath2\" }, expect={", "while not finished and time.time() < deadline: # The frontend.page() function returns None", "\"Yes\") check_cell(rows[1], \"users\", \"\") with frontend.signin(): # Check that this URL isn't handled", "doesn't parse nested tables correctly, so these rows aren't actually part # of", "repository.url, \"branch\": \"master\" }}) # If it hasn't happened after 30 seconds, something", "rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) #", "after 30 seconds, something must be wrong. deadline = time.time() + 30 finished", "that this URL isn't handled already. We're using it later to detect #", "< deadline: # The frontend.page() function returns None if the HTTP status was", "be wrong. deadline = time.time() + 30 finished = False while not finished", "string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows", "with frontend.signin(): # Check that this URL isn't handled already. We're using it", "document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\",", "happened after 30 seconds, something must be wrong. deadline = time.time() + 30", "\"remote\": { \"url\": repository.url, \"branch\": \"master\" }}) # If it hasn't happened after", "in the system. frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository", "30 seconds.\") raise testing.TestFailure # Check that /repositories still loads correctly now that", "rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would like to use 'tables[0].findAll()' here, but BeautifulSoup", "to it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0],", "branch ('refs/heads/master') not fetched after 30 seconds.\") raise testing.TestFailure # Check that /repositories", "cells[0].findAll(\"i\")[0].string else: string = cells[0].string if string is None: string = \"\" testing.expect.check(expected_string,", "it later to detect # that the repository has been created and the", "mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail: break logger.error(\"Administrator message: %s\\n > %s\" % (mail.header(\"Subject\"),", "HTTP status was # 404, and a BeautifulSoup object if it was 200.", "has been created and the tracked branch fetched, and # if it's already", "attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would like to", "seconds.\") raise testing.TestFailure # Check that /repositories still loads correctly now that there's", "check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1],", "else: string = cells[0].string if string is None: string = \"\" testing.expect.check(expected_string, string)", "import time def check_repository(document): rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"repository\")) testing.expect.check(1, len(rows)) def check_cell(row, class_name,", "is None: string = \"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\"", "= cells[0].string if string is None: string = \"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\",", "system. frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\",", "# The frontend.page() function returns None if the HTTP status was # 404,", "class_name, expected_string, inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type)))", "still loads correctly now that there's a # repository in the system. frontend.page(", "seconds, something must be wrong. deadline = time.time() + 30 finished = False", "= row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else:", "\"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\") with frontend.signin(): # Check that this URL isn't", "repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\",", "while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail: break logger.error(\"Administrator message: %s\\n", "reason, that check won't be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\":", "/repositories still loads correctly now that there's a # repository in the system.", "\"critic\", \"remote\": { \"url\": repository.url, \"branch\": \"master\" }}) # If it hasn't happened", "\"master\" }}) # If it hasn't happened after 30 seconds, something must be", "be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\": \"critic\", \"remote\": { \"url\":", "\"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\", data={ \"name\": \"a\" *", "\"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1,", "status was # 404, and a BeautifulSoup object if it was 200. if", "# Check that this URL isn't handled already. We're using it later to", "len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else: string = cells[0].string if string is None: string", "check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\") with", "\"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\",", "\"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\",", "here, but BeautifulSoup apparently # doesn't parse nested tables correctly, so these rows", "30 finished = False while not finished and time.time() < deadline: # The", "to use 'tables[0].findAll()' here, but BeautifulSoup apparently # doesn't parse nested tables correctly,", "finished = True if not finished: logger.error(\"Repository main branch ('refs/heads/master') not fetched after", "was # 404, and a BeautifulSoup object if it was 200. if frontend.page(\"critic/master\",", "rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"repository\")) testing.expect.check(1, len(rows)) def check_cell(row, class_name, expected_string, inline_element_type=None): cells =", "cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string", "check_repository(document): rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"repository\")) testing.expect.check(1, len(rows)) def check_cell(row, class_name, expected_string, inline_element_type=None): cells", "the 'trackedbranches' table according to it. rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0],", "raise testing.TestFailure # Check that /repositories still loads correctly now that there's a", "if the HTTP status was # 404, and a BeautifulSoup object if it", "check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\") with frontend.signin(): # Check", "but BeautifulSoup apparently # doesn't parse nested tables correctly, so these rows aren't", "check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows =", "row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else: string", "cells[0].string if string is None: string = \"\" testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\")", "# doesn't parse nested tables correctly, so these rows aren't actually part #", "testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\")", "\"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\",", "def check_repository(document): rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"repository\")) testing.expect.check(1, len(rows)) def check_cell(row, class_name, expected_string, inline_element_type=None):", "check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1,", "True if not finished: logger.error(\"Repository main branch ('refs/heads/master') not fetched after 30 seconds.\")", "\")) if not mail: break logger.error(\"Administrator message: %s\\n > %s\" % (mail.header(\"Subject\"), \"\\n", "check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1],", "\"name\": \"critic\", \"path\": \"critic\", \"remote\": { \"url\": repository.url, \"branch\": \"master\" }}) # If", "frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\": \"validpath1\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" })", "(mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise testing.TestFailure else: finished = True if not finished:", "Would like to use 'tables[0].findAll()' here, but BeautifulSoup apparently # doesn't parse nested", "# Check that /repositories still loads correctly now that there's a # repository", "was 200. if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None: time.sleep(0.5) while True: mail =", "\"name\": \"a\" * 65, \"path\": \"validpath2\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" })", "and a BeautifulSoup object if it was 200. if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is", "\"branch\": \"master\" }}) # If it hasn't happened after 30 seconds, something must", "finished and time.time() < deadline: # The frontend.page() function returns None if the", "tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would like to use 'tables[0].findAll()' here,", "expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\", data={ \"name\": \"a\"", "30 seconds, something must be wrong. deadline = time.time() + 30 finished =", "repository in the system. frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\":", "check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\") with frontend.signin(): # Check that this URL", "else: finished = True if not finished: logger.error(\"Repository main branch ('refs/heads/master') not fetched", "\"status\": \"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\": \"validpath1\" }, expect={", "# 404, and a BeautifulSoup object if it was 200. if frontend.page(\"critic/master\", expected_http_status=[200,", "len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would like to use 'tables[0].findAll()'", "loads correctly now that there's a # repository in the system. frontend.page( \"repositories\",", "document.findAll(\"tr\", attrs=testing.expect.with_class(\"repository\")) testing.expect.check(1, len(rows)) def check_cell(row, class_name, expected_string, inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name))", "\"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\",", "frontend.page() function returns None if the HTTP status was # 404, and a", "# If it hasn't happened after 30 seconds, something must be wrong. deadline", "data={ \"name\": \"critic\", \"path\": \"critic\", \"remote\": { \"url\": repository.url, \"branch\": \"master\" }}) #", "\"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\": \"validpath1\" }, expect={ \"status\": \"failure\", \"code\":", "use 'tables[0].findAll()' here, but BeautifulSoup apparently # doesn't parse nested tables correctly, so", "}) frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\": \"validpath1\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\"", "wrong. deadline = time.time() + 30 finished = False while not finished and", "inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\",", "now that there's a # repository in the system. frontend.page( \"repositories\", expect={ \"document_title\":", "object if it was 200. if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None: time.sleep(0.5) while", "attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would like to use 'tables[0].findAll()' here, but BeautifulSoup apparently", "%s\" % (mail.header(\"Subject\"), \"\\n > \".join(mail.lines))) raise testing.TestFailure else: finished = True if", "\"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository }) frontend.operation(\"addrepository\", data={ \"name\":", "\"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\": \"validpath1\" }, expect={ \"status\":", "testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else: string = cells[0].string if string is None:", "testing.expect.check(expected_string, string) check_cell(rows[0], \"name\", \"critic\") check_cell(rows[0], \"location\", \"http://%s/critic.git\" % instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\")", "the system. frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\": testing.expect.paleyellow_title(0, u\"Repositories\"), \"repository\": check_repository })", "if not mail: break logger.error(\"Administrator message: %s\\n > %s\" % (mail.header(\"Subject\"), \"\\n >", "not finished and time.time() < deadline: # The frontend.page() function returns None if", "% instance.hostname) check_cell(rows[0], \"upstream\", \"&nbsp;\") rows = document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables =", "logger.error(\"Repository main branch ('refs/heads/master') not fetched after 30 seconds.\") raise testing.TestFailure # Check", "\"remote\", repository.url) check_cell(rows[0], \"remotename\", \"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1],", "a BeautifulSoup object if it was 200. if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None:", "= document.findAll(\"tr\", attrs=testing.expect.with_class(\"branch\")) testing.expect.check(2, len(rows)) check_cell(rows[0], \"localname\", \"Tags\", inline_element_type=\"i\") check_cell(rows[0], \"remote\", repository.url) check_cell(rows[0],", "that /repositories still loads correctly now that there's a # repository in the", "not mail: break logger.error(\"Administrator message: %s\\n > %s\" % (mail.header(\"Subject\"), \"\\n > \".join(mail.lines)))", "= document.findAll(\"tr\", attrs=testing.expect.with_class(\"details\")) testing.expect.check(1, len(rows)) tables = rows[0].findAll(\"table\", attrs=testing.expect.with_class(\"trackedbranches\")) testing.expect.check(1, len(tables)) # Would", "there's a # repository in the system. frontend.page( \"repositories\", expect={ \"document_title\": testing.expect.document_title(u\"Repositories\"), \"content_title\":", "> \".join(mail.lines))) raise testing.TestFailure else: finished = True if not finished: logger.error(\"Repository main", "\"\") with frontend.signin(): # Check that this URL isn't handled already. We're using", "\".join(mail.lines))) raise testing.TestFailure else: finished = True if not finished: logger.error(\"Repository main branch", "\"users\", \"\") with frontend.signin(): # Check that this URL isn't handled already. We're", "the repository has been created and the tracked branch fetched, and # if", "if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None: time.sleep(0.5) while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \"))", "later to detect # that the repository has been created and the tracked", "The frontend.page() function returns None if the HTTP status was # 404, and", "frontend.signin(): # Check that this URL isn't handled already. We're using it later", "like to use 'tables[0].findAll()' here, but BeautifulSoup apparently # doesn't parse nested tables", "\"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\": \"\", \"path\": \"validpath1\" }, expect={ \"status\": \"failure\",", "\"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\")", "inline_element_type=None): cells = row.findAll(\"td\", attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string =", "so these rows aren't actually part # of the 'trackedbranches' table according to", "404]) is None: time.sleep(0.5) while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail:", "expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\", \"path\": \"critic\", \"remote\": { \"url\": repository.url, \"branch\": \"master\"", "65, \"path\": \"validpath2\" }, expect={ \"status\": \"failure\", \"code\": \"invalidshortname\" }) frontend.operation(\"addrepository\", data={ \"name\":", "not fetched after 30 seconds.\") raise testing.TestFailure # Check that /repositories still loads", "404, and a BeautifulSoup object if it was 200. if frontend.page(\"critic/master\", expected_http_status=[200, 404])", "\"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\") check_cell(rows[1], \"enabled\", \"Yes\") check_cell(rows[1], \"users\", \"\") with frontend.signin():", "\"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\", repository.url) check_cell(rows[1], \"remotename\", \"master\")", "testing.TestFailure # Check that /repositories still loads correctly now that there's a #", "some reason, that check won't be reliable. frontend.page(\"critic/master\", expected_http_status=404) frontend.operation(\"addrepository\", data={ \"name\": \"critic\",", "this URL isn't handled already. We're using it later to detect # that", "tracked branch fetched, and # if it's already handled for some reason, that", "check_repository }) frontend.operation(\"addrepository\", data={ \"name\": \"a\" * 65, \"path\": \"validpath2\" }, expect={ \"status\":", "\"N/A\", inline_element_type=\"i\") check_cell(rows[0], \"enabled\", \"Yes\") check_cell(rows[0], \"users\", \"\") check_cell(rows[1], \"localname\", \"master\") check_cell(rows[1], \"remote\",", "time.sleep(0.5) while True: mail = mailbox.pop(accept=testing.mailbox.with_subject(\"^branchtracker.log: \")) if not mail: break logger.error(\"Administrator message:", "BeautifulSoup object if it was 200. if frontend.page(\"critic/master\", expected_http_status=[200, 404]) is None: time.sleep(0.5)", "attrs=testing.expect.with_class(class_name)) testing.expect.check(1, len(cells)) if inline_element_type: testing.expect.check(1, len(cells[0].findAll(inline_element_type))) string = cells[0].findAll(\"i\")[0].string else: string =" ]
[ "for i in range(n): temp = queue.pop() print(temp.val) if temp.left: queue.insert(0,temp.left) if temp.right:", "root: TreeNode) -> List[List[int]]: queue = [] queue.insert(0,root) res = [] if not", "= queue.pop() print(temp.val) if temp.left: queue.insert(0,temp.left) if temp.right: queue.insert(0,temp.right) layer.append(temp.val) res.append(layer) return res", "range(n): temp = queue.pop() print(temp.val) if temp.left: queue.insert(0,temp.left) if temp.right: queue.insert(0,temp.right) layer.append(temp.val) res.append(layer)", "queue = [] queue.insert(0,root) res = [] if not root: return [] while", "[] for i in range(n): temp = queue.pop() print(temp.val) if temp.left: queue.insert(0,temp.left) if", "class Solution: def XXX(self, root: TreeNode) -> List[List[int]]: queue = [] queue.insert(0,root) res", "return [] while queue: n = len(queue) layer = [] for i in", "not root: return [] while queue: n = len(queue) layer = [] for", "queue.insert(0,root) res = [] if not root: return [] while queue: n =", "= [] if not root: return [] while queue: n = len(queue) layer", "-> List[List[int]]: queue = [] queue.insert(0,root) res = [] if not root: return", "[] queue.insert(0,root) res = [] if not root: return [] while queue: n", "queue: n = len(queue) layer = [] for i in range(n): temp =", "n = len(queue) layer = [] for i in range(n): temp = queue.pop()", "def XXX(self, root: TreeNode) -> List[List[int]]: queue = [] queue.insert(0,root) res = []", "layer = [] for i in range(n): temp = queue.pop() print(temp.val) if temp.left:", "res = [] if not root: return [] while queue: n = len(queue)", "root: return [] while queue: n = len(queue) layer = [] for i", "= [] for i in range(n): temp = queue.pop() print(temp.val) if temp.left: queue.insert(0,temp.left)", "in range(n): temp = queue.pop() print(temp.val) if temp.left: queue.insert(0,temp.left) if temp.right: queue.insert(0,temp.right) layer.append(temp.val)", "i in range(n): temp = queue.pop() print(temp.val) if temp.left: queue.insert(0,temp.left) if temp.right: queue.insert(0,temp.right)", "len(queue) layer = [] for i in range(n): temp = queue.pop() print(temp.val) if", "= [] queue.insert(0,root) res = [] if not root: return [] while queue:", "List[List[int]]: queue = [] queue.insert(0,root) res = [] if not root: return []", "TreeNode) -> List[List[int]]: queue = [] queue.insert(0,root) res = [] if not root:", "temp = queue.pop() print(temp.val) if temp.left: queue.insert(0,temp.left) if temp.right: queue.insert(0,temp.right) layer.append(temp.val) res.append(layer) return", "while queue: n = len(queue) layer = [] for i in range(n): temp", "[] while queue: n = len(queue) layer = [] for i in range(n):", "[] if not root: return [] while queue: n = len(queue) layer =", "Solution: def XXX(self, root: TreeNode) -> List[List[int]]: queue = [] queue.insert(0,root) res =", "XXX(self, root: TreeNode) -> List[List[int]]: queue = [] queue.insert(0,root) res = [] if", "= len(queue) layer = [] for i in range(n): temp = queue.pop() print(temp.val)", "if not root: return [] while queue: n = len(queue) layer = []" ]
[ "from os.path import join import numpy as np #def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.',", "argparse import pandas as pd from funcs import utils from os.path import join", "= annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae'] =", "Healthy','cell type: Central airway epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy', 'cell type: Peripheral airway", "classes[cls][1]] for cls in classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls in classes]))", "if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls in classes} logging.info('", "np #def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s',", "logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated =", "Asthmatic', 'cell type: Central airway epithelium'] classes['asthma_pae'] = ['diagnosis: Severe Asthmatic', 'cell type:", "classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls in classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls]))", "Central airway epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy', 'cell type: Peripheral airway epithelium'] classes['asthma_cae']", "#def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")])", "format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE',", "= ['diagnosis: Severe Asthmatic', 'cell type: Peripheral airway epithelium'] logging.info(classes) gsms = {cls:", "and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls in classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for", "\"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed'))", "join import numpy as np #def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix)", "postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913',", "\"<NAME>\" __version__ = \"0.1.0\" __license__ = \"MIT\" import logging import GEOparse import argparse", "'expr.tsv'), annotated2) for cls in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ ==", "argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory for expression data file and GSM lists')", "= ['diagnosis: Healthy', 'cell type: Peripheral airway epithelium'] classes['asthma_cae'] = ['diagnosis: Severe Asthmatic',", "utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for cls in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls])", "gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2", "= annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes =", "classes['healthy_cae'] = ['diagnosis: Healthy','cell type: Central airway epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy', 'cell", "Peripheral airway epithelium'] classes['asthma_cae'] = ['diagnosis: Severe Asthmatic', 'cell type: Central airway epithelium']", "= annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae'] = ['diagnosis: Healthy','cell type:", "['diagnosis: Healthy', 'cell type: Peripheral airway epithelium'] classes['asthma_cae'] = ['diagnosis: Severe Asthmatic', 'cell", "annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae'] = ['diagnosis: Healthy','cell type: Central airway epithelium'] classes['healthy_pae']", "annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] =", "logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID')", "parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory for expression data file and", "airway epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy', 'cell type: Peripheral airway epithelium'] classes['asthma_cae'] =", "#!/usr/bin/env python3 \"\"\" Generate GSE64913 \"\"\" __author__ = \"<NAME>\" __version__ = \"0.1.0\" __license__", "classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for cls in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)),", "= \"0.1.0\" __license__ = \"MIT\" import logging import GEOparse import argparse import pandas", "annotated2) for cls in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ == \"__main__\":", "= ['diagnosis: Severe Asthmatic', 'cell type: Central airway epithelium'] classes['asthma_pae'] = ['diagnosis: Severe", "= argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory for expression data file and GSM", "= {cls: [gsm for gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5]", "handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'],", "1) + postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse", "'cell type: Peripheral airway epithelium'] classes['asthma_cae'] = ['diagnosis: Severe Asthmatic', 'cell type: Central", "\"0.1.0\" __license__ = \"MIT\" import logging import GEOparse import argparse import pandas as", "type: Peripheral airway epithelium'] logging.info(classes) gsms = {cls: [gsm for gsm in gse.gsms", "cls in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ == \"__main__\": parser =", "__license__ = \"MIT\" import logging import GEOparse import argparse import pandas as pd", "cls in classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir,", "utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for cls in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if", "logging import GEOparse import argparse import pandas as pd from funcs import utils", "import GEOparse import argparse import pandas as pd from funcs import utils from", "gsms = {cls: [gsm for gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and", "append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args)", "gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls in classes} logging.info(' '.join(['{}", "Peripheral airway epithelium'] logging.info(classes) gsms = {cls: [gsm for gsm in gse.gsms if", "\"\"\" __author__ = \"<NAME>\" __version__ = \"0.1.0\" __license__ = \"MIT\" import logging import", "import utils from os.path import join import numpy as np #def append_postfix(filename,postfix): #", "\"MIT\" import logging import GEOparse import argparse import pandas as pd from funcs", "Asthmatic', 'cell type: Peripheral airway epithelium'] logging.info(classes) gsms = {cls: [gsm for gsm", "python3 \"\"\" Generate GSE64913 \"\"\" __author__ = \"<NAME>\" __version__ = \"0.1.0\" __license__ =", "__version__ = \"0.1.0\" __license__ = \"MIT\" import logging import GEOparse import argparse import", "[gsm for gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]]", "= {} classes['healthy_cae'] = ['diagnosis: Healthy','cell type: Central airway epithelium'] classes['healthy_pae'] = ['diagnosis:", "Central airway epithelium'] classes['asthma_pae'] = ['diagnosis: Severe Asthmatic', 'cell type: Peripheral airway epithelium']", "in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls in", "for cls in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ == \"__main__\": parser", "in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Process", "type: Central airway epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy', 'cell type: Peripheral airway epithelium']", "classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'),", "classes['healthy_pae'] = ['diagnosis: Healthy', 'cell type: Peripheral airway epithelium'] classes['asthma_cae'] = ['diagnosis: Severe", "def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw'))", "classes['asthma_pae'] = ['diagnosis: Severe Asthmatic', 'cell type: Peripheral airway epithelium'] logging.info(classes) gsms =", "epithelium'] logging.info(classes) gsms = {cls: [gsm for gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] ==", "gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 =", "utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 =", "help='Output directory for expression data file and GSM lists') args = parser.parse_args() main(args)", "for gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for", "'.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for", "type=str, help='Output directory for expression data file and GSM lists') args = parser.parse_args()", "'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str,", "cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for cls in classes: utils.write_text(join(args.out_expr_dir,", "== \"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory for expression data", "numpy as np #def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def main(args):", "airway epithelium'] classes['asthma_pae'] = ['diagnosis: Severe Asthmatic', 'cell type: Peripheral airway epithelium'] logging.info(classes)", "gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls in classes}", "as pd from funcs import utils from os.path import join import numpy as", "os.path import join import numpy as np #def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1)", "= GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 =", "classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913')", "\"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory for expression data file", "= gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int)", "'{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output", "{} classes['healthy_cae'] = ['diagnosis: Healthy','cell type: Central airway epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy',", "epithelium'] classes['asthma_cae'] = ['diagnosis: Severe Asthmatic', 'cell type: Central airway epithelium'] classes['asthma_pae'] =", "Severe Asthmatic', 'cell type: Peripheral airway epithelium'] logging.info(classes) gsms = {cls: [gsm for", "gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2", "if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory for", "{cls: [gsm for gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] ==", "gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls", "GSE64913 \"\"\" __author__ = \"<NAME>\" __version__ = \"0.1.0\" __license__ = \"MIT\" import logging", "Healthy', 'cell type: Peripheral airway epithelium'] classes['asthma_cae'] = ['diagnosis: Severe Asthmatic', 'cell type:", "return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw'))", "__name__ == \"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory for expression", "logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2)", "Generate GSE64913 \"\"\" __author__ = \"<NAME>\" __version__ = \"0.1.0\" __license__ = \"MIT\" import", "destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID']", "type: Central airway epithelium'] classes['asthma_pae'] = ['diagnosis: Severe Asthmatic', 'cell type: Peripheral airway", "from funcs import utils from os.path import join import numpy as np #def", "annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes = {}", "annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae'] = ['diagnosis: Healthy','cell type: Central airway", "utils from os.path import join import numpy as np #def append_postfix(filename,postfix): # return", "+ postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse =", "['diagnosis: Severe Asthmatic', 'cell type: Peripheral airway epithelium'] logging.info(classes) gsms = {cls: [gsm", "pd from funcs import utils from os.path import join import numpy as np", "= ['diagnosis: Healthy','cell type: Central airway epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy', 'cell type:", "len(gsms[cls])) for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for cls in", "'cell type: Peripheral airway epithelium'] logging.info(classes) gsms = {cls: [gsm for gsm in", "Severe Asthmatic', 'cell type: Central airway epithelium'] classes['asthma_pae'] = ['diagnosis: Severe Asthmatic', 'cell", "== classes[cls][1]] for cls in classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls in", "import pandas as pd from funcs import utils from os.path import join import", "annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae'] = ['diagnosis: Healthy','cell", "'cell type: Central airway epithelium'] classes['asthma_pae'] = ['diagnosis: Severe Asthmatic', 'cell type: Peripheral", "annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae'] = ['diagnosis: Healthy','cell type: Central", "airway epithelium'] logging.info(classes) gsms = {cls: [gsm for gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1]", "== classes[cls][0] and gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls in classes} logging.info(' '.join(['{} GSM:{}'.format(cls,", "parser.add_argument('out_expr_dir', type=str, help='Output directory for expression data file and GSM lists') args =", "in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for cls in classes: utils.write_text(join(args.out_expr_dir, 'processed',", "import join import numpy as np #def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) +", "= \"<NAME>\" __version__ = \"0.1.0\" __license__ = \"MIT\" import logging import GEOparse import", "['diagnosis: Severe Asthmatic', 'cell type: Central airway epithelium'] classes['asthma_pae'] = ['diagnosis: Severe Asthmatic',", "# return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir)", "import logging import GEOparse import argparse import pandas as pd from funcs import", "GEOparse import argparse import pandas as pd from funcs import utils from os.path", "'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID')", "airway epithelium'] classes['asthma_cae'] = ['diagnosis: Severe Asthmatic', 'cell type: Central airway epithelium'] classes['asthma_pae']", "gse.gsms[gsm].metadata['characteristics_ch1'][5] == classes[cls][1]] for cls in classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls", "for cls in classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir)", "pandas as pd from funcs import utils from os.path import join import numpy", "utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir',", "'processed', 'expr.tsv'), annotated2) for cls in classes: utils.write_text(join(args.out_expr_dir, 'processed', '{}_gsms.txt'.format(cls)), gsms[cls]) if __name__", "\"\"\" Generate GSE64913 \"\"\" __author__ = \"<NAME>\" __version__ = \"0.1.0\" __license__ = \"MIT\"", "import argparse import pandas as pd from funcs import utils from os.path import", "utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)]", "gsms[cls]) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='Process GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory", "GSE64913') parser.add_argument('out_expr_dir', type=str, help='Output directory for expression data file and GSM lists') args", "main(args): logging.basicConfig(level=logging.INFO, format='%(module)s:%(levelname)s:%(asctime)s:%(message)s', handlers=[logging.FileHandler(\"../logs/report.log\")]) logging.info(args) utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated", "import numpy as np #def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def", "epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy', 'cell type: Peripheral airway epithelium'] classes['asthma_cae'] = ['diagnosis:", "annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes", "classes['asthma_cae'] = ['diagnosis: Severe Asthmatic', 'cell type: Central airway epithelium'] classes['asthma_pae'] = ['diagnosis:", "classes = {} classes['healthy_cae'] = ['diagnosis: Healthy','cell type: Central airway epithelium'] classes['healthy_pae'] =", "GSM:{}'.format(cls, len(gsms[cls])) for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for cls", "logging.info(classes) gsms = {cls: [gsm for gsm in gse.gsms if gse.gsms[gsm].metadata['characteristics_ch1'][1] == classes[cls][0]", "for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed', 'expr.tsv'), annotated2) for cls in classes:", "as np #def append_postfix(filename,postfix): # return \"{0}_{2}.{1}\".format(*filename.rsplit('.', 1) + postfix) def main(args): logging.basicConfig(level=logging.INFO,", "utils.create_dir_if_not_exist(args.out_expr_dir) utils.create_dir_if_not_exist(join(args.out_expr_dir,'raw')) utils.create_dir_if_not_exist(join(args.out_expr_dir,'processed')) gse = GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2", "__author__ = \"<NAME>\" __version__ = \"0.1.0\" __license__ = \"MIT\" import logging import GEOparse", "['diagnosis: Healthy','cell type: Central airway epithelium'] classes['healthy_pae'] = ['diagnosis: Healthy', 'cell type: Peripheral", "= annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae'] = ['diagnosis: Healthy','cell type: Central airway epithelium']", "annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae']", "= \"MIT\" import logging import GEOparse import argparse import pandas as pd from", "in classes} logging.info(' '.join(['{} GSM:{}'.format(cls, len(gsms[cls])) for cls in classes])) utils.create_dir_if_not_exist(args.out_expr_dir) utils.write_expr(join(args.out_expr_dir, 'processed',", "type: Peripheral airway epithelium'] classes['asthma_cae'] = ['diagnosis: Severe Asthmatic', 'cell type: Central airway", "GEOparse.get_GEO(geo='GSE64913', destdir=join(args.out_expr_dir,'raw')) annotated = gse.pivot_and_annotate('VALUE', gse.gpls['GPL570'], 'ENTREZ_GENE_ID') annotated2 = annotated[~pd.isnull(annotated.ENTREZ_GENE_ID)] annotated2 = annotated2.loc[~annotated2.isnull().values.all(axis=1)]", "funcs import utils from os.path import join import numpy as np #def append_postfix(filename,postfix):", "epithelium'] classes['asthma_pae'] = ['diagnosis: Severe Asthmatic', 'cell type: Peripheral airway epithelium'] logging.info(classes) gsms", "annotated2.loc[~annotated2.isnull().values.all(axis=1)] annotated2['ENTREZ_GENE_ID'] = annotated2.ENTREZ_GENE_ID.str.split('///').str[0].astype(int) annotated2 = annotated2.set_index('ENTREZ_GENE_ID') classes = {} classes['healthy_cae'] = ['diagnosis:" ]
[]
[ "async def init_redis(app): app['redis'] = aioredis.from_url( app['redis_location'], ) async def close_redis(app): await app['redis'].close()", "expire is None: res = await conn.set(key, value) else: res = await conn.set(key,", "async with redis.client() as conn: val = await conn.get(key) return val async def", ") async def close_redis(app): await app['redis'].close() def setup_redis(app, redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis)", "async def close_redis(app): await app['redis'].close() def setup_redis(app, redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis)", "with redis.client() as conn: val = await conn.get(key) return val async def set_redis_key(redis,", "return val async def set_redis_key(redis, key, value, expire=None): async with redis.client() as conn:", "await app['redis'].close() def setup_redis(app, redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis,", "app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis, key): async with redis.client() as conn: val =", "get_redis_key(redis, key): async with redis.client() as conn: val = await conn.get(key) return val", "app['redis'].close() def setup_redis(app, redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis, key):", "conn.get(key) return val async def set_redis_key(redis, key, value, expire=None): async with redis.client() as", "def close_redis(app): await app['redis'].close() def setup_redis(app, redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async", "app.on_cleanup.append(close_redis) async def get_redis_key(redis, key): async with redis.client() as conn: val = await", "key): async with redis.client() as conn: val = await conn.get(key) return val async", "aioredis.from_url( app['redis_location'], ) async def close_redis(app): await app['redis'].close() def setup_redis(app, redis_location): app['redis_location'] =", "import aioredis async def init_redis(app): app['redis'] = aioredis.from_url( app['redis_location'], ) async def close_redis(app):", "= redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis, key): async with redis.client() as conn:", "conn: val = await conn.get(key) return val async def set_redis_key(redis, key, value, expire=None):", "val async def set_redis_key(redis, key, value, expire=None): async with redis.client() as conn: if", "res = await conn.set(key, value) else: res = await conn.set(key, value, ex=expire) return", "redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis, key): async with redis.client() as conn: val", "= aioredis.from_url( app['redis_location'], ) async def close_redis(app): await app['redis'].close() def setup_redis(app, redis_location): app['redis_location']", "async with redis.client() as conn: if expire is None: res = await conn.set(key,", "with redis.client() as conn: if expire is None: res = await conn.set(key, value)", "redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis, key): async with redis.client()", "def get_redis_key(redis, key): async with redis.client() as conn: val = await conn.get(key) return", "redis.client() as conn: val = await conn.get(key) return val async def set_redis_key(redis, key,", "key, value, expire=None): async with redis.client() as conn: if expire is None: res", "expire=None): async with redis.client() as conn: if expire is None: res = await", "init_redis(app): app['redis'] = aioredis.from_url( app['redis_location'], ) async def close_redis(app): await app['redis'].close() def setup_redis(app,", "def init_redis(app): app['redis'] = aioredis.from_url( app['redis_location'], ) async def close_redis(app): await app['redis'].close() def", "as conn: if expire is None: res = await conn.set(key, value) else: res", "<reponame>iliadmitriev/auth-api<filename>backends/redis.py<gh_stars>1-10 import aioredis async def init_redis(app): app['redis'] = aioredis.from_url( app['redis_location'], ) async def", "def set_redis_key(redis, key, value, expire=None): async with redis.client() as conn: if expire is", "app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis, key): async with redis.client() as", "val = await conn.get(key) return val async def set_redis_key(redis, key, value, expire=None): async", "await conn.get(key) return val async def set_redis_key(redis, key, value, expire=None): async with redis.client()", "redis.client() as conn: if expire is None: res = await conn.set(key, value) else:", "= await conn.get(key) return val async def set_redis_key(redis, key, value, expire=None): async with", "if expire is None: res = await conn.set(key, value) else: res = await", "as conn: val = await conn.get(key) return val async def set_redis_key(redis, key, value,", "aioredis async def init_redis(app): app['redis'] = aioredis.from_url( app['redis_location'], ) async def close_redis(app): await", "setup_redis(app, redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis, key): async with", "is None: res = await conn.set(key, value) else: res = await conn.set(key, value,", "= await conn.set(key, value) else: res = await conn.set(key, value, ex=expire) return res", "async def get_redis_key(redis, key): async with redis.client() as conn: val = await conn.get(key)", "app['redis_location'], ) async def close_redis(app): await app['redis'].close() def setup_redis(app, redis_location): app['redis_location'] = redis_location", "async def set_redis_key(redis, key, value, expire=None): async with redis.client() as conn: if expire", "app['redis'] = aioredis.from_url( app['redis_location'], ) async def close_redis(app): await app['redis'].close() def setup_redis(app, redis_location):", "set_redis_key(redis, key, value, expire=None): async with redis.client() as conn: if expire is None:", "None: res = await conn.set(key, value) else: res = await conn.set(key, value, ex=expire)", "close_redis(app): await app['redis'].close() def setup_redis(app, redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def", "conn: if expire is None: res = await conn.set(key, value) else: res =", "def setup_redis(app, redis_location): app['redis_location'] = redis_location app.on_startup.append(init_redis) app.on_cleanup.append(close_redis) async def get_redis_key(redis, key): async", "value, expire=None): async with redis.client() as conn: if expire is None: res =" ]
[ "terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight of sum of weighted style divergence terms\")", "beta_2 val for adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to set the starting epoch", "of sum of weighted divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight of sum", "parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to indicate", "type=int, default=dim_text, help=\"dimension of modality text\") parser.add_argument('--data_dir_root', type=str, default=data_dir_root, help=\"data dir\") FLAGS =", "help='choose method for training the model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False,", "help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") # LOSS TERM WEIGHTS", "data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root,", "model will be loaded\") # DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to", "FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image =", "image_text, image_only, text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose method for training the model')", "train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image =", "type=str, default='zsl', help='normal or zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text, image_only, text_only') #multimodal", "help=\"default initial weight of sum of weighted divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default", "parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal or zsl') parser.add_argument('--aug_type',", "help=\"image embedding model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal or zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug,", "= sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain", "DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of common factor latent space\") # SAVE", "modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension", "to set the starting epoch for training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to indicate", "= parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train", "final epoch of training\") # DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of common", "factor latent space\") # SAVE and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save for", "FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image", "content divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight of intra_mi terms\") parser.add_argument('--lambda2', type=float,", "weight of sum of weighted divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight of", "parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1 val for adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2", "default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding model\")", "of sum of weighted style divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight of", "beta_1 val for adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2 val for adam\") parser.add_argument('--start_epoch',", "help=\"directory to save logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri", "default=32, help=\"dimension of common factor latent space\") # SAVE and LOAD parser.add_argument('--mm_vae_save', type=str,", "parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to indicate if a saved model will be loaded\")", "parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of modality", "training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1 val", "import os import argparse import torch import scipy.io as sio parser = argparse.ArgumentParser()", "torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image = train_image.shape[1] dim_text = train_text.shape[1]", "text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose method for training the model') parser.add_argument('--modality_jsd', type=bool,", "to save logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\")", "help=\"default beta_1 val for adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2 val for adam\")", "train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of modality brain\") parser.add_argument('--m2_dim', type=int,", "help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") # LOSS TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default", "zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text, image_only, text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose", "of modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text,", "parser = argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch size for training\") parser.add_argument('--initial_learning_rate',", "type=float, default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1 val for adam\")", "= os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain =", "= sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image)", "default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding", "help='no_aug, image_text, image_only, text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose method for training the", "for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to indicate if a saved model will", "parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type',", "scipy.io as sio parser = argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch size", "type=float, default=0.9, help=\"default beta_1 val for adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2 val", "sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text", "sum of weighted content divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight of intra_mi", "saved model will be loaded\") # DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory", "be loaded\") # DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to save logs", "text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train,", "type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool,", "default=0.999, help=\"default beta_2 val for adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to set the", "as sio parser = argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch size for", "help=\"dimension of modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of modality image\") parser.add_argument('--m3_dim', type=int,", "default=dim_text, help=\"dimension of modality text\") parser.add_argument('--data_dir_root', type=str, default=data_dir_root, help=\"data dir\") FLAGS = parser.parse_args()", "parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") # LOSS TERM WEIGHTS parser.add_argument('--beta',", "default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1 val for adam\") parser.add_argument('--beta_2',", "of sum of weighted content divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight of", "terms\") FLAGS = parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi,", "train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain", "torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image = train_image.shape[1]", "= os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train =", "will be loaded\") # DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to save", "embedding model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal or zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text,", "of common factor latent space\") # SAVE and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model", "LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to", "type=str, default='mm_vae', help=\"model save for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to indicate if", "type=str, default='joint_elbo', help='choose method for training the model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe',", "#multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose method for training the model') parser.add_argument('--modality_jsd', type=bool, default=False,", "parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2 val for adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to", "size for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default", "train_text = torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image = train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim',", "sio parser = argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch size for training\")", "help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\")", "import scipy.io as sio parser = argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch", "initial weight of sum of weighted divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight", "sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain)", "type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") # LOSS", "type=int, default=512, help=\"batch size for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1',", "for adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to set the starting epoch for training\")", "type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding", "= os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining',", "parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight of inter_mi terms\") FLAGS = parser.parse_args() data_dir_root =", "set the starting epoch for training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to indicate the", "os import argparse import torch import scipy.io as sio parser = argparse.ArgumentParser() #", "parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of modality", "help=\"flag to set the starting epoch for training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to", "loaded\") # DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to save logs in\")", "save logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi',", "<reponame>cvsubmittemp/BraVL import os import argparse import torch import scipy.io as sio parser =", "import torch import scipy.io as sio parser = argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int,", "DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of common factor latent space\") # SAVE and", "parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of common factor latent space\") # SAVE and LOAD", "learning rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1 val for adam\") parser.add_argument('--beta_2', type=float, default=0.999,", "style divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight of sum of weighted content", "type=float, default=0.999, help=\"default beta_2 val for adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to set", "FLAGS = parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj)", "type=bool, default=False, help=\"flag to indicate if a saved model will be loaded\") #", "type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal or zsl') parser.add_argument('--aug_type', type=str,", "sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain =", "save for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to indicate if a saved model", "the final epoch of training\") # DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of", "divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight of sum of weighted content divergence", "parser.add_argument('--method', type=str, default='joint_elbo', help='choose method for training the model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\")", "argparse import torch import scipy.io as sio parser = argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size',", "type=int, default=100, help=\"flag to indicate the final epoch of training\") # DATA DEPENDENT", "type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image", "parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") # LOSS TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default initial", "default='./logs', help=\"directory to save logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03',", "weight of intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight of inter_mi terms\") FLAGS", "parser.add_argument('--beta', type=float, default=0.0, help=\"default initial weight of sum of weighted divergence terms\") parser.add_argument('--beta_style',", "action='store_true', default=False, help=\"factorized_representation\") # LOSS TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default initial weight", "subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model', type=str,", "parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to set the starting epoch for training\") parser.add_argument('--end_epoch', type=int,", "default=0.9, help=\"default beta_1 val for adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2 val for", "type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true',", "type=int, default=dim_image, help=\"dimension of modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of modality text\")", "training the model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool,", "indicate if a saved model will be loaded\") # DIRECTORIES # experiments parser.add_argument('--dir_experiment',", "default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type', type=str, default='zsl',", "FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj)", "DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to save logs in\") parser.add_argument('--dataname', type=str,", "default=512, help=\"batch size for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1', type=float,", "SAVE and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False,", "model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal or zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text, image_only,", "epoch of training\") # DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of common factor", "method for training the model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\")", "default='joint_elbo', help='choose method for training the model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool,", "help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\")", "help=\"dimension of modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of modality text\") parser.add_argument('--data_dir_root', type=str,", "rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1 val for adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default", "default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") # LOSS TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0,", "default=False, help=\"flag to indicate if a saved model will be loaded\") # DIRECTORIES", "help=\"factorized_representation\") # LOSS TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default initial weight of sum", "type=float, default=0.001, help=\"default weight of inter_mi terms\") FLAGS = parser.parse_args() data_dir_root = os.path.join('./data',", "inter_mi terms\") FLAGS = parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature',", "image_only, text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose method for training the model') parser.add_argument('--modality_jsd',", "val for adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to set the starting epoch for", "image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain", "indicate the final epoch of training\") # DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension", "= train_brain.shape[1] dim_image = train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of", "parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to indicate the final epoch of training\") # DATA", "help=\"flag to indicate the final epoch of training\") # DATA DEPENDENT parser.add_argument('--class_dim', type=int,", "help=\"default weight of sum of weighted style divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default", "type=str, default='image_text', help='no_aug, image_text, image_only, text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose method for", "for adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2 val for adam\") parser.add_argument('--start_epoch', type=int, default=0,", "to indicate the final epoch of training\") # DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32,", "default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal or zsl') parser.add_argument('--aug_type', type=str, default='image_text',", "parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4',", "FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model,", "type=float, default=0.001, help=\"default weight of intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight of", "= os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000]", "and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag", "parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1 val for", "help=\"batch size for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1', type=float, default=0.9,", "parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight of intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight", "adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to set the starting epoch for training\") parser.add_argument('--end_epoch',", "help=\"default weight of sum of weighted content divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default", "'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text =", "default=0.0, help=\"default initial weight of sum of weighted divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0,", "type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool,", "type=str, default='./logs', help=\"directory to save logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str,", "help='normal or zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text, image_only, text_only') #multimodal parser.add_argument('--method', type=str,", "type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model',", "help=\"dimension of modality text\") parser.add_argument('--data_dir_root', type=str, default=data_dir_root, help=\"data dir\") FLAGS = parser.parse_args() print(FLAGS)", "weight of sum of weighted style divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight", "help=\"default weight of intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight of inter_mi terms\")", "default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False,", "of weighted style divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight of sum of", "image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of modality text\") parser.add_argument('--data_dir_root', type=str, default=data_dir_root, help=\"data dir\")", "dim_brain = train_brain.shape[1] dim_image = train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension", "default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") # LOSS TERM", "weighted divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight of sum of weighted style", "default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str,", "terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight of intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default", "import argparse import torch import scipy.io as sio parser = argparse.ArgumentParser() # TRAINING", "# experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to save logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki',", "modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of modality text\") parser.add_argument('--data_dir_root', type=str, default=data_dir_root, help=\"data", "parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text, image_only, text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose method", "the starting epoch for training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to indicate the final", "train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text = torch.from_numpy(train_text)", "weight of inter_mi terms\") FLAGS = parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir =", "default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True,", "parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text", "space\") # SAVE and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save for vae_bimodal\") parser.add_argument('--load_saved',", "of training\") # DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of common factor latent", "os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA',", "= train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of modality brain\") parser.add_argument('--m2_dim',", "help=\"starting learning rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1 val for adam\") parser.add_argument('--beta_2', type=float,", "parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train =", "help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo',", "the model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False,", "divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight of intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001,", "= torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image = train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int,", "terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight of sum of weighted content divergence terms\")", "= torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image =", "vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to indicate if a saved model will be", "epoch for training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to indicate the final epoch of", "logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str,", "default=False, help=\"factorized_representation\") # LOSS TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default initial weight of", "WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default initial weight of sum of weighted divergence terms\")", "intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight of inter_mi terms\") FLAGS = parser.parse_args()", "FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double')", "parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo',", "FLAGS.dataname) brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj)", "to indicate if a saved model will be loaded\") # DIRECTORIES # experiments", "for training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to indicate the final epoch of training\")", "default=0.001, help=\"default weight of inter_mi terms\") FLAGS = parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname)", "model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal or zsl')", "parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation',", "help=\"flag to indicate if a saved model will be loaded\") # DIRECTORIES #", "default=1.0, help=\"default weight of sum of weighted content divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001,", "default='zsl', help='normal or zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text, image_only, text_only') #multimodal parser.add_argument('--method',", "type=float, default=1.0, help=\"default weight of sum of weighted content divergence terms\") parser.add_argument('--lambda1', type=float,", "help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\")", "parser.add_argument('--batch_size', type=int, default=512, help=\"batch size for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning rate\")", "weighted style divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight of sum of weighted", "default=100, help=\"flag to indicate the final epoch of training\") # DATA DEPENDENT parser.add_argument('--class_dim',", "or zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text, image_only, text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo',", "default=dim_image, help=\"dimension of modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of modality text\") parser.add_argument('--data_dir_root',", "= argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch size for training\") parser.add_argument('--initial_learning_rate', type=float,", "help=\"dimension of common factor latent space\") # SAVE and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae',", "torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image = train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain,", "'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain = train_brain.shape[1]", "dim_image = train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of modality brain\")", "default='mm_vae', help=\"model save for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to indicate if a", "'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double')", "weight of sum of weighted content divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight", "parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight of sum of weighted style divergence terms\") parser.add_argument('--beta_content',", "train_brain = torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image", "sum of weighted style divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight of sum", "parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\")", "if a saved model will be loaded\") # DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str,", "= torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image = train_image.shape[1] dim_text =", "# DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of common factor latent space\") #", "terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight of inter_mi terms\") FLAGS = parser.parse_args() data_dir_root", "training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to indicate the final epoch of training\") #", "common factor latent space\") # SAVE and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save", "default=0, help=\"flag to set the starting epoch for training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag", "os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text", "of intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight of inter_mi terms\") FLAGS =", "model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\")", "type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") # LOSS TERM WEIGHTS parser.add_argument('--beta', type=float,", "default='image_text', help='no_aug, image_text, image_only, text_only') #multimodal parser.add_argument('--method', type=str, default='joint_elbo', help='choose method for training", "sum of weighted divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight of sum of", "starting epoch for training\") parser.add_argument('--end_epoch', type=int, default=100, help=\"flag to indicate the final epoch", "parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\") #", "# DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to save logs in\") parser.add_argument('--dataname',", "= train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension", "type=int, default=0, help=\"flag to set the starting epoch for training\") parser.add_argument('--end_epoch', type=int, default=100,", "= sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain =", "'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image", "'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text',", "type=float, default=0.0, help=\"default initial weight of sum of weighted divergence terms\") parser.add_argument('--beta_style', type=float,", "dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image,", "train_image = torch.from_numpy(train_image) train_text = torch.from_numpy(train_text) dim_brain = train_brain.shape[1] dim_image = train_image.shape[1] dim_text", "type=int, default=dim_brain, help=\"dimension of modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of modality image\")", "help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False, help=\"factorized_representation\")", "TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch size for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning", "help=\"text embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal", "help=\"model save for vae_bimodal\") parser.add_argument('--load_saved', type=bool, default=False, help=\"flag to indicate if a saved", "training\") # DATA DEPENDENT parser.add_argument('--class_dim', type=int, default=32, help=\"dimension of common factor latent space\")", "help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT', help=\"ROI\") parser.add_argument('--text_model', type=str, default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model',", "default=1.0, help=\"default weight of sum of weighted style divergence terms\") parser.add_argument('--beta_content', type=float, default=1.0,", "type=int, default=32, help=\"dimension of common factor latent space\") # SAVE and LOAD parser.add_argument('--mm_vae_save',", "train_brain.shape[1] dim_image = train_image.shape[1] dim_text = train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of modality", "help=\"default weight of inter_mi terms\") FLAGS = parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir", "a saved model will be loaded\") # DIRECTORIES # experiments parser.add_argument('--dir_experiment', type=str, default='./logs',", "weighted content divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight of intra_mi terms\") parser.add_argument('--lambda2',", "TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default initial weight of sum of weighted divergence", "train_text.shape[1] parser.add_argument('--m1_dim', type=int, default=dim_brain, help=\"dimension of modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of", "# LOSS TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default initial weight of sum of", "# TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch size for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting", "of weighted divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight of sum of weighted", "'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train, 'text_feat_train.mat'))['data'].astype('double') train_brain = torch.from_numpy(train_brain) train_image = torch.from_numpy(train_image) train_text =", "torch import scipy.io as sio parser = argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int, default=512,", "divergence terms\") parser.add_argument('--beta_style', type=float, default=1.0, help=\"default weight of sum of weighted style divergence", "default=dim_brain, help=\"dimension of modality brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of modality image\") parser.add_argument('--m3_dim',", "brain_dir = os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train", "parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to save logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj',", "brain\") parser.add_argument('--m2_dim', type=int, default=dim_image, help=\"dimension of modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of", "parser.add_argument('--test_type', type=str, default='zsl', help='normal or zsl') parser.add_argument('--aug_type', type=str, default='image_text', help='no_aug, image_text, image_only, text_only')", "adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2 val for adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag", "LOSS TERM WEIGHTS parser.add_argument('--beta', type=float, default=0.0, help=\"default initial weight of sum of weighted", "argparse.ArgumentParser() # TRAINING parser.add_argument('--batch_size', type=int, default=512, help=\"batch size for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001,", "parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of modality text\") parser.add_argument('--data_dir_root', type=str, default=data_dir_root, help=\"data dir\") FLAGS", "of weighted content divergence terms\") parser.add_argument('--lambda1', type=float, default=0.001, help=\"default weight of intra_mi terms\")", "# SAVE and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save for vae_bimodal\") parser.add_argument('--load_saved', type=bool,", "default=0.001, help=\"default weight of intra_mi terms\") parser.add_argument('--lambda2', type=float, default=0.001, help=\"default weight of inter_mi", "FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir, 'fmri_train_data.mat'))['data'].astype('double') train_image = sio.loadmat(os.path.join(image_dir_train, 'feat_pca_train.mat'))['data'].astype('double')#[:,0:3000] train_text = sio.loadmat(os.path.join(text_dir_train,", "latent space\") # SAVE and LOAD parser.add_argument('--mm_vae_save', type=str, default='mm_vae', help=\"model save for vae_bimodal\")", "default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos', type=bool, default=True, help=\"unimodal_klds\") parser.add_argument('--factorized_representation', action='store_true', default=False,", "val for adam\") parser.add_argument('--beta_2', type=float, default=0.999, help=\"default beta_2 val for adam\") parser.add_argument('--start_epoch', type=int,", "for training the model') parser.add_argument('--modality_jsd', type=bool, default=False, help=\"modality_jsd\") parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe',", "of modality image\") parser.add_argument('--m3_dim', type=int, default=dim_text, help=\"dimension of modality text\") parser.add_argument('--data_dir_root', type=str, default=data_dir_root,", "in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\") parser.add_argument('--sbj', type=str, default='sub-03', help=\"fmri subject\") parser.add_argument('--roi', type=str, default='LVC_HVC_IT',", "for training\") parser.add_argument('--initial_learning_rate', type=float, default=0.0001, help=\"starting learning rate\") parser.add_argument('--beta_1', type=float, default=0.9, help=\"default beta_1", "experiments parser.add_argument('--dir_experiment', type=str, default='./logs', help=\"directory to save logs in\") parser.add_argument('--dataname', type=str, default='DIR-Wiki', help=\"dataset\")", "parser.add_argument('--beta_content', type=float, default=1.0, help=\"default weight of sum of weighted content divergence terms\") parser.add_argument('--lambda1',", "os.path.join(data_dir_root, 'brain_feature', FLAGS.roi, FLAGS.sbj) image_dir_train = os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root,", "os.path.join(data_dir_root, 'visual_feature/ImageNetTraining', FLAGS.image_model+'-PCA', FLAGS.sbj) text_dir_train = os.path.join(data_dir_root, 'textual_feature/ImageNetTraining/text', FLAGS.text_model, FLAGS.sbj) train_brain = sio.loadmat(os.path.join(brain_dir,", "embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type', type=str, default='zsl', help='normal or", "parser.add_argument('--modality_poe', type=bool, default=False, help=\"modality_poe\") parser.add_argument('--modality_moe', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--joint_elbo', type=bool, default=False, help=\"modality_moe\") parser.add_argument('--poe_unimodal_elbos',", "type=float, default=1.0, help=\"default weight of sum of weighted style divergence terms\") parser.add_argument('--beta_content', type=float,", "help=\"default beta_2 val for adam\") parser.add_argument('--start_epoch', type=int, default=0, help=\"flag to set the starting", "of inter_mi terms\") FLAGS = parser.parse_args() data_dir_root = os.path.join('./data', FLAGS.dataname) brain_dir = os.path.join(data_dir_root,", "type=str, default='GPTNeo', help=\"text embedding model\") parser.add_argument('--image_model', type=str, default='pytorch/repvgg_b3g4', help=\"image embedding model\") parser.add_argument('--test_type', type=str," ]
[ "and under the MIT license # from mineturtle import * import lsystem t", "the MIT license # from mineturtle import * import lsystem t = Turtle()", "ensure angles are always integral multiples of 90 degrees t.gridalign() rules = {'X':'X+YF+',", "'+': lambda: t.yaw(90), '-': lambda: t.yaw(-90), 'F': lambda: go() } lsystem.lsystem('FX', rules, dictionary,", "'Y':'-FX-Y'} def go(): # draw a wall segment with a door t.pendown() t.penblock(block.BRICK_BLOCK)", "t.startface() for i in range(4): t.go(4) t.pitch(90) t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90)", "by <NAME> and under the MIT license # from mineturtle import * import", "t.penblock(block.BRICK_BLOCK) t.startface() for i in range(4): t.go(4) t.pitch(90) t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR)", "import lsystem t = Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles are always", "<NAME> and under the MIT license # from mineturtle import * import lsystem", "license # from mineturtle import * import lsystem t = Turtle() t.pendelay(0) t.turtle(None)", "from mineturtle import * import lsystem t = Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) #", "* import lsystem t = Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles are", "t.penblock(block.BRICK_BLOCK) # ensure angles are always integral multiples of 90 degrees t.gridalign() rules", "segment with a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i in range(4): t.go(4) t.pitch(90)", "a wall segment with a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i in range(4):", "import * import lsystem t = Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles", "{'X':'X+YF+', 'Y':'-FX-Y'} def go(): # draw a wall segment with a door t.pendown()", "t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary = { '+': lambda: t.yaw(90),", "t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary = { '+': lambda: t.yaw(90), '-': lambda: t.yaw(-90),", "def go(): # draw a wall segment with a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface()", "t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i in range(4): t.go(4) t.pitch(90) t.endface() t.penup() t.go(2) t.pendown()", "lsystem t = Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles are always integral", "range(4): t.go(4) t.pitch(90) t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1)", "= { '+': lambda: t.yaw(90), '-': lambda: t.yaw(-90), 'F': lambda: go() } lsystem.lsystem('FX',", "with a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i in range(4): t.go(4) t.pitch(90) t.endface()", "= Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles are always integral multiples of", "t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles are always integral multiples of 90 degrees", "door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i in range(4): t.go(4) t.pitch(90) t.endface() t.penup() t.go(2)", "= {'X':'X+YF+', 'Y':'-FX-Y'} def go(): # draw a wall segment with a door", "of 90 degrees t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'} def go(): # draw a", "in range(4): t.go(4) t.pitch(90) t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180)", "a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i in range(4): t.go(4) t.pitch(90) t.endface() t.penup()", "mineturtle import * import lsystem t = Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure", "t.go(2) dictionary = { '+': lambda: t.yaw(90), '-': lambda: t.yaw(-90), 'F': lambda: go()", "lambda: t.yaw(90), '-': lambda: t.yaw(-90), 'F': lambda: go() } lsystem.lsystem('FX', rules, dictionary, 14)", "angles are always integral multiples of 90 degrees t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'}", "# from mineturtle import * import lsystem t = Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK)", "for i in range(4): t.go(4) t.pitch(90) t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1)", "t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles are always integral multiples of 90 degrees t.gridalign()", "Code by <NAME> and under the MIT license # from mineturtle import *", "# # Code by <NAME> and under the MIT license # from mineturtle", "t.pitch(90) t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2)", "dictionary = { '+': lambda: t.yaw(90), '-': lambda: t.yaw(-90), 'F': lambda: go() }", "90 degrees t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'} def go(): # draw a wall", "t.pitch(90) t.go(2) dictionary = { '+': lambda: t.yaw(90), '-': lambda: t.yaw(-90), 'F': lambda:", "t.go(1) t.pitch(90) t.go(2) dictionary = { '+': lambda: t.yaw(90), '-': lambda: t.yaw(-90), 'F':", "rules = {'X':'X+YF+', 'Y':'-FX-Y'} def go(): # draw a wall segment with a", "are always integral multiples of 90 degrees t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'} def", "t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary", "Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles are always integral multiples of 90", "i in range(4): t.go(4) t.pitch(90) t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup()", "t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary = { '+': lambda: t.yaw(90), '-': lambda:", "draw a wall segment with a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i in", "{ '+': lambda: t.yaw(90), '-': lambda: t.yaw(-90), 'F': lambda: go() } lsystem.lsystem('FX', rules,", "MIT license # from mineturtle import * import lsystem t = Turtle() t.pendelay(0)", "t.go(4) t.pitch(90) t.endface() t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90)", "t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary = { '+':", "# ensure angles are always integral multiples of 90 degrees t.gridalign() rules =", "wall segment with a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i in range(4): t.go(4)", "degrees t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'} def go(): # draw a wall segment", "t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'} def go(): # draw a wall segment with", "multiples of 90 degrees t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'} def go(): # draw", "t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary = { '+': lambda:", "# Code by <NAME> and under the MIT license # from mineturtle import", "t = Turtle() t.pendelay(0) t.turtle(None) t.penblock(block.BRICK_BLOCK) # ensure angles are always integral multiples", "t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary = {", "t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary = { '+': lambda: t.yaw(90), '-':", "go(): # draw a wall segment with a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for", "always integral multiples of 90 degrees t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'} def go():", "integral multiples of 90 degrees t.gridalign() rules = {'X':'X+YF+', 'Y':'-FX-Y'} def go(): #", "# draw a wall segment with a door t.pendown() t.penblock(block.BRICK_BLOCK) t.startface() for i", "t.penup() t.go(2) t.pendown() t.penblock(block.AIR) t.pitch(90) t.go(1) t.penup() t.pitch(180) t.go(1) t.pitch(90) t.go(2) dictionary =", "under the MIT license # from mineturtle import * import lsystem t =" ]
[ "} ) assert response.status_code == 201 response_2 = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\",", "def test_signup_returns_200(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\"", "\"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 def", "@pytest.mark.usefixtures(\"test_db_session\") class TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\":", "201 response_2 = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert", "from fastapi.testclient import TestClient @pytest.mark.integration @pytest.mark.usefixtures(\"test_db_session\") class TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient): response", "import TestClient @pytest.mark.integration @pytest.mark.usefixtures(\"test_db_session\") class TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient): response = client.post(", "class TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\",", "response_2 = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response_2.status_code", "fastapi.testclient import TestClient @pytest.mark.integration @pytest.mark.usefixtures(\"test_db_session\") class TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient): response =", "assert response.status_code == 201 def test_signup_existing_user_returns_422(self, client: TestClient): response = client.post( \"/users/signup\", json={", ") assert response.status_code == 201 def test_signup_existing_user_returns_422(self, client: TestClient): response = client.post( \"/users/signup\",", "client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } )", "import pytest from fastapi.testclient import TestClient @pytest.mark.integration @pytest.mark.usefixtures(\"test_db_session\") class TestSignupEndpoint: def test_signup_returns_200(self, client:", "201 def test_signup_existing_user_returns_422(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\":", "def test_signup_existing_user_returns_422(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\"", "response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code", "\"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 def test_signup_existing_user_returns_422(self, client: TestClient): response", "test_signup_returns_200(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" }", "\"<PASSWORD>\" } ) assert response.status_code == 201 response_2 = client.post( \"/users/signup\", json={ \"email\":", "TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\":", "\"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 response_2 = client.post( \"/users/signup\", json={", "TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert", "assert response.status_code == 201 response_2 = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\"", "\"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 def test_signup_existing_user_returns_422(self, client:", "response.status_code == 201 response_2 = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" }", "pytest from fastapi.testclient import TestClient @pytest.mark.integration @pytest.mark.usefixtures(\"test_db_session\") class TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient):", ") assert response.status_code == 201 response_2 = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\":", "json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 def test_signup_existing_user_returns_422(self,", "} ) assert response.status_code == 201 def test_signup_existing_user_returns_422(self, client: TestClient): response = client.post(", "\"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 response_2 = client.post(", "test_signup_existing_user_returns_422(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" }", "json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 response_2 =", "response.status_code == 201 def test_signup_existing_user_returns_422(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\":", "\"<PASSWORD>\" } ) assert response.status_code == 201 def test_signup_existing_user_returns_422(self, client: TestClient): response =", "== 201 def test_signup_existing_user_returns_422(self, client: TestClient): response = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\",", "@pytest.mark.integration @pytest.mark.usefixtures(\"test_db_session\") class TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient): response = client.post( \"/users/signup\", json={", "TestClient @pytest.mark.integration @pytest.mark.usefixtures(\"test_db_session\") class TestSignupEndpoint: def test_signup_returns_200(self, client: TestClient): response = client.post( \"/users/signup\",", "\"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 response_2", "= client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response_2.status_code ==", "== 201 response_2 = client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } )", "client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response_2.status_code == 422", "\"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 def test_signup_existing_user_returns_422(self, client: TestClient):", "client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201", "\"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code == 201 response_2 = client.post( \"/users/signup\",", "= client.post( \"/users/signup\", json={ \"email\": \"<EMAIL>\", \"password\": \"<PASSWORD>\" } ) assert response.status_code ==" ]
[ "{ romaji english } siteUrl } } image { large } description(asHtml: true)", "} media(perPage: 1) { nodes { title { romaji english } siteUrl }", "english } siteUrl } } image { large } description(asHtml: true) } }", "1) { nodes { title { romaji english } siteUrl } } image", "name { full } media(perPage: 1) { nodes { title { romaji english", "searchChar(): query = ''' query ($search: String) { Character(search: $search) { siteUrl name", "''' query ($search: String) { Character(search: $search) { siteUrl name { full }", "siteUrl name { full } media(perPage: 1) { nodes { title { romaji", "siteUrl } } image { large } description(asHtml: true) } } ''' return", "{ nodes { title { romaji english } siteUrl } } image {", "query = ''' query ($search: String) { Character(search: $search) { siteUrl name {", "{ title { romaji english } siteUrl } } image { large }", "media(perPage: 1) { nodes { title { romaji english } siteUrl } }", "title { romaji english } siteUrl } } image { large } description(asHtml:", "{ full } media(perPage: 1) { nodes { title { romaji english }", "String) { Character(search: $search) { siteUrl name { full } media(perPage: 1) {", "nodes { title { romaji english } siteUrl } } image { large", "{ siteUrl name { full } media(perPage: 1) { nodes { title {", "= ''' query ($search: String) { Character(search: $search) { siteUrl name { full", "romaji english } siteUrl } } image { large } description(asHtml: true) }", "$search) { siteUrl name { full } media(perPage: 1) { nodes { title", "{ Character(search: $search) { siteUrl name { full } media(perPage: 1) { nodes", "Character(search: $search) { siteUrl name { full } media(perPage: 1) { nodes {", "full } media(perPage: 1) { nodes { title { romaji english } siteUrl", "} siteUrl } } image { large } description(asHtml: true) } } '''", "def searchChar(): query = ''' query ($search: String) { Character(search: $search) { siteUrl", "($search: String) { Character(search: $search) { siteUrl name { full } media(perPage: 1)", "query ($search: String) { Character(search: $search) { siteUrl name { full } media(perPage:", "} } image { large } description(asHtml: true) } } ''' return query" ]
[ "aln_dict): \"\"\" Annotate each mutation as either nonsynonymous or synonymous \"\"\" coding_status =", "= seq_parent.replace(\"-\", \"\") # collapse gaps seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent,", "== \"__main__\": infile_aln = sys.argv[1] infile_fitness_tree = sys.argv[2] outfile = sys.argv[3] print infile_fitness_tree", "boundaries_gapped = np.array(boundaries_gapped) - 1 # not used anymore (we do transform earlier)", "= Align.MultipleSeqAlignment([]) aln_dict = {} with open(infile, 'r') as f: for seq_record in", "Align, AlignIO, Phylo from itertools import izip def load_tree(f): t = Phylo.read(f, 'newick')", "ungapped sequence to corresponding positions in a gapped sequence \"\"\" # count number", "# translate AA_mutated = Seq(seq_mutated, generic_dna).translate() if AA_parent != AA_mutated: # compare AA", "gaps[x] x_transformed = x + my_gaps positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs):", "\"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] = regions return", "seq3 = Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x) for x in seq1.split(\"*\")]) # find", "print infile_fitness_tree print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0) aln,", "in seq1.split(\"*\")]) # find longest ORF in each frame L_seq2 = max([len(x) for", "= [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped", "t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True) return t def load_aln(infile): aln = Align.MultipleSeqAlignment([])", "in enumerate(izip(X,Y)): if x != y: d = [i, x, y] diffs.append(d) return", "every frame seq2 = Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x)", "a gapped sequence \"\"\" # count number of gaps before each position counter", "boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped) - 1 # not used anymore (we do", "i, x in enumerate(Ls) if x == L_max] # get frame of longest", "load_tree(f): t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True) return t", "int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] # transform positions of region boundaries to corresponding positions", "longest ORF s = s.replace(\"-\", \"\") seq1 = Seq(s, generic_dna).translate() # translate in", "= seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent, generic_dna).translate() # translate AA_mutated = Seq(seq_mutated, generic_dna).translate()", "boundaries labels = [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"],", "new sequence positions_transformed = [] for x in positions: my_gaps = gaps[x] x_transformed", "np import pandas as pd from Bio.Seq import Seq from Bio.Alphabet import generic_dna", "regions return df_mutations if __name__ == \"__main__\": infile_aln = sys.argv[1] infile_fitness_tree = sys.argv[2]", "row[\"base_after\"] # introduce mutation seq_mutated = \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\") # collapse", "in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] # get parent sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])]", "= {} with open(infile, 'r') as f: for seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record)", "from Bio.Alphabet import generic_dna from Bio import SeqIO, Align, AlignIO, Phylo from itertools", "each mutation (CDR/FWR) \"\"\" # get one sequence sequence_uids = [x for x", "= [] for i, (x, y) in enumerate(izip(X,Y)): if x != y: d", "> 1: print \"Warning: more than one reading frame had max length ORF\"", "[i for i, x in enumerate(Ls) if x == L_max] # get frame", "[\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped =", "\"\") AA_parent = Seq(seq_parent, generic_dna).translate() # translate AA_mutated = Seq(seq_mutated, generic_dna).translate() if AA_parent", "df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict = load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations", "(CDR/FWR) \"\"\" # get one sequence sequence_uids = [x for x in aln_dict.keys()", "features = [clade.name, parent.name, position, base_before, base_after] df.loc[i] = features i += 1", "AA_mutated: # compare AA before and after mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] =", "seq2 = Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x) for x", "longest ORF among all frames frames_max = [i for i, x in enumerate(Ls)", "in positions: my_gaps = gaps[x] x_transformed = x + my_gaps positions_transformed.append(x_transformed) return positions_transformed", "gapped sequence \"\"\" # count number of gaps before each position counter =", "region boundaries to corresponding positions in gapped alignment fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\",", "= [L_seq1, L_seq2, L_seq3] L_max = max(Ls) # get longest ORF among all", "= pd.DataFrame(columns=header) i = 0 for clade in T.find_clades(): if clade.name in [None,", "{} with open(infile, 'r') as f: for seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id]", "diffs.append(d) return diffs def get_mutations(T, aln_dict): \"\"\" Get mutations on each branch of", "seq_clade) for diff in diffs: position, base_before, base_after = tuple(diff) features = [clade.name,", "longest ORF if len(frames_max) > 1: print \"Warning: more than one reading frame", "load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict = {} with open(infile, 'r') as f: for", "child_clade): node_path = tree.get_path(child_clade) return node_path[-2] def str_diffs(X, Y): diffs = [] for", "to corresponding positions in a gapped sequence \"\"\" # count number of gaps", "- 1 # not used anymore (we do transform earlier) boundaries_gapped[0] = 0", "return df_mutations if __name__ == \"__main__\": infile_aln = sys.argv[1] infile_fitness_tree = sys.argv[2] outfile", "def str_diffs(X, Y): diffs = [] for i, (x, y) in enumerate(izip(X,Y)): if", "x in seq2.split(\"*\")]) L_seq3 = max([len(x) for x in seq3.split(\"*\")]) Ls = [L_seq1,", "counter = 0 gaps = [] for i, x in enumerate(s): if x", "def load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict = {} with open(infile, 'r') as f:", "# decrement C region boundary (end of sequence) to fit within array boundaries_gapped", "[\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"] df = pd.DataFrame(columns=header) i = 0 for clade", "x] my_sequence_uid = int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] # transform positions of region boundaries", "boundaries_gapped[0] = 0 boundaries_gapped[-1] += 1 # map mutations to regions using boundaries", "get_parent(T, clade) seq_parent = aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade) for", "coding_status return df_mutations def map_positions(s, positions): \"\"\" Maps positions in an ungapped sequence", "either nonsynonymous or synonymous \"\"\" coding_status = [] for i, row in df_mutations.iterrows():", "def load_tree(f): t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True) return", "clade) seq_parent = aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade) for diff", "not in x] my_sequence_uid = int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] # transform positions of", "Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True) return t def load_aln(infile): aln", "SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return aln, aln_dict def get_parent(tree, child_clade): node_path", "do transform earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1] += 1 # map mutations to", "return frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each mutation as either nonsynonymous or", "sequence_uids = [x for x in aln_dict.keys() if \"_\" not in x] my_sequence_uid", "x in enumerate(Ls) if x == L_max] # get frame of longest ORF", "\"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) - 1 # transform to zero-indexed", "str_diffs(X, Y): diffs = [] for i, (x, y) in enumerate(izip(X,Y)): if x", "positions): \"\"\" Maps positions in an ungapped sequence to corresponding positions in a", "for seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return aln, aln_dict def", "= aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade) for diff in diffs:", "def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate region of each mutation (CDR/FWR) \"\"\" #", "\"FWR3\", \"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] = regions", "# transform to zero-indexed positions boundaries_ungapped[-1] -= 1 # decrement C region boundary", "decrement C region boundary (end of sequence) to fit within array boundaries_gapped =", "AA_parent = Seq(seq_parent, generic_dna).translate() # translate AA_mutated = Seq(seq_mutated, generic_dna).translate() if AA_parent !=", "seq3.split(\"*\")]) Ls = [L_seq1, L_seq2, L_seq3] L_max = max(Ls) # get longest ORF", "= str_diffs(seq_parent, seq_clade) for diff in diffs: position, base_before, base_after = tuple(diff) features", "= \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict = load_aln(infile_aln) fitness_tree =", "branch of the tree \"\"\" header = [\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"] df", "diffs = str_diffs(seq_parent, seq_clade) for diff in diffs: position, base_before, base_after = tuple(diff)", "= tuple(diff) features = [clade.name, parent.name, position, base_before, base_after] df.loc[i] = features i", "\"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) - 1 #", "translate AA_mutated = Seq(seq_mutated, generic_dna).translate() if AA_parent != AA_mutated: # compare AA before", "positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate region of each mutation", "diff in diffs: position, base_before, base_after = tuple(diff) features = [clade.name, parent.name, position,", "aln_dict = load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations,", "with open(infile, 'r') as f: for seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] =", "earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1] += 1 # map mutations to regions using", "features i += 1 return df def find_frame(s): # Finds longest ORF s", "annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each mutation as either nonsynonymous or synonymous \"\"\" coding_status", "= df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) - 1 # transform to zero-indexed positions boundaries_ungapped[-1]", "import izip def load_tree(f): t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 #", "\"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\") # collapse gaps seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent", "= aln_dict[str(my_sequence_uid)] # transform positions of region boundaries to corresponding positions in gapped", "= Seq(seq_mutated, generic_dna).translate() if AA_parent != AA_mutated: # compare AA before and after", "each mutation as either nonsynonymous or synonymous \"\"\" coding_status = [] for i,", "= 0 boundaries_gapped[-1] += 1 # map mutations to regions using boundaries labels", "df_mutations[\"region\"] = regions return df_mutations if __name__ == \"__main__\": infile_aln = sys.argv[1] infile_fitness_tree", "\"\"\" header = [\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"] df = pd.DataFrame(columns=header) i =", "= Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x) for x in seq1.split(\"*\")]) # find longest", "clade in T.find_clades(): if clade.name in [None, \"germline\", \"2_\"]: continue parent = get_parent(T,", "find longest ORF in each frame L_seq2 = max([len(x) for x in seq2.split(\"*\")])", "return t def load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict = {} with open(infile, 'r')", "coding_status = [] for i, row in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] # get", "generic_dna).translate() # translate in every frame seq2 = Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:],", "region of each mutation (CDR/FWR) \"\"\" # get one sequence sequence_uids = [x", "\"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) - 1 # transform", "positions: my_gaps = gaps[x] x_transformed = x + my_gaps positions_transformed.append(x_transformed) return positions_transformed def", "AA before and after mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return df_mutations", "+= 1 return df def find_frame(s): # Finds longest ORF s = s.replace(\"-\",", "= [x for x in aln_dict.keys() if \"_\" not in x] my_sequence_uid =", "C region boundary (end of sequence) to fit within array boundaries_gapped = map_positions(s,", "region boundary (end of sequence) to fit within array boundaries_gapped = map_positions(s, boundaries_ungapped)", "boundaries_gapped = map_positions(s, boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped) - 1 # not used", "return diffs def get_mutations(T, aln_dict): \"\"\" Get mutations on each branch of the", "i, x in enumerate(s): if x == \"-\": counter += 1 gaps.append(counter) #", "T.find_clades(): if clade.name in [None, \"germline\", \"2_\"]: continue parent = get_parent(T, clade) seq_parent", "= 0 gaps = [] for i, x in enumerate(s): if x ==", "position counter = 0 gaps = [] for i, x in enumerate(s): if", "return df_mutations def map_positions(s, positions): \"\"\" Maps positions in an ungapped sequence to", "1 return df def find_frame(s): # Finds longest ORF s = s.replace(\"-\", \"\")", "t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True) return t def load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict", "(end of sequence) to fit within array boundaries_gapped = map_positions(s, boundaries_ungapped) # boundaries_gapped", "sequence to corresponding positions in a gapped sequence \"\"\" # count number of", "for i, x in enumerate(Ls) if x == L_max] # get frame of", "corresponding positions in gapped alignment fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\",", "max(Ls) # get longest ORF among all frames frames_max = [i for i,", "gaps = [] for i, x in enumerate(s): if x == \"-\": counter", "# find longest ORF in each frame L_seq2 = max([len(x) for x in", "one reading frame had max length ORF\" return frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\"", "str(seq_record.seq) return aln, aln_dict def get_parent(tree, child_clade): node_path = tree.get_path(child_clade) return node_path[-2] def", "before and after mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return df_mutations def", "if AA_parent != AA_mutated: # compare AA before and after mutation coding_status.append(\"N\") else:", "as either nonsynonymous or synonymous \"\"\" coding_status = [] for i, row in", "if clade.name in [None, \"germline\", \"2_\"]: continue parent = get_parent(T, clade) seq_parent =", "len(frames_max) > 1: print \"Warning: more than one reading frame had max length", "Seq from Bio.Alphabet import generic_dna from Bio import SeqIO, Align, AlignIO, Phylo from", "seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent, generic_dna).translate() # translate AA_mutated = Seq(seq_mutated,", "for i, row in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] # get parent sequence seq_mutated", "parent.name, position, base_before, base_after] df.loc[i] = features i += 1 return df def", "if len(frames_max) > 1: print \"Warning: more than one reading frame had max", "of region boundaries to corresponding positions in gapped alignment fields = [\"FWR1_start\", \"CDR1_start\",", "parent sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce mutation seq_mutated =", "[\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False,", "aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade) for diff in diffs: position,", "return df def find_frame(s): # Finds longest ORF s = s.replace(\"-\", \"\") seq1", "'r') as f: for seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return", "print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict =", "[None, \"germline\", \"2_\"]: continue parent = get_parent(T, clade) seq_parent = aln_dict[parent.name] seq_clade =", "t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True) return t def", "[clade.name, parent.name, position, base_before, base_after] df.loc[i] = features i += 1 return df", "aln_dict.keys() if \"_\" not in x] my_sequence_uid = int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] #", "frame had max length ORF\" return frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each", "from Bio.Seq import Seq from Bio.Alphabet import generic_dna from Bio import SeqIO, Align,", "include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] = regions return df_mutations if __name__ == \"__main__\": infile_aln", "sys.argv[1] infile_fitness_tree = sys.argv[2] outfile = sys.argv[3] print infile_fitness_tree print infile_aln infile_df_seqs =", "pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] = regions return df_mutations if __name__ ==", "infile_aln = sys.argv[1] infile_fitness_tree = sys.argv[2] outfile = sys.argv[3] print infile_fitness_tree print infile_aln", "translate in every frame seq2 = Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate() L_seq1", "pandas as pd from Bio.Seq import Seq from Bio.Alphabet import generic_dna from Bio", "for clade in T.find_clades(): if clade.name in [None, \"germline\", \"2_\"]: continue parent =", "= 0.0 # t.ladderize(reverse=True) return t def load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict =", "boundaries_ungapped[-1] -= 1 # decrement C region boundary (end of sequence) to fit", "f: for seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return aln, aln_dict", "'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True) return t def load_aln(infile): aln =", "+= 1 gaps.append(counter) # transform boundaries to corresponding positions in new sequence positions_transformed", "if x == \"-\": counter += 1 gaps.append(counter) # transform boundaries to corresponding", "# transform boundaries to corresponding positions in new sequence positions_transformed = [] for", "aln_dict): \"\"\" Get mutations on each branch of the tree \"\"\" header =", "length ORF\" return frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each mutation as either", "L_max = max(Ls) # get longest ORF among all frames frames_max = [i", "= Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True) return t def load_aln(infile):", "in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return aln, aln_dict def get_parent(tree, child_clade):", "position, base_before, base_after] df.loc[i] = features i += 1 return df def find_frame(s):", "annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate region of each mutation (CDR/FWR) \"\"\" # get", "= np.array(boundaries_ungapped) - 1 # transform to zero-indexed positions boundaries_ungapped[-1] -= 1 #", "\"position\", \"base_before\", \"base_after\"] df = pd.DataFrame(columns=header) i = 0 for clade in T.find_clades():", "= Seq(s, generic_dna).translate() # translate in every frame seq2 = Seq(s[1:], generic_dna).translate() seq3", "[L_seq1, L_seq2, L_seq3] L_max = max(Ls) # get longest ORF among all frames", "enumerate(Ls) if x == L_max] # get frame of longest ORF if len(frames_max)", "aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict) df_mutations = annotate_regions(df_mutations, aln_dict, df_seqs) df_mutations.to_csv(outfile) print \"Done!!\"", "\"\") # collapse gaps seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent, generic_dna).translate() #", "mutations on each branch of the tree \"\"\" header = [\"name\", \"parent_name\", \"position\",", "\"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"]", "boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] = regions return df_mutations if __name__ == \"__main__\":", "zero-indexed positions boundaries_ungapped[-1] -= 1 # decrement C region boundary (end of sequence)", "str_diffs(seq_parent, seq_clade) for diff in diffs: position, base_before, base_after = tuple(diff) features =", "node_path[-2] def str_diffs(X, Y): diffs = [] for i, (x, y) in enumerate(izip(X,Y)):", "max length ORF\" return frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each mutation as", "tree \"\"\" header = [\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"] df = pd.DataFrame(columns=header) i", "boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) - 1 # transform to zero-indexed positions", "y] diffs.append(d) return diffs def get_mutations(T, aln_dict): \"\"\" Get mutations on each branch", "sequence \"\"\" # count number of gaps before each position counter = 0", "\"\"\" Annotate region of each mutation (CDR/FWR) \"\"\" # get one sequence sequence_uids", "in [None, \"germline\", \"2_\"]: continue parent = get_parent(T, clade) seq_parent = aln_dict[parent.name] seq_clade", "= s.replace(\"-\", \"\") seq1 = Seq(s, generic_dna).translate() # translate in every frame seq2", "for i, x in enumerate(s): if x == \"-\": counter += 1 gaps.append(counter)", "= Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x) for x in", "sys import numpy as np import pandas as pd from Bio.Seq import Seq", "[] for i, (x, y) in enumerate(izip(X,Y)): if x != y: d =", "enumerate(s): if x == \"-\": counter += 1 gaps.append(counter) # transform boundaries to", "number of gaps before each position counter = 0 gaps = [] for", "1 # not used anymore (we do transform earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1]", "as f: for seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return aln,", "the tree \"\"\" header = [\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"] df = pd.DataFrame(columns=header)", "+ my_gaps positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate region of", "= aln_dict[row[\"parent_name\"]] # get parent sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] #", "= regions return df_mutations if __name__ == \"__main__\": infile_aln = sys.argv[1] infile_fitness_tree =", "x != y: d = [i, x, y] diffs.append(d) return diffs def get_mutations(T,", "an ungapped sequence to corresponding positions in a gapped sequence \"\"\" # count", "had max length ORF\" return frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each mutation", "in seq2.split(\"*\")]) L_seq3 = max([len(x) for x in seq3.split(\"*\")]) Ls = [L_seq1, L_seq2,", "= np.array(boundaries_gapped) - 1 # not used anymore (we do transform earlier) boundaries_gapped[0]", "import SeqIO, Align, AlignIO, Phylo from itertools import izip def load_tree(f): t =", "to zero-indexed positions boundaries_ungapped[-1] -= 1 # decrement C region boundary (end of", "seq_clade = aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade) for diff in diffs: position, base_before,", "counter += 1 gaps.append(counter) # transform boundaries to corresponding positions in new sequence", "in each frame L_seq2 = max([len(x) for x in seq2.split(\"*\")]) L_seq3 = max([len(x)", "import Seq from Bio.Alphabet import generic_dna from Bio import SeqIO, Align, AlignIO, Phylo", "from Bio import SeqIO, Align, AlignIO, Phylo from itertools import izip def load_tree(f):", "in an ungapped sequence to corresponding positions in a gapped sequence \"\"\" #", "L_seq1 = max([len(x) for x in seq1.split(\"*\")]) # find longest ORF in each", "L_seq3 = max([len(x) for x in seq3.split(\"*\")]) Ls = [L_seq1, L_seq2, L_seq3] L_max", "= [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True,", "frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each mutation as either nonsynonymous or synonymous", "x == L_max] # get frame of longest ORF if len(frames_max) > 1:", "= \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\") # collapse gaps seq_mutated = seq_mutated.replace(\"-\", \"\")", "import pandas as pd from Bio.Seq import Seq from Bio.Alphabet import generic_dna from", "fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields]", "regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] = regions return df_mutations if", "= max([len(x) for x in seq2.split(\"*\")]) L_seq3 = max([len(x) for x in seq3.split(\"*\")])", "count number of gaps before each position counter = 0 gaps = []", "# not used anymore (we do transform earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1] +=", "transform boundaries to corresponding positions in new sequence positions_transformed = [] for x", "# get parent sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce mutation", "L_max] # get frame of longest ORF if len(frames_max) > 1: print \"Warning:", "boundaries_ungapped = np.array(boundaries_ungapped) - 1 # transform to zero-indexed positions boundaries_ungapped[-1] -= 1", "for x in aln_dict.keys() if \"_\" not in x] my_sequence_uid = int(sequence_uids[0]) s", "= str(seq_record.seq) return aln, aln_dict def get_parent(tree, child_clade): node_path = tree.get_path(child_clade) return node_path[-2]", "mutation seq_mutated = \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\") # collapse gaps seq_mutated =", "in x] my_sequence_uid = int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] # transform positions of region", "infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict = load_aln(infile_aln)", "1: print \"Warning: more than one reading frame had max length ORF\" return", "Maps positions in an ungapped sequence to corresponding positions in a gapped sequence", "[] for i, row in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] # get parent sequence", "i = 0 for clade in T.find_clades(): if clade.name in [None, \"germline\", \"2_\"]:", "\"\"\" # count number of gaps before each position counter = 0 gaps", "1 gaps.append(counter) # transform boundaries to corresponding positions in new sequence positions_transformed =", "return aln, aln_dict def get_parent(tree, child_clade): node_path = tree.get_path(child_clade) return node_path[-2] def str_diffs(X,", "my_sequence_uid = int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] # transform positions of region boundaries to", "in a gapped sequence \"\"\" # count number of gaps before each position", "tuple(diff) features = [clade.name, parent.name, position, base_before, base_after] df.loc[i] = features i +=", "x in enumerate(s): if x == \"-\": counter += 1 gaps.append(counter) # transform", "pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict = load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree,", "print \"Warning: more than one reading frame had max length ORF\" return frames_max[0]", "s.replace(\"-\", \"\") seq1 = Seq(s, generic_dna).translate() # translate in every frame seq2 =", "df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict) df_mutations = annotate_regions(df_mutations, aln_dict, df_seqs)", "df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) - 1 # transform to zero-indexed positions boundaries_ungapped[-1] -=", "= list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce mutation seq_mutated = \"\".join(seq_mutated) seq_parent =", "aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade) for diff in diffs: position, base_before, base_after =", "\"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels)", "+= 1 # map mutations to regions using boundaries labels = [\"FWR1\", \"CDR1\",", "df_mutations if __name__ == \"__main__\": infile_aln = sys.argv[1] infile_fitness_tree = sys.argv[2] outfile =", "Align.MultipleSeqAlignment([]) aln_dict = {} with open(infile, 'r') as f: for seq_record in SeqIO.parse(f,", "positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate region of each mutation (CDR/FWR) \"\"\"", "x in seq1.split(\"*\")]) # find longest ORF in each frame L_seq2 = max([len(x)", "mutation (CDR/FWR) \"\"\" # get one sequence sequence_uids = [x for x in", "seq_parent = aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade) for diff in", "seq_parent = seq_parent.replace(\"-\", \"\") # collapse gaps seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent =", "positions of region boundaries to corresponding positions in gapped alignment fields = [\"FWR1_start\",", "anymore (we do transform earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1] += 1 # map", "AlignIO, Phylo from itertools import izip def load_tree(f): t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\")", "get frame of longest ORF if len(frames_max) > 1: print \"Warning: more than", "df = pd.DataFrame(columns=header) i = 0 for clade in T.find_clades(): if clade.name in", "in enumerate(Ls) if x == L_max] # get frame of longest ORF if", "\"_\" not in x] my_sequence_uid = int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] # transform positions", "1 # map mutations to regions using boundaries labels = [\"FWR1\", \"CDR1\", \"FWR2\",", "if x != y: d = [i, x, y] diffs.append(d) return diffs def", "map_positions(s, positions): \"\"\" Maps positions in an ungapped sequence to corresponding positions in", "get parent sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce mutation seq_mutated", "= sys.argv[2] outfile = sys.argv[3] print infile_fitness_tree print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs", "y: d = [i, x, y] diffs.append(d) return diffs def get_mutations(T, aln_dict): \"\"\"", "def find_frame(s): # Finds longest ORF s = s.replace(\"-\", \"\") seq1 = Seq(s,", "compare AA before and after mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return", "each branch of the tree \"\"\" header = [\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"]", "row in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] # get parent sequence seq_mutated = list(seq_parent)", "in T.find_clades(): if clade.name in [None, \"germline\", \"2_\"]: continue parent = get_parent(T, clade)", "aln_dict def get_parent(tree, child_clade): node_path = tree.get_path(child_clade) return node_path[-2] def str_diffs(X, Y): diffs", "= sys.argv[1] infile_fitness_tree = sys.argv[2] outfile = sys.argv[3] print infile_fitness_tree print infile_aln infile_df_seqs", "all frames frames_max = [i for i, x in enumerate(Ls) if x ==", "to fit within array boundaries_gapped = map_positions(s, boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped) -", "# Finds longest ORF s = s.replace(\"-\", \"\") seq1 = Seq(s, generic_dna).translate() #", "of sequence) to fit within array boundaries_gapped = map_positions(s, boundaries_ungapped) # boundaries_gapped =", "= row[\"base_after\"] # introduce mutation seq_mutated = \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\") #", "L_seq3] L_max = max(Ls) # get longest ORF among all frames frames_max =", "get_mutations(T, aln_dict): \"\"\" Get mutations on each branch of the tree \"\"\" header", "as pd from Bio.Seq import Seq from Bio.Alphabet import generic_dna from Bio import", "pd from Bio.Seq import Seq from Bio.Alphabet import generic_dna from Bio import SeqIO,", "fit within array boundaries_gapped = map_positions(s, boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped) - 1", "= load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict)", "__name__ == \"__main__\": infile_aln = sys.argv[1] infile_fitness_tree = sys.argv[2] outfile = sys.argv[3] print", "\"\") seq1 = Seq(s, generic_dna).translate() # translate in every frame seq2 = Seq(s[1:],", "return positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate region of each mutation (CDR/FWR)", "Annotate region of each mutation (CDR/FWR) \"\"\" # get one sequence sequence_uids =", "ORF if len(frames_max) > 1: print \"Warning: more than one reading frame had", "= map_positions(s, boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped) - 1 # not used anymore", "# get longest ORF among all frames frames_max = [i for i, x", "# transform positions of region boundaries to corresponding positions in gapped alignment fields", "each frame L_seq2 = max([len(x) for x in seq2.split(\"*\")]) L_seq3 = max([len(x) for", "get longest ORF among all frames frames_max = [i for i, x in", "to corresponding positions in new sequence positions_transformed = [] for x in positions:", "max([len(x) for x in seq1.split(\"*\")]) # find longest ORF in each frame L_seq2", "generic_dna from Bio import SeqIO, Align, AlignIO, Phylo from itertools import izip def", "\"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] = regions return df_mutations", "longest ORF in each frame L_seq2 = max([len(x) for x in seq2.split(\"*\")]) L_seq3", "\"parent_name\", \"position\", \"base_before\", \"base_after\"] df = pd.DataFrame(columns=header) i = 0 for clade in", "Phylo from itertools import izip def load_tree(f): t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length", "open(infile, 'r') as f: for seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq)", "\"germline\", \"2_\"]: continue parent = get_parent(T, clade) seq_parent = aln_dict[parent.name] seq_clade = aln_dict[clade.name]", "diffs: position, base_before, base_after = tuple(diff) features = [clade.name, parent.name, position, base_before, base_after]", "== \"-\": counter += 1 gaps.append(counter) # transform boundaries to corresponding positions in", "\"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] =", "labels=labels) df_mutations[\"region\"] = regions return df_mutations if __name__ == \"__main__\": infile_aln = sys.argv[1]", "0 gaps = [] for i, x in enumerate(s): if x == \"-\":", "to regions using boundaries labels = [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"]", "d = [i, x, y] diffs.append(d) return diffs def get_mutations(T, aln_dict): \"\"\" Get", "ORF among all frames frames_max = [i for i, x in enumerate(Ls) if", "seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce mutation seq_mutated = \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\")", "ORF s = s.replace(\"-\", \"\") seq1 = Seq(s, generic_dna).translate() # translate in every", "alignment fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped =", "frames frames_max = [i for i, x in enumerate(Ls) if x == L_max]", "Y): diffs = [] for i, (x, y) in enumerate(izip(X,Y)): if x !=", "df_seqs): \"\"\" Annotate region of each mutation (CDR/FWR) \"\"\" # get one sequence", "(x, y) in enumerate(izip(X,Y)): if x != y: d = [i, x, y]", "AA_mutated = Seq(seq_mutated, generic_dna).translate() if AA_parent != AA_mutated: # compare AA before and", "x in positions: my_gaps = gaps[x] x_transformed = x + my_gaps positions_transformed.append(x_transformed) return", "t def load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict = {} with open(infile, 'r') as", "of longest ORF if len(frames_max) > 1: print \"Warning: more than one reading", "for x in seq3.split(\"*\")]) Ls = [L_seq1, L_seq2, L_seq3] L_max = max(Ls) #", "= aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade) for diff in diffs: position, base_before, base_after", "sequence positions_transformed = [] for x in positions: my_gaps = gaps[x] x_transformed =", "\"\"\" # get one sequence sequence_uids = [x for x in aln_dict.keys() if", "<gh_stars>1-10 import sys import numpy as np import pandas as pd from Bio.Seq", "index_col=0) aln, aln_dict = load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations", "seq_parent = aln_dict[row[\"parent_name\"]] # get parent sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"]", "if __name__ == \"__main__\": infile_aln = sys.argv[1] infile_fitness_tree = sys.argv[2] outfile = sys.argv[3]", "aln_dict[str(my_sequence_uid)] # transform positions of region boundaries to corresponding positions in gapped alignment", "within array boundaries_gapped = map_positions(s, boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped) - 1 #", "sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce mutation seq_mutated = \"\".join(seq_mutated)", "= tree.get_path(child_clade) return node_path[-2] def str_diffs(X, Y): diffs = [] for i, (x,", "frames_max = [i for i, x in enumerate(Ls) if x == L_max] #", "= gaps[x] x_transformed = x + my_gaps positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations, aln_dict,", "for diff in diffs: position, base_before, base_after = tuple(diff) features = [clade.name, parent.name,", "# translate in every frame seq2 = Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate()", "!= y: d = [i, x, y] diffs.append(d) return diffs def get_mutations(T, aln_dict):", "coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return df_mutations def map_positions(s, positions): \"\"\" Maps", "x == \"-\": counter += 1 gaps.append(counter) # transform boundaries to corresponding positions", "s = aln_dict[str(my_sequence_uid)] # transform positions of region boundaries to corresponding positions in", "of each mutation (CDR/FWR) \"\"\" # get one sequence sequence_uids = [x for", "fitness_tree = load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict) df_mutations =", "x_transformed = x + my_gaps positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\"", "ORF in each frame L_seq2 = max([len(x) for x in seq2.split(\"*\")]) L_seq3 =", "positions in new sequence positions_transformed = [] for x in positions: my_gaps =", "\"\"\" coding_status = [] for i, row in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] #", "of gaps before each position counter = 0 gaps = [] for i,", "\"\"\" Maps positions in an ungapped sequence to corresponding positions in a gapped", "= sys.argv[3] print infile_fitness_tree print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0,", "continue parent = get_parent(T, clade) seq_parent = aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs =", "[x for x in aln_dict.keys() if \"_\" not in x] my_sequence_uid = int(sequence_uids[0])", "aln_dict = {} with open(infile, 'r') as f: for seq_record in SeqIO.parse(f, 'fasta'):", "# boundaries_gapped = np.array(boundaries_gapped) - 1 # not used anymore (we do transform", "clade.name in [None, \"germline\", \"2_\"]: continue parent = get_parent(T, clade) seq_parent = aln_dict[parent.name]", "= max([len(x) for x in seq3.split(\"*\")]) Ls = [L_seq1, L_seq2, L_seq3] L_max =", "seq1.split(\"*\")]) # find longest ORF in each frame L_seq2 = max([len(x) for x", "Finds longest ORF s = s.replace(\"-\", \"\") seq1 = Seq(s, generic_dna).translate() # translate", "mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return df_mutations def map_positions(s, positions): \"\"\"", "i, row in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] # get parent sequence seq_mutated =", "!= AA_mutated: # compare AA before and after mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"]", "aln_dict[row[\"parent_name\"]] # get parent sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce", "itertools import izip def load_tree(f): t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0", "1 # transform to zero-indexed positions boundaries_ungapped[-1] -= 1 # decrement C region", "= [] for i, x in enumerate(s): if x == \"-\": counter +=", "infile_fitness_tree = sys.argv[2] outfile = sys.argv[3] print infile_fitness_tree print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\"", "Seq(seq_parent, generic_dna).translate() # translate AA_mutated = Seq(seq_mutated, generic_dna).translate() if AA_parent != AA_mutated: #", "gapped alignment fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped", "i, (x, y) in enumerate(izip(X,Y)): if x != y: d = [i, x,", "def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each mutation as either nonsynonymous or synonymous \"\"\"", "map mutations to regions using boundaries labels = [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\",", "gaps seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent, generic_dna).translate() # translate AA_mutated =", "in enumerate(s): if x == \"-\": counter += 1 gaps.append(counter) # transform boundaries", "frame L_seq2 = max([len(x) for x in seq2.split(\"*\")]) L_seq3 = max([len(x) for x", "load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict) df_mutations = annotate_regions(df_mutations, aln_dict,", "reading frame had max length ORF\" return frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate", "[] for i, x in enumerate(s): if x == \"-\": counter += 1", "df_mutations[\"coding_status\"] = coding_status return df_mutations def map_positions(s, positions): \"\"\" Maps positions in an", "\"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict = load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree)", "np.array(boundaries_gapped) - 1 # not used anymore (we do transform earlier) boundaries_gapped[0] =", "def get_parent(tree, child_clade): node_path = tree.get_path(child_clade) return node_path[-2] def str_diffs(X, Y): diffs =", "one sequence sequence_uids = [x for x in aln_dict.keys() if \"_\" not in", "= [] for x in positions: my_gaps = gaps[x] x_transformed = x +", "Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x) for x in seq1.split(\"*\")]) # find longest ORF", "import sys import numpy as np import pandas as pd from Bio.Seq import", "def map_positions(s, positions): \"\"\" Maps positions in an ungapped sequence to corresponding positions", "= load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict) df_mutations = annotate_regions(df_mutations,", "generic_dna).translate() if AA_parent != AA_mutated: # compare AA before and after mutation coding_status.append(\"N\")", "sys.argv[3] print infile_fitness_tree print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0)", "0 boundaries_gapped[-1] += 1 # map mutations to regions using boundaries labels =", "seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce mutation seq_mutated = \"\".join(seq_mutated) seq_parent", "def get_mutations(T, aln_dict): \"\"\" Get mutations on each branch of the tree \"\"\"", "L_seq2 = max([len(x) for x in seq2.split(\"*\")]) L_seq3 = max([len(x) for x in", "import generic_dna from Bio import SeqIO, Align, AlignIO, Phylo from itertools import izip", "t.ladderize(reverse=True) return t def load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict = {} with open(infile,", "aln, aln_dict = load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations =", "\"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped)", "'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return aln, aln_dict def get_parent(tree, child_clade): node_path =", "diffs = [] for i, (x, y) in enumerate(izip(X,Y)): if x != y:", "= 0 for clade in T.find_clades(): if clade.name in [None, \"germline\", \"2_\"]: continue", "max([len(x) for x in seq3.split(\"*\")]) Ls = [L_seq1, L_seq2, L_seq3] L_max = max(Ls)", "seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent, generic_dna).translate() # translate AA_mutated = Seq(seq_mutated, generic_dna).translate() if", "tree.get_path(child_clade) return node_path[-2] def str_diffs(X, Y): diffs = [] for i, (x, y)", "seq1 = Seq(s, generic_dna).translate() # translate in every frame seq2 = Seq(s[1:], generic_dna).translate()", "\"base_before\", \"base_after\"] df = pd.DataFrame(columns=header) i = 0 for clade in T.find_clades(): if", "seq_mutated = \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\") # collapse gaps seq_mutated = seq_mutated.replace(\"-\",", "boundaries to corresponding positions in new sequence positions_transformed = [] for x in", "= pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict = load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations =", "= get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict) df_mutations = annotate_regions(df_mutations, aln_dict, df_seqs) df_mutations.to_csv(outfile)", "\"base_after\"] df = pd.DataFrame(columns=header) i = 0 for clade in T.find_clades(): if clade.name", "seq_parent.replace(\"-\", \"\") # collapse gaps seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent, generic_dna).translate()", "my_gaps = gaps[x] x_transformed = x + my_gaps positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations,", "else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return df_mutations def map_positions(s, positions): \"\"\" Maps positions", "0.0 # t.ladderize(reverse=True) return t def load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict = {}", "L_seq2, L_seq3] L_max = max(Ls) # get longest ORF among all frames frames_max", "after mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return df_mutations def map_positions(s, positions):", "outfile = sys.argv[3] print infile_fitness_tree print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs,", "using boundaries labels = [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions =", "base_after = tuple(diff) features = [clade.name, parent.name, position, base_before, base_after] df.loc[i] = features", "Ls = [L_seq1, L_seq2, L_seq3] L_max = max(Ls) # get longest ORF among", "= features i += 1 return df def find_frame(s): # Finds longest ORF", "of the tree \"\"\" header = [\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"] df =", "= [\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"] df = pd.DataFrame(columns=header) i = 0 for", "= get_parent(T, clade) seq_parent = aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs = str_diffs(seq_parent, seq_clade)", "right=False, labels=labels) df_mutations[\"region\"] = regions return df_mutations if __name__ == \"__main__\": infile_aln =", "and after mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return df_mutations def map_positions(s,", "nonsynonymous or synonymous \"\"\" coding_status = [] for i, row in df_mutations.iterrows(): seq_parent", "aln_dict, df_seqs): \"\"\" Annotate region of each mutation (CDR/FWR) \"\"\" # get one", "my_gaps positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate region of each", "gaps before each position counter = 0 gaps = [] for i, x", "introduce mutation seq_mutated = \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\") # collapse gaps seq_mutated", "positions in a gapped sequence \"\"\" # count number of gaps before each", "than one reading frame had max length ORF\" return frames_max[0] def annotate_coding(df_mutations, aln_dict):", "sequence sequence_uids = [x for x in aln_dict.keys() if \"_\" not in x]", "labels = [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions = pd.cut(df_mutations[\"position\"], boundaries_gapped,", "transform earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1] += 1 # map mutations to regions", "[i, x, y] diffs.append(d) return diffs def get_mutations(T, aln_dict): \"\"\" Get mutations on", "not used anymore (we do transform earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1] += 1", "SeqIO, Align, AlignIO, Phylo from itertools import izip def load_tree(f): t = Phylo.read(f,", "collapse gaps seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent, generic_dna).translate() # translate AA_mutated", "= max(Ls) # get longest ORF among all frames frames_max = [i for", "map_positions(s, boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped) - 1 # not used anymore (we", "infile_fitness_tree print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict", "\"__main__\": infile_aln = sys.argv[1] infile_fitness_tree = sys.argv[2] outfile = sys.argv[3] print infile_fitness_tree print", "corresponding positions in a gapped sequence \"\"\" # count number of gaps before", "numpy as np import pandas as pd from Bio.Seq import Seq from Bio.Alphabet", "seq2.split(\"*\")]) L_seq3 = max([len(x) for x in seq3.split(\"*\")]) Ls = [L_seq1, L_seq2, L_seq3]", "\"-\": counter += 1 gaps.append(counter) # transform boundaries to corresponding positions in new", "seq_record in SeqIO.parse(f, 'fasta'): aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return aln, aln_dict def get_parent(tree,", "s = s.replace(\"-\", \"\") seq1 = Seq(s, generic_dna).translate() # translate in every frame", "Annotate each mutation as either nonsynonymous or synonymous \"\"\" coding_status = [] for", "x + my_gaps positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate region", "synonymous \"\"\" coding_status = [] for i, row in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]]", "more than one reading frame had max length ORF\" return frames_max[0] def annotate_coding(df_mutations,", "infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs = pd.read_csv(infile_df_seqs, header=0, index_col=0) aln, aln_dict = load_aln(infile_aln) fitness_tree", "df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] # get parent sequence seq_mutated = list(seq_parent) seq_mutated[int(row[\"position\"])] =", "header = [\"name\", \"parent_name\", \"position\", \"base_before\", \"base_after\"] df = pd.DataFrame(columns=header) i = 0", "coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status return df_mutations def map_positions(s, positions): \"\"\" Maps positions in", "frame of longest ORF if len(frames_max) > 1: print \"Warning: more than one", "position, base_before, base_after = tuple(diff) features = [clade.name, parent.name, position, base_before, base_after] df.loc[i]", "izip def load_tree(f): t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length = 0.0 # t.ladderize(reverse=True)", "or synonymous \"\"\" coding_status = [] for i, row in df_mutations.iterrows(): seq_parent =", "generic_dna).translate() # translate AA_mutated = Seq(seq_mutated, generic_dna).translate() if AA_parent != AA_mutated: # compare", "parent = get_parent(T, clade) seq_parent = aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs = str_diffs(seq_parent,", "in every frame seq2 = Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate() L_seq1 =", "gaps.append(counter) # transform boundaries to corresponding positions in new sequence positions_transformed = []", "(we do transform earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1] += 1 # map mutations", "positions_transformed = [] for x in positions: my_gaps = gaps[x] x_transformed = x", "in seq3.split(\"*\")]) Ls = [L_seq1, L_seq2, L_seq3] L_max = max(Ls) # get longest", "sys.argv[2] outfile = sys.argv[3] print infile_fitness_tree print infile_aln infile_df_seqs = \"/local10G/rfhorns/Bcell/flu_highres/figures/v5/data/FitnessMutations.df_seqs_raw.csv\" df_seqs =", "boundaries to corresponding positions in gapped alignment fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\",", "\"2_\"]: continue parent = get_parent(T, clade) seq_parent = aln_dict[parent.name] seq_clade = aln_dict[clade.name] diffs", "df def find_frame(s): # Finds longest ORF s = s.replace(\"-\", \"\") seq1 =", "Bio import SeqIO, Align, AlignIO, Phylo from itertools import izip def load_tree(f): t", "\"\"\" Annotate each mutation as either nonsynonymous or synonymous \"\"\" coding_status = []", "corresponding positions in new sequence positions_transformed = [] for x in positions: my_gaps", "base_before, base_after = tuple(diff) features = [clade.name, parent.name, position, base_before, base_after] df.loc[i] =", "in gapped alignment fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"]", "aln, aln_dict def get_parent(tree, child_clade): node_path = tree.get_path(child_clade) return node_path[-2] def str_diffs(X, Y):", "# t.ladderize(reverse=True) return t def load_aln(infile): aln = Align.MultipleSeqAlignment([]) aln_dict = {} with", "Seq(seq_mutated, generic_dna).translate() if AA_parent != AA_mutated: # compare AA before and after mutation", "# collapse gaps seq_mutated = seq_mutated.replace(\"-\", \"\") AA_parent = Seq(seq_parent, generic_dna).translate() # translate", "for x in seq2.split(\"*\")]) L_seq3 = max([len(x) for x in seq3.split(\"*\")]) Ls =", "- 1 # transform to zero-indexed positions boundaries_ungapped[-1] -= 1 # decrement C", "ORF\" return frames_max[0] def annotate_coding(df_mutations, aln_dict): \"\"\" Annotate each mutation as either nonsynonymous", "x, y] diffs.append(d) return diffs def get_mutations(T, aln_dict): \"\"\" Get mutations on each", "base_before, base_after] df.loc[i] = features i += 1 return df def find_frame(s): #", "x in seq3.split(\"*\")]) Ls = [L_seq1, L_seq2, L_seq3] L_max = max(Ls) # get", "boundaries_gapped[-1] += 1 # map mutations to regions using boundaries labels = [\"FWR1\",", "enumerate(izip(X,Y)): if x != y: d = [i, x, y] diffs.append(d) return diffs", "y) in enumerate(izip(X,Y)): if x != y: d = [i, x, y] diffs.append(d)", "array boundaries_gapped = map_positions(s, boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped) - 1 # not", "-= 1 # decrement C region boundary (end of sequence) to fit within", "Get mutations on each branch of the tree \"\"\" header = [\"name\", \"parent_name\",", "0 for clade in T.find_clades(): if clade.name in [None, \"germline\", \"2_\"]: continue parent", "[] for x in positions: my_gaps = gaps[x] x_transformed = x + my_gaps", "if x == L_max] # get frame of longest ORF if len(frames_max) >", "# count number of gaps before each position counter = 0 gaps =", "Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x) for x in seq1.split(\"*\")])", "positions in gapped alignment fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\",", "1 # decrement C region boundary (end of sequence) to fit within array", "AA_parent != AA_mutated: # compare AA before and after mutation coding_status.append(\"N\") else: coding_status.append(\"S\")", "aln.append(seq_record) aln_dict[seq_record.id] = str(seq_record.seq) return aln, aln_dict def get_parent(tree, child_clade): node_path = tree.get_path(child_clade)", "# compare AA before and after mutation coding_status.append(\"N\") else: coding_status.append(\"S\") df_mutations[\"coding_status\"] = coding_status", "= [clade.name, parent.name, position, base_before, base_after] df.loc[i] = features i += 1 return", "node_path = tree.get_path(child_clade) return node_path[-2] def str_diffs(X, Y): diffs = [] for i,", "i += 1 return df def find_frame(s): # Finds longest ORF s =", "= [] for i, row in df_mutations.iterrows(): seq_parent = aln_dict[row[\"parent_name\"]] # get parent", "as np import pandas as pd from Bio.Seq import Seq from Bio.Alphabet import", "get one sequence sequence_uids = [x for x in aln_dict.keys() if \"_\" not", "\"\"\" Get mutations on each branch of the tree \"\"\" header = [\"name\",", "among all frames frames_max = [i for i, x in enumerate(Ls) if x", "\"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) - 1", "# map mutations to regions using boundaries labels = [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\",", "\"Warning: more than one reading frame had max length ORF\" return frames_max[0] def", "generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x) for x in seq1.split(\"*\")]) #", "header=0, index_col=0) aln, aln_dict = load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict)", "positions boundaries_ungapped[-1] -= 1 # decrement C region boundary (end of sequence) to", "aln_dict[seq_record.id] = str(seq_record.seq) return aln, aln_dict def get_parent(tree, child_clade): node_path = tree.get_path(child_clade) return", "== L_max] # get frame of longest ORF if len(frames_max) > 1: print", "each position counter = 0 gaps = [] for i, x in enumerate(s):", "to corresponding positions in gapped alignment fields = [\"FWR1_start\", \"CDR1_start\", \"FWR2_start\", \"CDR2_start\", \"FWR3_start\",", "Bio.Alphabet import generic_dna from Bio import SeqIO, Align, AlignIO, Phylo from itertools import", "mutation as either nonsynonymous or synonymous \"\"\" coding_status = [] for i, row", "x in aln_dict.keys() if \"_\" not in x] my_sequence_uid = int(sequence_uids[0]) s =", "for i, (x, y) in enumerate(izip(X,Y)): if x != y: d = [i,", "load_aln(infile_aln) fitness_tree = load_tree(infile_fitness_tree) df_mutations = get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict) df_mutations", "list(seq_parent) seq_mutated[int(row[\"position\"])] = row[\"base_after\"] # introduce mutation seq_mutated = \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\",", "import numpy as np import pandas as pd from Bio.Seq import Seq from", "base_after] df.loc[i] = features i += 1 return df def find_frame(s): # Finds", "= Seq(seq_parent, generic_dna).translate() # translate AA_mutated = Seq(seq_mutated, generic_dna).translate() if AA_parent != AA_mutated:", "df_mutations def map_positions(s, positions): \"\"\" Maps positions in an ungapped sequence to corresponding", "before each position counter = 0 gaps = [] for i, x in", "= [i, x, y] diffs.append(d) return diffs def get_mutations(T, aln_dict): \"\"\" Get mutations", "generic_dna).translate() L_seq1 = max([len(x) for x in seq1.split(\"*\")]) # find longest ORF in", "from itertools import izip def load_tree(f): t = Phylo.read(f, 'newick') t.root_with_outgroup(\"germline\") t.get_nonterminals()[0].branch_length =", "= max([len(x) for x in seq1.split(\"*\")]) # find longest ORF in each frame", "positions in an ungapped sequence to corresponding positions in a gapped sequence \"\"\"", "sequence) to fit within array boundaries_gapped = map_positions(s, boundaries_ungapped) # boundaries_gapped = np.array(boundaries_gapped)", "Bio.Seq import Seq from Bio.Alphabet import generic_dna from Bio import SeqIO, Align, AlignIO,", "pd.DataFrame(columns=header) i = 0 for clade in T.find_clades(): if clade.name in [None, \"germline\",", "for x in seq1.split(\"*\")]) # find longest ORF in each frame L_seq2 =", "if \"_\" not in x] my_sequence_uid = int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] # transform", "in diffs: position, base_before, base_after = tuple(diff) features = [clade.name, parent.name, position, base_before,", "df.loc[i] = features i += 1 return df def find_frame(s): # Finds longest", "get_parent(tree, child_clade): node_path = tree.get_path(child_clade) return node_path[-2] def str_diffs(X, Y): diffs = []", "for x in positions: my_gaps = gaps[x] x_transformed = x + my_gaps positions_transformed.append(x_transformed)", "diffs def get_mutations(T, aln_dict): \"\"\" Get mutations on each branch of the tree", "frame seq2 = Seq(s[1:], generic_dna).translate() seq3 = Seq(s[2:], generic_dna).translate() L_seq1 = max([len(x) for", "Seq(s, generic_dna).translate() # translate in every frame seq2 = Seq(s[1:], generic_dna).translate() seq3 =", "get_mutations(fitness_tree, aln_dict) df_mutations = annotate_coding(df_mutations, aln_dict) df_mutations = annotate_regions(df_mutations, aln_dict, df_seqs) df_mutations.to_csv(outfile) print", "= pd.cut(df_mutations[\"position\"], boundaries_gapped, include_lowest=True, right=False, labels=labels) df_mutations[\"region\"] = regions return df_mutations if __name__", "return node_path[-2] def str_diffs(X, Y): diffs = [] for i, (x, y) in", "= x + my_gaps positions_transformed.append(x_transformed) return positions_transformed def annotate_regions(df_mutations, aln_dict, df_seqs): \"\"\" Annotate", "boundary (end of sequence) to fit within array boundaries_gapped = map_positions(s, boundaries_ungapped) #", "np.array(boundaries_ungapped) - 1 # transform to zero-indexed positions boundaries_ungapped[-1] -= 1 # decrement", "in new sequence positions_transformed = [] for x in positions: my_gaps = gaps[x]", "= int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)] # transform positions of region boundaries to corresponding", "# introduce mutation seq_mutated = \"\".join(seq_mutated) seq_parent = seq_parent.replace(\"-\", \"\") # collapse gaps", "used anymore (we do transform earlier) boundaries_gapped[0] = 0 boundaries_gapped[-1] += 1 #", "on each branch of the tree \"\"\" header = [\"name\", \"parent_name\", \"position\", \"base_before\",", "mutations to regions using boundaries labels = [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\",", "find_frame(s): # Finds longest ORF s = s.replace(\"-\", \"\") seq1 = Seq(s, generic_dna).translate()", "transform to zero-indexed positions boundaries_ungapped[-1] -= 1 # decrement C region boundary (end", "# get frame of longest ORF if len(frames_max) > 1: print \"Warning: more", "in aln_dict.keys() if \"_\" not in x] my_sequence_uid = int(sequence_uids[0]) s = aln_dict[str(my_sequence_uid)]", "transform positions of region boundaries to corresponding positions in gapped alignment fields =", "regions using boundaries labels = [\"FWR1\", \"CDR1\", \"FWR2\", \"CDR2\", \"FWR3\", \"CDR3\", \"FWR4\"] regions", "= [i for i, x in enumerate(Ls) if x == L_max] # get", "\"FWR2_start\", \"CDR2_start\", \"FWR3_start\", \"CDR3_start\", \"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) -", "aln = Align.MultipleSeqAlignment([]) aln_dict = {} with open(infile, 'r') as f: for seq_record", "max([len(x) for x in seq2.split(\"*\")]) L_seq3 = max([len(x) for x in seq3.split(\"*\")]) Ls", "\"FWR4_start\", \"C_start\"] boundaries_ungapped = df_seqs.loc[my_sequence_uid][fields] boundaries_ungapped = np.array(boundaries_ungapped) - 1 # transform to", "# get one sequence sequence_uids = [x for x in aln_dict.keys() if \"_\"", "= coding_status return df_mutations def map_positions(s, positions): \"\"\" Maps positions in an ungapped" ]
[ "hell are u thinking?\" print \"a very important function that can only exec", "print \"a after import b\" _once = 0 def dofoo(): global _once; _once", "dofoo(): global _once; _once += 1 if _once > 1: print \"what the", "global _once; _once += 1 if _once > 1: print \"what the hell", "\"what the hell are u thinking?\" print \"a very important function that can", "b print \"a after import b\" _once = 0 def dofoo(): global _once;", "import b\" _once = 0 def dofoo(): global _once; _once += 1 if", "\"a before b\" import b print \"a after import b\" _once = 0", "1: print \"what the hell are u thinking?\" print \"a very important function", "+= 1 if _once > 1: print \"what the hell are u thinking?\"", "_once = 0 def dofoo(): global _once; _once += 1 if _once >", "print \"a very important function that can only exec once\" dofoo() print \"complete", "before b\" import b print \"a after import b\" _once = 0 def", "\"a after import b\" _once = 0 def dofoo(): global _once; _once +=", "_once; _once += 1 if _once > 1: print \"what the hell are", "1 if _once > 1: print \"what the hell are u thinking?\" print", "= 0 def dofoo(): global _once; _once += 1 if _once > 1:", "import b print \"a after import b\" _once = 0 def dofoo(): global", "<reponame>abos5/pythontutor<gh_stars>0 print \"a before b\" import b print \"a after import b\" _once", "b\" _once = 0 def dofoo(): global _once; _once += 1 if _once", "after import b\" _once = 0 def dofoo(): global _once; _once += 1", "b\" import b print \"a after import b\" _once = 0 def dofoo():", "the hell are u thinking?\" print \"a very important function that can only", "print \"a before b\" import b print \"a after import b\" _once =", "thinking?\" print \"a very important function that can only exec once\" dofoo() print", "> 1: print \"what the hell are u thinking?\" print \"a very important", "if _once > 1: print \"what the hell are u thinking?\" print \"a", "\"a very important function that can only exec once\" dofoo() print \"complete a\"", "def dofoo(): global _once; _once += 1 if _once > 1: print \"what", "_once > 1: print \"what the hell are u thinking?\" print \"a very", "are u thinking?\" print \"a very important function that can only exec once\"", "u thinking?\" print \"a very important function that can only exec once\" dofoo()", "print \"what the hell are u thinking?\" print \"a very important function that", "_once += 1 if _once > 1: print \"what the hell are u", "0 def dofoo(): global _once; _once += 1 if _once > 1: print" ]
[ "by subclasses \"\"\" pass @property def query_data(self) -> bytes: \"\"\"Returns the ``data`` field", "bytes: \"\"\"Returns the query ``id`` for use with the ``TellorX.Oracle.tipQuery()`` and ``TellorX.Oracle.submitValue()`` contract", "base class for all Queries, and implements default behaviors. Each subclass corresponds to", "from clamfig import Serializable from web3 import Web3 from telliot_core.dtypes.value_type import ValueType class", "field for use in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return self.descriptor.encode(\"utf-8\") @property def query_id(self)", "network. All public attributes of an OracleQuery represent an input that can be", "descriptor is required for users to specify the query to TellorX through the", "``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return self.descriptor.encode(\"utf-8\") @property def query_id(self) -> bytes: \"\"\"Returns the", "for users to specify the query to TellorX through the ``TellorX.Oracle.tipQuery()`` contract call.", "This method must be overridden by subclasses \"\"\" pass @property def query_data(self) ->", "a unique Query Type supported by the TellorX network. All public attributes of", "include with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls. \"\"\" @property def descriptor(self) ->", "data type/structure of the ``value`` submitted to the contract through ``TellorX.Oracle.submitValue()`` This method", "subclass corresponds to a unique Query Type supported by the TellorX network. All", "expected by the current Query configuration The value type defines required data type/structure", "of the query. The descriptor is required for users to specify the query", "required for users to specify the query to TellorX through the ``TellorX.Oracle.tipQuery()`` contract", "the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state = self.get_state() jstr = json.dumps(state, separators=(\",\", \":\"))", "\"\"\" return self.descriptor.encode(\"utf-8\") @property def query_id(self) -> bytes: \"\"\"Returns the query ``id`` for", "of the `data` field to include with the `TellorX.Oracle.tipQuery()` contract call. - Calculation", "behaviors. Each subclass corresponds to a unique Query Type supported by the TellorX", "def descriptor(self) -> str: \"\"\"Get the query descriptor string. The Query descriptor is", "be overridden by subclasses \"\"\" pass @property def query_data(self) -> bytes: \"\"\"Returns the", "class serves as the base class for all Queries, and implements default behaviors.", "the `data` field to include with the `TellorX.Oracle.tipQuery()` contract call. - Calculation of", "\"\"\"Returns the query ``id`` for use with the ``TellorX.Oracle.tipQuery()`` and ``TellorX.Oracle.submitValue()`` contract calls.", "state = self.get_state() jstr = json.dumps(state, separators=(\",\", \":\")) return jstr @property def value_type(self)", "OracleQuery specifies how to pose a question to the Tellor Oracle and how", "Queries, and implements default behaviors. Each subclass corresponds to a unique Query Type", "value type defines required data type/structure of the ``value`` submitted to the contract", "def query_id(self) -> bytes: \"\"\"Returns the query ``id`` for use with the ``TellorX.Oracle.tipQuery()``", "through ``TellorX.Oracle.submitValue()`` This method must be overridden by subclasses \"\"\" pass @property def", "clamfig import Serializable from web3 import Web3 from telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable):", "how to format/interpret the response. The OracleQuery class serves as the base class", "type/structure of the ``value`` submitted to the contract through ``TellorX.Oracle.submitValue()`` This method must", "include with the `TellorX.Oracle.tipQuery()` contract call. - Calculation of the `id` field field", "contract through ``TellorX.Oracle.submitValue()`` This method must be overridden by subclasses \"\"\" pass @property", "jstr = json.dumps(state, separators=(\",\", \":\")) return jstr @property def value_type(self) -> ValueType: \"\"\"Returns", "pass @property def query_data(self) -> bytes: \"\"\"Returns the ``data`` field for use in", "query to TellorX through the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state = self.get_state() jstr", "import Serializable from web3 import Web3 from telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable): \"\"\"Oracle", "ValueType expected by the current Query configuration The value type defines required data", "to the contract through ``TellorX.Oracle.submitValue()`` This method must be overridden by subclasses \"\"\"", "to the Tellor Oracle and how to format/interpret the response. The OracleQuery class", "how to pose a question to the Tellor Oracle and how to format/interpret", "default behaviors. Each subclass corresponds to a unique Query Type supported by the", "- Calculation of the `id` field field to include with the `TellorX.Oracle.tipQuery()` and", "string representation of the query. The descriptor is required for users to specify", "import ValueType class OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery specifies how to pose a", "Query An OracleQuery specifies how to pose a question to the Tellor Oracle", "json.dumps(state, separators=(\",\", \":\")) return jstr @property def value_type(self) -> ValueType: \"\"\"Returns the ValueType", "call. \"\"\" state = self.get_state() jstr = json.dumps(state, separators=(\",\", \":\")) return jstr @property", "subclasses \"\"\" pass @property def query_data(self) -> bytes: \"\"\"Returns the ``data`` field for", "query ``id`` for use with the ``TellorX.Oracle.tipQuery()`` and ``TellorX.Oracle.submitValue()`` contract calls. \"\"\" return", "bytes: \"\"\"Returns the ``data`` field for use in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return", "public attributes of an OracleQuery represent an input that can be used to", "to include with the `TellorX.Oracle.tipQuery()` contract call. - Calculation of the `id` field", "the current Query configuration The value type defines required data type/structure of the", "through the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state = self.get_state() jstr = json.dumps(state, separators=(\",\",", "the contract through ``TellorX.Oracle.submitValue()`` This method must be overridden by subclasses \"\"\" pass", "input that can be used to customize the query. The base class provides:", "contents of the `data` field to include with the `TellorX.Oracle.tipQuery()` contract call. -", "to pose a question to the Tellor Oracle and how to format/interpret the", "the query to TellorX through the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state = self.get_state()", "-> bytes: \"\"\"Returns the query ``id`` for use with the ``TellorX.Oracle.tipQuery()`` and ``TellorX.Oracle.submitValue()``", "\"\"\"Oracle Query An OracleQuery specifies how to pose a question to the Tellor", "\"\"\"Get the query descriptor string. The Query descriptor is a unique string representation", "is required for users to specify the query to TellorX through the ``TellorX.Oracle.tipQuery()``", "def value_type(self) -> ValueType: \"\"\"Returns the ValueType expected by the current Query configuration", "the `id` field field to include with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls.", "the query. The base class provides: - Calculation of the contents of the", "`TellorX.Oracle.tipQuery()` contract call. - Calculation of the `id` field field to include with", "of the ``value`` submitted to the contract through ``TellorX.Oracle.submitValue()`` This method must be", "and how to format/interpret the response. The OracleQuery class serves as the base", "format/interpret the response. The OracleQuery class serves as the base class for all", "serves as the base class for all Queries, and implements default behaviors. Each", "Module \"\"\" import json from clamfig import Serializable from web3 import Web3 from", "to customize the query. The base class provides: - Calculation of the contents", "Oracle Query Module \"\"\" import json from clamfig import Serializable from web3 import", "separators=(\",\", \":\")) return jstr @property def value_type(self) -> ValueType: \"\"\"Returns the ValueType expected", "-> ValueType: \"\"\"Returns the ValueType expected by the current Query configuration The value", "implements default behaviors. Each subclass corresponds to a unique Query Type supported by", "by the TellorX network. All public attributes of an OracleQuery represent an input", "Query configuration The value type defines required data type/structure of the ``value`` submitted", "calls. \"\"\" @property def descriptor(self) -> str: \"\"\"Get the query descriptor string. The", "query. The base class provides: - Calculation of the contents of the `data`", "Tellor Oracle and how to format/interpret the response. The OracleQuery class serves as", "representation of the query. The descriptor is required for users to specify the", "-> bytes: \"\"\"Returns the ``data`` field for use in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\"", "of the `id` field field to include with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract", "``data`` field for use in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return self.descriptor.encode(\"utf-8\") @property def", "users to specify the query to TellorX through the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\"", "field field to include with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls. \"\"\" @property", "field to include with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls. \"\"\" @property def", "OracleQuery represent an input that can be used to customize the query. The", "represent an input that can be used to customize the query. The base", "import json from clamfig import Serializable from web3 import Web3 from telliot_core.dtypes.value_type import", "descriptor string. The Query descriptor is a unique string representation of the query.", "contract call. \"\"\" return self.descriptor.encode(\"utf-8\") @property def query_id(self) -> bytes: \"\"\"Returns the query", "as the base class for all Queries, and implements default behaviors. Each subclass", "the ``value`` submitted to the contract through ``TellorX.Oracle.submitValue()`` This method must be overridden", "the response. The OracleQuery class serves as the base class for all Queries,", "customize the query. The base class provides: - Calculation of the contents of", "The value type defines required data type/structure of the ``value`` submitted to the", "\"\"\" state = self.get_state() jstr = json.dumps(state, separators=(\",\", \":\")) return jstr @property def", "def query_data(self) -> bytes: \"\"\"Returns the ``data`` field for use in ``TellorX.Oracle.tipQuery()`` contract", "@property def value_type(self) -> ValueType: \"\"\"Returns the ValueType expected by the current Query", "\":\")) return jstr @property def value_type(self) -> ValueType: \"\"\"Returns the ValueType expected by", "The base class provides: - Calculation of the contents of the `data` field", "contract call. \"\"\" state = self.get_state() jstr = json.dumps(state, separators=(\",\", \":\")) return jstr", "from telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery specifies how to", "\"\"\" @property def descriptor(self) -> str: \"\"\"Get the query descriptor string. The Query", "the contents of the `data` field to include with the `TellorX.Oracle.tipQuery()` contract call.", "``value`` submitted to the contract through ``TellorX.Oracle.submitValue()`` This method must be overridden by", "`TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls. \"\"\" @property def descriptor(self) -> str: \"\"\"Get the", "telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery specifies how to pose", "a unique string representation of the query. The descriptor is required for users", "is a unique string representation of the query. The descriptor is required for", "the query. The descriptor is required for users to specify the query to", "and `TellorX.Oracle.submitValue()` contract calls. \"\"\" @property def descriptor(self) -> str: \"\"\"Get the query", "current Query configuration The value type defines required data type/structure of the ``value``", "specifies how to pose a question to the Tellor Oracle and how to", "by the current Query configuration The value type defines required data type/structure of", "that can be used to customize the query. The base class provides: -", "to TellorX through the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state = self.get_state() jstr =", "Each subclass corresponds to a unique Query Type supported by the TellorX network.", "used to customize the query. The base class provides: - Calculation of the", "can be used to customize the query. The base class provides: - Calculation", "= self.get_state() jstr = json.dumps(state, separators=(\",\", \":\")) return jstr @property def value_type(self) ->", "an input that can be used to customize the query. The base class", "and implements default behaviors. Each subclass corresponds to a unique Query Type supported", "-> str: \"\"\"Get the query descriptor string. The Query descriptor is a unique", "self.descriptor.encode(\"utf-8\") @property def query_id(self) -> bytes: \"\"\"Returns the query ``id`` for use with", "to include with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls. \"\"\" @property def descriptor(self)", "``id`` for use with the ``TellorX.Oracle.tipQuery()`` and ``TellorX.Oracle.submitValue()`` contract calls. \"\"\" return bytes(Web3.keccak(self.query_data))", "from web3 import Web3 from telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable): \"\"\"Oracle Query An", "field to include with the `TellorX.Oracle.tipQuery()` contract call. - Calculation of the `id`", "overridden by subclasses \"\"\" pass @property def query_data(self) -> bytes: \"\"\"Returns the ``data``", "self.get_state() jstr = json.dumps(state, separators=(\",\", \":\")) return jstr @property def value_type(self) -> ValueType:", "return jstr @property def value_type(self) -> ValueType: \"\"\"Returns the ValueType expected by the", "Oracle and how to format/interpret the response. The OracleQuery class serves as the", "to format/interpret the response. The OracleQuery class serves as the base class for", "in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return self.descriptor.encode(\"utf-8\") @property def query_id(self) -> bytes: \"\"\"Returns", "to a unique Query Type supported by the TellorX network. All public attributes", "An OracleQuery specifies how to pose a question to the Tellor Oracle and", "the TellorX network. All public attributes of an OracleQuery represent an input that", "All public attributes of an OracleQuery represent an input that can be used", "with the `TellorX.Oracle.tipQuery()` contract call. - Calculation of the `id` field field to", "the ValueType expected by the current Query configuration The value type defines required", "@property def query_id(self) -> bytes: \"\"\"Returns the query ``id`` for use with the", "Query Module \"\"\" import json from clamfig import Serializable from web3 import Web3", "@property def query_data(self) -> bytes: \"\"\"Returns the ``data`` field for use in ``TellorX.Oracle.tipQuery()``", "The OracleQuery class serves as the base class for all Queries, and implements", "class for all Queries, and implements default behaviors. Each subclass corresponds to a", "with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls. \"\"\" @property def descriptor(self) -> str:", "Query Type supported by the TellorX network. All public attributes of an OracleQuery", "provides: - Calculation of the contents of the `data` field to include with", "specify the query to TellorX through the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state =", "Type supported by the TellorX network. All public attributes of an OracleQuery represent", "class provides: - Calculation of the contents of the `data` field to include", "the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls. \"\"\" @property def descriptor(self) -> str: \"\"\"Get", "\"\"\" pass @property def query_data(self) -> bytes: \"\"\"Returns the ``data`` field for use", "\"\"\"Returns the ``data`` field for use in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return self.descriptor.encode(\"utf-8\")", "ValueType: \"\"\"Returns the ValueType expected by the current Query configuration The value type", "\"\"\" import json from clamfig import Serializable from web3 import Web3 from telliot_core.dtypes.value_type", "OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery specifies how to pose a question to the", "string. The Query descriptor is a unique string representation of the query. The", "corresponds to a unique Query Type supported by the TellorX network. All public", "query descriptor string. The Query descriptor is a unique string representation of the", "TellorX through the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state = self.get_state() jstr = json.dumps(state,", "query. The descriptor is required for users to specify the query to TellorX", "``TellorX.Oracle.submitValue()`` This method must be overridden by subclasses \"\"\" pass @property def query_data(self)", "call. - Calculation of the `id` field field to include with the `TellorX.Oracle.tipQuery()`", "of an OracleQuery represent an input that can be used to customize the", "- Calculation of the contents of the `data` field to include with the", "TellorX network. All public attributes of an OracleQuery represent an input that can", "\"\"\"Returns the ValueType expected by the current Query configuration The value type defines", "defines required data type/structure of the ``value`` submitted to the contract through ``TellorX.Oracle.submitValue()``", "web3 import Web3 from telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery", "question to the Tellor Oracle and how to format/interpret the response. The OracleQuery", "OracleQuery class serves as the base class for all Queries, and implements default", "Calculation of the `id` field field to include with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()`", "descriptor(self) -> str: \"\"\"Get the query descriptor string. The Query descriptor is a", "Calculation of the contents of the `data` field to include with the `TellorX.Oracle.tipQuery()`", "`id` field field to include with the `TellorX.Oracle.tipQuery()` and `TellorX.Oracle.submitValue()` contract calls. \"\"\"", "use in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return self.descriptor.encode(\"utf-8\") @property def query_id(self) -> bytes:", "an OracleQuery represent an input that can be used to customize the query.", "configuration The value type defines required data type/structure of the ``value`` submitted to", "query_data(self) -> bytes: \"\"\"Returns the ``data`` field for use in ``TellorX.Oracle.tipQuery()`` contract call.", "the ``data`` field for use in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return self.descriptor.encode(\"utf-8\") @property", "the `TellorX.Oracle.tipQuery()` contract call. - Calculation of the `id` field field to include", "must be overridden by subclasses \"\"\" pass @property def query_data(self) -> bytes: \"\"\"Returns", "unique string representation of the query. The descriptor is required for users to", "json from clamfig import Serializable from web3 import Web3 from telliot_core.dtypes.value_type import ValueType", "the Tellor Oracle and how to format/interpret the response. The OracleQuery class serves", "base class provides: - Calculation of the contents of the `data` field to", "the base class for all Queries, and implements default behaviors. Each subclass corresponds", "required data type/structure of the ``value`` submitted to the contract through ``TellorX.Oracle.submitValue()`` This", "Query descriptor is a unique string representation of the query. The descriptor is", "The descriptor is required for users to specify the query to TellorX through", "return self.descriptor.encode(\"utf-8\") @property def query_id(self) -> bytes: \"\"\"Returns the query ``id`` for use", "ValueType class OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery specifies how to pose a question", "`TellorX.Oracle.submitValue()` contract calls. \"\"\" @property def descriptor(self) -> str: \"\"\"Get the query descriptor", "= json.dumps(state, separators=(\",\", \":\")) return jstr @property def value_type(self) -> ValueType: \"\"\"Returns the", "of the contents of the `data` field to include with the `TellorX.Oracle.tipQuery()` contract", "str: \"\"\"Get the query descriptor string. The Query descriptor is a unique string", "the query descriptor string. The Query descriptor is a unique string representation of", "value_type(self) -> ValueType: \"\"\"Returns the ValueType expected by the current Query configuration The", "class OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery specifies how to pose a question to", "be used to customize the query. The base class provides: - Calculation of", "to specify the query to TellorX through the ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state", "method must be overridden by subclasses \"\"\" pass @property def query_data(self) -> bytes:", "@property def descriptor(self) -> str: \"\"\"Get the query descriptor string. The Query descriptor", "type defines required data type/structure of the ``value`` submitted to the contract through", "contract calls. \"\"\" @property def descriptor(self) -> str: \"\"\"Get the query descriptor string.", "The Query descriptor is a unique string representation of the query. The descriptor", "pose a question to the Tellor Oracle and how to format/interpret the response.", "a question to the Tellor Oracle and how to format/interpret the response. The", "submitted to the contract through ``TellorX.Oracle.submitValue()`` This method must be overridden by subclasses", "descriptor is a unique string representation of the query. The descriptor is required", "query_id(self) -> bytes: \"\"\"Returns the query ``id`` for use with the ``TellorX.Oracle.tipQuery()`` and", "the query ``id`` for use with the ``TellorX.Oracle.tipQuery()`` and ``TellorX.Oracle.submitValue()`` contract calls. \"\"\"", "call. \"\"\" return self.descriptor.encode(\"utf-8\") @property def query_id(self) -> bytes: \"\"\"Returns the query ``id``", "all Queries, and implements default behaviors. Each subclass corresponds to a unique Query", "`data` field to include with the `TellorX.Oracle.tipQuery()` contract call. - Calculation of the", "contract call. - Calculation of the `id` field field to include with the", "import Web3 from telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery specifies", "response. The OracleQuery class serves as the base class for all Queries, and", "jstr @property def value_type(self) -> ValueType: \"\"\"Returns the ValueType expected by the current", "for all Queries, and implements default behaviors. Each subclass corresponds to a unique", "``TellorX.Oracle.tipQuery()`` contract call. \"\"\" state = self.get_state() jstr = json.dumps(state, separators=(\",\", \":\")) return", "for use in ``TellorX.Oracle.tipQuery()`` contract call. \"\"\" return self.descriptor.encode(\"utf-8\") @property def query_id(self) ->", "attributes of an OracleQuery represent an input that can be used to customize", "Serializable from web3 import Web3 from telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable): \"\"\"Oracle Query", "\"\"\" Oracle Query Module \"\"\" import json from clamfig import Serializable from web3", "unique Query Type supported by the TellorX network. All public attributes of an", "Web3 from telliot_core.dtypes.value_type import ValueType class OracleQuery(Serializable): \"\"\"Oracle Query An OracleQuery specifies how", "supported by the TellorX network. All public attributes of an OracleQuery represent an" ]
[ "465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME = True", "EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL", "'<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME = True DEFAULT_FROM_EMAIL = 'GPUTasker<{}>'.format(EMAIL_HOST_USER)", "EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME = True DEFAULT_FROM_EMAIL", "= '<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME = True DEFAULT_FROM_EMAIL = 'GPUTasker<{}>'.format(EMAIL_HOST_USER) SERVER_EMAIL =", "<reponame>cnstark/awesome_gpu_scheduler EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '<EMAIL>'", "= 465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME =", "'<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME = True DEFAULT_FROM_EMAIL = 'GPUTasker<{}>'.format(EMAIL_HOST_USER) SERVER_EMAIL = EMAIL_HOST_USER", "'smtp.163.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL = True", "= '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME = True DEFAULT_FROM_EMAIL =", "= 'smtp.163.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL =", "EMAIL_PORT = 465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME", "EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_USE_SSL = True EMAIL_USE_LOCALTIME = True DEFAULT_FROM_EMAIL = 'GPUTasker<{}>'.format(EMAIL_HOST_USER) SERVER_EMAIL", "= 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD =", "'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>'", "EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD" ]
[ "import torch import torch.nn as nn import onmt from onmt.BleuCal import fetch_data import", "[], [] lenSrcData = len(srcData) for i, line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" %", "generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch,", "torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] # del(checkpoint) opt.cuda = True", "for i, line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) + ' of '", "from onmt.BleuCal import fetch_data import sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt", "= torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] # del(checkpoint) opt.cuda = True srcData, references =", "translator = onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate = [], [], []", "1) % opt.trans_batch_size == 0: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:',", "= onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator", "checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate = [], [], [] lenSrcData = len(srcData) for i,", "'predBatch:', len(predBatch) for b in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch", "\".join(predBatch[b][0]) + '\\n'] srcBatch = [] else: continue print 'candidate length:', len(candidate) print", "model.generator = generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt'])", "range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] elif (i +", "predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b in range(len(predBatch)):", "onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator model.cuda()", "model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate = [], [], [] lenSrcData = len(srcData)", "sys.stdout.write(\"%s\" % (str(i) + ' of ' + str(lenSrcData))) sys.stdout.flush() srcTokens = line.split()", "str(lenSrcData))) sys.stdout.flush() srcTokens = line.split() srcBatch += [srcTokens] if (i + 1) %", "fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder,", "onmt.BleuCal import fetch_data import sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt =", "len(predBatch) for b in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch =", "nn import onmt from onmt.BleuCal import fetch_data import sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint", "tgtBatch, candidate = [], [], [] lenSrcData = len(srcData) for i, line in", "if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] # del(checkpoint) opt.cuda =", "srcTokens = line.split() srcBatch += [srcTokens] if (i + 1) % opt.trans_batch_size ==", "[\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] else: continue print 'candidate length:', len(candidate)", "checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] # del(checkpoint) opt.cuda = True srcData, references", "onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax())", "lenSrcData = len(srcData) for i, line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) +", "as nn import onmt from onmt.BleuCal import fetch_data import sys if torch.cuda.is_available(): torch.cuda.set_device(3)", "+= [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] elif (i + 1) ==", "% opt.trans_batch_size == 0: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch)", "onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate = [], [], [] lenSrcData =", "if (i + 1) % opt.trans_batch_size == 0: predBatch, _, _ = translator.translate(srcBatch,", "translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0])", "in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] elif (i", "' + str(lenSrcData))) sys.stdout.flush() srcTokens = line.split() srcBatch += [srcTokens] if (i +", "[\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] elif (i + 1) == lenSrcData:", "range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] else: continue print", "srcBatch = [] else: continue print 'candidate length:', len(candidate) print 'referece length', len(references[0])", "nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt,", "lenSrcData: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b in", "model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator model.cuda() opt.model =", "import fetch_data import sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt']", "= fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model =", "import onmt from onmt.BleuCal import fetch_data import sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint =", "+= [srcTokens] if (i + 1) % opt.trans_batch_size == 0: predBatch, _, _", "[srcTokens] if (i + 1) % opt.trans_batch_size == 0: predBatch, _, _ =", "opt.trans_batch_size == 0: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for", "[] elif (i + 1) == lenSrcData: predBatch, _, _ = translator.translate(srcBatch, tgtBatch)", "fetch_data import sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] #", "nn.LogSoftmax()) model.generator = generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model, checkpoint['dicts']['src'],", "b in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] else:", "candidate = [], [], [] lenSrcData = len(srcData) for i, line in enumerate(srcData):", "for b in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = []", "torch.nn as nn import onmt from onmt.BleuCal import fetch_data import sys if torch.cuda.is_available():", "opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate =", "= onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate = [], [], [] lenSrcData", "(i + 1) == lenSrcData: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:',", "decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator model.cuda() opt.model", "_ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b in range(len(predBatch)): candidate +=", "print 'predBatch:', len(predBatch) for b in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n']", "(i + 1) % opt.trans_batch_size == 0: predBatch, _, _ = translator.translate(srcBatch, tgtBatch)", "opt.cuda = True srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder", "line.split() srcBatch += [srcTokens] if (i + 1) % opt.trans_batch_size == 0: predBatch,", "import torch.nn as nn import onmt from onmt.BleuCal import fetch_data import sys if", "torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] # del(checkpoint) opt.cuda = True srcData, references = fetch_data('IWSLT/test.de.small.tok',", "# del(checkpoint) opt.cuda = True srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt,", "1) == lenSrcData: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for", "elif (i + 1) == lenSrcData: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print", "enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) + ' of ' + str(lenSrcData))) sys.stdout.flush() srcTokens", "= [] elif (i + 1) == lenSrcData: predBatch, _, _ = translator.translate(srcBatch,", "candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] else: continue print 'candidate", "= generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch,", "== lenSrcData: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b", "encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model'])", "= nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator", "checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator", "of ' + str(lenSrcData))) sys.stdout.flush() srcTokens = line.split() srcBatch += [srcTokens] if (i", "in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] else: continue", "'\\n'] srcBatch = [] elif (i + 1) == lenSrcData: predBatch, _, _", "tgtBatch) print 'predBatch:', len(predBatch) for b in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) +", "+= [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] else: continue print 'candidate length:',", "= [], [], [] lenSrcData = len(srcData) for i, line in enumerate(srcData): sys.stdout.write('\\r')", "len(srcData) for i, line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) + ' of", "sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] # del(checkpoint) opt.cuda", "+ '\\n'] srcBatch = [] else: continue print 'candidate length:', len(candidate) print 'referece", "\".join(predBatch[b][0]) + '\\n'] srcBatch = [] elif (i + 1) == lenSrcData: predBatch,", "'\\n'] srcBatch = [] else: continue print 'candidate length:', len(candidate) print 'referece length',", "= '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate = [],", "= checkpoint['opt'] # del(checkpoint) opt.cuda = True srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder", "sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) + ' of ' + str(lenSrcData))) sys.stdout.flush() srcTokens =", "opt = checkpoint['opt'] # del(checkpoint) opt.cuda = True srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok')", "_, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b in range(len(predBatch)): candidate", "onmt from onmt.BleuCal import fetch_data import sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt')", "'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder)", "' of ' + str(lenSrcData))) sys.stdout.flush() srcTokens = line.split() srcBatch += [srcTokens] if", "del(checkpoint) opt.cuda = True srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src'])", "+ ' of ' + str(lenSrcData))) sys.stdout.flush() srcTokens = line.split() srcBatch += [srcTokens]", "in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) + ' of ' + str(lenSrcData))) sys.stdout.flush()", "[] lenSrcData = len(srcData) for i, line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i)", "= len(srcData) for i, line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) + '", "model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator =", "= onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator", "import sys if torch.cuda.is_available(): torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] # del(checkpoint)", "checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model,", "+ 1) == lenSrcData: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch)", "model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate", "decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size,", "checkpoint['opt'] # del(checkpoint) opt.cuda = True srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder =", "% (str(i) + ' of ' + str(lenSrcData))) sys.stdout.flush() srcTokens = line.split() srcBatch", "= translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b in range(len(predBatch)): candidate += [\"", "nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator =", "sys.stdout.flush() srcTokens = line.split() srcBatch += [srcTokens] if (i + 1) % opt.trans_batch_size", "torch import torch.nn as nn import onmt from onmt.BleuCal import fetch_data import sys", "srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt'])", "0: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b in", "srcBatch, tgtBatch, candidate = [], [], [] lenSrcData = len(srcData) for i, line", "= line.split() srcBatch += [srcTokens] if (i + 1) % opt.trans_batch_size == 0:", "= onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()),", "[], [], [] lenSrcData = len(srcData) for i, line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\"", "<filename>debug.py import torch import torch.nn as nn import onmt from onmt.BleuCal import fetch_data", "'../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt' translator = onmt.Translator(opt, model, checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate = [], [],", "+ 1) % opt.trans_batch_size == 0: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print", "line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) + ' of ' + str(lenSrcData)))", "candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] elif (i + 1)", "srcBatch += [srcTokens] if (i + 1) % opt.trans_batch_size == 0: predBatch, _,", "i, line in enumerate(srcData): sys.stdout.write('\\r') sys.stdout.write(\"%s\" % (str(i) + ' of ' +", "True srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt,", "references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model", "+ str(lenSrcData))) sys.stdout.flush() srcTokens = line.split() srcBatch += [srcTokens] if (i + 1)", "generator = nn.Sequential( nn.Linear(opt.rnn_size, checkpoint['dicts']['tgt'].size()), nn.LogSoftmax()) model.generator = generator model.cuda() opt.model = '../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt'", "torch.cuda.set_device(3) checkpoint = torch.load('../Models/V1_IWSLT_Models/de2en_30k_bz64_bc5_bleu_26.06_e24.pt') opt = checkpoint['opt'] # del(checkpoint) opt.cuda = True srcData,", "(str(i) + ' of ' + str(lenSrcData))) sys.stdout.flush() srcTokens = line.split() srcBatch +=", "== 0: predBatch, _, _ = translator.translate(srcBatch, tgtBatch) print 'predBatch:', len(predBatch) for b", "= True srcData, references = fetch_data('IWSLT/test.de.small.tok', 'IWSLT/test.en.small.tok') encoder = onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder =", "onmt.Models.Encoder(opt, checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator =", "b in range(len(predBatch)): candidate += [\" \".join(predBatch[b][0]) + '\\n'] srcBatch = [] elif", "+ '\\n'] srcBatch = [] elif (i + 1) == lenSrcData: predBatch, _,", "srcBatch = [] elif (i + 1) == lenSrcData: predBatch, _, _ =", "checkpoint['dicts']['src'], checkpoint['dicts']['tgt']) srcBatch, tgtBatch, candidate = [], [], [] lenSrcData = len(srcData) for", "checkpoint['dicts']['src']) decoder = onmt.Models.Decoder(opt, checkpoint['dicts']['tgt']) model = onmt.Models.NMTModel(encoder, decoder) model.load_state_dict(checkpoint['model']) generator = nn.Sequential(" ]
[ "msgs first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id", "db = await hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg() for i in range(10)] entries", "in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) await db.delete(entries[0].id)", "first_id is None assert last_id is None msgs = [create_msg() for i in", "nonlocal counter counter += 1 return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid),", "procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}') return create_msg async def test_create(db_path): assert not", "assert db_path.exists() async def test_add_msgs(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) first_id", "db.add_msgs(msgs) assert entries == [] msgs = [create_msg() for i in range(10)] entries", "1 return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no", "== [] msgs = [create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp,", "create_msg): db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id = await", "entries[-1].id msgs = [create_msg() for i in range(10)] new_entries = await db.add_msgs([(timestamp, msg)", "msgs]) assert len(entries) == len(msgs) assert [entry.msg for entry in entries] == msgs", "hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id ==", "= await db.add_msgs([(timestamp, msg) for msg in msgs]) assert len(entries) == len(msgs) assert", "= await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id", "= await hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg() for i in range(10)] entries =", "db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id + 1)", "first_id == entries[-1].id assert last_id == entries[-1].id msgs = [create_msg() for i in", "first_id is None assert last_id is None msgs = [] entries = await", "'syslog.db' @pytest.fixture def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def create_msg(timestamp): counter", "db_path.exists() db = await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await db.async_close() assert db_path.exists() async", "def test_delete(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg() for", "await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id", "range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) await db.delete(entries[0].id) first_id", "import os import socket import pytest from hat.syslog.server import common import hat.syslog.server.database pytestmark", "await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.async_close() async", "assert first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id + 1) first_id", "assert last_id == entries[-1].id await db.async_close() db = await hat.syslog.server.database.create_database(db_path, False) first_id =", "== entries[-1].id await db.async_close() db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id()", "is None assert last_id is None msgs = [] entries = await db.add_msgs(msgs)", "entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id) first_id = await db.get_first_id() last_id =", "return tmp_path / 'syslog.db' @pytest.fixture def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture", "await db.get_last_id() assert first_id == entries[-1].id assert last_id == entries[-1].id msgs = [create_msg()", "msgs]) entries = [entries[-1], *new_entries] first_id = await db.get_first_id() last_id = await db.get_last_id()", "await db.delete(entries[0].id) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id ==", "msgs]) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id", "db.delete(entries[-1].id) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[-1].id", "in msgs]) await db.delete(entries[0].id) first_id = await db.get_first_id() last_id = await db.get_last_id() assert", "severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter += 1 return common.Msg(facility=facility, severity=severity, version=1,", "import pytest from hat.syslog.server import common import hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture def", "assert last_id is None msgs = [] entries = await db.add_msgs(msgs) assert entries", "hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await db.async_close() assert db_path.exists() async def test_add_msgs(db_path, timestamp, create_msg):", "db.async_close() db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id = await", "entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) await db.delete(entries[0].id) first_id =", "for msg in msgs]) await db.delete(entries[0].id) first_id = await db.get_first_id() last_id = await", "= [create_msg() for i in range(10)] new_entries = await db.add_msgs([(timestamp, msg) for msg", "False) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id", "+ 1) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id is", "== msgs first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id ==", "db.delete(entries[0].id) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id", "[create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in", "last_id == entries[-1].id await db.delete(entries[-1].id + 1) first_id = await db.get_first_id() last_id =", "range(10)] new_entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) entries = [entries[-1],", "== entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id + 1) first_id = await", "await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id assert last_id ==", "in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) first_id =", "severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}') return create_msg", "range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) assert len(entries) ==", "== entries[-1].id await db.delete(entries[-1].id) first_id = await db.get_first_id() last_id = await db.get_last_id() assert", "db_path.exists() async def test_add_msgs(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) first_id =", "= await db.add_msgs([(timestamp, msg) for msg in msgs]) await db.delete(entries[0].id) first_id = await", "db.async_close() async def test_delete(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) msgs =", "db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.async_close() db =", "await db.add_msgs([(timestamp, msg) for msg in msgs]) assert len(entries) == len(msgs) assert [entry.msg", "[create_msg() for i in range(10)] new_entries = await db.add_msgs([(timestamp, msg) for msg in", "assert first_id is None assert last_id is None msgs = [] entries =", "entries = await db.add_msgs(msgs) assert entries == [] msgs = [create_msg() for i", "first_id == entries[0].id assert last_id == entries[-1].id await db.async_close() db = await hat.syslog.server.database.create_database(db_path,", "assert entries == [] msgs = [create_msg() for i in range(10)] entries =", "from hat.syslog.server import common import hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return", "timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg() for i in", "await hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg() for i in range(10)] entries = await", "await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[-1].id assert last_id ==", "for msg in msgs]) assert len(entries) == len(msgs) assert [entry.msg for entry in", "db.add_msgs([(timestamp, msg) for msg in msgs]) first_id = await db.get_first_id() last_id = await", "for entry in entries] == msgs first_id = await db.get_first_id() last_id = await", "await db.add_msgs([(timestamp, msg) for msg in msgs]) first_id = await db.get_first_id() last_id =", "await db.delete(entries[-1].id) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id ==", "last_id = await db.get_last_id() assert first_id == entries[-1].id assert last_id == entries[-1].id msgs", "= await db.get_last_id() assert first_id == entries[-1].id assert last_id == entries[-1].id msgs =", "= [entries[-1], *new_entries] first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id", "*new_entries] first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id", "= await db.add_msgs(msgs) assert entries == [] msgs = [create_msg() for i in", "@pytest.fixture def create_msg(timestamp): counter = 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal", "= await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id assert last_id", "pytestmark = pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return tmp_path / 'syslog.db' @pytest.fixture def timestamp():", "entries[0].id assert last_id == entries[-1].id await db.async_close() db = await hat.syslog.server.database.create_database(db_path, False) first_id", "@pytest.fixture def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def create_msg(timestamp): counter =", "new_entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) entries = [entries[-1], *new_entries]", "False) assert db_path.exists() await db.async_close() assert db_path.exists() async def test_add_msgs(db_path, timestamp, create_msg): db", "assert not db_path.exists() db = await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await db.async_close() assert", "common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}') return", "await db.add_msgs([(timestamp, msg) for msg in msgs]) entries = [entries[-1], *new_entries] first_id =", "{counter}') return create_msg async def test_create(db_path): assert not db_path.exists() db = await hat.syslog.server.database.create_database(db_path,", "dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def create_msg(timestamp): counter = 0 def create_msg(facility=common.Facility.USER,", "last_id = await db.get_last_id() assert first_id is None assert last_id is None msgs", "timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id =", "= await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[-1].id assert last_id", "assert first_id == entries[0].id assert last_id == entries[-1].id await db.async_close() db = await", "== entries[-1].id msgs = [create_msg() for i in range(10)] new_entries = await db.add_msgs([(timestamp,", "last_id is None msgs = [] entries = await db.add_msgs(msgs) assert entries ==", "1) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id is None", "msg in msgs]) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id", "in entries] == msgs first_id = await db.get_first_id() last_id = await db.get_last_id() assert", "app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter += 1 return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname,", "i in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) assert", "= 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter += 1", "timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}') return create_msg async def", "def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def create_msg(timestamp): counter = 0", "[] entries = await db.add_msgs(msgs) assert entries == [] msgs = [create_msg() for", "for i in range(10)] new_entries = await db.add_msgs([(timestamp, msg) for msg in msgs])", "await db.get_last_id() assert first_id is None assert last_id is None msgs = [create_msg()", "db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.async_close() async def", "app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}') return create_msg async def test_create(db_path): assert", "await db.add_msgs(msgs) assert entries == [] msgs = [create_msg() for i in range(10)]", "None msgs = [] entries = await db.add_msgs(msgs) assert entries == [] msgs", "= [create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg", "await db.async_close() async def test_delete(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) msgs", "entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) first_id = await db.get_first_id()", "last_id == entries[-1].id await db.async_close() async def test_delete(db_path, timestamp, create_msg): db = await", "db.get_first_id() last_id = await db.get_last_id() assert first_id is None assert last_id is None", "tmp_path / 'syslog.db' @pytest.fixture def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def", "entries] == msgs first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id", "== entries[0].id assert last_id == entries[-1].id await db.async_close() db = await hat.syslog.server.database.create_database(db_path, False)", "assert first_id is None assert last_id is None msgs = [create_msg() for i", "assert db_path.exists() await db.async_close() assert db_path.exists() async def test_add_msgs(db_path, timestamp, create_msg): db =", "[] msgs = [create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp, msg)", "assert last_id == entries[-1].id await db.delete(entries[-1].id) first_id = await db.get_first_id() last_id = await", "version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}') return create_msg async", "for msg in msgs]) first_id = await db.get_first_id() last_id = await db.get_last_id() assert", "last_id == entries[-1].id await db.async_close() db = await hat.syslog.server.database.create_database(db_path, False) first_id = await", "in msgs]) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id ==", "def test_create(db_path): assert not db_path.exists() db = await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await", "socket import pytest from hat.syslog.server import common import hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture", "def create_msg(timestamp): counter = 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter", "timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def create_msg(timestamp): counter = 0 def", "is None msgs = [create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp,", "db.add_msgs([(timestamp, msg) for msg in msgs]) entries = [entries[-1], *new_entries] first_id = await", "hat.syslog.server import common import hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return tmp_path", "= await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await db.async_close() assert db_path.exists() async def test_add_msgs(db_path,", "entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id + 1) first_id = await db.get_first_id()", "is None msgs = [] entries = await db.add_msgs(msgs) assert entries == []", "None assert last_id is None msgs = [create_msg() for i in range(10)] entries", "await db.async_close() assert db_path.exists() async def test_add_msgs(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path,", "pytest from hat.syslog.server import common import hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture def db_path(tmp_path):", "= await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.async_close()", "test_add_msgs(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id", "0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter += 1 return", "last_id == entries[-1].id msgs = [create_msg() for i in range(10)] new_entries = await", "counter counter += 1 return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend',", "in msgs]) assert len(entries) == len(msgs) assert [entry.msg for entry in entries] ==", "entries = [entries[-1], *new_entries] first_id = await db.get_first_id() last_id = await db.get_last_id() assert", "async def test_delete(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg()", "in msgs]) entries = [entries[-1], *new_entries] first_id = await db.get_first_id() last_id = await", "no {counter}') return create_msg async def test_create(db_path): assert not db_path.exists() db = await", "db_path.exists() await db.async_close() assert db_path.exists() async def test_add_msgs(db_path, timestamp, create_msg): db = await", "@pytest.fixture def db_path(tmp_path): return tmp_path / 'syslog.db' @pytest.fixture def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc)", "= datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def create_msg(timestamp): counter = 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR,", "msgs = [] entries = await db.add_msgs(msgs) assert entries == [] msgs =", "await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.async_close() db", "== entries[0].id assert last_id == entries[-1].id await db.async_close() async def test_delete(db_path, timestamp, create_msg):", "await db.add_msgs([(timestamp, msg) for msg in msgs]) await db.delete(entries[0].id) first_id = await db.get_first_id()", "len(msgs) assert [entry.msg for entry in entries] == msgs first_id = await db.get_first_id()", "entries[-1].id await db.delete(entries[-1].id + 1) first_id = await db.get_first_id() last_id = await db.get_last_id()", "= await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id = await db.get_last_id() assert", "False) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id is None", "msgs = [create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp, msg) for", "assert first_id == entries[-1].id assert last_id == entries[-1].id msgs = [create_msg() for i", "db.add_msgs([(timestamp, msg) for msg in msgs]) assert len(entries) == len(msgs) assert [entry.msg for", "last_id == entries[-1].id await db.delete(entries[-1].id) first_id = await db.get_first_id() last_id = await db.get_last_id()", "datetime import os import socket import pytest from hat.syslog.server import common import hat.syslog.server.database", "create_msg(timestamp): counter = 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter", "in range(10)] new_entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) entries =", "create_msg async def test_create(db_path): assert not db_path.exists() db = await hat.syslog.server.database.create_database(db_path, False) assert", "= await db.get_first_id() last_id = await db.get_last_id() assert first_id is None assert last_id", "entries[-1].id await db.async_close() async def test_delete(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False)", "entry in entries] == msgs first_id = await db.get_first_id() last_id = await db.get_last_id()", "None msgs = [create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp, msg)", "def test_add_msgs(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id()", "False) msgs = [create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp, msg)", "msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}') return create_msg async def test_create(db_path): assert not db_path.exists()", "== entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id) first_id = await db.get_first_id() last_id", "msgs = [create_msg() for i in range(10)] new_entries = await db.add_msgs([(timestamp, msg) for", "import common import hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return tmp_path /", "not db_path.exists() db = await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await db.async_close() assert db_path.exists()", "counter = 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter +=", "== len(msgs) assert [entry.msg for entry in entries] == msgs first_id = await", "i in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) await", "async def test_add_msgs(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) first_id = await", "db.add_msgs([(timestamp, msg) for msg in msgs]) await db.delete(entries[0].id) first_id = await db.get_first_id() last_id", "= await db.get_last_id() assert first_id is None assert last_id is None msgs =", "entries == [] msgs = [create_msg() for i in range(10)] entries = await", "msg) for msg in msgs]) assert len(entries) == len(msgs) assert [entry.msg for entry", "first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id assert", "== entries[-1].id assert last_id == entries[-1].id msgs = [create_msg() for i in range(10)]", "await db.delete(entries[-1].id + 1) first_id = await db.get_first_id() last_id = await db.get_last_id() assert", "assert last_id is None msgs = [create_msg() for i in range(10)] entries =", "assert last_id == entries[-1].id await db.delete(entries[-1].id + 1) first_id = await db.get_first_id() last_id", "entries[0].id assert last_id == entries[-1].id await db.async_close() async def test_delete(db_path, timestamp, create_msg): db", "msg in msgs]) await db.delete(entries[0].id) first_id = await db.get_first_id() last_id = await db.get_last_id()", "first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id) first_id = await db.get_first_id()", "create_msg): db = await hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg() for i in range(10)]", "hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter += 1 return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp,", "= await db.add_msgs([(timestamp, msg) for msg in msgs]) first_id = await db.get_first_id() last_id", "entries[-1].id await db.async_close() db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id", "msg) for msg in msgs]) first_id = await db.get_first_id() last_id = await db.get_last_id()", "await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id) first_id", "msg in msgs]) entries = [entries[-1], *new_entries] first_id = await db.get_first_id() last_id =", "return create_msg async def test_create(db_path): assert not db_path.exists() db = await hat.syslog.server.database.create_database(db_path, False)", "return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}')", "== entries[-1].id await db.delete(entries[-1].id + 1) first_id = await db.get_first_id() last_id = await", "async def test_create(db_path): assert not db_path.exists() db = await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists()", "return dt.timestamp() @pytest.fixture def create_msg(timestamp): counter = 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__,", "hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id is", "range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) first_id = await", "first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id is None assert", "assert len(entries) == len(msgs) assert [entry.msg for entry in entries] == msgs first_id", "db.get_last_id() assert first_id is None assert last_id is None msgs = [create_msg() for", "await db.get_first_id() last_id = await db.get_last_id() assert first_id is None assert last_id is", "data=\"\", msg=f'message no {counter}') return create_msg async def test_create(db_path): assert not db_path.exists() db", "in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) assert len(entries)", "import hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return tmp_path / 'syslog.db' @pytest.fixture", "dt.timestamp() @pytest.fixture def create_msg(timestamp): counter = 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()):", "first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id + 1) first_id =", "db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id) first_id =", "def db_path(tmp_path): return tmp_path / 'syslog.db' @pytest.fixture def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return", "db.get_last_id() assert first_id is None assert last_id is None msgs = [] entries", "= [] entries = await db.add_msgs(msgs) assert entries == [] msgs = [create_msg()", "assert first_id == entries[0].id assert last_id == entries[-1].id await db.async_close() async def test_delete(db_path,", "first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[-1].id assert", "assert [entry.msg for entry in entries] == msgs first_id = await db.get_first_id() last_id", "= await db.add_msgs([(timestamp, msg) for msg in msgs]) entries = [entries[-1], *new_entries] first_id", "None assert last_id is None msgs = [] entries = await db.add_msgs(msgs) assert", "for msg in msgs]) entries = [entries[-1], *new_entries] first_id = await db.get_first_id() last_id", "import datetime import os import socket import pytest from hat.syslog.server import common import", "procid=os.getpid()): nonlocal counter counter += 1 return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name,", "entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) assert len(entries) == len(msgs)", "= await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id)", "await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id +", "os import socket import pytest from hat.syslog.server import common import hat.syslog.server.database pytestmark =", "hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return tmp_path / 'syslog.db' @pytest.fixture def", "[entry.msg for entry in entries] == msgs first_id = await db.get_first_id() last_id =", "last_id = await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id await", "entries[-1].id await db.delete(entries[-1].id) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id", "for i in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs])", "is None assert last_id is None msgs = [create_msg() for i in range(10)]", "msg) for msg in msgs]) await db.delete(entries[0].id) first_id = await db.get_first_id() last_id =", "msgs]) await db.delete(entries[0].id) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id", "msg in msgs]) assert len(entries) == len(msgs) assert [entry.msg for entry in entries]", "db.get_last_id() assert first_id == entries[-1].id assert last_id == entries[-1].id msgs = [create_msg() for", "[entries[-1], *new_entries] first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id ==", "hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg() for i in range(10)] entries = await db.add_msgs([(timestamp,", "msg) for msg in msgs]) entries = [entries[-1], *new_entries] first_id = await db.get_first_id()", "counter += 1 return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\",", "/ 'syslog.db' @pytest.fixture def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def create_msg(timestamp):", "msg=f'message no {counter}') return create_msg async def test_create(db_path): assert not db_path.exists() db =", "= pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return tmp_path / 'syslog.db' @pytest.fixture def timestamp(): dt", "pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return tmp_path / 'syslog.db' @pytest.fixture def timestamp(): dt =", "db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id = await db.get_last_id()", "hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message no {counter}') return create_msg async def test_create(db_path):", "assert last_id == entries[-1].id await db.async_close() async def test_delete(db_path, timestamp, create_msg): db =", "last_id is None msgs = [create_msg() for i in range(10)] entries = await", "await db.get_last_id() assert first_id is None assert last_id is None msgs = []", "db_path(tmp_path): return tmp_path / 'syslog.db' @pytest.fixture def timestamp(): dt = datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp()", "db = await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await db.async_close() assert db_path.exists() async def", "== entries[-1].id await db.async_close() async def test_delete(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path,", "import socket import pytest from hat.syslog.server import common import hat.syslog.server.database pytestmark = pytest.mark.asyncio", "test_delete(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False) msgs = [create_msg() for i", "assert first_id == entries[0].id assert last_id == entries[-1].id await db.delete(entries[-1].id) first_id = await", "len(entries) == len(msgs) assert [entry.msg for entry in entries] == msgs first_id =", "common import hat.syslog.server.database pytestmark = pytest.mark.asyncio @pytest.fixture def db_path(tmp_path): return tmp_path / 'syslog.db'", "db.async_close() assert db_path.exists() async def test_add_msgs(db_path, timestamp, create_msg): db = await hat.syslog.server.database.create_database(db_path, False)", "assert last_id == entries[-1].id msgs = [create_msg() for i in range(10)] new_entries =", "first_id == entries[0].id assert last_id == entries[-1].id await db.async_close() async def test_delete(db_path, timestamp,", "test_create(db_path): assert not db_path.exists() db = await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await db.async_close()", "datetime.datetime.now(tz=datetime.timezone.utc) return dt.timestamp() @pytest.fixture def create_msg(timestamp): counter = 0 def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(),", "entries[-1].id assert last_id == entries[-1].id msgs = [create_msg() for i in range(10)] new_entries", "<reponame>hat-open/hat-syslog<filename>test_pytest/test_unit/test_database.py import datetime import os import socket import pytest from hat.syslog.server import common", "i in range(10)] new_entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) entries", "+= 1 return common.Msg(facility=facility, severity=severity, version=1, timestamp=timestamp, hostname=hostname, app_name=app_name, procid=str(procid), msgid='test_syslog.backend', data=\"\", msg=f'message", "await db.async_close() db = await hat.syslog.server.database.create_database(db_path, False) first_id = await db.get_first_id() last_id =", "def create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter += 1 return common.Msg(facility=facility,", "create_msg(facility=common.Facility.USER, severity=common.Severity.ERROR, hostname=socket.gethostname(), app_name=pytest.__file__, procid=os.getpid()): nonlocal counter counter += 1 return common.Msg(facility=facility, severity=severity,", "i in range(10)] entries = await db.add_msgs([(timestamp, msg) for msg in msgs]) first_id", "db.delete(entries[-1].id + 1) first_id = await db.get_first_id() last_id = await db.get_last_id() assert first_id", "await hat.syslog.server.database.create_database(db_path, False) assert db_path.exists() await db.async_close() assert db_path.exists() async def test_add_msgs(db_path, timestamp,", "db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[0].id assert last_id == entries[-1].id", "db.get_first_id() last_id = await db.get_last_id() assert first_id == entries[-1].id assert last_id == entries[-1].id" ]
[ "# find multiple tag def has_class_but_no_id(tag): return tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) #", "print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains key \"my_url\" pprint(soup.find_all(id=True)) # all links", "all class name contains 7 characters pprint(soup.find_all(\"a\", \"sister\")) # find all a tag", "'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all a tag have class named contains 'sister'", "soap for tag in soup.find_all(re.compile(\"^p\")): # find all tag start with p print", "and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find", "url name contains elsie and have id = link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id':", "contains key \"my_url\" pprint(soup.find_all(id=True)) # all links has id pprint(soup.find_all(class_=True)) # all links", "making soap for tag in soup.find_all(re.compile(\"^p\")): # find all tag start with p", "link1 pprint(soup.find_all(\"a\", limit=2)) # use limit on findall pprint(soup.html.find_all(\"title\", recursive=True)) # use recursive", "print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find multiple tag def has_class_but_no_id(tag): return tag.has_key('class') and", "find all tag print tag.name pprint(soup.find_all('a')) # find all a tag print 20*\"++\"", "contains t print tag.name for tag in soup.find_all(True): # find all tag print", "# all links has class def has_six_characters(css_class): return css_class is not None and", "pprint(soup.find_all(class_=True)) # all links has class def has_six_characters(css_class): return css_class is not None", "# url name contains elsie and have id = link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"),", "# making soap for tag in soup.find_all(re.compile(\"^p\")): # find all tag start with", "tag.name pprint(soup.find_all('a')) # find all a tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find", "import re from bs4 import BeautifulSoup html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup =", "contains elsie and have id = link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'})) #", "has id pprint(soup.find_all(class_=True)) # all links has class def has_six_characters(css_class): return css_class is", "find all class name contains 7 characters pprint(soup.find_all(\"a\", \"sister\")) # find all a", "for tag in soup.find_all(re.compile(\"^p\")): # find all tag start with p print tag.name", "# all links has id pprint(soup.find_all(class_=True)) # all links has class def has_six_characters(css_class):", "tag have class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all a tag have", "# url name contains elsie and have id = link1 pprint(soup.find_all(\"a\", limit=2)) #", "\"my_url\" pprint(soup.find_all(id=True)) # all links has id pprint(soup.find_all(class_=True)) # all links has class", "'link1'})) # url name contains elsie and have id = link1 pprint(soup.find_all(\"a\", limit=2))", "soup.find_all(re.compile(\"^p\")): # find all tag start with p print tag.name for tag in", "id='link1')) # url name contains elsie and have id = link1 pprint(soup.find_all(attrs={'href' :", "contains 7 characters pprint(soup.find_all(\"a\", \"sister\")) # find all a tag have class named", "pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'})) # url name contains elsie and have id", "in soup.find_all(re.compile(\"t\")): # find all tag contains t print tag.name for tag in", "is not None and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) # find all class name", "function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag content contains key 'sisters' print", "print tag.name for tag in soup.find_all(re.compile(\"t\")): # find all tag contains t print", "= open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) # making soap for tag in", "def has_class_but_no_id(tag): return tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a function to", "name contains elsie and have id = link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'}))", "pprint(soup.find_all(\"a\", \"sister\")) # find all a tag have class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\")))", "all tag content contains key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains", "# find all tag contains t print tag.name for tag in soup.find_all(True): #", "all links contains key \"my_url\" pprint(soup.find_all(id=True)) # all links has id pprint(soup.find_all(class_=True)) #", "all links has class def has_six_characters(css_class): return css_class is not None and len(css_class)", "import pprint import re from bs4 import BeautifulSoup html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html", "return tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\")))", "all a tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find multiple tag def has_class_but_no_id(tag):", "from bs4 import BeautifulSoup html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) #", "'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name contains elsie and have id", "named contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name contains elsie and", "tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find multiple tag def has_class_but_no_id(tag): return tag.has_key('class')", ": re.compile(\"elsie\"), 'id': 'link1'})) # url name contains elsie and have id =", "soup.find_all(True): # find all tag print tag.name pprint(soup.find_all('a')) # find all a tag", "class named contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name contains elsie", "= link1 pprint(soup.find_all(\"a\", limit=2)) # use limit on findall pprint(soup.html.find_all(\"title\", recursive=True)) # use", "pprint(soup.find_all(has_class_but_no_id)) # pass a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag content", "= BeautifulSoup(html_content) # making soap for tag in soup.find_all(re.compile(\"^p\")): # find all tag", "t print tag.name for tag in soup.find_all(True): # find all tag print tag.name", "7 characters pprint(soup.find_all(\"a\", \"sister\")) # find all a tag have class named 'sister'", "return css_class is not None and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) # find all", "multiple tag def has_class_but_no_id(tag): return tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a", "http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) # making soap for tag in soup.find_all(re.compile(\"^p\")): # find", "= link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'})) # url name contains elsie and", "in soup.find_all(re.compile(\"^p\")): # find all tag start with p print tag.name for tag", "has_class_but_no_id(tag): return tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a function to find_all", "20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains key \"my_url\" pprint(soup.find_all(id=True)) # all links has", "contains elsie and have id = link1 pprint(soup.find_all(\"a\", limit=2)) # use limit on", "re from bs4 import BeautifulSoup html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content)", "pprint import re from bs4 import BeautifulSoup html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup", "from pprint import pprint import re from bs4 import BeautifulSoup html_content = open('bs_sample.html')", "pprint(soup.find_all(\"a\", limit=2)) # use limit on findall pprint(soup.html.find_all(\"title\", recursive=True)) # use recursive on", "tag in soup.find_all(re.compile(\"^p\")): # find all tag start with p print tag.name for", "# find all class name contains 7 characters pprint(soup.find_all(\"a\", \"sister\")) # find all", "tag print tag.name pprint(soup.find_all('a')) # find all a tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"]))", "have id = link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'})) # url name contains", "limit=2)) # use limit on findall pprint(soup.html.find_all(\"title\", recursive=True)) # use recursive on findall", "bs4 import BeautifulSoup html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) # making", "not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all", "print tag.name pprint(soup.find_all('a')) # find all a tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) #", "BeautifulSoup html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) # making soap for", "in soup.find_all(True): # find all tag print tag.name pprint(soup.find_all('a')) # find all a", "# find all a tag have class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find", "for tag in soup.find_all(True): # find all tag print tag.name pprint(soup.find_all('a')) # find", "with p print tag.name for tag in soup.find_all(re.compile(\"t\")): # find all tag contains", "name contains elsie and have id = link1 pprint(soup.find_all(\"a\", limit=2)) # use limit", "20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find multiple tag def has_class_but_no_id(tag): return tag.has_key('class') and not", "elsie and have id = link1 pprint(soup.find_all(\"a\", limit=2)) # use limit on findall", "and have id = link1 pprint(soup.find_all(\"a\", limit=2)) # use limit on findall pprint(soup.html.find_all(\"title\",", "pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains key \"my_url\" pprint(soup.find_all(id=True)) # all links has id", "characters pprint(soup.find_all(\"a\", \"sister\")) # find all a tag have class named 'sister' pprint(soup.find_all(\"a\",", "id = link1 pprint(soup.find_all(\"a\", limit=2)) # use limit on findall pprint(soup.html.find_all(\"title\", recursive=True)) #", "<filename>web_scraping/beautifulsoup/bs4_sample2.py from pprint import pprint import re from bs4 import BeautifulSoup html_content =", "soup.find_all(re.compile(\"t\")): # find all tag contains t print tag.name for tag in soup.find_all(True):", "pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all a tag have class named contains 'sister' print", "pprint import pprint import re from bs4 import BeautifulSoup html_content = open('bs_sample.html') #", "re.compile(\"sister\"))) # find all a tag have class named contains 'sister' print 20*\"++\"", "20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name contains elsie and have id = link1", "html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) # making soap for tag", "import BeautifulSoup html_content = open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) # making soap", "elsie and have id = link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'})) # url", "all tag start with p print tag.name for tag in soup.find_all(re.compile(\"t\")): # find", "# find all a tag have class named contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"),", "have id = link1 pprint(soup.find_all(\"a\", limit=2)) # use limit on findall pprint(soup.html.find_all(\"title\", recursive=True))", "find all a tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find multiple tag def", "and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) # find all class name contains 7 characters", "key \"my_url\" pprint(soup.find_all(id=True)) # all links has id pprint(soup.find_all(class_=True)) # all links has", "class name contains 7 characters pprint(soup.find_all(\"a\", \"sister\")) # find all a tag have", "tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) #", "BeautifulSoup(html_content) # making soap for tag in soup.find_all(re.compile(\"^p\")): # find all tag start", "all a tag have class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all a", "tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag", "pprint(soup.find_all([\"a\", \"b\"])) # find multiple tag def has_class_but_no_id(tag): return tag.has_key('class') and not tag.has_key('id')", "re.compile(\"elsie\"), 'id': 'link1'})) # url name contains elsie and have id = link1", "tag in soup.find_all(re.compile(\"t\")): # find all tag contains t print tag.name for tag", "class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all a tag have class named", "None and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) # find all class name contains 7", "a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag content contains key 'sisters'", "tag content contains key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains key", "find multiple tag def has_class_but_no_id(tag): return tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass", "contains key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains key \"my_url\" pprint(soup.find_all(id=True))", "all links has id pprint(soup.find_all(class_=True)) # all links has class def has_six_characters(css_class): return", "id = link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'})) # url name contains elsie", "# find all a tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find multiple tag", "have class named contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name contains", "7 pprint(soup.find_all(class_=has_six_characters)) # find all class name contains 7 characters pprint(soup.find_all(\"a\", \"sister\")) #", "find all tag start with p print tag.name for tag in soup.find_all(re.compile(\"t\")): #", "p print tag.name for tag in soup.find_all(re.compile(\"t\")): # find all tag contains t", "content contains key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains key \"my_url\"", "has_six_characters(css_class): return css_class is not None and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) # find", "link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'})) # url name contains elsie and have", "== 7 pprint(soup.find_all(class_=has_six_characters)) # find all class name contains 7 characters pprint(soup.find_all(\"a\", \"sister\"))", "name contains 7 characters pprint(soup.find_all(\"a\", \"sister\")) # find all a tag have class", "links has class def has_six_characters(css_class): return css_class is not None and len(css_class) ==", "contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name contains elsie and have", "find all a tag have class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all", "a tag have class named contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url", "tag have class named contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name", "# find all tag start with p print tag.name for tag in soup.find_all(re.compile(\"t\")):", "class def has_six_characters(css_class): return css_class is not None and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters))", "tag def has_class_but_no_id(tag): return tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id)) # pass a function", "key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains key \"my_url\" pprint(soup.find_all(id=True)) #", "url name contains elsie and have id = link1 pprint(soup.find_all(\"a\", limit=2)) # use", "\"b\"])) # find multiple tag def has_class_but_no_id(tag): return tag.has_key('class') and not tag.has_key('id') pprint(soup.find_all(has_class_but_no_id))", "all a tag have class named contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) #", "tag.name for tag in soup.find_all(re.compile(\"t\")): # find all tag contains t print tag.name", "# find all tag print tag.name pprint(soup.find_all('a')) # find all a tag print", "tag.name for tag in soup.find_all(True): # find all tag print tag.name pprint(soup.find_all('a')) #", "have class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all a tag have class", "to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag content contains key 'sisters' print 20*\"++\"", "\"sister\")) # find all a tag have class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) #", "'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links contains key \"my_url\" pprint(soup.find_all(id=True)) # all", "pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag content contains key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) #", "links has id pprint(soup.find_all(class_=True)) # all links has class def has_six_characters(css_class): return css_class", "has class def has_six_characters(css_class): return css_class is not None and len(css_class) == 7", "tag start with p print tag.name for tag in soup.find_all(re.compile(\"t\")): # find all", "start with p print tag.name for tag in soup.find_all(re.compile(\"t\")): # find all tag", "for tag in soup.find_all(re.compile(\"t\")): # find all tag contains t print tag.name for", "links contains key \"my_url\" pprint(soup.find_all(id=True)) # all links has id pprint(soup.find_all(class_=True)) # all", "not None and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) # find all class name contains", "find all a tag have class named contains 'sister' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1'))", "# all links contains key \"my_url\" pprint(soup.find_all(id=True)) # all links has id pprint(soup.find_all(class_=True))", "pprint(soup.find_all(id=True)) # all links has id pprint(soup.find_all(class_=True)) # all links has class def", "tag in soup.find_all(True): # find all tag print tag.name pprint(soup.find_all('a')) # find all", "find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag content contains key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\")))", "pass a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag content contains key", "a tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find multiple tag def has_class_but_no_id(tag): return", "'id': 'link1'})) # url name contains elsie and have id = link1 pprint(soup.find_all(\"a\",", "# http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) # making soap for tag in soup.find_all(re.compile(\"^p\")): #", "# find all tag content contains key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all", "a tag have class named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all a tag", "pprint(soup.find_all('a')) # find all a tag print 20*\"++\" pprint(soup.find_all([\"a\", \"b\"])) # find multiple", "all tag contains t print tag.name for tag in soup.find_all(True): # find all", "all tag print tag.name pprint(soup.find_all('a')) # find all a tag print 20*\"++\" pprint(soup.find_all([\"a\",", "soup = BeautifulSoup(html_content) # making soap for tag in soup.find_all(re.compile(\"^p\")): # find all", "# pass a function to find_all pprint(soup.find_all(text=re.compile(\"sisters\"))) # find all tag content contains", "pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name contains elsie and have id = link1 pprint(soup.find_all(attrs={'href'", "open('bs_sample.html') # http://dl.dropbox.com/u/49962071/blog/python/resource/bs_sample.html soup = BeautifulSoup(html_content) # making soap for tag in soup.find_all(re.compile(\"^p\")):", "find all tag content contains key 'sisters' print 20*\"++\" pprint(soup.find_all(href=re.compile(\"my_url\"))) # all links", "css_class is not None and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) # find all class", "print 20*\"++\" pprint(soup.find_all(href=re.compile(\"elsie\"), id='link1')) # url name contains elsie and have id =", "len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) # find all class name contains 7 characters pprint(soup.find_all(\"a\",", "tag contains t print tag.name for tag in soup.find_all(True): # find all tag", "pprint(soup.find_all(class_=has_six_characters)) # find all class name contains 7 characters pprint(soup.find_all(\"a\", \"sister\")) # find", "find all tag contains t print tag.name for tag in soup.find_all(True): # find", "id pprint(soup.find_all(class_=True)) # all links has class def has_six_characters(css_class): return css_class is not", "print tag.name for tag in soup.find_all(True): # find all tag print tag.name pprint(soup.find_all('a'))", "def has_six_characters(css_class): return css_class is not None and len(css_class) == 7 pprint(soup.find_all(class_=has_six_characters)) #", "and have id = link1 pprint(soup.find_all(attrs={'href' : re.compile(\"elsie\"), 'id': 'link1'})) # url name", "named 'sister' pprint(soup.find_all(\"a\", re.compile(\"sister\"))) # find all a tag have class named contains" ]
[ "# found. set idhor c.execute('update linhas set idhor=%s where id=%s', [idhor, id]) c.close()", "import horarios, linhas, env, dias def get_linha_hor(idhor, nome): c = env.db.cursor() # look", "print 'ponto: %s, dias: %s' % (pto, dia) idponto = get_ponto_hor(pto) d =", "where id=%s', [idhor, id]) c.close() return id # not found. insert a new", "dias def get_linha_hor(idhor, nome): c = env.db.cursor() # look for id horario r", "= c.select_onerow('linhas', ['id'], 'idhor is null and nome=%s', [nome]) if r: id =", "env.db.cursor() # look for id horario r = c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if", "id def get_ponto_hor(nome): c = env.db.cursor() r = c.select_onerow('pontos', ['id'], 'nome=%s', nome) if", "nome): c = env.db.cursor() # look for id horario r = c.select_onerow('linhas', ['id'],", "if r: id = r[0] # found. set idhor c.execute('update linhas set idhor=%s", "if r: c.close() return r[0] # not found c.insert_one('pontos', nome=nome) id = c.lastrowid", "else: c.execute('commit') c.close() def fetch_hor_all(): for cod,nome in horarios.lista_linhas(): print 'Fetching %s:%s' %", "= c.select_onerow('pontos', ['id'], 'nome=%s', nome) if r: c.close() return r[0] # not found", "idponto=idponto, dia=d, apartir=apartir) idset = c.lastrowid for sp,h in horas: c.insert_one('horarios', idset=idset, hora=h,", "r: c.close() return r[0] # not found. look for a similar name, but", "= r[0] # found. set idhor c.execute('update linhas set idhor=%s where id=%s', [idhor,", "special=sp) except: c.execute('rollback') else: c.execute('commit') c.close() def fetch_hor_all(): for cod,nome in horarios.lista_linhas(): print", "transaction') try: c.execute('delete from hs, h \\ using horsets hs, horarios h \\", "c.close() def fetch_hor_all(): for cod,nome in horarios.lista_linhas(): print 'Fetching %s:%s' % (cod, nome)", "'idhor is null and nome=%s', [nome]) if r: id = r[0] # found.", "sp,h in horas: c.insert_one('horarios', idset=idset, hora=h, special=sp) except: c.execute('rollback') else: c.execute('commit') c.close() def", "r = c.select_onerow('pontos', ['id'], 'nome=%s', nome) if r: c.close() return r[0] # not", "= env.db.cursor() idlinha = get_linha_hor(idhor, nome) #TODO: check if this really works c.execute('start", "[idhor]) if r: c.close() return r[0] # not found. look for a similar", "c.execute('update linhas set idhor=%s where id=%s', [idhor, id]) c.close() return id # not", "r: c.close() return r[0] # not found c.insert_one('pontos', nome=nome) id = c.lastrowid c.close()", "for cod,nome in horarios.lista_linhas(): print 'Fetching %s:%s' % (cod, nome) fetch_horarios(cod, nome) if", "horsets hs, horarios h \\ where hs.idlinha=%s and h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor)", "= get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset = c.lastrowid", "in horas: c.insert_one('horarios', idset=idset, hora=h, special=sp) except: c.execute('rollback') else: c.execute('commit') c.close() def fetch_hor_all():", "idhor set r = c.select_onerow('linhas', ['id'], 'idhor is null and nome=%s', [nome]) if", "return id def fetch_horarios(idhor, nome): c = env.db.cursor() idlinha = get_linha_hor(idhor, nome) #TODO:", "= dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset = c.lastrowid for sp,h in", "c.execute('rollback') else: c.execute('commit') c.close() def fetch_hor_all(): for cod,nome in horarios.lista_linhas(): print 'Fetching %s:%s'", "get_ponto_hor(nome): c = env.db.cursor() r = c.select_onerow('pontos', ['id'], 'nome=%s', nome) if r: c.close()", "[nome]) if r: id = r[0] # found. set idhor c.execute('update linhas set", "c.lastrowid c.close() return id def get_ponto_hor(nome): c = env.db.cursor() r = c.select_onerow('pontos', ['id'],", "found. look for a similar name, but with no idhor set r =", "where hs.idlinha=%s and h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html): print", "return r[0] # not found. look for a similar name, but with no", "nome=nome) id = c.lastrowid c.close() return id def get_ponto_hor(nome): c = env.db.cursor() r", "horas: c.insert_one('horarios', idset=idset, hora=h, special=sp) except: c.execute('rollback') else: c.execute('commit') c.close() def fetch_hor_all(): for", "for pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto: %s, dias: %s' % (pto, dia) idponto", "% (cod, nome) fetch_horarios(cod, nome) if __name__ == '__main__': #fetch_horarios('022', u'INTER 2 (Horário)')", "record c.insert_one('linhas', idhor=idhor, nome=nome) id = c.lastrowid c.close() return id def get_ponto_hor(nome): c", "id horario r = c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if r: c.close() return r[0]", "set idhor=%s where id=%s', [idhor, id]) c.close() return id # not found. insert", "get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset = c.lastrowid for", "(cod, nome) fetch_horarios(cod, nome) if __name__ == '__main__': #fetch_horarios('022', u'INTER 2 (Horário)') fetch_hor_all()", "env, dias def get_linha_hor(idhor, nome): c = env.db.cursor() # look for id horario", "c.insert_one('pontos', nome=nome) id = c.lastrowid c.close() return id def fetch_horarios(idhor, nome): c =", "not found c.insert_one('pontos', nome=nome) id = c.lastrowid c.close() return id def fetch_horarios(idhor, nome):", "c.lastrowid for sp,h in horas: c.insert_one('horarios', idset=idset, hora=h, special=sp) except: c.execute('rollback') else: c.execute('commit')", "%s, dias: %s' % (pto, dia) idponto = get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets',", "c.close() return id def fetch_horarios(idhor, nome): c = env.db.cursor() idlinha = get_linha_hor(idhor, nome)", "in horarios.parse_hor_html(html): print 'ponto: %s, dias: %s' % (pto, dia) idponto = get_ponto_hor(pto)", "id=%s', [idhor, id]) c.close() return id # not found. insert a new record", "get_linha_hor(idhor, nome) #TODO: check if this really works c.execute('start transaction') try: c.execute('delete from", "%s' % (pto, dia) idponto = get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto,", "c.close() return r[0] # not found. look for a similar name, but with", "hs.idlinha=%s and h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto:", "-* import horarios, linhas, env, dias def get_linha_hor(idhor, nome): c = env.db.cursor() #", "def get_linha_hor(idhor, nome): c = env.db.cursor() # look for id horario r =", "linhas, env, dias def get_linha_hor(idhor, nome): c = env.db.cursor() # look for id", "'idhor=%s', [idhor]) if r: c.close() return r[0] # not found. look for a", "h \\ where hs.idlinha=%s and h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in", "% (pto, dia) idponto = get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d,", "and nome=%s', [nome]) if r: id = r[0] # found. set idhor c.execute('update", "for id horario r = c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if r: c.close() return", "h \\ using horsets hs, horarios h \\ where hs.idlinha=%s and h.idset=hs.id', [idlinha])", "c.execute('commit') c.close() def fetch_hor_all(): for cod,nome in horarios.lista_linhas(): print 'Fetching %s:%s' % (cod,", "%s:%s' % (cod, nome) fetch_horarios(cod, nome) if __name__ == '__main__': #fetch_horarios('022', u'INTER 2", "c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if r: c.close() return r[0] # not found. look", "id]) c.close() return id # not found. insert a new record c.insert_one('linhas', idhor=idhor,", "['id'], 'nome=%s', nome) if r: c.close() return r[0] # not found c.insert_one('pontos', nome=nome)", "set idhor c.execute('update linhas set idhor=%s where id=%s', [idhor, id]) c.close() return id", "and h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto: %s,", "pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto: %s, dias: %s' % (pto, dia) idponto =", "works c.execute('start transaction') try: c.execute('delete from hs, h \\ using horsets hs, horarios", "horarios.parse_hor_html(html): print 'ponto: %s, dias: %s' % (pto, dia) idponto = get_ponto_hor(pto) d", "'ponto: %s, dias: %s' % (pto, dia) idponto = get_ponto_hor(pto) d = dias.id_dias(dia)", "# not found. insert a new record c.insert_one('linhas', idhor=idhor, nome=nome) id = c.lastrowid", "not found. look for a similar name, but with no idhor set r", "found c.insert_one('pontos', nome=nome) id = c.lastrowid c.close() return id def fetch_horarios(idhor, nome): c", "check if this really works c.execute('start transaction') try: c.execute('delete from hs, h \\", "new record c.insert_one('linhas', idhor=idhor, nome=nome) id = c.lastrowid c.close() return id def get_ponto_hor(nome):", "linhas set idhor=%s where id=%s', [idhor, id]) c.close() return id # not found.", "= c.lastrowid for sp,h in horas: c.insert_one('horarios', idset=idset, hora=h, special=sp) except: c.execute('rollback') else:", "= horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto: %s, dias: %s' % (pto,", "c.close() return id def get_ponto_hor(nome): c = env.db.cursor() r = c.select_onerow('pontos', ['id'], 'nome=%s',", "return id def get_ponto_hor(nome): c = env.db.cursor() r = c.select_onerow('pontos', ['id'], 'nome=%s', nome)", "\\ using horsets hs, horarios h \\ where hs.idlinha=%s and h.idset=hs.id', [idlinha]) html", "coding: utf-8 -* import horarios, linhas, env, dias def get_linha_hor(idhor, nome): c =", "['id'], 'idhor is null and nome=%s', [nome]) if r: id = r[0] #", "idponto = get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset =", "similar name, but with no idhor set r = c.select_onerow('linhas', ['id'], 'idhor is", "a similar name, but with no idhor set r = c.select_onerow('linhas', ['id'], 'idhor", "apartir=apartir) idset = c.lastrowid for sp,h in horas: c.insert_one('horarios', idset=idset, hora=h, special=sp) except:", "env.db.cursor() r = c.select_onerow('pontos', ['id'], 'nome=%s', nome) if r: c.close() return r[0] #", "horarios.lista_linhas(): print 'Fetching %s:%s' % (cod, nome) fetch_horarios(cod, nome) if __name__ == '__main__':", "= env.db.cursor() r = c.select_onerow('pontos', ['id'], 'nome=%s', nome) if r: c.close() return r[0]", "except: c.execute('rollback') else: c.execute('commit') c.close() def fetch_hor_all(): for cod,nome in horarios.lista_linhas(): print 'Fetching", "def fetch_hor_all(): for cod,nome in horarios.lista_linhas(): print 'Fetching %s:%s' % (cod, nome) fetch_horarios(cod,", "hora=h, special=sp) except: c.execute('rollback') else: c.execute('commit') c.close() def fetch_hor_all(): for cod,nome in horarios.lista_linhas():", "= c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if r: c.close() return r[0] # not found.", "get_linha_hor(idhor, nome): c = env.db.cursor() # look for id horario r = c.select_onerow('linhas',", "but with no idhor set r = c.select_onerow('linhas', ['id'], 'idhor is null and", "really works c.execute('start transaction') try: c.execute('delete from hs, h \\ using horsets hs,", "c.close() return r[0] # not found c.insert_one('pontos', nome=nome) id = c.lastrowid c.close() return", "c.select_onerow('linhas', ['id'], 'idhor is null and nome=%s', [nome]) if r: id = r[0]", "#TODO: check if this really works c.execute('start transaction') try: c.execute('delete from hs, h", "name, but with no idhor set r = c.select_onerow('linhas', ['id'], 'idhor is null", "\\ where hs.idlinha=%s and h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html):", "not found. insert a new record c.insert_one('linhas', idhor=idhor, nome=nome) id = c.lastrowid c.close()", "'nome=%s', nome) if r: c.close() return r[0] # not found c.insert_one('pontos', nome=nome) id", "c.lastrowid c.close() return id def fetch_horarios(idhor, nome): c = env.db.cursor() idlinha = get_linha_hor(idhor,", "r[0] # not found c.insert_one('pontos', nome=nome) id = c.lastrowid c.close() return id def", "fetch_hor_all(): for cod,nome in horarios.lista_linhas(): print 'Fetching %s:%s' % (cod, nome) fetch_horarios(cod, nome)", "idlinha = get_linha_hor(idhor, nome) #TODO: check if this really works c.execute('start transaction') try:", "# not found. look for a similar name, but with no idhor set", "c.insert_one('linhas', idhor=idhor, nome=nome) id = c.lastrowid c.close() return id def get_ponto_hor(nome): c =", "h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto: %s, dias:", "c = env.db.cursor() r = c.select_onerow('pontos', ['id'], 'nome=%s', nome) if r: c.close() return", "id # not found. insert a new record c.insert_one('linhas', idhor=idhor, nome=nome) id =", "for sp,h in horas: c.insert_one('horarios', idset=idset, hora=h, special=sp) except: c.execute('rollback') else: c.execute('commit') c.close()", "utf-8 -* import horarios, linhas, env, dias def get_linha_hor(idhor, nome): c = env.db.cursor()", "dia) idponto = get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset", "def get_ponto_hor(nome): c = env.db.cursor() r = c.select_onerow('pontos', ['id'], 'nome=%s', nome) if r:", "if r: c.close() return r[0] # not found. look for a similar name,", "hs, h \\ using horsets hs, horarios h \\ where hs.idlinha=%s and h.idset=hs.id',", "this really works c.execute('start transaction') try: c.execute('delete from hs, h \\ using horsets", "<reponame>ehabkost/busmap<filename>python/busmap/fetch.py<gh_stars>1-10 # -*- coding: utf-8 -* import horarios, linhas, env, dias def get_linha_hor(idhor,", "dia=d, apartir=apartir) idset = c.lastrowid for sp,h in horas: c.insert_one('horarios', idset=idset, hora=h, special=sp)", "look for id horario r = c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if r: c.close()", "insert a new record c.insert_one('linhas', idhor=idhor, nome=nome) id = c.lastrowid c.close() return id", "c.execute('start transaction') try: c.execute('delete from hs, h \\ using horsets hs, horarios h", "idset = c.lastrowid for sp,h in horas: c.insert_one('horarios', idset=idset, hora=h, special=sp) except: c.execute('rollback')", "id = r[0] # found. set idhor c.execute('update linhas set idhor=%s where id=%s',", "nome=%s', [nome]) if r: id = r[0] # found. set idhor c.execute('update linhas", "print 'Fetching %s:%s' % (cod, nome) fetch_horarios(cod, nome) if __name__ == '__main__': #fetch_horarios('022',", "[idhor, id]) c.close() return id # not found. insert a new record c.insert_one('linhas',", "horarios h \\ where hs.idlinha=%s and h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas", "look for a similar name, but with no idhor set r = c.select_onerow('linhas',", "r: id = r[0] # found. set idhor c.execute('update linhas set idhor=%s where", "cod,nome in horarios.lista_linhas(): print 'Fetching %s:%s' % (cod, nome) fetch_horarios(cod, nome) if __name__", "idhor=%s where id=%s', [idhor, id]) c.close() return id # not found. insert a", "is null and nome=%s', [nome]) if r: id = r[0] # found. set", "# look for id horario r = c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if r:", "nome=nome) id = c.lastrowid c.close() return id def fetch_horarios(idhor, nome): c = env.db.cursor()", "id def fetch_horarios(idhor, nome): c = env.db.cursor() idlinha = get_linha_hor(idhor, nome) #TODO: check", "id = c.lastrowid c.close() return id def fetch_horarios(idhor, nome): c = env.db.cursor() idlinha", "nome) #TODO: check if this really works c.execute('start transaction') try: c.execute('delete from hs,", "c.select_onerow('pontos', ['id'], 'nome=%s', nome) if r: c.close() return r[0] # not found c.insert_one('pontos',", "= env.db.cursor() # look for id horario r = c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor])", "idset=idset, hora=h, special=sp) except: c.execute('rollback') else: c.execute('commit') c.close() def fetch_hor_all(): for cod,nome in", "def fetch_horarios(idhor, nome): c = env.db.cursor() idlinha = get_linha_hor(idhor, nome) #TODO: check if", "horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto: %s, dias: %s' % (pto, dia)", "c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset = c.lastrowid for sp,h in horas: c.insert_one('horarios',", "nome) if r: c.close() return r[0] # not found c.insert_one('pontos', nome=nome) id =", "horarios, linhas, env, dias def get_linha_hor(idhor, nome): c = env.db.cursor() # look for", "r = c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if r: c.close() return r[0] # not", "try: c.execute('delete from hs, h \\ using horsets hs, horarios h \\ where", "= c.lastrowid c.close() return id def fetch_horarios(idhor, nome): c = env.db.cursor() idlinha =", "set r = c.select_onerow('linhas', ['id'], 'idhor is null and nome=%s', [nome]) if r:", "c.close() return id # not found. insert a new record c.insert_one('linhas', idhor=idhor, nome=nome)", "dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset = c.lastrowid for sp,h in horas:", "c.execute('delete from hs, h \\ using horsets hs, horarios h \\ where hs.idlinha=%s", "in horarios.lista_linhas(): print 'Fetching %s:%s' % (cod, nome) fetch_horarios(cod, nome) if __name__ ==", "c.insert_one('horarios', idset=idset, hora=h, special=sp) except: c.execute('rollback') else: c.execute('commit') c.close() def fetch_hor_all(): for cod,nome", "env.db.cursor() idlinha = get_linha_hor(idhor, nome) #TODO: check if this really works c.execute('start transaction')", "# not found c.insert_one('pontos', nome=nome) id = c.lastrowid c.close() return id def fetch_horarios(idhor,", "c = env.db.cursor() idlinha = get_linha_hor(idhor, nome) #TODO: check if this really works", "idhor=idhor, nome=nome) id = c.lastrowid c.close() return id def get_ponto_hor(nome): c = env.db.cursor()", "html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto: %s, dias: %s' %", "found. set idhor c.execute('update linhas set idhor=%s where id=%s', [idhor, id]) c.close() return", "found. insert a new record c.insert_one('linhas', idhor=idhor, nome=nome) id = c.lastrowid c.close() return", "nome): c = env.db.cursor() idlinha = get_linha_hor(idhor, nome) #TODO: check if this really", "using horsets hs, horarios h \\ where hs.idlinha=%s and h.idset=hs.id', [idlinha]) html =", "return id # not found. insert a new record c.insert_one('linhas', idhor=idhor, nome=nome) id", "no idhor set r = c.select_onerow('linhas', ['id'], 'idhor is null and nome=%s', [nome])", "= get_linha_hor(idhor, nome) #TODO: check if this really works c.execute('start transaction') try: c.execute('delete", "horario r = c.select_onerow('linhas', ['id'], 'idhor=%s', [idhor]) if r: c.close() return r[0] #", "idhor c.execute('update linhas set idhor=%s where id=%s', [idhor, id]) c.close() return id #", "from hs, h \\ using horsets hs, horarios h \\ where hs.idlinha=%s and", "['id'], 'idhor=%s', [idhor]) if r: c.close() return r[0] # not found. look for", "if this really works c.execute('start transaction') try: c.execute('delete from hs, h \\ using", "for a similar name, but with no idhor set r = c.select_onerow('linhas', ['id'],", "[idlinha]) html = horarios.get_horarios_html(idhor) for pto,dia,apartir,horas in horarios.parse_hor_html(html): print 'ponto: %s, dias: %s'", "'Fetching %s:%s' % (cod, nome) fetch_horarios(cod, nome) if __name__ == '__main__': #fetch_horarios('022', u'INTER", "hs, horarios h \\ where hs.idlinha=%s and h.idset=hs.id', [idlinha]) html = horarios.get_horarios_html(idhor) for", "dias: %s' % (pto, dia) idponto = get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha,", "id = c.lastrowid c.close() return id def get_ponto_hor(nome): c = env.db.cursor() r =", "d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset = c.lastrowid for sp,h", "r = c.select_onerow('linhas', ['id'], 'idhor is null and nome=%s', [nome]) if r: id", "fetch_horarios(idhor, nome): c = env.db.cursor() idlinha = get_linha_hor(idhor, nome) #TODO: check if this", "= c.lastrowid c.close() return id def get_ponto_hor(nome): c = env.db.cursor() r = c.select_onerow('pontos',", "with no idhor set r = c.select_onerow('linhas', ['id'], 'idhor is null and nome=%s',", "return r[0] # not found c.insert_one('pontos', nome=nome) id = c.lastrowid c.close() return id", "(pto, dia) idponto = get_ponto_hor(pto) d = dias.id_dias(dia) c.insert_one('horsets', idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir)", "r[0] # not found. look for a similar name, but with no idhor", "r[0] # found. set idhor c.execute('update linhas set idhor=%s where id=%s', [idhor, id])", "a new record c.insert_one('linhas', idhor=idhor, nome=nome) id = c.lastrowid c.close() return id def", "c = env.db.cursor() # look for id horario r = c.select_onerow('linhas', ['id'], 'idhor=%s',", "null and nome=%s', [nome]) if r: id = r[0] # found. set idhor", "# -*- coding: utf-8 -* import horarios, linhas, env, dias def get_linha_hor(idhor, nome):", "-*- coding: utf-8 -* import horarios, linhas, env, dias def get_linha_hor(idhor, nome): c", "idlinha=idlinha, idponto=idponto, dia=d, apartir=apartir) idset = c.lastrowid for sp,h in horas: c.insert_one('horarios', idset=idset," ]
[ "faceCascade = cv2.CascadeClassifier(cascPath) anterior = 0 try: from pylibfreenect2 import CudaPacketPipeline pipeline =", "default=80, help=\"Range to clip from nearest object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024,", "= CudaPacketPipeline() except: try: from pylibfreenect2 import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except: try:", "of 65535\") args = vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior =", "65535\") args = vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior = 0", "try: from pylibfreenect2 import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except: try: from pylibfreenect2 import", "listener = SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True) #", "nearest, nearest + args[\"depth_range\"]) face_depth -= nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth,", "np.average(nearest_buffer) # Apply clip from nearest on depth image face_depth = np.clip(face_depth, nearest,", "for (x,y,w,h) in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth = depth[y:y+h,", "import cv2 import numpy as np import sys from pylibfreenect2 import Freenect2, SyncMultiFrameListener", "type=int, default=32768, help=\"IR maximum value clip, out of a maximum value of 65535\")", "invalid depth value (0) to maximum value, to clean up blown-out patches at", "due to depth noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest = np.average(nearest_buffer)", "device connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color", "average of nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range to clip from nearest", "of nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range to clip from nearest object,", "args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames) key = cv2.waitKey(delay=1) if key ==", "args = vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior = 0 try:", "infinity depth[depth == 0] = np.amax(depth) # Apply clip on infrared image ir", "# Flip invalid depth value (0) to maximum value, to clean up blown-out", "SyncMultiFrameListener from pylibfreenect2 import FrameType, Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int,", "buffer for moving average of nearest value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN", "the average # Needed to combat flickering due to depth noise #nearest_buffer[:-1] =", "CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn = Freenect2() num_devices = fn.enumerateDevices() if num_devices ==", "10th lowest value nearest = np.partition(face_depth, 10, None)[9] # Determine nearest value by", "65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR maximum value clip, out of a maximum", "nearest #nearest = np.average(nearest_buffer) # Apply clip from nearest on depth image face_depth", "= argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number of samples for moving average of", "- args[\"ir_min\"]) / 256) ) #ir = np.uint8(frames[\"ir\"].asarray() / 256) faces = faceCascade.detectMultiScale(ir,", "except: try: from pylibfreenect2 import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except: from pylibfreenect2 import", "#nearest = np.average(nearest_buffer) # Apply clip from nearest on depth image face_depth =", "on depth image face_depth = np.clip(face_depth, nearest, nearest + args[\"depth_range\"]) face_depth -= nearest", "faces = faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h) in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]),", "value of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR maximum value clip, out of", "in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth = depth[y:y+h, x:x+w] #", "depth[y:y+h, x:x+w] # Clip noise around nearest value by taking 10th lowest value", "| FrameType.Ir | FrameType.Depth listener = SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) #", "listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True) # Initialize buffer for moving average", "print(\"No device connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline) types =", "argparse import cv2 import numpy as np import sys from pylibfreenect2 import Freenect2,", "lowest value nearest = np.partition(face_depth, 10, None)[9] # Determine nearest value by updating", "updating buffer and taking the average # Needed to combat flickering due to", "Determine nearest value by updating buffer and taking the average # Needed to", "np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN # Iterate acquiring frames while True: frames = listener.waitForNewFrame()", "Needed to combat flickering due to depth noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] =", "of nearest value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN # Iterate acquiring frames", "\"--ir-min\", type=int, default=1024, help=\"IR minimum value clip, out of a maximum value of", "pylibfreenect2 import Freenect2, SyncMultiFrameListener from pylibfreenect2 import FrameType, Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)", "for moving average of nearest value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN #", "nearest + args[\"depth_range\"]) face_depth -= nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800,", "args[\"depth_range\"]) face_depth -= nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames)", "maximum value, to clean up blown-out patches at infinity depth[depth == 0] =", "nearest = np.partition(face_depth, 10, None)[9] # Determine nearest value by updating buffer and", "depth noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest = np.average(nearest_buffer) # Apply", "streams device.startStreams(rgb=True,depth=True) # Initialize buffer for moving average of nearest value nearest_buffer =", "nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range to clip from nearest object, in", "#nearest_buffer[-1] = nearest #nearest = np.average(nearest_buffer) # Apply clip from nearest on depth", "device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True) # Initialize buffer for moving average of", "cv2 import numpy as np import sys from pylibfreenect2 import Freenect2, SyncMultiFrameListener from", "by updating buffer and taking the average # Needed to combat flickering due", "import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except: try: from pylibfreenect2 import OpenCLPacketPipeline pipeline =", "CudaPacketPipeline() except: try: from pylibfreenect2 import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except: try: from", "5) for (x,y,w,h) in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth =", "OpenGLPacketPipeline() except: try: from pylibfreenect2 import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except: from pylibfreenect2", "((args[\"ir_max\"] - args[\"ir_min\"]) / 256) ) #ir = np.uint8(frames[\"ir\"].asarray() / 256) faces =", "pipeline:\", type(pipeline).__name__) fn = Freenect2() num_devices = fn.enumerateDevices() if num_devices == 0: print(\"No", "depth image face_depth = np.clip(face_depth, nearest, nearest + args[\"depth_range\"]) face_depth -= nearest face_depth", "0] = np.amax(depth) # Apply clip on infrared image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(),", "(800, 800))) face_depth = depth[y:y+h, x:x+w] # Clip noise around nearest value by", "num_devices = fn.enumerateDevices() if num_devices == 0: print(\"No device connected!\") sys.exit(1) serial =", "= np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN # Iterate acquiring frames while True: frames =", ") #ir = np.uint8(frames[\"ir\"].asarray() / 256) faces = faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h)", "to combat flickering due to depth noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] = nearest", "(np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] - 1) / ((args[\"ir_max\"] - args[\"ir_min\"]) / 256)", "faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h) in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800)))", "nearest object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR minimum value clip, out", "try: from pylibfreenect2 import CudaPacketPipeline pipeline = CudaPacketPipeline() except: try: from pylibfreenect2 import", "args[\"ir_min\"]) / 256) ) #ir = np.uint8(frames[\"ir\"].asarray() / 256) faces = faceCascade.detectMultiScale(ir, 1.3,", "up blown-out patches at infinity depth[depth == 0] = np.amax(depth) # Apply clip", "(0) to maximum value, to clean up blown-out patches at infinity depth[depth ==", "= vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior = 0 try: from", "value clip, out of a maximum value of 65535\") args = vars(ap.parse_args()) cascPath", "types = FrameType.Color | FrameType.Ir | FrameType.Depth listener = SyncMultiFrameListener(types) # Register listeners", "ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] - 1) / ((args[\"ir_max\"] -", "clean up blown-out patches at infinity depth[depth == 0] = np.amax(depth) # Apply", "-= nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames) key =", "from pylibfreenect2 import CudaPacketPipeline pipeline = CudaPacketPipeline() except: try: from pylibfreenect2 import OpenGLPacketPipeline", "anterior = 0 try: from pylibfreenect2 import CudaPacketPipeline pipeline = CudaPacketPipeline() except: try:", "<reponame>ndoo/libfreenect2-facial-recognition<filename>facenet.py<gh_stars>0 import argparse import cv2 import numpy as np import sys from pylibfreenect2", "value (0) to maximum value, to clean up blown-out patches at infinity depth[depth", "= listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() # Flip invalid depth value", "cv2.CascadeClassifier(cascPath) anterior = 0 try: from pylibfreenect2 import CudaPacketPipeline pipeline = CudaPacketPipeline() except:", "(x,y,w,h) in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth = depth[y:y+h, x:x+w]", "face_depth = depth[y:y+h, x:x+w] # Clip noise around nearest value by taking 10th", "except: try: from pylibfreenect2 import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except: try: from pylibfreenect2", "import Freenect2, SyncMultiFrameListener from pylibfreenect2 import FrameType, Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\",", "image face_depth = np.clip(face_depth, nearest, nearest + args[\"depth_range\"]) face_depth -= nearest face_depth /=", "ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range to clip from nearest object, in millimeters\") ap.add_argument(\"-m\",", "= np.partition(face_depth, 10, None)[9] # Determine nearest value by updating buffer and taking", "value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN # Iterate acquiring frames while True:", "taking the average # Needed to combat flickering due to depth noise #nearest_buffer[:-1]", "+ args[\"depth_range\"]) face_depth -= nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800)))", "combat flickering due to depth noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest", "FrameType.Depth listener = SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True)", "blown-out patches at infinity depth[depth == 0] = np.amax(depth) # Apply clip on", "listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() # Flip invalid depth value (0)", "type=int, default=1024, help=\"IR minimum value clip, out of a maximum value of 65535\")", "connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color |", "cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth = depth[y:y+h, x:x+w] # Clip noise", "\"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior = 0 try: from pylibfreenect2 import CudaPacketPipeline pipeline", "Apply clip from nearest on depth image face_depth = np.clip(face_depth, nearest, nearest +", "# Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True) # Initialize buffer for", "type=int, default=80, help=\"Range to clip from nearest object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int,", "face_depth -= nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames) key", "(800, 800))) listener.release(frames) key = cv2.waitKey(delay=1) if key == ord('q'): break device.stop() device.close()", "1.3, 5) for (x,y,w,h) in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth", "0: print(\"No device connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline) types", "num_devices == 0: print(\"No device connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0) device = fn.openDevice(serial,", "on infrared image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] - 1)", "args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] - 1) / ((args[\"ir_max\"] - args[\"ir_min\"]) / 256) )", "fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color | FrameType.Ir | FrameType.Depth listener = SyncMultiFrameListener(types) #", "type=int, default=20, help=\"Number of samples for moving average of nearest point\") ap.add_argument(\"-r\", \"--depth-range\",", "10, None)[9] # Determine nearest value by updating buffer and taking the average", "device = fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color | FrameType.Ir | FrameType.Depth listener =", "of a maximum value of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR maximum value", "OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except: try: from pylibfreenect2 import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline()", "nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames) key = cv2.waitKey(delay=1)", "and taking the average # Needed to combat flickering due to depth noise", "clip on infrared image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] -", "print(\"Packet pipeline:\", type(pipeline).__name__) fn = Freenect2() num_devices = fn.enumerateDevices() if num_devices == 0:", "depth[depth == 0] = np.amax(depth) # Apply clip on infrared image ir =", "nearest_buffer[:] = np.NaN # Iterate acquiring frames while True: frames = listener.waitForNewFrame() depth", "= FrameType.Color | FrameType.Ir | FrameType.Depth listener = SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener)", "fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color | FrameType.Ir | FrameType.Depth listener", "nearest value by taking 10th lowest value nearest = np.partition(face_depth, 10, None)[9] #", "value clip, out of a maximum value of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768,", "fn = Freenect2() num_devices = fn.enumerateDevices() if num_devices == 0: print(\"No device connected!\")", "vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior = 0 try: from pylibfreenect2", "\"--ir-max\", type=int, default=32768, help=\"IR maximum value clip, out of a maximum value of", "args[\"ir_min\"] - 1) / ((args[\"ir_max\"] - args[\"ir_min\"]) / 256) ) #ir = np.uint8(frames[\"ir\"].asarray()", "at infinity depth[depth == 0] = np.amax(depth) # Apply clip on infrared image", "# Iterate acquiring frames while True: frames = listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color", "flickering due to depth noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest =", "CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn = Freenect2() num_devices = fn.enumerateDevices()", "from pylibfreenect2 import Freenect2, SyncMultiFrameListener from pylibfreenect2 import FrameType, Registration, Frame ap =", "around nearest value by taking 10th lowest value nearest = np.partition(face_depth, 10, None)[9]", "out of a maximum value of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR maximum", "= Freenect2() num_devices = fn.enumerateDevices() if num_devices == 0: print(\"No device connected!\") sys.exit(1)", "import sys from pylibfreenect2 import Freenect2, SyncMultiFrameListener from pylibfreenect2 import FrameType, Registration, Frame", "cv2.resize(face_depth, (800, 800))) listener.release(frames) key = cv2.waitKey(delay=1) if key == ord('q'): break device.stop()", "Initialize buffer for moving average of nearest value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] =", "frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() # Flip invalid depth value (0) to maximum value,", "color = frames[\"color\"].asarray() # Flip invalid depth value (0) to maximum value, to", "clip, out of a maximum value of 65535\") args = vars(ap.parse_args()) cascPath =", "pylibfreenect2 import CudaPacketPipeline pipeline = CudaPacketPipeline() except: try: from pylibfreenect2 import OpenGLPacketPipeline pipeline", "noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest = np.average(nearest_buffer) # Apply clip", "FrameType.Color | FrameType.Ir | FrameType.Depth listener = SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener)", "in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR minimum value clip, out of a", "Apply clip on infrared image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"]", "average of nearest value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN # Iterate acquiring", "= frames[\"color\"].asarray() # Flip invalid depth value (0) to maximum value, to clean", "argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number of samples for moving average of nearest", "1) / ((args[\"ir_max\"] - args[\"ir_min\"]) / 256) ) #ir = np.uint8(frames[\"ir\"].asarray() / 256)", "default=20, help=\"Number of samples for moving average of nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int,", "== 0: print(\"No device connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline)", "nearest value by updating buffer and taking the average # Needed to combat", "SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True) # Initialize buffer", "np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] - 1) / ((args[\"ir_max\"] - args[\"ir_min\"]) /", "nearest value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN # Iterate acquiring frames while", "# Initialize buffer for moving average of nearest value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:]", "Iterate acquiring frames while True: frames = listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color =", "= fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color | FrameType.Ir | FrameType.Depth", "args[\"ir_max\"]) - args[\"ir_min\"] - 1) / ((args[\"ir_max\"] - args[\"ir_min\"]) / 256) ) #ir", "= depth[y:y+h, x:x+w] # Clip noise around nearest value by taking 10th lowest", "faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth = depth[y:y+h, x:x+w] # Clip", "device.startStreams(rgb=True,depth=True) # Initialize buffer for moving average of nearest value nearest_buffer = np.empty(args[\"depth_smooth\"])", "= faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h) in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800,", "= np.average(nearest_buffer) # Apply clip from nearest on depth image face_depth = np.clip(face_depth,", "# Apply clip on infrared image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) -", "while True: frames = listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() # Flip", "pylibfreenect2 import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except: try: from pylibfreenect2 import OpenCLPacketPipeline pipeline", "infrared image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] - 1) /", "# Determine nearest value by updating buffer and taking the average # Needed", "to clip from nearest object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR minimum", "value, to clean up blown-out patches at infinity depth[depth == 0] = np.amax(depth)", "a maximum value of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR maximum value clip,", "pipeline = CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn = Freenect2() num_devices = fn.enumerateDevices() if", "value by updating buffer and taking the average # Needed to combat flickering", "of samples for moving average of nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range", "by taking 10th lowest value nearest = np.partition(face_depth, 10, None)[9] # Determine nearest", "ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR minimum value clip, out of a maximum value", "# Clip noise around nearest value by taking 10th lowest value nearest =", "- 1) / ((args[\"ir_max\"] - args[\"ir_min\"]) / 256) ) #ir = np.uint8(frames[\"ir\"].asarray() /", "256) ) #ir = np.uint8(frames[\"ir\"].asarray() / 256) faces = faceCascade.detectMultiScale(ir, 1.3, 5) for", "np.amax(depth) # Apply clip on infrared image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"])", "clip from nearest on depth image face_depth = np.clip(face_depth, nearest, nearest + args[\"depth_range\"])", "/= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames) key = cv2.waitKey(delay=1) if key", "IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth = depth[y:y+h, x:x+w] # Clip noise around", "millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR minimum value clip, out of a maximum", "x:x+w] # Clip noise around nearest value by taking 10th lowest value nearest", "device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True) # Initialize buffer for moving average of nearest", "patches at infinity depth[depth == 0] = np.amax(depth) # Apply clip on infrared", "= np.amax(depth) # Apply clip on infrared image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"],", "- args[\"ir_min\"] - 1) / ((args[\"ir_max\"] - args[\"ir_min\"]) / 256) ) #ir =", "maximum value clip, out of a maximum value of 65535\") args = vars(ap.parse_args())", "#nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest = np.average(nearest_buffer) # Apply clip from", "Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True) # Initialize buffer for moving", "cascPath = \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior = 0 try: from pylibfreenect2 import", "nearest on depth image face_depth = np.clip(face_depth, nearest, nearest + args[\"depth_range\"]) face_depth -=", "OpenCLPacketPipeline() except: from pylibfreenect2 import CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn", "= np.NaN # Iterate acquiring frames while True: frames = listener.waitForNewFrame() depth =", "ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number of samples for moving average of nearest point\")", "# Start streams device.startStreams(rgb=True,depth=True) # Initialize buffer for moving average of nearest value", "value by taking 10th lowest value nearest = np.partition(face_depth, 10, None)[9] # Determine", "value of 65535\") args = vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior", "Flip invalid depth value (0) to maximum value, to clean up blown-out patches", "| FrameType.Depth listener = SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams", "except: from pylibfreenect2 import CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn =", "pipeline=pipeline) types = FrameType.Color | FrameType.Ir | FrameType.Depth listener = SyncMultiFrameListener(types) # Register", "/ 256) ) #ir = np.uint8(frames[\"ir\"].asarray() / 256) faces = faceCascade.detectMultiScale(ir, 1.3, 5)", "point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range to clip from nearest object, in millimeters\")", "type(pipeline).__name__) fn = Freenect2() num_devices = fn.enumerateDevices() if num_devices == 0: print(\"No device", "object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR minimum value clip, out of", "maximum value of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR maximum value clip, out", "import CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn = Freenect2() num_devices =", "= np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] - 1) / ((args[\"ir_max\"] - args[\"ir_min\"])", "sys.exit(1) serial = fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color | FrameType.Ir", "help=\"Number of samples for moving average of nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80,", "frames while True: frames = listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() #", "from pylibfreenect2 import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except: from pylibfreenect2 import CpuPacketPipeline pipeline", "help=\"Range to clip from nearest object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR", "import FrameType, Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number of", "to clean up blown-out patches at infinity depth[depth == 0] = np.amax(depth) #", "sys from pylibfreenect2 import Freenect2, SyncMultiFrameListener from pylibfreenect2 import FrameType, Registration, Frame ap", "= CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn = Freenect2() num_devices = fn.enumerateDevices() if num_devices", "800))) face_depth = depth[y:y+h, x:x+w] # Clip noise around nearest value by taking", "of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR maximum value clip, out of a", "for moving average of nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range to clip", "as np import sys from pylibfreenect2 import Freenect2, SyncMultiFrameListener from pylibfreenect2 import FrameType,", "face_depth = np.clip(face_depth, nearest, nearest + args[\"depth_range\"]) face_depth -= nearest face_depth /= args[\"depth_range\"]", "pylibfreenect2 import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except: from pylibfreenect2 import CpuPacketPipeline pipeline =", "frames[\"color\"].asarray() # Flip invalid depth value (0) to maximum value, to clean up", "= np.clip(face_depth, nearest, nearest + args[\"depth_range\"]) face_depth -= nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face", "FrameType.Ir | FrameType.Depth listener = SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start", "numpy as np import sys from pylibfreenect2 import Freenect2, SyncMultiFrameListener from pylibfreenect2 import", "acquiring frames while True: frames = listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray()", "= \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath) anterior = 0 try: from pylibfreenect2 import CudaPacketPipeline", "np import sys from pylibfreenect2 import Freenect2, SyncMultiFrameListener from pylibfreenect2 import FrameType, Registration,", "of a maximum value of 65535\") args = vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade", "from pylibfreenect2 import FrameType, Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20,", "moving average of nearest value nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN # Iterate", "== 0] = np.amax(depth) # Apply clip on infrared image ir = np.uint8(", "np.NaN # Iterate acquiring frames while True: frames = listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32)", "CudaPacketPipeline pipeline = CudaPacketPipeline() except: try: from pylibfreenect2 import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline()", "= frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() # Flip invalid depth value (0) to maximum", "taking 10th lowest value nearest = np.partition(face_depth, 10, None)[9] # Determine nearest value", "Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number of samples for moving", "Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number of samples for", "= np.uint8(frames[\"ir\"].asarray() / 256) faces = faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h) in faces:", "depth = frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() # Flip invalid depth value (0) to", "clip from nearest object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR minimum value", "= OpenCLPacketPipeline() except: from pylibfreenect2 import CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__)", "try: from pylibfreenect2 import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except: from pylibfreenect2 import CpuPacketPipeline", "average # Needed to combat flickering due to depth noise #nearest_buffer[:-1] = nearest_buffer[1:]", "OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except: from pylibfreenect2 import CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet", "ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR maximum value clip, out of a maximum value", "= fn.enumerateDevices() if num_devices == 0: print(\"No device connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0)", "buffer and taking the average # Needed to combat flickering due to depth", "Start streams device.startStreams(rgb=True,depth=True) # Initialize buffer for moving average of nearest value nearest_buffer", "Freenect2, SyncMultiFrameListener from pylibfreenect2 import FrameType, Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\",", "out of a maximum value of 65535\") args = vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\"", "image ir = np.uint8( (np.clip(frames[\"ir\"].asarray(), args[\"ir_min\"], args[\"ir_max\"]) - args[\"ir_min\"] - 1) / ((args[\"ir_max\"]", "ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number of samples for moving average", "0 try: from pylibfreenect2 import CudaPacketPipeline pipeline = CudaPacketPipeline() except: try: from pylibfreenect2", "if num_devices == 0: print(\"No device connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0) device =", "pipeline = OpenCLPacketPipeline() except: from pylibfreenect2 import CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet pipeline:\",", "np.uint8(frames[\"ir\"].asarray() / 256) faces = faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h) in faces: cv2.imshow(\"Face", "Freenect2() num_devices = fn.enumerateDevices() if num_devices == 0: print(\"No device connected!\") sys.exit(1) serial", "\"--depth-smooth\", type=int, default=20, help=\"Number of samples for moving average of nearest point\") ap.add_argument(\"-r\",", "from nearest on depth image face_depth = np.clip(face_depth, nearest, nearest + args[\"depth_range\"]) face_depth", "np.clip(face_depth, nearest, nearest + args[\"depth_range\"]) face_depth -= nearest face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\",", "nearest_buffer = np.empty(args[\"depth_smooth\"]) nearest_buffer[:] = np.NaN # Iterate acquiring frames while True: frames", "\"--depth-range\", type=int, default=80, help=\"Range to clip from nearest object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\",", "True: frames = listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() # Flip invalid", "x:x+w]), (800, 800))) face_depth = depth[y:y+h, x:x+w] # Clip noise around nearest value", "pipeline = CudaPacketPipeline() except: try: from pylibfreenect2 import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except:", "FrameType, Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number of samples", "= fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color | FrameType.Ir | FrameType.Depth listener = SyncMultiFrameListener(types)", "= cv2.CascadeClassifier(cascPath) anterior = 0 try: from pylibfreenect2 import CudaPacketPipeline pipeline = CudaPacketPipeline()", "nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest = np.average(nearest_buffer) # Apply clip from nearest on", "value nearest = np.partition(face_depth, 10, None)[9] # Determine nearest value by updating buffer", "800))) listener.release(frames) key = cv2.waitKey(delay=1) if key == ord('q'): break device.stop() device.close() sys.exit(0)", "clip, out of a maximum value of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int, default=32768, help=\"IR", "= SyncMultiFrameListener(types) # Register listeners device.setColorFrameListener(listener) device.setIrAndDepthFrameListener(listener) # Start streams device.startStreams(rgb=True,depth=True) # Initialize", "/ 256) faces = faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h) in faces: cv2.imshow(\"Face IR\",", "a maximum value of 65535\") args = vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade =", "from pylibfreenect2 import CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn = Freenect2()", "from pylibfreenect2 import OpenGLPacketPipeline pipeline = OpenGLPacketPipeline() except: try: from pylibfreenect2 import OpenCLPacketPipeline", "pipeline = OpenGLPacketPipeline() except: try: from pylibfreenect2 import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except:", "cv2.resize(cv2.equalizeHist(ir[y:y+h, x:x+w]), (800, 800))) face_depth = depth[y:y+h, x:x+w] # Clip noise around nearest", "/ ((args[\"ir_max\"] - args[\"ir_min\"]) / 256) ) #ir = np.uint8(frames[\"ir\"].asarray() / 256) faces", "default=32768, help=\"IR maximum value clip, out of a maximum value of 65535\") args", "Clip noise around nearest value by taking 10th lowest value nearest = np.partition(face_depth,", "to depth noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest = np.average(nearest_buffer) #", "default=1024, help=\"IR minimum value clip, out of a maximum value of 65535\") ap.add_argument(\"-M\",", "None)[9] # Determine nearest value by updating buffer and taking the average #", "256) faces = faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h) in faces: cv2.imshow(\"Face IR\", cv2.resize(cv2.equalizeHist(ir[y:y+h,", "# Needed to combat flickering due to depth noise #nearest_buffer[:-1] = nearest_buffer[1:] #nearest_buffer[-1]", "serial = fn.getDeviceSerialNumber(0) device = fn.openDevice(serial, pipeline=pipeline) types = FrameType.Color | FrameType.Ir |", "Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames) key = cv2.waitKey(delay=1) if key == ord('q'): break", "np.partition(face_depth, 10, None)[9] # Determine nearest value by updating buffer and taking the", "= nearest_buffer[1:] #nearest_buffer[-1] = nearest #nearest = np.average(nearest_buffer) # Apply clip from nearest", "help=\"IR maximum value clip, out of a maximum value of 65535\") args =", "# Apply clip from nearest on depth image face_depth = np.clip(face_depth, nearest, nearest", "from nearest object, in millimeters\") ap.add_argument(\"-m\", \"--ir-min\", type=int, default=1024, help=\"IR minimum value clip,", "fn.enumerateDevices() if num_devices == 0: print(\"No device connected!\") sys.exit(1) serial = fn.getDeviceSerialNumber(0) device", "maximum value of 65535\") args = vars(ap.parse_args()) cascPath = \"haarcascade_frontalface_default.xml\" faceCascade = cv2.CascadeClassifier(cascPath)", "import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except: from pylibfreenect2 import CpuPacketPipeline pipeline = CpuPacketPipeline()", "noise around nearest value by taking 10th lowest value nearest = np.partition(face_depth, 10,", "#ir = np.uint8(frames[\"ir\"].asarray() / 256) faces = faceCascade.detectMultiScale(ir, 1.3, 5) for (x,y,w,h) in", "cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames) key = cv2.waitKey(delay=1) if key == ord('q'):", "depth value (0) to maximum value, to clean up blown-out patches at infinity", "import argparse import cv2 import numpy as np import sys from pylibfreenect2 import", "pylibfreenect2 import FrameType, Registration, Frame ap = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) ap.add_argument(\"-s\", \"--depth-smooth\", type=int, default=20, help=\"Number", "frames = listener.waitForNewFrame() depth = frames[\"depth\"].asarray(np.float32) color = frames[\"color\"].asarray() # Flip invalid depth", "import numpy as np import sys from pylibfreenect2 import Freenect2, SyncMultiFrameListener from pylibfreenect2", "minimum value clip, out of a maximum value of 65535\") ap.add_argument(\"-M\", \"--ir-max\", type=int,", "help=\"IR minimum value clip, out of a maximum value of 65535\") ap.add_argument(\"-M\", \"--ir-max\",", "pylibfreenect2 import CpuPacketPipeline pipeline = CpuPacketPipeline() print(\"Packet pipeline:\", type(pipeline).__name__) fn = Freenect2() num_devices", "to maximum value, to clean up blown-out patches at infinity depth[depth == 0]", "samples for moving average of nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range to", "= OpenGLPacketPipeline() except: try: from pylibfreenect2 import OpenCLPacketPipeline pipeline = OpenCLPacketPipeline() except: from", "face_depth /= args[\"depth_range\"] cv2.imshow(\"Face Depth\", cv2.resize(face_depth, (800, 800))) listener.release(frames) key = cv2.waitKey(delay=1) if", "= nearest #nearest = np.average(nearest_buffer) # Apply clip from nearest on depth image", "import CudaPacketPipeline pipeline = CudaPacketPipeline() except: try: from pylibfreenect2 import OpenGLPacketPipeline pipeline =", "moving average of nearest point\") ap.add_argument(\"-r\", \"--depth-range\", type=int, default=80, help=\"Range to clip from", "= 0 try: from pylibfreenect2 import CudaPacketPipeline pipeline = CudaPacketPipeline() except: try: from" ]
[ "import NxosMdsPatterns from unicon.statemachine import State, Path patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def", "<gh_stars>10-100 __author__ = \"<NAME> <<EMAIL>>\" from unicon.plugins.nxos.statemachine import NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns", "Path(tie, enable, 'end', None) # Add State and Path to State Machine self.add_path(enable_to_shell)", "unicon.statemachine import State, Path patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable',", "and Path to State Machine self.add_path(enable_to_shell) self.add_path(shell_to_enable) self.add_path(enable_to_tie) self.add_path(tie_to_enable) class NxosMdsDualRpStateMachine(NxosMdsSingleRpStateMachine): def create(self):", "# Add State and Path to State Machine self.add_path(enable_to_shell) self.add_path(shell_to_enable) self.add_path(enable_to_tie) self.add_path(tie_to_enable) class", "__author__ = \"<NAME> <<EMAIL>>\" from unicon.plugins.nxos.statemachine import NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from", "Path to State Machine self.add_path(enable_to_shell) self.add_path(shell_to_enable) self.add_path(enable_to_tie) self.add_path(tie_to_enable) class NxosMdsDualRpStateMachine(NxosMdsSingleRpStateMachine): def create(self): super().create()", "NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell = State('shell', patterns.shell_prompt)", "State('shell', patterns.shell_prompt) tie = State('tie', patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell =", "None) enable_to_tie = Path(enable, tie, 'san-ext-tuner', None) tie_to_enable = Path(tie, enable, 'end', None)", "self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable, shell, 'bash', None) shell_to_enable = Path(shell, enable, 'exit',", "'enable') self.remove_state('shell') shell = State('shell', patterns.shell_prompt) tie = State('tie', patterns.tie_prompt) enable = self.get_state('enable')", "'end', None) # Add State and Path to State Machine self.add_path(enable_to_shell) self.add_path(shell_to_enable) self.add_path(enable_to_tie)", "self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell = State('shell', patterns.shell_prompt) tie = State('tie', patterns.tie_prompt)", "<<EMAIL>>\" from unicon.plugins.nxos.statemachine import NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine import State,", "Path patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable')", "= self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable, shell, 'bash', None) shell_to_enable = Path(shell,", "tie_to_enable = Path(tie, enable, 'end', None) # Add State and Path to State", "None) # Add State and Path to State Machine self.add_path(enable_to_shell) self.add_path(shell_to_enable) self.add_path(enable_to_tie) self.add_path(tie_to_enable)", "State('tie', patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable, shell, 'bash', None)", "shell_to_enable = Path(shell, enable, 'exit', None) enable_to_tie = Path(enable, tie, 'san-ext-tuner', None) tie_to_enable", "from unicon.statemachine import State, Path patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create()", "Path(enable, shell, 'bash', None) shell_to_enable = Path(shell, enable, 'exit', None) enable_to_tie = Path(enable,", "= Path(enable, tie, 'san-ext-tuner', None) tie_to_enable = Path(tie, enable, 'end', None) # Add", "import NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine import State, Path patterns =", "= NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell", "'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell = State('shell', patterns.shell_prompt) tie = State('tie', patterns.tie_prompt) enable", "def create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell = State('shell', patterns.shell_prompt) tie", "State, Path patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell',", "super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell = State('shell', patterns.shell_prompt) tie = State('tie',", "= State('tie', patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable, shell, 'bash',", "patterns.shell_prompt) tie = State('tie', patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable,", "Path(shell, enable, 'exit', None) enable_to_tie = Path(enable, tie, 'san-ext-tuner', None) tie_to_enable = Path(tie,", "patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell')", "= Path(tie, enable, 'end', None) # Add State and Path to State Machine", "enable = self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable, shell, 'bash', None) shell_to_enable =", "None) tie_to_enable = Path(tie, enable, 'end', None) # Add State and Path to", "import State, Path patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable', 'shell')", "self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable, shell, 'bash', None) shell_to_enable = Path(shell, enable,", "None) shell_to_enable = Path(shell, enable, 'exit', None) enable_to_tie = Path(enable, tie, 'san-ext-tuner', None)", "tie = State('tie', patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable, shell,", "from unicon.plugins.nxos.statemachine import NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine import State, Path", "\"<NAME> <<EMAIL>>\" from unicon.plugins.nxos.statemachine import NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine import", "= Path(shell, enable, 'exit', None) enable_to_tie = Path(enable, tie, 'san-ext-tuner', None) tie_to_enable =", "enable_to_tie = Path(enable, tie, 'san-ext-tuner', None) tie_to_enable = Path(tie, enable, 'end', None) #", "enable, 'end', None) # Add State and Path to State Machine self.add_path(enable_to_shell) self.add_path(shell_to_enable)", "= State('shell', patterns.shell_prompt) tie = State('tie', patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell", "'exit', None) enable_to_tie = Path(enable, tie, 'san-ext-tuner', None) tie_to_enable = Path(tie, enable, 'end',", "Add State and Path to State Machine self.add_path(enable_to_shell) self.add_path(shell_to_enable) self.add_path(enable_to_tie) self.add_path(tie_to_enable) class NxosMdsDualRpStateMachine(NxosMdsSingleRpStateMachine):", "patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell) self.add_state(tie) enable_to_shell = Path(enable, shell, 'bash', None) shell_to_enable", "shell, 'bash', None) shell_to_enable = Path(shell, enable, 'exit', None) enable_to_tie = Path(enable, tie,", "Path(enable, tie, 'san-ext-tuner', None) tie_to_enable = Path(tie, enable, 'end', None) # Add State", "self.remove_path('shell', 'enable') self.remove_state('shell') shell = State('shell', patterns.shell_prompt) tie = State('tie', patterns.tie_prompt) enable =", "shell = State('shell', patterns.shell_prompt) tie = State('tie', patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell) self.add_state(tie)", "= Path(enable, shell, 'bash', None) shell_to_enable = Path(shell, enable, 'exit', None) enable_to_tie =", "unicon.plugins.nxos.statemachine import NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine import State, Path patterns", "unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine import State, Path patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine):", "enable_to_shell = Path(enable, shell, 'bash', None) shell_to_enable = Path(shell, enable, 'exit', None) enable_to_tie", "State and Path to State Machine self.add_path(enable_to_shell) self.add_path(shell_to_enable) self.add_path(enable_to_tie) self.add_path(tie_to_enable) class NxosMdsDualRpStateMachine(NxosMdsSingleRpStateMachine): def", "'san-ext-tuner', None) tie_to_enable = Path(tie, enable, 'end', None) # Add State and Path", "self.remove_state('shell') shell = State('shell', patterns.shell_prompt) tie = State('tie', patterns.tie_prompt) enable = self.get_state('enable') self.add_state(shell)", "= \"<NAME> <<EMAIL>>\" from unicon.plugins.nxos.statemachine import NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine", "'bash', None) shell_to_enable = Path(shell, enable, 'exit', None) enable_to_tie = Path(enable, tie, 'san-ext-tuner',", "create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell = State('shell', patterns.shell_prompt) tie =", "class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell = State('shell',", "enable, 'exit', None) enable_to_tie = Path(enable, tie, 'san-ext-tuner', None) tie_to_enable = Path(tie, enable,", "NxosMdsPatterns from unicon.statemachine import State, Path patterns = NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self):", "NxosMdsPatterns() class NxosMdsSingleRpStateMachine(NxosSingleRpStateMachine): def create(self): super().create() self.remove_path('enable', 'shell') self.remove_path('shell', 'enable') self.remove_state('shell') shell =", "from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine import State, Path patterns = NxosMdsPatterns() class", "tie, 'san-ext-tuner', None) tie_to_enable = Path(tie, enable, 'end', None) # Add State and", "self.add_state(tie) enable_to_shell = Path(enable, shell, 'bash', None) shell_to_enable = Path(shell, enable, 'exit', None)", "NxosSingleRpStateMachine from unicon.plugins.nxos.mds.patterns import NxosMdsPatterns from unicon.statemachine import State, Path patterns = NxosMdsPatterns()" ]
[ "setup with SaltStack and Apache Libcloud\"\"\" __version__ = '0.1.0-git' if __name__ == '__main__':", "with SaltStack and Apache Libcloud\"\"\" __version__ = '0.1.0-git' if __name__ == '__main__': from", "SaltStack and Apache Libcloud\"\"\" __version__ = '0.1.0-git' if __name__ == '__main__': from cardice.commandline", "and Apache Libcloud\"\"\" __version__ = '0.1.0-git' if __name__ == '__main__': from cardice.commandline import", "Apache Libcloud\"\"\" __version__ = '0.1.0-git' if __name__ == '__main__': from cardice.commandline import main", "Libcloud\"\"\" __version__ = '0.1.0-git' if __name__ == '__main__': from cardice.commandline import main main()", "Cloud setup with SaltStack and Apache Libcloud\"\"\" __version__ = '0.1.0-git' if __name__ ==", "\"\"\"Compute Cloud setup with SaltStack and Apache Libcloud\"\"\" __version__ = '0.1.0-git' if __name__" ]
[]
[ "def __init__(self, message, path, post_data, debug=False, stack_trace=None): \"\"\" :param message: exception message :type", ":param path: path after server URL of connection. :type path: str :param post_data:", "errors. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, reason): self.args = reason,", ":param required_version: minimum required version :type required_version: distutils.version.StrictVersion \"\"\" if required_version: package =", "= post_data def __str__(self): if isinstance(self.post_data, dict): message = 'Got error \"%s\" at", "traceback' return message class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for HTTP response errors. Extends", "Base class for Genestack exceptions. Use it to catch all exceptions raised explicitly", "+= '\\nStacktrace from server is:\\n%s' % self.stack_trace else: message += '\\nEnable debug option", "server. \"\"\" pass class GenestackVersionException(GenestackException): \"\"\" Exception thrown if server requires a newer", "Exception thrown if server requires a newer version on Python Client. \"\"\" def", "import * from urllib.error import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class", "= reason, self.reason = reason def __str__(self): return '<urlopen error %s>' % self.reason", "Genestack Java code, not an HTTP error). \"\"\" def __init__(self, message, path, post_data,", "post_data: POST data (file or dict) :type debug: bool :param debug: flag if", "self.args = reason, self.reason = reason def __str__(self): return '<urlopen error %s>' %", "current_version, required_version=None): \"\"\" :param current_version: current version :type current_version: distutils.version.StrictVersion :param required_version: minimum", "of \"%s\"' % ( self.message, self.post_data.get('method', '<unknown>'), self.path ) else: # upload file", "if isinstance(message, bytes) else message) GenestackException.__init__(self, message, path, post_data, debug, stack_trace) self.message =", "else PYPI_PACKAGE message = ( 'Your Genestack Client version \"{current_version}\" is too old,", "Client-side exception class. Raise its instances (instead of :py:class:`~exceptions.Exception`) if anything is wrong", "\"%s\" of \"%s\"' % ( self.message, self.post_data.get('method', '<unknown>'), self.path ) else: # upload", "\"\"\" message = (message.decode('utf-8', 'ignore') if isinstance(message, bytes) else message) GenestackException.__init__(self, message, path,", "post_data, debug, stack_trace) self.message = message self.debug = debug self.stack_trace = stack_trace self.path", "\"\"\" :param current_version: current version :type current_version: distutils.version.StrictVersion :param required_version: minimum required version", ":type path: str :param post_data: POST data (file or dict) :type debug: bool", "else: package = PYPI_PACKAGE message = 'Cannot get required version from server.\\n' message", "message): self.message = \"<connection failed %s>\" % message def __str__(self): return self.message class", "(error message generated by Genestack Java code, not an HTTP error). \"\"\" def", "__future__ import division from __future__ import print_function from __future__ import unicode_literals from future", "-*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from", "class GenestackServerException(GenestackException): \"\"\" Server-side exception class. Raised when Genestack server returns an error", "= 'Got error \"%s\" at call of \"%s\"' % ( self.message, self.path )", "exception class. Raise its instances (instead of :py:class:`~exceptions.Exception`) if anything is wrong on", "error). \"\"\" def __init__(self, message, path, post_data, debug=False, stack_trace=None): \"\"\" :param message: exception", "least \"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version) else: package = PYPI_PACKAGE message = 'Cannot", "def __str__(self): return '<urlopen error %s>' % self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper", "= 'Cannot get required version from server.\\n' message += ( 'You can update", "required version from server.\\n' message += ( 'You can update client with the", "isinstance(message, bytes) else message) GenestackException.__init__(self, message, path, post_data, debug, stack_trace) self.message = message", "client side. \"\"\" pass class GenestackServerException(GenestackException): \"\"\" Server-side exception class. Raised when Genestack", "not an HTTP error). \"\"\" def __init__(self, message, path, post_data, debug=False, stack_trace=None): \"\"\"", "required.\\n' ).format(current_version=current_version, required_version=required_version) else: package = PYPI_PACKAGE message = 'Cannot get required version", "self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for server connection failures. Extends :py:class:`urllib2.URLError` for", "compatibility. \"\"\" def __init__(self, message): self.message = \"<connection failed %s>\" % message def", "URLError): \"\"\" Wrapper for server connection failures. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\"", "\"\"\" Wrapper for HTTP response errors. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def", "package = PYPI_PACKAGE message = 'Cannot get required version from server.\\n' message +=", "def __str__(self): return self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on an authentication error", "Python Client. \"\"\" pass class GenestackException(GenestackBaseException): \"\"\" Client-side exception class. Raise its instances", "for server connection failures. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, message):", ":param stack_trace: server stack trace :type stack_trace: str \"\"\" message = (message.decode('utf-8', 'ignore')", "message, path, post_data, debug, stack_trace) self.message = message self.debug = debug self.stack_trace =", "MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE message = ( 'Your Genestack Client version \"{current_version}\"", "%s>' % self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for server connection failures. Extends", "* from urllib.error import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception):", "call of \"%s\"' % ( self.message, self.path ) if self.stack_trace: if self.debug: message", "'Got error \"%s\" at call of \"%s\"' % ( self.message, self.path ) if", "message: exception message :type message: str :param path: path after server URL of", "should be printed :param stack_trace: server stack trace :type stack_trace: str \"\"\" message", "can update client with the following command:\\n' ' pip install {package} --upgrade' ).format(package=package)", "HTTP response errors. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, reason): self.args", "future import standard_library standard_library.install_aliases() from builtins import * from urllib.error import URLError MASTER_BRANCH", "message def __str__(self): return self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on an authentication", "required_version.prerelease else PYPI_PACKAGE message = ( 'Your Genestack Client version \"{current_version}\" is too", "Genestack Python Client. \"\"\" pass class GenestackException(GenestackBaseException): \"\"\" Client-side exception class. Raise its", "Client. \"\"\" def __init__(self, current_version, required_version=None): \"\"\" :param current_version: current version :type current_version:", "required version :type required_version: distutils.version.StrictVersion \"\"\" if required_version: package = MASTER_BRANCH if required_version.prerelease", ":py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, reason): self.args = reason, self.reason =", "error \"%s\" at call of \"%s\"' % ( self.message, self.path ) if self.stack_trace:", "def __str__(self): if isinstance(self.post_data, dict): message = 'Got error \"%s\" at call of", "unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * from urllib.error import", "message :type message: str :param path: path after server URL of connection. :type", "= stack_trace self.path = path self.post_data = post_data def __str__(self): if isinstance(self.post_data, dict):", "for backward compatibility. \"\"\" def __init__(self, reason): self.args = reason, self.reason = reason", "class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for server connection failures. Extends :py:class:`urllib2.URLError` for backward", "to retrieve traceback' return message class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for HTTP response", "response errors. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, reason): self.args =", "\"\"\" Base class for Genestack exceptions. Use it to catch all exceptions raised", "stack_trace) self.message = message self.debug = debug self.stack_trace = stack_trace self.path = path", "message += '\\nEnable debug option to retrieve traceback' return message class GenestackResponseError(GenestackBaseException, URLError):", "else: message += '\\nEnable debug option to retrieve traceback' return message class GenestackResponseError(GenestackBaseException,", "message self.debug = debug self.stack_trace = stack_trace self.path = path self.post_data = post_data", "class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on an authentication error response from server. \"\"\"", "__future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from", "\"\"\" def __init__(self, message): self.message = \"<connection failed %s>\" % message def __str__(self):", "GenestackException(GenestackBaseException): \"\"\" Client-side exception class. Raise its instances (instead of :py:class:`~exceptions.Exception`) if anything", "% self.stack_trace else: message += '\\nEnable debug option to retrieve traceback' return message", "print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import", "absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals", "'You can update client with the following command:\\n' ' pip install {package} --upgrade'", "isinstance(self.post_data, dict): message = 'Got error \"%s\" at call of method \"%s\" of", "'Got error \"%s\" at call of method \"%s\" of \"%s\"' % ( self.message,", "( self.message, self.post_data.get('method', '<unknown>'), self.path ) else: # upload file message = 'Got", "__str__(self): if isinstance(self.post_data, dict): message = 'Got error \"%s\" at call of method", "'<urlopen error %s>' % self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for server connection", "GenestackServerException(GenestackException): \"\"\" Server-side exception class. Raised when Genestack server returns an error response", "\"\"\" Client-side exception class. Raise its instances (instead of :py:class:`~exceptions.Exception`) if anything is", "debug option to retrieve traceback' return message class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for", "exceptions. Use it to catch all exceptions raised explicitly by Genestack Python Client.", "\"%s\" at call of method \"%s\" of \"%s\"' % ( self.message, self.post_data.get('method', '<unknown>'),", "'at least \"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version) else: package = PYPI_PACKAGE message =", "wrong on client side. \"\"\" pass class GenestackServerException(GenestackException): \"\"\" Server-side exception class. Raised", "of connection. :type path: str :param post_data: POST data (file or dict) :type", "'Your Genestack Client version \"{current_version}\" is too old, ' 'at least \"{required_version}\" is", "explicitly by Genestack Python Client. \"\"\" pass class GenestackException(GenestackBaseException): \"\"\" Client-side exception class.", "' 'at least \"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version) else: package = PYPI_PACKAGE message", "call of method \"%s\" of \"%s\"' % ( self.message, self.post_data.get('method', '<unknown>'), self.path )", "__init__(self, current_version, required_version=None): \"\"\" :param current_version: current version :type current_version: distutils.version.StrictVersion :param required_version:", "\"\"\" if required_version: package = MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE message = (", "division from __future__ import print_function from __future__ import unicode_literals from future import standard_library", "stack trace :type stack_trace: str \"\"\" message = (message.decode('utf-8', 'ignore') if isinstance(message, bytes)", "bytes) else message) GenestackException.__init__(self, message, path, post_data, debug, stack_trace) self.message = message self.debug", "on Python Client. \"\"\" def __init__(self, current_version, required_version=None): \"\"\" :param current_version: current version", "( 'You can update client with the following command:\\n' ' pip install {package}", "from server.\\n' message += ( 'You can update client with the following command:\\n'", "stack_trace: server stack trace :type stack_trace: str \"\"\" message = (message.decode('utf-8', 'ignore') if", "required_version=None): \"\"\" :param current_version: current version :type current_version: distutils.version.StrictVersion :param required_version: minimum required", "by Genestack Java code, not an HTTP error). \"\"\" def __init__(self, message, path,", "\"\"\" pass class GenestackException(GenestackBaseException): \"\"\" Client-side exception class. Raise its instances (instead of", "distutils.version.StrictVersion :param required_version: minimum required version :type required_version: distutils.version.StrictVersion \"\"\" if required_version: package", "retrieve traceback' return message class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for HTTP response errors.", "if self.debug: message += '\\nStacktrace from server is:\\n%s' % self.stack_trace else: message +=", "anything is wrong on client side. \"\"\" pass class GenestackServerException(GenestackException): \"\"\" Server-side exception", "= 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception): \"\"\" Base class for Genestack exceptions.", "'ignore') if isinstance(message, bytes) else message) GenestackException.__init__(self, message, path, post_data, debug, stack_trace) self.message", "class. Raised when Genestack server returns an error response (error message generated by", "= 'genestack-client' class GenestackBaseException(Exception): \"\"\" Base class for Genestack exceptions. Use it to", "utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import", "__str__(self): return '<urlopen error %s>' % self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for", "failures. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, message): self.message = \"<connection", "= MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE message = ( 'Your Genestack Client version", "response from server. \"\"\" pass class GenestackVersionException(GenestackException): \"\"\" Exception thrown if server requires", "Wrapper for HTTP response errors. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self,", "if required_version: package = MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE message = ( 'Your", "message generated by Genestack Java code, not an HTTP error). \"\"\" def __init__(self,", "debug=False, stack_trace=None): \"\"\" :param message: exception message :type message: str :param path: path", "\"%s\"' % ( self.message, self.path ) if self.stack_trace: if self.debug: message += '\\nStacktrace", "urllib.error import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception): \"\"\" Base", "server requires a newer version on Python Client. \"\"\" def __init__(self, current_version, required_version=None):", "message = 'Cannot get required version from server.\\n' message += ( 'You can", "path, post_data, debug=False, stack_trace=None): \"\"\" :param message: exception message :type message: str :param", "# upload file message = 'Got error \"%s\" at call of \"%s\"' %", "generated by Genestack Java code, not an HTTP error). \"\"\" def __init__(self, message,", "\"\"\" pass class GenestackVersionException(GenestackException): \"\"\" Exception thrown if server requires a newer version", "self.debug = debug self.stack_trace = stack_trace self.path = path self.post_data = post_data def", "def __init__(self, current_version, required_version=None): \"\"\" :param current_version: current version :type current_version: distutils.version.StrictVersion :param", "(instead of :py:class:`~exceptions.Exception`) if anything is wrong on client side. \"\"\" pass class", "self.message, self.post_data.get('method', '<unknown>'), self.path ) else: # upload file message = 'Got error", "data (file or dict) :type debug: bool :param debug: flag if stack trace", "\"{current_version}\" is too old, ' 'at least \"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version) else:", "__init__(self, reason): self.args = reason, self.reason = reason def __str__(self): return '<urlopen error", "it to catch all exceptions raised explicitly by Genestack Python Client. \"\"\" pass", "= path self.post_data = post_data def __str__(self): if isinstance(self.post_data, dict): message = 'Got", "POST data (file or dict) :type debug: bool :param debug: flag if stack", "def __init__(self, message): self.message = \"<connection failed %s>\" % message def __str__(self): return", "too old, ' 'at least \"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version) else: package =", "= debug self.stack_trace = stack_trace self.path = path self.post_data = post_data def __str__(self):", "authentication error response from server. \"\"\" pass class GenestackVersionException(GenestackException): \"\"\" Exception thrown if", "pass class GenestackVersionException(GenestackException): \"\"\" Exception thrown if server requires a newer version on", "\"<connection failed %s>\" % message def __str__(self): return self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception", "Use it to catch all exceptions raised explicitly by Genestack Python Client. \"\"\"", "% message def __str__(self): return self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on an", "MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception): \"\"\" Base class for Genestack", "GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for HTTP response errors. Extends :py:class:`urllib2.URLError` for backward compatibility.", "reason, self.reason = reason def __str__(self): return '<urlopen error %s>' % self.reason class", "flag if stack trace should be printed :param stack_trace: server stack trace :type", "if self.stack_trace: if self.debug: message += '\\nStacktrace from server is:\\n%s' % self.stack_trace else:", "Server-side exception class. Raised when Genestack server returns an error response (error message", "message += '\\nStacktrace from server is:\\n%s' % self.stack_trace else: message += '\\nEnable debug", "\"%s\"' % ( self.message, self.post_data.get('method', '<unknown>'), self.path ) else: # upload file message", "on client side. \"\"\" pass class GenestackServerException(GenestackException): \"\"\" Server-side exception class. Raised when", "URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception): \"\"\" Base class for", "raised explicitly by Genestack Python Client. \"\"\" pass class GenestackException(GenestackBaseException): \"\"\" Client-side exception", "if server requires a newer version on Python Client. \"\"\" def __init__(self, current_version,", "\"\"\" def __init__(self, reason): self.args = reason, self.reason = reason def __str__(self): return", "str :param path: path after server URL of connection. :type path: str :param", "coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__", "for Genestack exceptions. Use it to catch all exceptions raised explicitly by Genestack", "import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins", "\"\"\" Exception thrown if server requires a newer version on Python Client. \"\"\"", "be printed :param stack_trace: server stack trace :type stack_trace: str \"\"\" message =", "GenestackVersionException(GenestackException): \"\"\" Exception thrown if server requires a newer version on Python Client.", "from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import *", "debug: flag if stack trace should be printed :param stack_trace: server stack trace", "at call of \"%s\"' % ( self.message, self.path ) if self.stack_trace: if self.debug:", "upload file message = 'Got error \"%s\" at call of \"%s\"' % (", "message class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for HTTP response errors. Extends :py:class:`urllib2.URLError` for", "'Cannot get required version from server.\\n' message += ( 'You can update client", "required_version: distutils.version.StrictVersion \"\"\" if required_version: package = MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE message", "self.post_data.get('method', '<unknown>'), self.path ) else: # upload file message = 'Got error \"%s\"", "__init__(self, message, path, post_data, debug=False, stack_trace=None): \"\"\" :param message: exception message :type message:", ":param message: exception message :type message: str :param path: path after server URL", "'<unknown>'), self.path ) else: # upload file message = 'Got error \"%s\" at", ":type required_version: distutils.version.StrictVersion \"\"\" if required_version: package = MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE", ":param current_version: current version :type current_version: distutils.version.StrictVersion :param required_version: minimum required version :type", "str :param post_data: POST data (file or dict) :type debug: bool :param debug:", "code, not an HTTP error). \"\"\" def __init__(self, message, path, post_data, debug=False, stack_trace=None):", "path after server URL of connection. :type path: str :param post_data: POST data", ":type message: str :param path: path after server URL of connection. :type path:", "= (message.decode('utf-8', 'ignore') if isinstance(message, bytes) else message) GenestackException.__init__(self, message, path, post_data, debug,", "message: str :param path: path after server URL of connection. :type path: str", "\"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version) else: package = PYPI_PACKAGE message = 'Cannot get", "trace :type stack_trace: str \"\"\" message = (message.decode('utf-8', 'ignore') if isinstance(message, bytes) else", "an authentication error response from server. \"\"\" pass class GenestackVersionException(GenestackException): \"\"\" Exception thrown", "(message.decode('utf-8', 'ignore') if isinstance(message, bytes) else message) GenestackException.__init__(self, message, path, post_data, debug, stack_trace)", "Client version \"{current_version}\" is too old, ' 'at least \"{required_version}\" is required.\\n' ).format(current_version=current_version,", "a newer version on Python Client. \"\"\" def __init__(self, current_version, required_version=None): \"\"\" :param", "error response (error message generated by Genestack Java code, not an HTTP error).", "its instances (instead of :py:class:`~exceptions.Exception`) if anything is wrong on client side. \"\"\"", "backward compatibility. \"\"\" def __init__(self, reason): self.args = reason, self.reason = reason def", "dict) :type debug: bool :param debug: flag if stack trace should be printed", "current_version: current version :type current_version: distutils.version.StrictVersion :param required_version: minimum required version :type required_version:", "= ( 'Your Genestack Client version \"{current_version}\" is too old, ' 'at least", "-*- from __future__ import absolute_import from __future__ import division from __future__ import print_function", "message = 'Got error \"%s\" at call of method \"%s\" of \"%s\"' %", "% ( self.message, self.path ) if self.stack_trace: if self.debug: message += '\\nStacktrace from", "if stack trace should be printed :param stack_trace: server stack trace :type stack_trace:", "after server URL of connection. :type path: str :param post_data: POST data (file", "\"%s\" at call of \"%s\"' % ( self.message, self.path ) if self.stack_trace: if", "connection. :type path: str :param post_data: POST data (file or dict) :type debug:", "'genestack-client' class GenestackBaseException(Exception): \"\"\" Base class for Genestack exceptions. Use it to catch", "class. Raise its instances (instead of :py:class:`~exceptions.Exception`) if anything is wrong on client", "newer version on Python Client. \"\"\" def __init__(self, current_version, required_version=None): \"\"\" :param current_version:", "PYPI_PACKAGE message = 'Cannot get required version from server.\\n' message += ( 'You", "on an authentication error response from server. \"\"\" pass class GenestackVersionException(GenestackException): \"\"\" Exception", "version on Python Client. \"\"\" def __init__(self, current_version, required_version=None): \"\"\" :param current_version: current", "class GenestackException(GenestackBaseException): \"\"\" Client-side exception class. Raise its instances (instead of :py:class:`~exceptions.Exception`) if", "self.stack_trace else: message += '\\nEnable debug option to retrieve traceback' return message class", "Java code, not an HTTP error). \"\"\" def __init__(self, message, path, post_data, debug=False,", "from __future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases()", "minimum required version :type required_version: distutils.version.StrictVersion \"\"\" if required_version: package = MASTER_BRANCH if", ":type debug: bool :param debug: flag if stack trace should be printed :param", "from future import standard_library standard_library.install_aliases() from builtins import * from urllib.error import URLError", "if isinstance(self.post_data, dict): message = 'Got error \"%s\" at call of method \"%s\"", "message) GenestackException.__init__(self, message, path, post_data, debug, stack_trace) self.message = message self.debug = debug", "class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for HTTP response errors. Extends :py:class:`urllib2.URLError` for backward", "%s>\" % message def __str__(self): return self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on", "failed %s>\" % message def __str__(self): return self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown", "class for Genestack exceptions. Use it to catch all exceptions raised explicitly by", "stack_trace self.path = path self.post_data = post_data def __str__(self): if isinstance(self.post_data, dict): message", "\"\"\" Wrapper for server connection failures. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def", "Raise its instances (instead of :py:class:`~exceptions.Exception`) if anything is wrong on client side.", "( 'Your Genestack Client version \"{current_version}\" is too old, ' 'at least \"{required_version}\"", "from server is:\\n%s' % self.stack_trace else: message += '\\nEnable debug option to retrieve", "stack trace should be printed :param stack_trace: server stack trace :type stack_trace: str", "URLError): \"\"\" Wrapper for HTTP response errors. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\"", "(file or dict) :type debug: bool :param debug: flag if stack trace should", "Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, message): self.message = \"<connection failed", "of \"%s\"' % ( self.message, self.path ) if self.stack_trace: if self.debug: message +=", "get required version from server.\\n' message += ( 'You can update client with", "message = (message.decode('utf-8', 'ignore') if isinstance(message, bytes) else message) GenestackException.__init__(self, message, path, post_data,", "returns an error response (error message generated by Genestack Java code, not an", "class GenestackBaseException(Exception): \"\"\" Base class for Genestack exceptions. Use it to catch all", "\"\"\" pass class GenestackServerException(GenestackException): \"\"\" Server-side exception class. Raised when Genestack server returns", "side. \"\"\" pass class GenestackServerException(GenestackException): \"\"\" Server-side exception class. Raised when Genestack server", "connection failures. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, message): self.message =", "return message class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for HTTP response errors. Extends :py:class:`urllib2.URLError`", "bool :param debug: flag if stack trace should be printed :param stack_trace: server", "version from server.\\n' message += ( 'You can update client with the following", "server returns an error response (error message generated by Genestack Java code, not", "self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on an authentication error response from server.", "self.post_data = post_data def __str__(self): if isinstance(self.post_data, dict): message = 'Got error \"%s\"", "distutils.version.StrictVersion \"\"\" if required_version: package = MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE message =", "= PYPI_PACKAGE message = 'Cannot get required version from server.\\n' message += (", "option to retrieve traceback' return message class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper for HTTP", "is too old, ' 'at least \"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version) else: package", "is:\\n%s' % self.stack_trace else: message += '\\nEnable debug option to retrieve traceback' return", "% ( self.message, self.post_data.get('method', '<unknown>'), self.path ) else: # upload file message =", "Genestack Client version \"{current_version}\" is too old, ' 'at least \"{required_version}\" is required.\\n'", "GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on an authentication error response from server. \"\"\" pass", "return self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on an authentication error response from", "message += ( 'You can update client with the following command:\\n' ' pip", "exception class. Raised when Genestack server returns an error response (error message generated", "def __init__(self, reason): self.args = reason, self.reason = reason def __str__(self): return '<urlopen", "error \"%s\" at call of method \"%s\" of \"%s\"' % ( self.message, self.post_data.get('method',", "package = MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE message = ( 'Your Genestack Client", "required_version: minimum required version :type required_version: distutils.version.StrictVersion \"\"\" if required_version: package = MASTER_BRANCH", "else: # upload file message = 'Got error \"%s\" at call of \"%s\"'", "'\\nEnable debug option to retrieve traceback' return message class GenestackResponseError(GenestackBaseException, URLError): \"\"\" Wrapper", "% self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for server connection failures. Extends :py:class:`urllib2.URLError`", "else message) GenestackException.__init__(self, message, path, post_data, debug, stack_trace) self.message = message self.debug =", "error response from server. \"\"\" pass class GenestackVersionException(GenestackException): \"\"\" Exception thrown if server", ":param post_data: POST data (file or dict) :type debug: bool :param debug: flag", "required_version=required_version) else: package = PYPI_PACKAGE message = 'Cannot get required version from server.\\n'", ":param debug: flag if stack trace should be printed :param stack_trace: server stack", "'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception): \"\"\" Base class for Genestack exceptions. Use", "thrown on an authentication error response from server. \"\"\" pass class GenestackVersionException(GenestackException): \"\"\"", "# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division", "path: path after server URL of connection. :type path: str :param post_data: POST", "an HTTP error). \"\"\" def __init__(self, message, path, post_data, debug=False, stack_trace=None): \"\"\" :param", "Wrapper for server connection failures. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self,", "when Genestack server returns an error response (error message generated by Genestack Java", "catch all exceptions raised explicitly by Genestack Python Client. \"\"\" pass class GenestackException(GenestackBaseException):", "version \"{current_version}\" is too old, ' 'at least \"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version)", "version :type current_version: distutils.version.StrictVersion :param required_version: minimum required version :type required_version: distutils.version.StrictVersion \"\"\"", "Genestack server returns an error response (error message generated by Genestack Java code,", "Exception thrown on an authentication error response from server. \"\"\" pass class GenestackVersionException(GenestackException):", "GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for server connection failures. Extends :py:class:`urllib2.URLError` for backward compatibility.", "HTTP error). \"\"\" def __init__(self, message, path, post_data, debug=False, stack_trace=None): \"\"\" :param message:", "\"\"\" Server-side exception class. Raised when Genestack server returns an error response (error", "class GenestackVersionException(GenestackException): \"\"\" Exception thrown if server requires a newer version on Python", "server stack trace :type stack_trace: str \"\"\" message = (message.decode('utf-8', 'ignore') if isinstance(message,", "standard_library.install_aliases() from builtins import * from urllib.error import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE", "thrown if server requires a newer version on Python Client. \"\"\" def __init__(self,", ":type stack_trace: str \"\"\" message = (message.decode('utf-8', 'ignore') if isinstance(message, bytes) else message)", "return '<urlopen error %s>' % self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for server", "from builtins import * from urllib.error import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE =", "from urllib.error import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception): \"\"\"", "by Genestack Python Client. \"\"\" pass class GenestackException(GenestackBaseException): \"\"\" Client-side exception class. Raise", "response (error message generated by Genestack Java code, not an HTTP error). \"\"\"", "is required.\\n' ).format(current_version=current_version, required_version=required_version) else: package = PYPI_PACKAGE message = 'Cannot get required", "message = 'Got error \"%s\" at call of \"%s\"' % ( self.message, self.path", "is wrong on client side. \"\"\" pass class GenestackServerException(GenestackException): \"\"\" Server-side exception class.", "version :type required_version: distutils.version.StrictVersion \"\"\" if required_version: package = MASTER_BRANCH if required_version.prerelease else", "self.reason = reason def __str__(self): return '<urlopen error %s>' % self.reason class GenestackConnectionFailure(GenestackBaseException,", "an error response (error message generated by Genestack Java code, not an HTTP", "Genestack exceptions. Use it to catch all exceptions raised explicitly by Genestack Python", "exceptions raised explicitly by Genestack Python Client. \"\"\" pass class GenestackException(GenestackBaseException): \"\"\" Client-side", "compatibility. \"\"\" def __init__(self, reason): self.args = reason, self.reason = reason def __str__(self):", "self.debug: message += '\\nStacktrace from server is:\\n%s' % self.stack_trace else: message += '\\nEnable", "__init__(self, message): self.message = \"<connection failed %s>\" % message def __str__(self): return self.message", "PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception): \"\"\" Base class for Genestack exceptions. Use it", "instances (instead of :py:class:`~exceptions.Exception`) if anything is wrong on client side. \"\"\" pass", "self.message, self.path ) if self.stack_trace: if self.debug: message += '\\nStacktrace from server is:\\n%s'", "post_data def __str__(self): if isinstance(self.post_data, dict): message = 'Got error \"%s\" at call", "from __future__ import absolute_import from __future__ import division from __future__ import print_function from", "to catch all exceptions raised explicitly by Genestack Python Client. \"\"\" pass class", "GenestackException.__init__(self, message, path, post_data, debug, stack_trace) self.message = message self.debug = debug self.stack_trace", "stack_trace=None): \"\"\" :param message: exception message :type message: str :param path: path after", "client with the following command:\\n' ' pip install {package} --upgrade' ).format(package=package) super(GenestackVersionException, self).__init__(message)", "__future__ import absolute_import from __future__ import division from __future__ import print_function from __future__", "message, path, post_data, debug=False, stack_trace=None): \"\"\" :param message: exception message :type message: str", "path, post_data, debug, stack_trace) self.message = message self.debug = debug self.stack_trace = stack_trace", "of method \"%s\" of \"%s\"' % ( self.message, self.post_data.get('method', '<unknown>'), self.path ) else:", "'\\nStacktrace from server is:\\n%s' % self.stack_trace else: message += '\\nEnable debug option to", "+= '\\nEnable debug option to retrieve traceback' return message class GenestackResponseError(GenestackBaseException, URLError): \"\"\"", "debug: bool :param debug: flag if stack trace should be printed :param stack_trace:", "\"\"\" Exception thrown on an authentication error response from server. \"\"\" pass class", "old, ' 'at least \"{required_version}\" is required.\\n' ).format(current_version=current_version, required_version=required_version) else: package = PYPI_PACKAGE", "requires a newer version on Python Client. \"\"\" def __init__(self, current_version, required_version=None): \"\"\"", "pass class GenestackServerException(GenestackException): \"\"\" Server-side exception class. Raised when Genestack server returns an", "method \"%s\" of \"%s\"' % ( self.message, self.post_data.get('method', '<unknown>'), self.path ) else: #", "import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client' class GenestackBaseException(Exception): \"\"\" Base class", ").format(current_version=current_version, required_version=required_version) else: package = PYPI_PACKAGE message = 'Cannot get required version from", "self.path ) else: # upload file message = 'Got error \"%s\" at call", "server is:\\n%s' % self.stack_trace else: message += '\\nEnable debug option to retrieve traceback'", "\"\"\" :param message: exception message :type message: str :param path: path after server", ":type current_version: distutils.version.StrictVersion :param required_version: minimum required version :type required_version: distutils.version.StrictVersion \"\"\" if", "+= ( 'You can update client with the following command:\\n' ' pip install", "reason def __str__(self): return '<urlopen error %s>' % self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\"", "self.path = path self.post_data = post_data def __str__(self): if isinstance(self.post_data, dict): message =", "self.message = \"<connection failed %s>\" % message def __str__(self): return self.message class GenestackAuthenticationException(GenestackException):", "self.stack_trace = stack_trace self.path = path self.post_data = post_data def __str__(self): if isinstance(self.post_data,", "if required_version.prerelease else PYPI_PACKAGE message = ( 'Your Genestack Client version \"{current_version}\" is", "from server. \"\"\" pass class GenestackVersionException(GenestackException): \"\"\" Exception thrown if server requires a", "Raised when Genestack server returns an error response (error message generated by Genestack", "__future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * from", ":py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, message): self.message = \"<connection failed %s>\"", "( self.message, self.path ) if self.stack_trace: if self.debug: message += '\\nStacktrace from server", "import standard_library standard_library.install_aliases() from builtins import * from urllib.error import URLError MASTER_BRANCH =", "path: str :param post_data: POST data (file or dict) :type debug: bool :param", "dict): message = 'Got error \"%s\" at call of method \"%s\" of \"%s\"'", "backward compatibility. \"\"\" def __init__(self, message): self.message = \"<connection failed %s>\" % message", "reason): self.args = reason, self.reason = reason def __str__(self): return '<urlopen error %s>'", "for HTTP response errors. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, reason):", "current_version: distutils.version.StrictVersion :param required_version: minimum required version :type required_version: distutils.version.StrictVersion \"\"\" if required_version:", "file message = 'Got error \"%s\" at call of \"%s\"' % ( self.message,", "Python Client. \"\"\" def __init__(self, current_version, required_version=None): \"\"\" :param current_version: current version :type", "server connection failures. Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, message): self.message", "PYPI_PACKAGE message = ( 'Your Genestack Client version \"{current_version}\" is too old, '", "at call of method \"%s\" of \"%s\"' % ( self.message, self.post_data.get('method', '<unknown>'), self.path", "debug, stack_trace) self.message = message self.debug = debug self.stack_trace = stack_trace self.path =", "or dict) :type debug: bool :param debug: flag if stack trace should be", "Client. \"\"\" pass class GenestackException(GenestackBaseException): \"\"\" Client-side exception class. Raise its instances (instead", ") else: # upload file message = 'Got error \"%s\" at call of", "import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * from urllib.error", "\"\"\" def __init__(self, current_version, required_version=None): \"\"\" :param current_version: current version :type current_version: distutils.version.StrictVersion", "required_version: package = MASTER_BRANCH if required_version.prerelease else PYPI_PACKAGE message = ( 'Your Genestack", "server URL of connection. :type path: str :param post_data: POST data (file or", "current version :type current_version: distutils.version.StrictVersion :param required_version: minimum required version :type required_version: distutils.version.StrictVersion", "from __future__ import division from __future__ import print_function from __future__ import unicode_literals from", "all exceptions raised explicitly by Genestack Python Client. \"\"\" pass class GenestackException(GenestackBaseException): \"\"\"", "pass class GenestackException(GenestackBaseException): \"\"\" Client-side exception class. Raise its instances (instead of :py:class:`~exceptions.Exception`)", "self.path ) if self.stack_trace: if self.debug: message += '\\nStacktrace from server is:\\n%s' %", "for backward compatibility. \"\"\" def __init__(self, message): self.message = \"<connection failed %s>\" %", "of :py:class:`~exceptions.Exception`) if anything is wrong on client side. \"\"\" pass class GenestackServerException(GenestackException):", "update client with the following command:\\n' ' pip install {package} --upgrade' ).format(package=package) super(GenestackVersionException,", "= message self.debug = debug self.stack_trace = stack_trace self.path = path self.post_data =", "exception message :type message: str :param path: path after server URL of connection.", ":py:class:`~exceptions.Exception`) if anything is wrong on client side. \"\"\" pass class GenestackServerException(GenestackException): \"\"\"", "if anything is wrong on client side. \"\"\" pass class GenestackServerException(GenestackException): \"\"\" Server-side", "Extends :py:class:`urllib2.URLError` for backward compatibility. \"\"\" def __init__(self, reason): self.args = reason, self.reason", "URL of connection. :type path: str :param post_data: POST data (file or dict)", "import division from __future__ import print_function from __future__ import unicode_literals from future import", "self.message = message self.debug = debug self.stack_trace = stack_trace self.path = path self.post_data", "trace should be printed :param stack_trace: server stack trace :type stack_trace: str \"\"\"", "path self.post_data = post_data def __str__(self): if isinstance(self.post_data, dict): message = 'Got error", "debug self.stack_trace = stack_trace self.path = path self.post_data = post_data def __str__(self): if", "__str__(self): return self.message class GenestackAuthenticationException(GenestackException): \"\"\" Exception thrown on an authentication error response", "import absolute_import from __future__ import division from __future__ import print_function from __future__ import", ") if self.stack_trace: if self.debug: message += '\\nStacktrace from server is:\\n%s' % self.stack_trace", "= \"<connection failed %s>\" % message def __str__(self): return self.message class GenestackAuthenticationException(GenestackException): \"\"\"", "= 'Got error \"%s\" at call of method \"%s\" of \"%s\"' % (", "error %s>' % self.reason class GenestackConnectionFailure(GenestackBaseException, URLError): \"\"\" Wrapper for server connection failures.", "standard_library standard_library.install_aliases() from builtins import * from urllib.error import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip'", "GenestackBaseException(Exception): \"\"\" Base class for Genestack exceptions. Use it to catch all exceptions", "stack_trace: str \"\"\" message = (message.decode('utf-8', 'ignore') if isinstance(message, bytes) else message) GenestackException.__init__(self,", "printed :param stack_trace: server stack trace :type stack_trace: str \"\"\" message = (message.decode('utf-8',", "message = ( 'Your Genestack Client version \"{current_version}\" is too old, ' 'at", "\"\"\" def __init__(self, message, path, post_data, debug=False, stack_trace=None): \"\"\" :param message: exception message", "server.\\n' message += ( 'You can update client with the following command:\\n' '", "str \"\"\" message = (message.decode('utf-8', 'ignore') if isinstance(message, bytes) else message) GenestackException.__init__(self, message,", "self.stack_trace: if self.debug: message += '\\nStacktrace from server is:\\n%s' % self.stack_trace else: message", "builtins import * from urllib.error import URLError MASTER_BRANCH = 'https://github.com/genestack/python-client/archive/master.zip' PYPI_PACKAGE = 'genestack-client'", "post_data, debug=False, stack_trace=None): \"\"\" :param message: exception message :type message: str :param path:", "= reason def __str__(self): return '<urlopen error %s>' % self.reason class GenestackConnectionFailure(GenestackBaseException, URLError):" ]
[ "len(arr) - count_elem[showFace] + count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int]) -> int: # return", "dice) # for v in range(1, 7) # ) # N = [6,", "count_elem[showFace] + count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int]) -> int: # return min( #", "- count_elem[showFace] + count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int]) -> int: # return min(", "2: 4, 4: 2, 3: 5, 5: 3 } count_elem = defaultdict(int) showFace", "showFace = None max_count = 0 for elem in arr: count_elem[elem] += 1", "7 else 2 for d in dice) # for v in range(1, 7)", "!= 7 else 2 for d in dice) # for v in range(1,", "d == v else 1 if d + v != 7 else 2", "= None max_count = 0 for elem in arr: count_elem[elem] += 1 if", "max_count: max_count = count_elem[elem] showFace = elem return len(arr) - count_elem[showFace] + count_elem[map_val[showFace]]", "# return min( # sum(0 if d == v else 1 if d", "in dice) # for v in range(1, 7) # ) # N =", "+= 1 if count_elem[elem] > max_count: max_count = count_elem[elem] showFace = elem return", "class Solution: def rollDice(self, arr): map_val = { 6: 1, 1: 6, 2:", "collections import defaultdict class Solution: def rollDice(self, arr): map_val = { 6: 1,", "return len(arr) - count_elem[showFace] + count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int]) -> int: #", "1: 6, 2: 4, 4: 2, 3: 5, 5: 3 } count_elem =", "3 } count_elem = defaultdict(int) showFace = None max_count = 0 for elem", "d in dice) # for v in range(1, 7) # ) # N", "= 0 for elem in arr: count_elem[elem] += 1 if count_elem[elem] > max_count:", "range(1, 7) # ) # N = [6, 6, 1] N = [6,", "def number_of_rotations(dice: List[int]) -> int: # return min( # sum(0 if d ==", "map_val = { 6: 1, 1: 6, 2: 4, 4: 2, 3: 5,", "count_elem = defaultdict(int) showFace = None max_count = 0 for elem in arr:", "max_count = count_elem[elem] showFace = elem return len(arr) - count_elem[showFace] + count_elem[map_val[showFace]] #", "count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int]) -> int: # return min( # sum(0 if", "defaultdict(int) showFace = None max_count = 0 for elem in arr: count_elem[elem] +=", "0 for elem in arr: count_elem[elem] += 1 if count_elem[elem] > max_count: max_count", "= { 6: 1, 1: 6, 2: 4, 4: 2, 3: 5, 5:", "v in range(1, 7) # ) # N = [6, 6, 1] N", "in arr: count_elem[elem] += 1 if count_elem[elem] > max_count: max_count = count_elem[elem] showFace", "min( # sum(0 if d == v else 1 if d + v", "6: 1, 1: 6, 2: 4, 4: 2, 3: 5, 5: 3 }", "} count_elem = defaultdict(int) showFace = None max_count = 0 for elem in", "if d + v != 7 else 2 for d in dice) #", "= defaultdict(int) showFace = None max_count = 0 for elem in arr: count_elem[elem]", "> max_count: max_count = count_elem[elem] showFace = elem return len(arr) - count_elem[showFace] +", "in range(1, 7) # ) # N = [6, 6, 1] N =", "return min( # sum(0 if d == v else 1 if d +", "else 1 if d + v != 7 else 2 for d in", "count_elem[elem] += 1 if count_elem[elem] > max_count: max_count = count_elem[elem] showFace = elem", "-> int: # return min( # sum(0 if d == v else 1", "number_of_rotations(dice: List[int]) -> int: # return min( # sum(0 if d == v", "List[int]) -> int: # return min( # sum(0 if d == v else", "4: 2, 3: 5, 5: 3 } count_elem = defaultdict(int) showFace = None", "7) # ) # N = [6, 6, 1] N = [6, 1,", "arr: count_elem[elem] += 1 if count_elem[elem] > max_count: max_count = count_elem[elem] showFace =", "None max_count = 0 for elem in arr: count_elem[elem] += 1 if count_elem[elem]", "6, 2: 4, 4: 2, 3: 5, 5: 3 } count_elem = defaultdict(int)", "# ) # N = [6, 6, 1] N = [6, 1, 5,", "int: # return min( # sum(0 if d == v else 1 if", "<gh_stars>0 from collections import defaultdict class Solution: def rollDice(self, arr): map_val = {", "v != 7 else 2 for d in dice) # for v in", "3: 5, 5: 3 } count_elem = defaultdict(int) showFace = None max_count =", "{ 6: 1, 1: 6, 2: 4, 4: 2, 3: 5, 5: 3", "for d in dice) # for v in range(1, 7) # ) #", "rollDice(self, arr): map_val = { 6: 1, 1: 6, 2: 4, 4: 2,", "v else 1 if d + v != 7 else 2 for d", "d + v != 7 else 2 for d in dice) # for", "arr): map_val = { 6: 1, 1: 6, 2: 4, 4: 2, 3:", "2 for d in dice) # for v in range(1, 7) # )", "+ v != 7 else 2 for d in dice) # for v", "5: 3 } count_elem = defaultdict(int) showFace = None max_count = 0 for", "2, 3: 5, 5: 3 } count_elem = defaultdict(int) showFace = None max_count", "defaultdict class Solution: def rollDice(self, arr): map_val = { 6: 1, 1: 6,", "# sum(0 if d == v else 1 if d + v !=", "# for v in range(1, 7) # ) # N = [6, 6,", "count_elem[elem] showFace = elem return len(arr) - count_elem[showFace] + count_elem[map_val[showFace]] # def number_of_rotations(dice:", "if count_elem[elem] > max_count: max_count = count_elem[elem] showFace = elem return len(arr) -", "import defaultdict class Solution: def rollDice(self, arr): map_val = { 6: 1, 1:", "elem in arr: count_elem[elem] += 1 if count_elem[elem] > max_count: max_count = count_elem[elem]", "# N = [6, 6, 1] N = [6, 1, 5, 4] print(Solution().rollDice(N))", "# def number_of_rotations(dice: List[int]) -> int: # return min( # sum(0 if d", "count_elem[elem] > max_count: max_count = count_elem[elem] showFace = elem return len(arr) - count_elem[showFace]", "for v in range(1, 7) # ) # N = [6, 6, 1]", "max_count = 0 for elem in arr: count_elem[elem] += 1 if count_elem[elem] >", "1, 1: 6, 2: 4, 4: 2, 3: 5, 5: 3 } count_elem", "from collections import defaultdict class Solution: def rollDice(self, arr): map_val = { 6:", "= elem return len(arr) - count_elem[showFace] + count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int]) ->", "== v else 1 if d + v != 7 else 2 for", "else 2 for d in dice) # for v in range(1, 7) #", "if d == v else 1 if d + v != 7 else", "for elem in arr: count_elem[elem] += 1 if count_elem[elem] > max_count: max_count =", "1 if count_elem[elem] > max_count: max_count = count_elem[elem] showFace = elem return len(arr)", "def rollDice(self, arr): map_val = { 6: 1, 1: 6, 2: 4, 4:", "= count_elem[elem] showFace = elem return len(arr) - count_elem[showFace] + count_elem[map_val[showFace]] # def", ") # N = [6, 6, 1] N = [6, 1, 5, 4]", "4, 4: 2, 3: 5, 5: 3 } count_elem = defaultdict(int) showFace =", "+ count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int]) -> int: # return min( # sum(0", "showFace = elem return len(arr) - count_elem[showFace] + count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int])", "elem return len(arr) - count_elem[showFace] + count_elem[map_val[showFace]] # def number_of_rotations(dice: List[int]) -> int:", "sum(0 if d == v else 1 if d + v != 7", "Solution: def rollDice(self, arr): map_val = { 6: 1, 1: 6, 2: 4,", "5, 5: 3 } count_elem = defaultdict(int) showFace = None max_count = 0", "1 if d + v != 7 else 2 for d in dice)" ]
[ "import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) logger", "return ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin, destination=self._conversations[userid]._dest ),", "update.message.from_user.first_name if update.message.from_user.last_name is not None: username += \" \" + update.message.from_user.last_name auth", "conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest, conv._date) else: logger.error(\"Problem, no other option", "bot, update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot, update) elif update.message.text", "self._RB._DB.get_user_auth(userid, username) if auth == 0: # Not authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username),", "userid, bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def", "self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self, userid, bot,", "return ret_code def _h_op_do_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"],", "def __init__(self, renfebot): self._conversations = {} self._RB = renfebot def _start_conv_for_user(self, userid): if", "update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self, userid, bot, update): self._conversations[userid]._option =", "update): ret_code = 0 userid = update.message.from_user.id username = update.message.from_user.first_name if update.message.from_user.last_name is", "userid): if userid not in self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot,", "conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option == BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query(", "logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) class BotOptions(Enum):", "self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res =", "logging from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import ConversationHandler from telegramcalendarkeyboard import", "TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid,", "else: logger.debug(\"Deleting query with index \"+str(query_index)) if len(user_queries) > query_index: query = user_queries[query_index]", "= userid self.reset() def reset(self): self._option = 0 self._origin = None self._dest =", "conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date))", "def handler_cancel(self, bot, update): return ConversationHandler.END def handler_option(self, bot, update): userid = update.message.from_user.id", "update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY", "bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self,", "_h_op_check_queries(self, userid, bot, update): user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else:", "BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self, userid, bot, update): self._conversations[userid]._option", "= self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin,", "= self._RB._DB.get_user_auth(userid, username) if auth == 0: # Not authorized logger.debug(\"NOT AUTHORIZED USER\")", "from texts import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',", "import Enum import logging from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import ConversationHandler", "Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest", "else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END", "res = self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"])", "self._RB = renfebot def _start_conv_for_user(self, userid): if userid not in self._conversations: self._conversations[userid] =", "def handler_option(self, bot, update): userid = update.message.from_user.id ret_code = 0 if update.message.text ==", "selected, query_index = telegramoptions.process_option_selection(bot, update) if not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove())", "0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot, update) elif update.message.text ==", "conv = self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"].", "reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin,", "DATE = 3 NUMERIC_OPTION = 4 class RenfeBotConversations: class Conversation: def __init__(self, userid):", "texts import texts as TEXTS from texts import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s -", "update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self, userid,", "update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self, userid,", "_h_op_del_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code = 0", "1 STATION = 2 DATE = 3 NUMERIC_OPTION = 4 class RenfeBotConversations: class", "ConversationHandler.END else: logger.debug(\"Deleting query with index \"+str(query_index)) if len(user_queries) > query_index: query =", "+ conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option == BotOptions.ADD_QUERY: res =", "in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code", "self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin, destination=self._conversations[userid]._dest ), reply_markup=ReplyKeyboardRemove()) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_DATE\"], reply_markup=telegramcalendar.create_calendar()) return", "TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid,", "ConversationHandler.END return ret_code def _h_op_do_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"],", "BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY:", "update.message.from_user.id ret_code = 0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot, update)", "in self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot, update): ret_code = 0", "update): user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q", "userid, bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def", "ret_code = ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True)", "= self._h_op_add_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot, update)", "3 class ConvStates(Enum): OPTION = 1 STATION = 2 DATE = 3 NUMERIC_OPTION", "return ConvStates.DATE else: logger.debug(\"selected\") userid = update.callback_query.from_user.id conv = self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\")", "4 class RenfeBotConversations: class Conversation: def __init__(self, userid): self._userid = userid self.reset() def", "bot, update): ret_code = 0 userid = update.message.from_user.id username = update.message.from_user.first_name if update.message.from_user.last_name", "return ConversationHandler.END else: logger.debug(\"Deleting query with index \"+str(query_index)) if len(user_queries) > query_index: query", "update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format(", "telegramcalendarkeyboard import telegramoptions from texts import texts as TEXTS from texts import keyboards", "TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return ret_code", "== 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else: options = [] for q in", "query_index = telegramoptions.process_option_selection(bot, update) if not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return", "from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import ConversationHandler from telegramcalendarkeyboard import telegramcalendar", "update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code = ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED USER\")", "0 if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else: options = []", "query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self, bot, update): logger.debug(\"Processing date\")", "else: logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin, destination=self._conversations[userid]._dest ), reply_markup=ReplyKeyboardRemove()) bot.send_message(chat_id=userid,", "= self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return ret_code def _h_op_do_query(self,", "\"\"\" from enum import Enum import logging from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from", "authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code = ConversationHandler.END else:", "update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username) if auth == 0: # Not authorized logger.debug(\"NOT", "date = telegramcalendar.process_calendar_selection(bot, update) if not selected: logger.debug(\"Not selected\") return ConvStates.DATE else: logger.debug(\"selected\")", "userid self.reset() def reset(self): self._option = 0 self._origin = None self._dest = None", "update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else: options = [] for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"].", "STATION = 2 DATE = 3 NUMERIC_OPTION = 4 class RenfeBotConversations: class Conversation:", "= 3 NUMERIC_OPTION = 4 class RenfeBotConversations: class Conversation: def __init__(self, userid): self._userid", "== TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return", "self._h_op_del_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot, update) else:", "from telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard import telegramoptions from texts import texts as", "USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION return ret_code def handler_cancel(self,", "logger.debug(\"Date is \" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option ==", "import ConversationHandler from telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard import telegramoptions from texts import", "elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]:", "handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric opion\") userid = update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected,", "no other option should lead HERE!\") return ConversationHandler.END def handler_station(self, bot, update): logger.debug(\"Setting", "if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else: options = [] for", "query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END", "date=conv._date)) if conv._option == BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1])", "KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) class", "2 DATE = 3 NUMERIC_OPTION = 4 class RenfeBotConversations: class Conversation: def __init__(self,", "+ update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username) if auth == 0: # Not authorized", "ret_code = 0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot, update) elif", "= None self._dest = None self._date = None self._data = None def __init__(self,", "= BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self, userid, bot, update):", "userid, bot, update): user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"])", "def __init__(self, userid): self._userid = userid self.reset() def reset(self): self._option = 0 self._origin", "bot, update): logger.debug(\"Processing date\") selected, date = telegramcalendar.process_calendar_selection(bot, update) if not selected: logger.debug(\"Not", "self._dest = None self._date = None self._data = None def __init__(self, renfebot): self._conversations", "date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric opion\") userid =", "Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin, destination=self._conversations[userid]._dest ), reply_markup=ReplyKeyboardRemove()) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_DATE\"], reply_markup=telegramcalendar.create_calendar())", "= self._h_op_do_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot, update)", "self.reset() def reset(self): self._option = 0 self._origin = None self._dest = None self._date", "if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]:", "= update.message.from_user.id username = update.message.from_user.first_name if update.message.from_user.last_name is not None: username += \"", "bot, update): user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for", "userid = update.callback_query.from_user.id conv = self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" +", "user_queries = self._RB._DB.get_user_queries(userid) ret_code = 0 if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code =", "== TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code =", "return ConvStates.STATION def _h_op_del_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid)", "elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]:", "update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric opion\") userid = update.callback_query.from_user.id", "userid = update.message.from_user.id username = update.message.from_user.first_name if update.message.from_user.last_name is not None: username +=", "import texts as TEXTS from texts import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s", "ret_code = ConversationHandler.END return ret_code def _h_op_do_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY", "from enum import Enum import logging from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext", "update): return ConversationHandler.END def handler_option(self, bot, update): userid = update.message.from_user.id ret_code = 0", "update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def", "bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting query with index \"+str(query_index)) if len(user_queries)", "self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest, conv._date) else: logger.error(\"Problem, no other", "TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid,", "= [] for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"]))", "ConversationHandler from telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard import telegramoptions from texts import texts", "== 0: # Not authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username)", "= ConvStates.OPTION return ret_code def handler_cancel(self, bot, update): return ConversationHandler.END def handler_option(self, bot,", "date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option", "telegramcalendar from telegramcalendarkeyboard import telegramoptions from texts import texts as TEXTS from texts", "self._conversations[userid]._data = user_queries ret_code = ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self, userid, bot, update):", "username) ret_code = ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]),", "AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code = ConversationHandler.END else: # Authorized", "update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code", "conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest,", "= ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code", "update.message.from_user.id username = update.message.from_user.first_name if update.message.from_user.last_name is not None: username += \" \"", "BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self, userid, bot, update): self._conversations[userid]._option", "self._RB._DB.get_user_queries(userid) ret_code = 0 if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else:", "userid, bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code = 0 if", "import telegramoptions from texts import texts as TEXTS from texts import keyboards as", "options = [] for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"],", "ret_code = ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self, userid, bot, update): user_queries = self._RB._DB.get_user_queries(userid)", "update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid,", "level=logging.DEBUG) logger = logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY = 2 DO_QUERY", "one_time_keyboard=True) ret_code = ConvStates.OPTION return ret_code def handler_cancel(self, bot, update): return ConversationHandler.END def", "self._RB._DB.get_user_queries(userid) if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"].", "None def __init__(self, renfebot): self._conversations = {} self._RB = renfebot def _start_conv_for_user(self, userid):", "= 0 if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else: options =", "auth = self._RB._DB.get_user_auth(userid, username) if auth == 0: # Not authorized logger.debug(\"NOT AUTHORIZED", "0 userid = update.message.from_user.id username = update.message.from_user.first_name if update.message.from_user.last_name is not None: username", "username) if auth == 0: # Not authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove())", "if update.message.from_user.last_name is not None: username += \" \" + update.message.from_user.last_name auth =", "selected: logger.debug(\"Not selected\") return ConvStates.DATE else: logger.debug(\"selected\") userid = update.callback_query.from_user.id conv = self._conversations[userid]", "= 2 DO_QUERY = 3 class ConvStates(Enum): OPTION = 1 STATION = 2", "= 0 userid = update.message.from_user.id username = update.message.from_user.first_name if update.message.from_user.last_name is not None:", "userid, res, conv._origin, conv._dest, conv._date) else: logger.error(\"Problem, no other option should lead HERE!\")", "logger.debug(\"Deleting query with index \"+str(query_index)) if len(user_queries) > query_index: query = user_queries[query_index] if", "update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION return ret_code def handler_cancel(self, bot, update):", "bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest, conv._date) else:", "one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries =", "should lead HERE!\") return ConversationHandler.END def handler_station(self, bot, update): logger.debug(\"Setting Station\") userid =", "self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest,", "def handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric opion\") userid = update.callback_query.from_user.id user_queries = self._conversations[userid]._data", "NUMERIC_OPTION = 4 class RenfeBotConversations: class Conversation: def __init__(self, userid): self._userid = userid", "def handler_station(self, bot, update): logger.debug(\"Setting Station\") userid = update.message.from_user.id if self._conversations[userid]._origin is None:", "= ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self, userid, bot, update): user_queries = self._RB._DB.get_user_queries(userid) if", "update) if not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting", "= 2 DATE = 3 NUMERIC_OPTION = 4 class RenfeBotConversations: class Conversation: def", "= 1 STATION = 2 DATE = 3 NUMERIC_OPTION = 4 class RenfeBotConversations:", "userid not in self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot, update): ret_code", "return ConversationHandler.END def handler_option(self, bot, update): userid = update.message.from_user.id ret_code = 0 if", "ConvStates.DATE else: logger.debug(\"selected\") userid = update.callback_query.from_user.id conv = self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date", "def _h_op_check_queries(self, userid, bot, update): user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"])", "# Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION return", "self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code = 0 if len(user_queries) == 0:", "update.message.from_user.last_name is not None: username += \" \" + update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid,", "else: options = [] for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid,", "res, conv._origin, conv._dest, conv._date) else: logger.error(\"Problem, no other option should lead HERE!\") return", "self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest, conv._date) else: logger.error(\"Problem, no other option should lead", "= self._RB._DB.get_user_queries(userid) ret_code = 0 if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END", "q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self, bot,", "conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date)", "return ConversationHandler.END def handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric opion\") userid = update.callback_query.from_user.id user_queries", "if not selected: logger.debug(\"Not selected\") return ConvStates.DATE else: logger.debug(\"selected\") userid = update.callback_query.from_user.id conv", "if userid not in self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot, update):", "user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self, bot, update): logger.debug(\"Processing", "self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot, update): ret_code = 0 userid", "userid = update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot, update) if not", "= telegramcalendar.process_calendar_selection(bot, update) if not selected: logger.debug(\"Not selected\") return ConvStates.DATE else: logger.debug(\"selected\") userid", "user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self,", "from texts import texts as TEXTS from texts import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s", "as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__)", "self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot, update): ret_code = 0 userid =", "userid = update.message.from_user.id ret_code = 0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid,", "= 0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot, update) elif update.message.text", "as TEXTS from texts import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s", "Station\") userid = update.message.from_user.id if self._conversations[userid]._origin is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper()", "userid = update.message.from_user.id if self._conversations[userid]._origin is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"],", "def _h_op_del_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code =", "self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION return ret_code def handler_cancel(self, bot,", "ConvStates(Enum): OPTION = 1 STATION = 2 DATE = 3 NUMERIC_OPTION = 4", "ret_code = self._h_op_del_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot,", "return ret_code def handler_cancel(self, bot, update): return ConversationHandler.END def handler_option(self, bot, update): userid", "class ConvStates(Enum): OPTION = 1 STATION = 2 DATE = 3 NUMERIC_OPTION =", "0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove())", "self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self, bot, update):", "update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot, update) if not selected: logger.debug(\"Nothing", "handler_option(self, bot, update): userid = update.message.from_user.id ret_code = 0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]:", "\" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option == BotOptions.ADD_QUERY: res", "bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return ret_code def _h_op_do_query(self, userid, bot,", "selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting query with index", "self._option = 0 self._origin = None self._dest = None self._date = None self._data", "def _start_conv_for_user(self, userid): if userid not in self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def", "def handler_start(self, bot, update): ret_code = 0 userid = update.message.from_user.id username = update.message.from_user.first_name", "not None: username += \" \" + update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username) if", "len(user_queries) > query_index: query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else:", "in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self, bot, update):", "renfebot def _start_conv_for_user(self, userid): if userid not in self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset()", "handler_station(self, bot, update): logger.debug(\"Setting Station\") userid = update.message.from_user.id if self._conversations[userid]._origin is None: logger.debug(\"Origin", "is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else:", "userid): self._userid = userid self.reset() def reset(self): self._option = 0 self._origin = None", "= user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def", "ConversationHandler.END def handler_station(self, bot, update): logger.debug(\"Setting Station\") userid = update.message.from_user.id if self._conversations[userid]._origin is", "DO_QUERY = 3 class ConvStates(Enum): OPTION = 1 STATION = 2 DATE =", "userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin,", "def _h_op_add_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return", "logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination Station\")", "None: logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination", "numeric opion\") userid = update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot, update)", "bot, update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot, update) elif update.message.text", "= update.message.from_user.id if self._conversations[userid]._origin is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"],", "update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code", "USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code = ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED", "return ConversationHandler.END def handler_date(self, bot, update): logger.debug(\"Processing date\") selected, date = telegramcalendar.process_calendar_selection(bot, update)", "update): userid = update.message.from_user.id ret_code = 0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code =", "handler_date(self, bot, update): logger.debug(\"Processing date\") selected, date = telegramcalendar.process_calendar_selection(bot, update) if not selected:", "None self._dest = None self._date = None self._data = None def __init__(self, renfebot):", "def handler_date(self, bot, update): logger.debug(\"Processing date\") selected, date = telegramcalendar.process_calendar_selection(bot, update) if not", "lead HERE!\") return ConversationHandler.END def handler_station(self, bot, update): logger.debug(\"Setting Station\") userid = update.message.from_user.id", "text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting query with index \"+str(query_index)) if len(user_queries) > query_index:", "DEL_QUERY = 2 DO_QUERY = 3 class ConvStates(Enum): OPTION = 1 STATION =", "userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting query with index \"+str(query_index)) if len(user_queries) >", "texts as TEXTS from texts import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s -", "= 0 self._origin = None self._dest = None self._date = None self._data =", "update): logger.debug(\"Setting Station\") userid = update.message.from_user.id if self._conversations[userid]._origin is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin", "telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard import telegramoptions from texts import texts as TEXTS", "RenfeBotConversations: class Conversation: def __init__(self, userid): self._userid = userid self.reset() def reset(self): self._option", "ret_code = 0 userid = update.message.from_user.id username = update.message.from_user.first_name if update.message.from_user.last_name is not", "telegramoptions from texts import texts as TEXTS from texts import keyboards as KEYBOARDS", "def _h_op_do_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return", "len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"],", "= update.callback_query.from_user.id conv = self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" + conv._date)", "conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest, conv._date) else: logger.error(\"Problem, no other option should", "_h_op_add_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION", "return ret_code def _h_op_check_queries(self, userid, bot, update): user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries) ==", "elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code =", "self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return ret_code def _h_op_do_query(self, userid,", "self._RB.ask_admin_for_access(bot, userid, username) ret_code = ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"],", "= BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code = 0 if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"])", "= self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res", "BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code = 0 if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code", "bot, update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"])", "conv._date) else: logger.error(\"Problem, no other option should lead HERE!\") return ConversationHandler.END def handler_station(self,", "update.message.from_user.id if self._conversations[userid]._origin is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True))", "else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return ret_code def _h_op_do_query(self, userid, bot, update): self._conversations[userid]._option", "%(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY =", "renfebot): self._conversations = {} self._RB = renfebot def _start_conv_for_user(self, userid): if userid not", "update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code", "= self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest, conv._date) else: logger.error(\"Problem, no", "self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self, userid, bot,", "ret_code def _h_op_do_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True))", "update.callback_query.from_user.id conv = self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" + conv._date) bot.send_message(chat_id=userid,", "date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code = ConvStates.NUMERIC_OPTION return ret_code def", "HERE!\") return ConversationHandler.END def handler_station(self, bot, update): logger.debug(\"Setting Station\") userid = update.message.from_user.id if", "for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data =", "ret_code = ConversationHandler.END else: options = [] for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"],", "ConversationHandler.END def handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric opion\") userid = update.callback_query.from_user.id user_queries =", "ret_code = self._h_op_add_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot,", "class Conversation: def __init__(self, userid): self._userid = userid self.reset() def reset(self): self._option =", "update): logger.debug(\"Processing numeric opion\") userid = update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected, query_index =", "%(levelname)s - %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY", "%(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY = 2", "class BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY = 2 DO_QUERY = 3 class ConvStates(Enum):", "other option should lead HERE!\") return ConversationHandler.END def handler_station(self, bot, update): logger.debug(\"Setting Station\")", "update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END", "telegram.ext import ConversationHandler from telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard import telegramoptions from texts", "self._h_op_do_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot, update) elif", "username = update.message.from_user.first_name if update.message.from_user.last_name is not None: username += \" \" +", "0 self._origin = None self._dest = None self._date = None self._data = None", "1 DEL_QUERY = 2 DO_QUERY = 3 class ConvStates(Enum): OPTION = 1 STATION", "user_queries ret_code = ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self, userid, bot, update): user_queries =", "__init__(self, renfebot): self._conversations = {} self._RB = renfebot def _start_conv_for_user(self, userid): if userid", "update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return ret_code def _h_op_do_query(self, userid, bot, update): self._conversations[userid]._option =", "None self._date = None self._data = None def __init__(self, renfebot): self._conversations = {}", "= telegramoptions.process_option_selection(bot, update) if not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END", "= 4 class RenfeBotConversations: class Conversation: def __init__(self, userid): self._userid = userid self.reset()", "ReplyKeyboardRemove) from telegram.ext import ConversationHandler from telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard import telegramoptions", "import telegramcalendar from telegramcalendarkeyboard import telegramoptions from texts import texts as TEXTS from", "self._conversations[userid]._origin is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION", "= update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper()", "ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code =", "update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot, update) elif update.message.text ==", "ConvStates.STATION def _h_op_add_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True))", "BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest, conv._date)", "if not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting query", "index \"+str(query_index)) if len(user_queries) > query_index: query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"],", "update) if not selected: logger.debug(\"Not selected\") return ConvStates.DATE else: logger.debug(\"selected\") userid = update.callback_query.from_user.id", "one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin, destination=self._conversations[userid]._dest", "TEXTS from texts import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s -", "None: username += \" \" + update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username) if auth", "logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code = ConversationHandler.END else: #", "= 1 DEL_QUERY = 2 DO_QUERY = 3 class ConvStates(Enum): OPTION = 1", "user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in", "ret_code = ConvStates.OPTION return ret_code def handler_cancel(self, bot, update): return ConversationHandler.END def handler_option(self,", "import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import ConversationHandler from telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard", "self._date = None self._data = None def __init__(self, renfebot): self._conversations = {} self._RB", "bot, update): logger.debug(\"Processing numeric opion\") userid = update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected, query_index", "reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"])", "return ConvStates.STATION def _h_op_add_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"],", "query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self, bot, update): logger.debug(\"Processing date\") selected,", "\"\"\" \"\"\" from enum import Enum import logging from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)", "[] for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data", "destination=conv._dest, date=conv._date)) if conv._option == BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date)", "def reset(self): self._option = 0 self._origin = None self._dest = None self._date =", "from telegramcalendarkeyboard import telegramoptions from texts import texts as TEXTS from texts import", "q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries", "Enum import logging from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import ConversationHandler from", "\" \" + update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username) if auth == 0: #", "with index \"+str(query_index)) if len(user_queries) > query_index: query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"],", "update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code = 0 if len(user_queries) ==", "BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY = 2 DO_QUERY = 3 class ConvStates(Enum): OPTION", "ret_code = self._h_op_check_queries(userid, bot, update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return ret_code def", "user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code =", "conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot,", "if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self, bot,", "Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION return ret_code", "format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code = ConvStates.NUMERIC_OPTION return", "reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries", "KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION return ret_code def handler_cancel(self, bot, update): return ConversationHandler.END", "is not None: username += \" \" + update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username)", "else: logger.debug(\"selected\") userid = update.callback_query.from_user.id conv = self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is", "from telegram.ext import ConversationHandler from telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard import telegramoptions from", "self._conversations = {} self._RB = renfebot def _start_conv_for_user(self, userid): if userid not in", "ret_code def handler_cancel(self, bot, update): return ConversationHandler.END def handler_option(self, bot, update): userid =", "bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code = 0 if len(user_queries)", "= self._h_op_del_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code = self._h_op_check_queries(userid, bot, update)", "ConversationHandler.END else: options = [] for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"])))", "update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code", "= update.message.from_user.id ret_code = 0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot,", "else: logger.error(\"Problem, no other option should lead HERE!\") return ConversationHandler.END def handler_station(self, bot,", "reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code = ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid)", "self._h_op_add_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot, update) elif", "ConversationHandler.END def handler_date(self, bot, update): logger.debug(\"Processing date\") selected, date = telegramcalendar.process_calendar_selection(bot, update) if", "logger.debug(\"Setting Station\") userid = update.message.from_user.id if self._conversations[userid]._origin is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin =", "bot, update): return ConversationHandler.END def handler_option(self, bot, update): userid = update.message.from_user.id ret_code =", "destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code = ConvStates.NUMERIC_OPTION return ret_code", "keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) logger =", "enum import Enum import logging from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import", "bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self,", "ret_code = self._h_op_do_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code = self._h_op_add_query(userid, bot,", "not in self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot, update): ret_code =", "query with index \"+str(query_index)) if len(user_queries) > query_index: query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"],", "telegramcalendar.process_calendar_selection(bot, update) if not selected: logger.debug(\"Not selected\") return ConvStates.DATE else: logger.debug(\"selected\") userid =", "update): logger.debug(\"Processing date\") selected, date = telegramcalendar.process_calendar_selection(bot, update) if not selected: logger.debug(\"Not selected\")", "ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self, userid, bot, update): user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries)", "selected\") return ConvStates.DATE else: logger.debug(\"selected\") userid = update.callback_query.from_user.id conv = self._conversations[userid] conv._date =", "query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self, bot, update): logger.debug(\"Processing", "= update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin, destination=self._conversations[userid]._dest ), reply_markup=ReplyKeyboardRemove()) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_DATE\"], reply_markup=telegramcalendar.create_calendar()) return ConvStates.DATE", "logger.debug(\"selected\") userid = update.callback_query.from_user.id conv = self._conversations[userid] conv._date = date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \"", "== 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"])))", "== BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option ==", "ConvStates.STATION def _h_op_del_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DEL_QUERY user_queries = self._RB._DB.get_user_queries(userid) ret_code", "ret_code = 0 if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else: options", "(ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import ConversationHandler from telegramcalendarkeyboard import telegramcalendar from telegramcalendarkeyboard import", "{} self._RB = renfebot def _start_conv_for_user(self, userid): if userid not in self._conversations: self._conversations[userid]", "self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot, update): ret_code = 0 userid = update.message.from_user.id username", "update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY", "OPTION = 1 STATION = 2 DATE = 3 NUMERIC_OPTION = 4 class", "self._data = None def __init__(self, renfebot): self._conversations = {} self._RB = renfebot def", "len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else: options = [] for q", "option should lead HERE!\") return ConversationHandler.END def handler_station(self, bot, update): logger.debug(\"Setting Station\") userid", "3 NUMERIC_OPTION = 4 class RenfeBotConversations: class Conversation: def __init__(self, userid): self._userid =", "logger.error(\"Problem, no other option should lead HERE!\") return ConversationHandler.END def handler_station(self, bot, update):", "0: # Not authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code", "update) else: update.message.reply_text(TEXTS[\"MAIN_OP_UNKNOWN\"]) ret_code = ConversationHandler.END return ret_code def _h_op_do_query(self, userid, bot, update):", "Not authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code = ConversationHandler.END", "text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option == BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid, conv._origin,", "bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code = ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self,", "if len(user_queries) > query_index: query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove())", "ConvStates.OPTION return ret_code def handler_cancel(self, bot, update): return ConversationHandler.END def handler_option(self, bot, update):", "res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest, conv._date) else: logger.error(\"Problem,", "= None self._data = None def __init__(self, renfebot): self._conversations = {} self._RB =", "handler_cancel(self, bot, update): return ConversationHandler.END def handler_option(self, bot, update): userid = update.message.from_user.id ret_code", "_start_conv_for_user(self, userid): if userid not in self._conversations: self._conversations[userid] = self.Conversation(userid) self._conversations[userid].reset() def handler_start(self,", "handler_start(self, bot, update): ret_code = 0 userid = update.message.from_user.id username = update.message.from_user.first_name if", "== TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code = self._h_op_do_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_ADD_QUERY\"]: ret_code =", "= BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self, userid, bot, update):", "is \" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option == BotOptions.ADD_QUERY:", "ConversationHandler.END def handler_option(self, bot, update): userid = update.message.from_user.id ret_code = 0 if update.message.text", "text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code = ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self, userid,", "date\") selected, date = telegramcalendar.process_calendar_selection(bot, update) if not selected: logger.debug(\"Not selected\") return ConvStates.DATE", "conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin,", "update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric", "one_time_keyboard=True)) return ConvStates.STATION def _h_op_add_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.ADD_QUERY update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"],", "conv._dest, conv._date) else: logger.error(\"Problem, no other option should lead HERE!\") return ConversationHandler.END def", "= logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY = 2 DO_QUERY = 3", "logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION return ret_code def", "bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self, bot, update): logger.debug(\"Processing date\") selected, date", "selected, date = telegramcalendar.process_calendar_selection(bot, update) if not selected: logger.debug(\"Not selected\") return ConvStates.DATE else:", "if self._conversations[userid]._origin is None: logger.debug(\"Origin Station\") self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return", "ADD_QUERY = 1 DEL_QUERY = 2 DO_QUERY = 3 class ConvStates(Enum): OPTION =", "return ConversationHandler.END def handler_station(self, bot, update): logger.debug(\"Setting Station\") userid = update.message.from_user.id if self._conversations[userid]._origin", "= renfebot def _start_conv_for_user(self, userid): if userid not in self._conversations: self._conversations[userid] = self.Conversation(userid)", "reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code = ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self, userid, bot,", "reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION return ret_code def handler_cancel(self, bot, update): return", "telegramoptions.process_option_selection(bot, update) if not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else:", "format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric opion\")", "format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option == BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest,", "- %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY =", "conv._option == BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif conv._option", "import logging from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import ConversationHandler from telegramcalendarkeyboard", "user_queries = self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot, update) if not selected: logger.debug(\"Nothing selected\")", "\"+str(query_index)) if len(user_queries) > query_index: query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]):", "telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import ConversationHandler from telegramcalendarkeyboard import telegramcalendar from", "texts import keyboards as KEYBOARDS logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)", "= 3 class ConvStates(Enum): OPTION = 1 STATION = 2 DATE = 3", "_h_op_do_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION", "selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting query with index \"+str(query_index)) if", "== BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res, conv._origin, conv._dest,", "logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY = 2 DO_QUERY = 3 class", "conv._origin, conv._dest, conv._date) else: logger.error(\"Problem, no other option should lead HERE!\") return ConversationHandler.END", "2 DO_QUERY = 3 class ConvStates(Enum): OPTION = 1 STATION = 2 DATE", "opion\") userid = update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot, update) if", "bot, update): logger.debug(\"Setting Station\") userid = update.message.from_user.id if self._conversations[userid]._origin is None: logger.debug(\"Origin Station\")", "if auth == 0: # Not authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot,", "update.message.reply_text(TEXTS[\"ADD_PERIODIC_QUERY\"]) update.message.reply_text(TEXTS[\"SELECT_ORIGIN_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION def _h_op_del_query(self, userid, bot, update): self._conversations[userid]._option =", "options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_TO_DETELE\"], reply_markup=telegramoptions.create_options_keyboard(options,TEXTS[\"CANCEL\"])) self._conversations[userid]._data = user_queries ret_code = ConvStates.NUMERIC_OPTION", "logger.debug(\"Not selected\") return ConvStates.DATE else: logger.debug(\"selected\") userid = update.callback_query.from_user.id conv = self._conversations[userid] conv._date", "query_index: query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return", "ret_code def _h_op_check_queries(self, userid, bot, update): user_queries = self._RB._DB.get_user_queries(userid) if len(user_queries) == 0:", "= update.message.from_user.first_name if update.message.from_user.last_name is not None: username += \" \" + update.message.from_user.last_name", "= user_queries ret_code = ConvStates.NUMERIC_OPTION return ret_code def _h_op_check_queries(self, userid, bot, update): user_queries", "= None def __init__(self, renfebot): self._conversations = {} self._RB = renfebot def _start_conv_for_user(self,", "self._origin = None self._dest = None self._date = None self._data = None def", "= self._RB._DB.get_user_queries(userid) if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries:", "logger.debug(\"Processing numeric opion\") userid = update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot,", "\" + update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username) if auth == 0: # Not", "auth == 0: # Not authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid,", "= self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot, update) if not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id=", "= date.strftime(\"%d/%m/%Y\") logger.debug(\"Date is \" + conv._date) bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if", "== TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot, update) elif update.message.text == TEXTS[\"MAIN_OP_CHECK_QUERY\"]: ret_code =", "- %(levelname)s - %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY = 1", "destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self, bot, update): logger.debug(\"Processing numeric opion\") userid", "logger.debug(\"Processing date\") selected, date = telegramcalendar.process_calendar_selection(bot, update) if not selected: logger.debug(\"Not selected\") return", "self._userid = userid self.reset() def reset(self): self._option = 0 self._origin = None self._dest", "None self._data = None def __init__(self, renfebot): self._conversations = {} self._RB = renfebot", "update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return", "else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self, bot, update): logger.debug(\"Processing date\") selected, date =", "bot, update): userid = update.message.from_user.id ret_code = 0 if update.message.text == TEXTS[\"MAIN_OP_DO_QUERY\"]: ret_code", "self._conversations[userid].reset() def handler_start(self, bot, update): ret_code = 0 userid = update.message.from_user.id username =", "= self.Conversation(userid) self._conversations[userid].reset() def handler_start(self, bot, update): ret_code = 0 userid = update.message.from_user.id", "update) elif update.message.text == TEXTS[\"MAIN_OP_DEL_QUERY\"]: ret_code = self._h_op_del_query(userid, bot, update) elif update.message.text ==", "bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_DATA\"]. format(origin=conv._origin, destination=conv._dest, date=conv._date)) if conv._option == BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid,", "else: # Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup( KEYBOARDS[\"MAIN_OPTIONS\"]), one_time_keyboard=True) ret_code = ConvStates.OPTION", "> query_index: query = user_queries[query_index] if self._RB._DB.remove_periodic_query(query[\"userid\"], query[\"origin\"], query[\"destination\"], query[\"date\"]): bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_REMOVED\"],reply_markup=ReplyKeyboardRemove()) else: bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove())", "username += \" \" + update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username) if auth ==", "not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting query with", "- %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY", "= update.callback_query.from_user.id user_queries = self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot, update) if not selected:", "logger = logging.getLogger(__name__) class BotOptions(Enum): ADD_QUERY = 1 DEL_QUERY = 2 DO_QUERY =", "not selected: logger.debug(\"Not selected\") return ConvStates.DATE else: logger.debug(\"selected\") userid = update.callback_query.from_user.id conv =", "class RenfeBotConversations: class Conversation: def __init__(self, userid): self._userid = userid self.reset() def reset(self):", "bot.send_message(chat_id=userid,text=res[1]) elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid,", "if conv._option == BotOptions.ADD_QUERY: res = self._RB._DB.add_periodic_query( userid, conv._origin, conv._dest, conv._date) bot.send_message(chat_id=userid,text=res[1]) elif", "elif conv._option == BotOptions.DO_QUERY: bot.send_message(chat_id=userid,text=TEXTS[\"WAIT_FOR_TRAINS\"]) res = self._RB._RF.check_trip(conv._origin, conv._dest, conv._date) self._RB.send_query_results_to_user(bot, userid, res,", "__init__(self, userid): self._userid = userid self.reset() def reset(self): self._option = 0 self._origin =", "self._conversations[userid]._data selected, query_index = telegramoptions.process_option_selection(bot, update) if not selected: logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid,", "logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin, destination=self._conversations[userid]._dest ), reply_markup=ReplyKeyboardRemove()) bot.send_message(chat_id=userid, text=TEXTS[\"SELECT_TRIP_DATE\"],", "0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) ret_code = ConversationHandler.END else: options = [] for q in user_queries:", "if len(user_queries) == 0: update.message.reply_text(TEXTS[\"NO_QUERIES_FOR_USERID\"]) else: update.message.reply_text(TEXTS[\"QUERIES_FOR_USERID\"]) for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"],", "userid, username) ret_code = ConversationHandler.END else: # Authorized logger.debug(\"AUTHORIZED USER\") self._start_conv_for_user(userid) update.message.reply_text(TEXTS[\"OPTION_SELECTION\"], reply_markup=ReplyKeyboardMarkup(", "self._conversations[userid]._origin = update.message.text.upper() update.message.reply_text(TEXTS[\"SELECT_DESTINATION_STATION\"], reply_markup=ReplyKeyboardMarkup(KEYBOARDS[\"STATIONS\"], one_time_keyboard=True)) return ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest =", "= ConversationHandler.END else: options = [] for q in user_queries: options.append(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"],", "reset(self): self._option = 0 self._origin = None self._dest = None self._date = None", "= ConversationHandler.END return ret_code def _h_op_do_query(self, userid, bot, update): self._conversations[userid]._option = BotOptions.DO_QUERY update.message.reply_text(TEXTS[\"DO_ONETIME_QUERY\"])", "= None self._date = None self._data = None def __init__(self, renfebot): self._conversations =", "# Not authorized logger.debug(\"NOT AUTHORIZED USER\") update.message.reply_text(TEXTS[\"NOT_AUTH_REPLY\"].format(username=username), reply_markup=ReplyKeyboardRemove()) self._RB.ask_admin_for_access(bot, userid, username) ret_code =", "Conversation: def __init__(self, userid): self._userid = userid self.reset() def reset(self): self._option = 0", "logger.debug(\"Nothing selected\") bot.send_message(chat_id= userid, text=TEXTS[\"DB_QUERY_NOT_REMOVED\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: logger.debug(\"Deleting query with index \"+str(query_index))", "ConvStates.STATION else: logger.debug(\"Destination Station\") self._conversations[userid]._dest = update.message.text.upper() bot.send_message(chat_id=userid, text=TEXTS[\"SELECTED_TRIP\"].format( origin=self._conversations[userid]._origin, destination=self._conversations[userid]._dest ), reply_markup=ReplyKeyboardRemove())", "= {} self._RB = renfebot def _start_conv_for_user(self, userid): if userid not in self._conversations:", "+= \" \" + update.message.from_user.last_name auth = self._RB._DB.get_user_auth(userid, username) if auth == 0:", "bot.send_message(chat_id=userid,text=TEXTS[\"DB_QUERY_NOT_PRESENT\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_date(self, bot, update): logger.debug(\"Processing date\") selected, date = telegramcalendar.process_calendar_selection(bot,", "for q in user_queries: update.message.reply_text(TEXTS[\"QUERY_IN_DB\"]. format(origin=q[\"origin\"], destination=q[\"destination\"], date=self._RB._DB.timestamp_to_date(q[\"date\"]))) update.message.reply_text(TEXTS[\"END_MESSAGE\"],reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def handler_numeric_option(self," ]
[ "file(s). # This too relies on a convention on the file names linking", "changes every time the core files are recreated. Should I commit the core", "import TestSuite as ts LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line(): parser = argparse.ArgumentParser(description='Utility to", "in changes: result_lines.append(line) if len(result_lines) > 0: print \" #################### FAIL ####################\" for", "are recreated. Should I commit the core files and the binaries in the", "args.test_case is None: test_list = ts.find_test_cases() else: test_list = [args.test_case] print \"Tests to", "print line, print \" ##############################################\" def generic_addresses(dot_content): \"\"\"The stack changes every time the", "+ \"_result.dot\") with open(expected_result_file) as f: expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f:", "Test rig to do tests on the completed machinery. # Runs GDB on", "\"\"\"Compares the expected and actual results. Prints the diff in case of error,", "expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with open(expected_result_file) as f: expected = f.readlines()", "dirs, files in os.walk(ts.CORES_FOLDER): for file in files: if file.startswith(test_name): return os.path.join(subdir, file)", "are listed in the CMakeList.txt in' ' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 -", "else: filtered_line += part filtered_result.append(filtered_line) return filtered_result def run_test(test_name): \"\"\"Calls gdb with our", "# Test rig to do tests on the completed machinery. # Runs GDB", "in the CMakeList.txt in' ' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)", "def parse_command_line(): parser = argparse.ArgumentParser(description='Utility to quickly run the full stack test cases.", "address_counter += 1 else: filtered_line += part filtered_result.append(filtered_line) return filtered_result def run_test(test_name): \"\"\"Calls", "\"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ == \"__main__\": args = parse_command_line() if", "only the specified test case. Runs everything if not provided (None).\", required=False) return", "\"_result.dot\") with open(expected_result_file) as f: expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual", "if replacement is None: replacement = \"0xAddress_\" + str(address_counter) address_translation[part] = replacement filtered_line", "wish I knew. For now, I replace the addresses with \"generics\".\"\"\" address_translation =", "output.\"\"\" core_file = find_core_file(test_name) if core_file is None: raise Exception(\"No core file for", "replace the addresses with \"generics\".\"\"\" address_translation = {} address = re.compile(\"(0x[0-9a-f]+)\") address_counter =", "\"__main__\": args = parse_command_line() if args.test_case is None: test_list = ts.find_test_cases() else: test_list", "file with the same name as the test case.\"\"\" for subdir, dirs, files", "too relies on a convention on the file names linking test cases, expected", "expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual = f.readlines() expected = generic_addresses(expected)", "\"0xAddress_\" + str(address_counter) address_translation[part] = replacement filtered_line += replacement address_counter += 1 else:", "len(result_lines) > 0: print \" #################### FAIL ####################\" for line in result_lines: print", "\"\"\"The stack changes every time the core files are recreated. Should I commit", "exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name)", "in result_lines: print line, print \" ##############################################\" def generic_addresses(dot_content): \"\"\"The stack changes every", "test result with what # is stored in the <test case name>_result.txt file(s).", "if len(result_lines) > 0: print \" #################### FAIL ####################\" for line in result_lines:", "argparse import difflib import os import re import subprocess import TestSuite as ts", "the addresses with \"generics\".\"\"\" address_translation = {} address = re.compile(\"(0x[0-9a-f]+)\") address_counter = 0", "None: raise Exception(\"No core file for \" + test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name)", "completed machinery. # Runs GDB on one (or all) test core files and", "is None: test_list = ts.find_test_cases() else: test_list = [args.test_case] print \"Tests to run", "[] for line in dot_content: parts = address.split(line) filtered_line = \"\" for part", "commit the core files and the binaries in the repo? Or should I", "case.\"\"\" for subdir, dirs, files in os.walk(ts.CORES_FOLDER): for file in files: if file.startswith(test_name):", "+= 1 else: filtered_line += part filtered_result.append(filtered_line) return filtered_result def run_test(test_name): \"\"\"Calls gdb", "2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the specified test case. Runs", "stack changes every time the core files are recreated. Should I commit the", "= \"FullStackTest.log\" def parse_command_line(): parser = argparse.ArgumentParser(description='Utility to quickly run the full stack", "LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ == \"__main__\": args = parse_command_line() if args.test_case", "line in dot_content: parts = address.split(line) filtered_line = \"\" for part in parts:", "For now, I replace the addresses with \"generics\".\"\"\" address_translation = {} address =", "the file naming conventions.' 'Test cases are listed in the CMakeList.txt in' '", "re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result = [] for line in dot_content: parts =", "' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only", "result_lines.append(line) if len(result_lines) > 0: print \" #################### FAIL ####################\" for line in", "the file names linking test cases, expected results, executables and core files. import", "with the expected output.\"\"\" core_file = find_core_file(test_name) if core_file is None: raise Exception(\"No", "file names linking test cases, expected results, executables and core files. import argparse", "{} address = re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result = [] for line in", "# This too relies on a convention on the file names linking test", "name>_result.txt file(s). # This too relies on a convention on the file names", "quickly run the full stack test cases. ' 'Run CreateTestCores.py first.' 'Stick to", "specified test case. Runs everything if not provided (None).\", required=False) return parser.parse_args() def", "'Test cases are listed in the CMakeList.txt in' ' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C)", "raise Exception(\"No core file for \" + test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\",", "changes: result_lines.append(line) if len(result_lines) > 0: print \" #################### FAIL ####################\" for line", "address.split(line) filtered_line = \"\" for part in parts: if re.match(address, part): replacement =", "I \"wildcard\" the addresses? Or abandon this way of testing? ...I wish I", "import difflib import os import re import subprocess import TestSuite as ts LOGS_FOR_TESTS", "= \"0xAddress_\" + str(address_counter) address_translation[part] = replacement filtered_line += replacement address_counter += 1", "= {} address = re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result = [] for line", "None: test_list = ts.find_test_cases() else: test_list = [args.test_case] print \"Tests to run \"", "> 0: print \" #################### FAIL ####################\" for line in result_lines: print line,", "expected results, executables and core files. import argparse import difflib import os import", "compare the test result with what # is stored in the <test case", "on a convention on the file names linking test cases, expected results, executables", "if re.match(address, part): replacement = address_translation.get(part) if replacement is None: replacement = \"0xAddress_\"", "is None: replacement = \"0xAddress_\" + str(address_counter) address_translation[part] = replacement filtered_line += replacement", "line, print \" ##############################################\" def generic_addresses(dot_content): \"\"\"The stack changes every time the core", "0 filtered_result = [] for line in dot_content: parts = address.split(line) filtered_line =", "tests on the completed machinery. # Runs GDB on one (or all) test", "the test case.\"\"\" for subdir, dirs, files in os.walk(ts.CORES_FOLDER): for file in files:", "= 0 filtered_result = [] for line in dot_content: parts = address.split(line) filtered_line", "results, executables and core files. import argparse import difflib import os import re", "tofile='RESULT_FROM_TEST', lineterm='') result_lines = [] for line in changes: result_lines.append(line) if len(result_lines) >", "what # is stored in the <test case name>_result.txt file(s). # This too", "machinery. # Runs GDB on one (or all) test core files and compare", "fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines = [] for line in changes: result_lines.append(line) if len(result_lines)", "address_translation = {} address = re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result = [] for", "in files: if file.startswith(test_name): return os.path.join(subdir, file) return None def assert_result(test_name): \"\"\"Compares the", "all) test core files and compare the test result with what # is", "in dot_content: parts = address.split(line) filtered_line = \"\" for part in parts: if", "'Run CreateTestCores.py first.' 'Stick to the file naming conventions.' 'Test cases are listed", "[args.test_case] print \"Tests to run \" + str(test_list) for test_case in test_list: run_test(test_case)", "+= part filtered_result.append(filtered_line) return filtered_result def run_test(test_name): \"\"\"Calls gdb with our driver and", "== \"__main__\": args = parse_command_line() if args.test_case is None: test_list = ts.find_test_cases() else:", "and core files. import argparse import difflib import os import re import subprocess", "core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ == \"__main__\": args =", "\"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ == \"__main__\": args = parse_command_line() if args.test_case is", "import subprocess import TestSuite as ts LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line(): parser =", "the CMakeList.txt in' ' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\",", "help=\"Runs only the specified test case. Runs everything if not provided (None).\", required=False)", "0: print \" #################### FAIL ####################\" for line in result_lines: print line, print", "the same name as the test case.\"\"\" for subdir, dirs, files in os.walk(ts.CORES_FOLDER):", "test case. Runs everything if not provided (None).\", required=False) return parser.parse_args() def find_core_file(test_name):", "cases. ' 'Run CreateTestCores.py first.' 'Stick to the file naming conventions.' 'Test cases", "in parts: if re.match(address, part): replacement = address_translation.get(part) if replacement is None: replacement", "def run_test(test_name): \"\"\"Calls gdb with our driver and compares the result with the", "= \"\" for part in parts: if re.match(address, part): replacement = address_translation.get(part) if", "\"--test_case\", help=\"Runs only the specified test case. Runs everything if not provided (None).\",", "def assert_result(test_name): \"\"\"Compares the expected and actual results. Prints the diff in case", "file for \" + test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file,", "the full stack test cases. ' 'Run CreateTestCores.py first.' 'Stick to the file", "= os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if", "find_core_file(test_name): \"\"\"Walks the test directory to detect a core file with the same", "test case.\"\"\" for subdir, dirs, files in os.walk(ts.CORES_FOLDER): for file in files: if", "result with the expected output.\"\"\" core_file = find_core_file(test_name) if core_file is None: raise", "the diff in case of error, nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name +", "return parser.parse_args() def find_core_file(test_name): \"\"\"Walks the test directory to detect a core file", "os import re import subprocess import TestSuite as ts LOGS_FOR_TESTS = \"FullStackTest.log\" def", "the repo? Or should I \"wildcard\" the addresses? Or abandon this way of", "core file for \" + test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file,", "to do tests on the completed machinery. # Runs GDB on one (or", "of error, nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with open(expected_result_file) as", "I replace the addresses with \"generics\".\"\"\" address_translation = {} address = re.compile(\"(0x[0-9a-f]+)\") address_counter", "in os.walk(ts.CORES_FOLDER): for file in files: if file.startswith(test_name): return os.path.join(subdir, file) return None", "\"generics\".\"\"\" address_translation = {} address = re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result = []", "with what # is stored in the <test case name>_result.txt file(s). # This", "actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines = [] for line in changes: result_lines.append(line) if", "first.' 'Stick to the file naming conventions.' 'Test cases are listed in the", "ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the specified test", "' 'Run CreateTestCores.py first.' 'Stick to the file naming conventions.' 'Test cases are", "assert_result(test_name) if __name__ == \"__main__\": args = parse_command_line() if args.test_case is None: test_list", "open(os.path.abspath(\"RememberOutput.dot\")) as f: actual = f.readlines() expected = generic_addresses(expected) actual = generic_addresses(actual) changes", "naming conventions.' 'Test cases are listed in the CMakeList.txt in' ' ' +", "the completed machinery. # Runs GDB on one (or all) test core files", "testing? ...I wish I knew. For now, I replace the addresses with \"generics\".\"\"\"", "filtered_result.append(filtered_line) return filtered_result def run_test(test_name): \"\"\"Calls gdb with our driver and compares the", "the test result with what # is stored in the <test case name>_result.txt", "executables and core files. import argparse import difflib import os import re import", "to the file naming conventions.' 'Test cases are listed in the CMakeList.txt in'", "actual = f.readlines() expected = generic_addresses(expected) actual = generic_addresses(actual) changes = difflib.unified_diff(expected, actual,", "subdir, dirs, files in os.walk(ts.CORES_FOLDER): for file in files: if file.startswith(test_name): return os.path.join(subdir,", "re import subprocess import TestSuite as ts LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line(): parser", "if __name__ == \"__main__\": args = parse_command_line() if args.test_case is None: test_list =", "parse_command_line(): parser = argparse.ArgumentParser(description='Utility to quickly run the full stack test cases. '", "changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines = [] for line in", "= parse_command_line() if args.test_case is None: test_list = ts.find_test_cases() else: test_list = [args.test_case]", "run_test(test_name): \"\"\"Calls gdb with our driver and compares the result with the expected", "def generic_addresses(dot_content): \"\"\"The stack changes every time the core files are recreated. Should", "def find_core_file(test_name): \"\"\"Walks the test directory to detect a core file with the", "= re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result = [] for line in dot_content: parts", "address = re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result = [] for line in dot_content:", "dot_content: parts = address.split(line) filtered_line = \"\" for part in parts: if re.match(address,", "one (or all) test core files and compare the test result with what", "gdb with our driver and compares the result with the expected output.\"\"\" core_file", "test cases, expected results, executables and core files. import argparse import difflib import", "####################\" for line in result_lines: print line, print \" ##############################################\" def generic_addresses(dot_content): \"\"\"The", "address_translation[part] = replacement filtered_line += replacement address_counter += 1 else: filtered_line += part", "now, I replace the addresses with \"generics\".\"\"\" address_translation = {} address = re.compile(\"(0x[0-9a-f]+)\")", "(or all) test core files and compare the test result with what #", "result with what # is stored in the <test case name>_result.txt file(s). #", "for subdir, dirs, files in os.walk(ts.CORES_FOLDER): for file in files: if file.startswith(test_name): return", "a core file with the same name as the test case.\"\"\" for subdir,", "to quickly run the full stack test cases. ' 'Run CreateTestCores.py first.' 'Stick", "= address_translation.get(part) if replacement is None: replacement = \"0xAddress_\" + str(address_counter) address_translation[part] =", "= generic_addresses(expected) actual = generic_addresses(actual) changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines", "# Runs GDB on one (or all) test core files and compare the", "our driver and compares the result with the expected output.\"\"\" core_file = find_core_file(test_name)", "file) return None def assert_result(test_name): \"\"\"Compares the expected and actual results. Prints the", "os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with open(expected_result_file) as f: expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\"))", "None: replacement = \"0xAddress_\" + str(address_counter) address_translation[part] = replacement filtered_line += replacement address_counter", "line in changes: result_lines.append(line) if len(result_lines) > 0: print \" #################### FAIL ####################\"", "if core_file is None: raise Exception(\"No core file for \" + test_name) exeutable_file", "<test case name>_result.txt file(s). # This too relies on a convention on the", "if args.test_case is None: test_list = ts.find_test_cases() else: test_list = [args.test_case] print \"Tests", "address_counter = 0 filtered_result = [] for line in dot_content: parts = address.split(line)", "this way of testing? ...I wish I knew. For now, I replace the", "core file with the same name as the test case.\"\"\" for subdir, dirs,", "name as the test case.\"\"\" for subdir, dirs, files in os.walk(ts.CORES_FOLDER): for file", "and the binaries in the repo? Or should I \"wildcard\" the addresses? Or", "f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual = f.readlines() expected = generic_addresses(expected) actual =", "binaries in the repo? Or should I \"wildcard\" the addresses? Or abandon this", "the core files and the binaries in the repo? Or should I \"wildcard\"", "ts.find_test_cases() else: test_list = [args.test_case] print \"Tests to run \" + str(test_list) for", "= address.split(line) filtered_line = \"\" for part in parts: if re.match(address, part): replacement", "part in parts: if re.match(address, part): replacement = address_translation.get(part) if replacement is None:", "# is stored in the <test case name>_result.txt file(s). # This too relies", "' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the", "same name as the test case.\"\"\" for subdir, dirs, files in os.walk(ts.CORES_FOLDER): for", "part filtered_result.append(filtered_line) return filtered_result def run_test(test_name): \"\"\"Calls gdb with our driver and compares", "test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"])", "filtered_line += replacement address_counter += 1 else: filtered_line += part filtered_result.append(filtered_line) return filtered_result", "replacement filtered_line += replacement address_counter += 1 else: filtered_line += part filtered_result.append(filtered_line) return", "return None def assert_result(test_name): \"\"\"Compares the expected and actual results. Prints the diff", "the result with the expected output.\"\"\" core_file = find_core_file(test_name) if core_file is None:", "test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ ==", "for part in parts: if re.match(address, part): replacement = address_translation.get(part) if replacement is", "parser.parse_args() def find_core_file(test_name): \"\"\"Walks the test directory to detect a core file with", "difflib import os import re import subprocess import TestSuite as ts LOGS_FOR_TESTS =", "the expected and actual results. Prints the diff in case of error, nothing", "I commit the core files and the binaries in the repo? Or should", "in the repo? Or should I \"wildcard\" the addresses? Or abandon this way", "listed in the CMakeList.txt in' ' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\",", "case name>_result.txt file(s). # This too relies on a convention on the file", "else: test_list = [args.test_case] print \"Tests to run \" + str(test_list) for test_case", "<reponame>stefanos-86/Remember<gh_stars>1-10 # Test rig to do tests on the completed machinery. # Runs", "= os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with open(expected_result_file) as f: expected = f.readlines() with", "result_lines = [] for line in changes: result_lines.append(line) if len(result_lines) > 0: print", "results. Prints the diff in case of error, nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER,", "os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__", "case of error, nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with open(expected_result_file)", "ts LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line(): parser = argparse.ArgumentParser(description='Utility to quickly run the", "linking test cases, expected results, executables and core files. import argparse import difflib", "as f: actual = f.readlines() expected = generic_addresses(expected) actual = generic_addresses(actual) changes =", "and actual results. Prints the diff in case of error, nothing otherwise.\"\"\" expected_result_file", "print \" #################### FAIL ####################\" for line in result_lines: print line, print \"", "address_translation.get(part) if replacement is None: replacement = \"0xAddress_\" + str(address_counter) address_translation[part] = replacement", "= replacement filtered_line += replacement address_counter += 1 else: filtered_line += part filtered_result.append(filtered_line)", "= argparse.ArgumentParser(description='Utility to quickly run the full stack test cases. ' 'Run CreateTestCores.py", "files and compare the test result with what # is stored in the", "\"\"\"Calls gdb with our driver and compares the result with the expected output.\"\"\"", "addresses with \"generics\".\"\"\" address_translation = {} address = re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result", "with the same name as the test case.\"\"\" for subdir, dirs, files in", "actual = generic_addresses(actual) changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines = []", "+ str(address_counter) address_translation[part] = replacement filtered_line += replacement address_counter += 1 else: filtered_line", "line in result_lines: print line, print \" ##############################################\" def generic_addresses(dot_content): \"\"\"The stack changes", "in' ' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs", "+ test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\",", "result_lines: print line, print \" ##############################################\" def generic_addresses(dot_content): \"\"\"The stack changes every time", "files. import argparse import difflib import os import re import subprocess import TestSuite", "I knew. For now, I replace the addresses with \"generics\".\"\"\" address_translation = {}", "with our driver and compares the result with the expected output.\"\"\" core_file =", "on the file names linking test cases, expected results, executables and core files.", "+ ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the specified", "difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines = [] for line in changes: result_lines.append(line)", "files in os.walk(ts.CORES_FOLDER): for file in files: if file.startswith(test_name): return os.path.join(subdir, file) return", "(None).\", required=False) return parser.parse_args() def find_core_file(test_name): \"\"\"Walks the test directory to detect a", "Exception(\"No core file for \" + test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\",", "#################### FAIL ####################\" for line in result_lines: print line, print \" ##############################################\" def", "do tests on the completed machinery. # Runs GDB on one (or all)", "test directory to detect a core file with the same name as the", "args = parse_command_line() if args.test_case is None: test_list = ts.find_test_cases() else: test_list =", "import argparse import difflib import os import re import subprocess import TestSuite as", "parts = address.split(line) filtered_line = \"\" for part in parts: if re.match(address, part):", "replacement address_counter += 1 else: filtered_line += part filtered_result.append(filtered_line) return filtered_result def run_test(test_name):", "files and the binaries in the repo? Or should I \"wildcard\" the addresses?", "with open(expected_result_file) as f: expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual =", "\"FullStackTest.log\" def parse_command_line(): parser = argparse.ArgumentParser(description='Utility to quickly run the full stack test", "files are recreated. Should I commit the core files and the binaries in", "as ts LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line(): parser = argparse.ArgumentParser(description='Utility to quickly run", "expected and actual results. Prints the diff in case of error, nothing otherwise.\"\"\"", "way of testing? ...I wish I knew. For now, I replace the addresses", "- Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the specified test case. Runs everything", "as the test case.\"\"\" for subdir, dirs, files in os.walk(ts.CORES_FOLDER): for file in", "test_list = [args.test_case] print \"Tests to run \" + str(test_list) for test_case in", "parser = argparse.ArgumentParser(description='Utility to quickly run the full stack test cases. ' 'Run", "TestSuite as ts LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line(): parser = argparse.ArgumentParser(description='Utility to quickly", "generic_addresses(actual) changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines = [] for line", "core files. import argparse import difflib import os import re import subprocess import", "1 else: filtered_line += part filtered_result.append(filtered_line) return filtered_result def run_test(test_name): \"\"\"Calls gdb with", "filtered_line = \"\" for part in parts: if re.match(address, part): replacement = address_translation.get(part)", "repo? Or should I \"wildcard\" the addresses? Or abandon this way of testing?", "CMakeList.txt in' ' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\",", "and compares the result with the expected output.\"\"\" core_file = find_core_file(test_name) if core_file", "with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual = f.readlines() expected = generic_addresses(expected) actual = generic_addresses(actual)", "driver and compares the result with the expected output.\"\"\" core_file = find_core_file(test_name) if", "convention on the file names linking test cases, expected results, executables and core", "provided (None).\", required=False) return parser.parse_args() def find_core_file(test_name): \"\"\"Walks the test directory to detect", "\"\"\"Walks the test directory to detect a core file with the same name", "\"\" for part in parts: if re.match(address, part): replacement = address_translation.get(part) if replacement", "expected output.\"\"\" core_file = find_core_file(test_name) if core_file is None: raise Exception(\"No core file", "formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the specified test case. Runs everything if not", "replacement is None: replacement = \"0xAddress_\" + str(address_counter) address_translation[part] = replacement filtered_line +=", "compares the result with the expected output.\"\"\" core_file = find_core_file(test_name) if core_file is", "for line in dot_content: parts = address.split(line) filtered_line = \"\" for part in", "the specified test case. Runs everything if not provided (None).\", required=False) return parser.parse_args()", "cases, expected results, executables and core files. import argparse import difflib import os", "...I wish I knew. For now, I replace the addresses with \"generics\".\"\"\" address_translation", "the expected output.\"\"\" core_file = find_core_file(test_name) if core_file is None: raise Exception(\"No core", "rig to do tests on the completed machinery. # Runs GDB on one", "filtered_line += part filtered_result.append(filtered_line) return filtered_result def run_test(test_name): \"\"\"Calls gdb with our driver", "filtered_result = [] for line in dot_content: parts = address.split(line) filtered_line = \"\"", "LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line(): parser = argparse.ArgumentParser(description='Utility to quickly run the full", "= [] for line in dot_content: parts = address.split(line) filtered_line = \"\" for", "conventions.' 'Test cases are listed in the CMakeList.txt in' ' ' + ts.TEST_PROGRAMS_FOLDER,", "for \" + test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\",", "os.path.join(subdir, file) return None def assert_result(test_name): \"\"\"Compares the expected and actual results. Prints", "the test directory to detect a core file with the same name as", "nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with open(expected_result_file) as f: expected", "Or should I \"wildcard\" the addresses? Or abandon this way of testing? ...I", "names linking test cases, expected results, executables and core files. import argparse import", "expected = generic_addresses(expected) actual = generic_addresses(actual) changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='')", "run the full stack test cases. ' 'Run CreateTestCores.py first.' 'Stick to the", "subprocess import TestSuite as ts LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line(): parser = argparse.ArgumentParser(description='Utility", "Prints the diff in case of error, nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name", "CreateTestCores.py first.' 'Stick to the file naming conventions.' 'Test cases are listed in", "otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with open(expected_result_file) as f: expected =", "in the <test case name>_result.txt file(s). # This too relies on a convention", "Or abandon this way of testing? ...I wish I knew. For now, I", "assert_result(test_name): \"\"\"Compares the expected and actual results. Prints the diff in case of", "stack test cases. ' 'Run CreateTestCores.py first.' 'Stick to the file naming conventions.'", "= find_core_file(test_name) if core_file is None: raise Exception(\"No core file for \" +", "open(expected_result_file) as f: expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual = f.readlines()", "argparse.ArgumentParser(description='Utility to quickly run the full stack test cases. ' 'Run CreateTestCores.py first.'", "core files and compare the test result with what # is stored in", "import re import subprocess import TestSuite as ts LOGS_FOR_TESTS = \"FullStackTest.log\" def parse_command_line():", "= ts.find_test_cases() else: test_list = [args.test_case] print \"Tests to run \" + str(test_list)", "Should I commit the core files and the binaries in the repo? Or", "is stored in the <test case name>_result.txt file(s). # This too relies on", "Runs GDB on one (or all) test core files and compare the test", "for line in changes: result_lines.append(line) if len(result_lines) > 0: print \" #################### FAIL", "= generic_addresses(actual) changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines = [] for", "for file in files: if file.startswith(test_name): return os.path.join(subdir, file) return None def assert_result(test_name):", "test_name + \"_result.dot\") with open(expected_result_file) as f: expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as", "= f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual = f.readlines() expected = generic_addresses(expected) actual", "test core files and compare the test result with what # is stored", "the binaries in the repo? Or should I \"wildcard\" the addresses? Or abandon", "= difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines = [] for line in changes:", "f: actual = f.readlines() expected = generic_addresses(expected) actual = generic_addresses(actual) changes = difflib.unified_diff(expected,", "GDB on one (or all) test core files and compare the test result", "on one (or all) test core files and compare the test result with", "file.startswith(test_name): return os.path.join(subdir, file) return None def assert_result(test_name): \"\"\"Compares the expected and actual", "recreated. Should I commit the core files and the binaries in the repo?", "time the core files are recreated. Should I commit the core files and", "core_file = find_core_file(test_name) if core_file is None: raise Exception(\"No core file for \"", "stored in the <test case name>_result.txt file(s). # This too relies on a", "None def assert_result(test_name): \"\"\"Compares the expected and actual results. Prints the diff in", "and compare the test result with what # is stored in the <test", "everything if not provided (None).\", required=False) return parser.parse_args() def find_core_file(test_name): \"\"\"Walks the test", "\" ##############################################\" def generic_addresses(dot_content): \"\"\"The stack changes every time the core files are", "test_list = ts.find_test_cases() else: test_list = [args.test_case] print \"Tests to run \" +", "if not provided (None).\", required=False) return parser.parse_args() def find_core_file(test_name): \"\"\"Walks the test directory", "filtered_result def run_test(test_name): \"\"\"Calls gdb with our driver and compares the result with", "full stack test cases. ' 'Run CreateTestCores.py first.' 'Stick to the file naming", "not provided (None).\", required=False) return parser.parse_args() def find_core_file(test_name): \"\"\"Walks the test directory to", "\"wildcard\" the addresses? Or abandon this way of testing? ...I wish I knew.", "to detect a core file with the same name as the test case.\"\"\"", "for line in result_lines: print line, print \" ##############################################\" def generic_addresses(dot_content): \"\"\"The stack", "case. Runs everything if not provided (None).\", required=False) return parser.parse_args() def find_core_file(test_name): \"\"\"Walks", "actual results. Prints the diff in case of error, nothing otherwise.\"\"\" expected_result_file =", "the addresses? Or abandon this way of testing? ...I wish I knew. For", "str(address_counter) address_translation[part] = replacement filtered_line += replacement address_counter += 1 else: filtered_line +=", "files: if file.startswith(test_name): return os.path.join(subdir, file) return None def assert_result(test_name): \"\"\"Compares the expected", "cases are listed in the CMakeList.txt in' ' ' + ts.TEST_PROGRAMS_FOLDER, epilog=\"(C) 2017", "generic_addresses(expected) actual = generic_addresses(actual) changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST', lineterm='') result_lines =", "print \" ##############################################\" def generic_addresses(dot_content): \"\"\"The stack changes every time the core files", "as f: expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual = f.readlines() expected", "part): replacement = address_translation.get(part) if replacement is None: replacement = \"0xAddress_\" + str(address_counter)", "subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ == \"__main__\":", "the <test case name>_result.txt file(s). # This too relies on a convention on", "find_core_file(test_name) if core_file is None: raise Exception(\"No core file for \" + test_name)", "parse_command_line() if args.test_case is None: test_list = ts.find_test_cases() else: test_list = [args.test_case] print", "test cases. ' 'Run CreateTestCores.py first.' 'Stick to the file naming conventions.' 'Test", "\" #################### FAIL ####################\" for line in result_lines: print line, print \" ##############################################\"", "on the completed machinery. # Runs GDB on one (or all) test core", "error, nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with open(expected_result_file) as f:", "abandon this way of testing? ...I wish I knew. For now, I replace", "This too relies on a convention on the file names linking test cases,", "addresses? Or abandon this way of testing? ...I wish I knew. For now,", "= [] for line in changes: result_lines.append(line) if len(result_lines) > 0: print \"", "relies on a convention on the file names linking test cases, expected results,", "should I \"wildcard\" the addresses? Or abandon this way of testing? ...I wish", "+= replacement address_counter += 1 else: filtered_line += part filtered_result.append(filtered_line) return filtered_result def", "return filtered_result def run_test(test_name): \"\"\"Calls gdb with our driver and compares the result", "re.match(address, part): replacement = address_translation.get(part) if replacement is None: replacement = \"0xAddress_\" +", "file naming conventions.' 'Test cases are listed in the CMakeList.txt in' ' '", "with \"generics\".\"\"\" address_translation = {} address = re.compile(\"(0x[0-9a-f]+)\") address_counter = 0 filtered_result =", "\"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ == \"__main__\": args", "= [args.test_case] print \"Tests to run \" + str(test_list) for test_case in test_list:", "the core files are recreated. Should I commit the core files and the", "\"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ == \"__main__\": args = parse_command_line() if args.test_case is None:", "parts: if re.match(address, part): replacement = address_translation.get(part) if replacement is None: replacement =", "import os import re import subprocess import TestSuite as ts LOGS_FOR_TESTS = \"FullStackTest.log\"", "required=False) return parser.parse_args() def find_core_file(test_name): \"\"\"Walks the test directory to detect a core", "##############################################\" def generic_addresses(dot_content): \"\"\"The stack changes every time the core files are recreated.", "generic_addresses(dot_content): \"\"\"The stack changes every time the core files are recreated. Should I", "diff in case of error, nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\")", "directory to detect a core file with the same name as the test", "replacement = \"0xAddress_\" + str(address_counter) address_translation[part] = replacement filtered_line += replacement address_counter +=", "= f.readlines() expected = generic_addresses(expected) actual = generic_addresses(actual) changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file',", "parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the specified test case. Runs everything if not provided", "__name__ == \"__main__\": args = parse_command_line() if args.test_case is None: test_list = ts.find_test_cases()", "is None: raise Exception(\"No core file for \" + test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER,", "return os.path.join(subdir, file) return None def assert_result(test_name): \"\"\"Compares the expected and actual results.", "f.readlines() expected = generic_addresses(expected) actual = generic_addresses(actual) changes = difflib.unified_diff(expected, actual, fromfile='expected_result_file', tofile='RESULT_FROM_TEST',", "core files are recreated. Should I commit the core files and the binaries", "every time the core files are recreated. Should I commit the core files", "file in files: if file.startswith(test_name): return os.path.join(subdir, file) return None def assert_result(test_name): \"\"\"Compares", "lineterm='') result_lines = [] for line in changes: result_lines.append(line) if len(result_lines) > 0:", "\" + test_name) exeutable_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name) subprocess.call([\"python\", \"remember.py\", core_file, exeutable_file, \"-l\", LOGS_FOR_TESTS,", "'Stick to the file naming conventions.' 'Test cases are listed in the CMakeList.txt", "os.walk(ts.CORES_FOLDER): for file in files: if file.startswith(test_name): return os.path.join(subdir, file) return None def", "if file.startswith(test_name): return os.path.join(subdir, file) return None def assert_result(test_name): \"\"\"Compares the expected and", "detect a core file with the same name as the test case.\"\"\" for", "in case of error, nothing otherwise.\"\"\" expected_result_file = os.path.join(ts.TEST_PROGRAMS_FOLDER, test_name + \"_result.dot\") with", "of testing? ...I wish I knew. For now, I replace the addresses with", "a convention on the file names linking test cases, expected results, executables and", "Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the specified test case. Runs everything if", "FAIL ####################\" for line in result_lines: print line, print \" ##############################################\" def generic_addresses(dot_content):", "core_file is None: raise Exception(\"No core file for \" + test_name) exeutable_file =", "epilog=\"(C) 2017 - Stefano\", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument(\"-t\", \"--test_case\", help=\"Runs only the specified test case.", "replacement = address_translation.get(part) if replacement is None: replacement = \"0xAddress_\" + str(address_counter) address_translation[part]", "f: expected = f.readlines() with open(os.path.abspath(\"RememberOutput.dot\")) as f: actual = f.readlines() expected =", "core files and the binaries in the repo? Or should I \"wildcard\" the", "Runs everything if not provided (None).\", required=False) return parser.parse_args() def find_core_file(test_name): \"\"\"Walks the", "exeutable_file, \"-l\", LOGS_FOR_TESTS, \"-o\", \"GraphFromLastTest.svg\"]) assert_result(test_name) if __name__ == \"__main__\": args = parse_command_line()", "knew. For now, I replace the addresses with \"generics\".\"\"\" address_translation = {} address", "[] for line in changes: result_lines.append(line) if len(result_lines) > 0: print \" ####################" ]
[ "Short name string destination: Room refrence \"\"\" Exit = namedtuple(\"Exit\", ['direction', 'destination']) class", "between rooms. Properties: direction: Short name string destination: Room refrence \"\"\" Exit =", "this room. Exits are appended to the end. \"\"\" description = self._short_description +", "return self._exits @property def short_description(self): \"\"\" Return the short description of this room.", "def short_description(self): \"\"\" Return the short description of this room. Exits are appended", "full_description=None, exits=[] meta={}): super(name, location, short_description, full_description, meta) self._exits = exits @property def", "game world. Properties: exits: List of Exit namedtuples \"\"\" def __init__(self, name, short_description,", "short_description, full_description, meta) self._exits = exits @property def exits(self): \"\"\" Return the list", "of Exit namedtuples \"\"\" def __init__(self, name, short_description, full_description=None, exits=[] meta={}): super(name, location,", "Room refrence \"\"\" Exit = namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity): \"\"\" Class representing", "to the end. \"\"\" description = self._full_description + \"\\n\\nThe exits are \" for", "\"\"\" Exit is a namedtuple which describes a unidirectional connection between rooms. Properties:", "are \" for exit in exits: description += \"{}, \".formatexit.direction) return description @property", "the end. \"\"\" description = self._short_description + \"\\n\\nThe exits are \" for exit", "representing locations in the game world. Properties: exits: List of Exit namedtuples \"\"\"", "return description @property def full_description(self): \"\"\" Return the short description of this room.", "Room(Entity): \"\"\" Class representing locations in the game world. Properties: exits: List of", "exits: List of Exit namedtuples \"\"\" def __init__(self, name, short_description, full_description=None, exits=[] meta={}):", "Return the list of exits. \"\"\" return self._exits @property def short_description(self): \"\"\" Return", "describes a unidirectional connection between rooms. Properties: direction: Short name string destination: Room", "Class representing locations in the game world. Properties: exits: List of Exit namedtuples", "destination: Room refrence \"\"\" Exit = namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity): \"\"\" Class", "entity import Entity \"\"\" Exit is a namedtuple which describes a unidirectional connection", "\"\"\" from collections import namedtuple from entity import Entity \"\"\" Exit is a", "= self._full_description + \"\\n\\nThe exits are \" for exit in exits: description +=", "'destination']) class Room(Entity): \"\"\" Class representing locations in the game world. Properties: exits:", "Exit namedtuples \"\"\" def __init__(self, name, short_description, full_description=None, exits=[] meta={}): super(name, location, short_description,", "List of Exit namedtuples \"\"\" def __init__(self, name, short_description, full_description=None, exits=[] meta={}): super(name,", "__init__(self, name, short_description, full_description=None, exits=[] meta={}): super(name, location, short_description, full_description, meta) self._exits =", "namedtuple from entity import Entity \"\"\" Exit is a namedtuple which describes a", "are appended to the end. \"\"\" description = self._full_description + \"\\n\\nThe exits are", "\"\"\" description = self._full_description + \"\\n\\nThe exits are \" for exit in exits:", "description of this room. Exits are appended to the end. \"\"\" description =", "of this room. Exits are appended to the end. \"\"\" description = self._full_description", "meta={}): super(name, location, short_description, full_description, meta) self._exits = exits @property def exits(self): \"\"\"", "full_description(self): \"\"\" Return the short description of this room. Exits are appended to", "@property def exits(self): \"\"\" Return the list of exits. \"\"\" return self._exits @property", "namedtuple which describes a unidirectional connection between rooms. Properties: direction: Short name string", "Entity \"\"\" Exit is a namedtuple which describes a unidirectional connection between rooms.", "which describes a unidirectional connection between rooms. Properties: direction: Short name string destination:", "class \"\"\" from collections import namedtuple from entity import Entity \"\"\" Exit is", "\" for exit in exits: description += \"{}, \".formatexit.direction) return description @property def", "namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity): \"\"\" Class representing locations in the game world.", "\"\"\" Class representing locations in the game world. Properties: exits: List of Exit", "['direction', 'destination']) class Room(Entity): \"\"\" Class representing locations in the game world. Properties:", "super(name, location, short_description, full_description, meta) self._exits = exits @property def exits(self): \"\"\" Return", "connection between rooms. Properties: direction: Short name string destination: Room refrence \"\"\" Exit", "\"\"\" Exit = namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity): \"\"\" Class representing locations in", "\".formatexit.direction) return description @property def full_description(self): \"\"\" Return the short description of this", "class Room(Entity): \"\"\" Class representing locations in the game world. Properties: exits: List", "def __init__(self, name, short_description, full_description=None, exits=[] meta={}): super(name, location, short_description, full_description, meta) self._exits", "of this room. Exits are appended to the end. \"\"\" description = self._short_description", "in exits: description += \"{}, \".formatexit.direction) return description @property def full_description(self): \"\"\" Return", "from collections import namedtuple from entity import Entity \"\"\" Exit is a namedtuple", "+ \"\\n\\nThe exits are \" for exit in exits: description += \"{}, \".formatexit.direction)", "room. Exits are appended to the end. \"\"\" description = self._full_description + \"\\n\\nThe", "end. \"\"\" description = self._full_description + \"\\n\\nThe exits are \" for exit in", "the game world. Properties: exits: List of Exit namedtuples \"\"\" def __init__(self, name,", "exits: description += \"{}, \".formatexit.direction) return description @property def full_description(self): \"\"\" Return the", "description += \"{}, \".formatexit.direction) return description @property def full_description(self): \"\"\" Return the short", "Module containing the Room class \"\"\" from collections import namedtuple from entity import", "description = self._full_description + \"\\n\\nThe exits are \" for exit in exits: description", "locations in the game world. Properties: exits: List of Exit namedtuples \"\"\" def", "appended to the end. \"\"\" description = self._full_description + \"\\n\\nThe exits are \"", "a namedtuple which describes a unidirectional connection between rooms. Properties: direction: Short name", "name, short_description, full_description=None, exits=[] meta={}): super(name, location, short_description, full_description, meta) self._exits = exits", "the short description of this room. Exits are appended to the end. \"\"\"", "room. Exits are appended to the end. \"\"\" description = self._short_description + \"\\n\\nThe", "appended to the end. \"\"\" description = self._short_description + \"\\n\\nThe exits are \"", "\"\\n\\nThe exits are \" for exit in exits: description += \"{}, \".formatexit.direction) return", "full_description, meta) self._exits = exits @property def exits(self): \"\"\" Return the list of", "this room. Exits are appended to the end. \"\"\" description = self._full_description +", "Exits are appended to the end. \"\"\" description = self._full_description + \"\\n\\nThe exits", "\"\"\" Return the short description of this room. Exits are appended to the", "+ \"\\n\\nThe exits are \" for exit in exits: description += \"{}, \".format(exit.direction)", "exits(self): \"\"\" Return the list of exits. \"\"\" return self._exits @property def short_description(self):", "\"\\n\\nThe exits are \" for exit in exits: description += \"{}, \".format(exit.direction) return", "end. \"\"\" description = self._short_description + \"\\n\\nThe exits are \" for exit in", "are appended to the end. \"\"\" description = self._short_description + \"\\n\\nThe exits are", "exit in exits: description += \"{}, \".formatexit.direction) return description @property def full_description(self): \"\"\"", "short_description(self): \"\"\" Return the short description of this room. Exits are appended to", "Properties: exits: List of Exit namedtuples \"\"\" def __init__(self, name, short_description, full_description=None, exits=[]", "\"\"\" return self._exits @property def short_description(self): \"\"\" Return the short description of this", "world. Properties: exits: List of Exit namedtuples \"\"\" def __init__(self, name, short_description, full_description=None,", "exits are \" for exit in exits: description += \"{}, \".formatexit.direction) return description", "meta) self._exits = exits @property def exits(self): \"\"\" Return the list of exits.", "for exit in exits: description += \"{}, \".formatexit.direction) return description @property def full_description(self):", "\"{}, \".formatexit.direction) return description @property def full_description(self): \"\"\" Return the short description of", "def exits(self): \"\"\" Return the list of exits. \"\"\" return self._exits @property def", "the end. \"\"\" description = self._full_description + \"\\n\\nThe exits are \" for exit", "name string destination: Room refrence \"\"\" Exit = namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity):", "Room class \"\"\" from collections import namedtuple from entity import Entity \"\"\" Exit", "exits. \"\"\" return self._exits @property def short_description(self): \"\"\" Return the short description of", "= namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity): \"\"\" Class representing locations in the game", "unidirectional connection between rooms. Properties: direction: Short name string destination: Room refrence \"\"\"", "the Room class \"\"\" from collections import namedtuple from entity import Entity \"\"\"", "of exits. \"\"\" return self._exits @property def short_description(self): \"\"\" Return the short description", "self._full_description + \"\\n\\nThe exits are \" for exit in exits: description += \"{},", "Return the short description of this room. Exits are appended to the end.", "= self._short_description + \"\\n\\nThe exits are \" for exit in exits: description +=", "self._exits = exits @property def exits(self): \"\"\" Return the list of exits. \"\"\"", "description = self._short_description + \"\\n\\nThe exits are \" for exit in exits: description", "a unidirectional connection between rooms. Properties: direction: Short name string destination: Room refrence", "Exits are appended to the end. \"\"\" description = self._short_description + \"\\n\\nThe exits", "exits @property def exits(self): \"\"\" Return the list of exits. \"\"\" return self._exits", "namedtuples \"\"\" def __init__(self, name, short_description, full_description=None, exits=[] meta={}): super(name, location, short_description, full_description,", "short description of this room. Exits are appended to the end. \"\"\" description", "\"\"\" Module containing the Room class \"\"\" from collections import namedtuple from entity", "containing the Room class \"\"\" from collections import namedtuple from entity import Entity", "short_description, full_description=None, exits=[] meta={}): super(name, location, short_description, full_description, meta) self._exits = exits @property", "+= \"{}, \".formatexit.direction) return description @property def full_description(self): \"\"\" Return the short description", "direction: Short name string destination: Room refrence \"\"\" Exit = namedtuple(\"Exit\", ['direction', 'destination'])", "def full_description(self): \"\"\" Return the short description of this room. Exits are appended", "exits=[] meta={}): super(name, location, short_description, full_description, meta) self._exits = exits @property def exits(self):", "from entity import Entity \"\"\" Exit is a namedtuple which describes a unidirectional", "list of exits. \"\"\" return self._exits @property def short_description(self): \"\"\" Return the short", "Exit is a namedtuple which describes a unidirectional connection between rooms. Properties: direction:", "Properties: direction: Short name string destination: Room refrence \"\"\" Exit = namedtuple(\"Exit\", ['direction',", "collections import namedtuple from entity import Entity \"\"\" Exit is a namedtuple which", "\"\"\" Return the list of exits. \"\"\" return self._exits @property def short_description(self): \"\"\"", "@property def full_description(self): \"\"\" Return the short description of this room. Exits are", "string destination: Room refrence \"\"\" Exit = namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity): \"\"\"", "rooms. Properties: direction: Short name string destination: Room refrence \"\"\" Exit = namedtuple(\"Exit\",", "refrence \"\"\" Exit = namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity): \"\"\" Class representing locations", "import namedtuple from entity import Entity \"\"\" Exit is a namedtuple which describes", "the list of exits. \"\"\" return self._exits @property def short_description(self): \"\"\" Return the", "\"\"\" def __init__(self, name, short_description, full_description=None, exits=[] meta={}): super(name, location, short_description, full_description, meta)", "import Entity \"\"\" Exit is a namedtuple which describes a unidirectional connection between", "is a namedtuple which describes a unidirectional connection between rooms. Properties: direction: Short", "in the game world. Properties: exits: List of Exit namedtuples \"\"\" def __init__(self,", "\"\"\" description = self._short_description + \"\\n\\nThe exits are \" for exit in exits:", "description @property def full_description(self): \"\"\" Return the short description of this room. Exits", "Exit = namedtuple(\"Exit\", ['direction', 'destination']) class Room(Entity): \"\"\" Class representing locations in the", "location, short_description, full_description, meta) self._exits = exits @property def exits(self): \"\"\" Return the", "exits are \" for exit in exits: description += \"{}, \".format(exit.direction) return description", "self._exits @property def short_description(self): \"\"\" Return the short description of this room. Exits", "to the end. \"\"\" description = self._short_description + \"\\n\\nThe exits are \" for", "= exits @property def exits(self): \"\"\" Return the list of exits. \"\"\" return", "self._short_description + \"\\n\\nThe exits are \" for exit in exits: description += \"{},", "@property def short_description(self): \"\"\" Return the short description of this room. Exits are" ]
[ "reduce=False, shuffle=seed) Xtr, Ytr = Xtr[:m], Ytr[:m] if da: logging.info(f'Adding {da} examples with", "maxpool, maxpool)) elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if", "AllPairsEncoder from quadboost.weak_learner import * from quadboost.callbacks import * from quadboost.datasets import MNISTDataset", "* from quadboost.datasets import MNISTDataset from quadboost.utils import parse, timed from quadboost.data_preprocessing.data_augmentation import", "### Or resume fitting a model else: logging.info(f'Resuming fit with max_round_number={max_round}.') qb =", "f'_{fn}' f_proc = [] if 'c' in fn: f_proc.append(center_weight) if 'n' in fn:", "mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset} (center: {center}, reduce: {reduce})') logging.info(f'Number of examples -", "best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if", "in nl: filename += f'-sigmoid' activation = torch.sigmoid filename += f'-{init_filters}' if degrees:", "1: filename += f'-nt={nt}' if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner", "from quadboost import QuadBoostMHCR from quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import", "seed: torch.manual_seed(seed) np.random.seed(seed) ### Data loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val),", "weak learner name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results',", "### Fitting the model if not resume: logging.info(f'Beginning fit with max_round_number={max_round} and patience={patience}.')", "Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if", "scale=.0, shear=.0, margin=2, nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed) ### Data loading mnist =", "OneHotEncoder(Ytr) elif encodings == 'allpairs': encoder = AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings) if", "= None filter_bank = None if init_filters == 'from_bank': if 0 < bank_ratio", "Yts):.3%}') print(f'Test accuracy on last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if __name__ == '__main__':", "of encoder if encodings == 'onehot': encoder = OneHotEncoder(Ytr) elif encodings == 'allpairs':", "Ytr = extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr,", "wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c',", "logging from quadboost import QuadBoostMHCR from quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner", "quadboost.weak_learner import * from quadboost.callbacks import * from quadboost.datasets import MNISTDataset from quadboost.utils", "wl in ['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs']", "filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters,", "Choice of encoder if encodings == 'onehot': encoder = OneHotEncoder(Ytr) elif encodings ==", "round recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%} |", "dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif wl in ['dt', 'decision-tree']: weak_learner =", "resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3,", "(X_val, Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr, Ytr = Xtr[:m],", "filter_bank = None if init_filters == 'from_bank': if 0 < bank_ratio < 1:", "[] if 'c' in fn: f_proc.append(center_weight) if 'n' in fn: f_proc.append(normalize_weight) if 'r'", "resume: logging.info(f'Beginning fit with max_round_number={max_round} and patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr,", "f'-nt={nt}' if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump)", "with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round", "on last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if __name__ == '__main__': logging.basicConfig(level=logging.INFO, style='{', format='[{levelname}]", "RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if fsh: filename += f'_to_{fsh}' if", "plot_images @timed @parse def main(m=60_000, val=10_000, da=0, dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000,", "= RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if fsh: filename += f'_to_{fsh}'", "filename += f'-scale={scale}' scale = (1-scale, 1/(1-scale)) else: scale = None if shear:", "kwargs['n_jobs'] = n_jobs elif wl in ['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs =", "quadboost.utils import parse, timed from quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution import plot_images @timed", "accuracy on best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on last model: {qb.evaluate(Xts, Yts,", "Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else: raise ValueError(f'Invalid bank_size {bank_size}.')", "= (1-scale, 1/(1-scale)) else: scale = None if shear: filename += f'-shear={shear}' else:", "< bank_ratio < 1: bank_size = int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr, Ytr =", "on best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}')", "encodings == 'onehot': encoder = OneHotEncoder(Ytr) elif encodings == 'allpairs': encoder = AllPairsEncoder(Ytr)", "degrees=degrees, scale=scale, shear=shear, ) if wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool,", "n_jobs else: raise ValueError(f'Invalid weak learner name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks", "'onehot': encoder = OneHotEncoder(Ytr) elif encodings == 'allpairs': encoder = AllPairsEncoder(Ytr) else: encoder", "Xtr[:m], Ytr[:m] if da: logging.info(f'Adding {da} examples with data augmentation.') Xtr, Ytr =", "qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or resume fitting a", "0 < bank_ratio < 1: bank_size = int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr, Ytr", "N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr)", "filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if nt > 1: filename", "'maxpool' in nl: filename += f'-maxpool{maxpool}' if 'relu' in nl: filename += f'-relu'", "= WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if fsh else None, filter_processing=f_proc, margin=margin, degrees=degrees,", "wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] =", "'sigmoid' in nl: filename += f'-sigmoid' activation = torch.sigmoid filename += f'-{init_filters}' if", "'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device)", "seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0, margin=2, nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed)", "if wl.startswith('rlc'): filename += f'-loc={locality}' activation = None if 'maxpool' in nl: filename", "logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv',", "fs), filters_shape_high=(fsh, fsh) if fsh else None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear, )", "def main(m=60_000, val=10_000, da=0, dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1,", "> 1: filename += f'-nt={nt}' if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'):", "{encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak learner kwargs = {} if", "Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset:", "in ['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] =", "= n_jobs elif wl in ['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X',", "max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%} | Valid", "encoder = AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label in encoder.labels_encoding):", "logging.info(f'Number of examples - train: {len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}') ### Choice of", "fsh else None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear, ) if wl.startswith('rcc'): filters =", "{qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test", "last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if __name__ == '__main__': logging.basicConfig(level=logging.INFO, style='{', format='[{levelname}] {message}')", "print(f'Test accuracy on last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if __name__ == '__main__': logging.basicConfig(level=logging.INFO,", "mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr, Ytr = Xtr[:m], Ytr[:m] if da: logging.info(f'Adding {da}", "extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr =", "quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution import plot_images @timed @parse def main(m=60_000, val=10_000, da=0,", "kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif wl in ['dt', 'decision-tree']:", "for label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice of", "f_proc.append(normalize_weight) if 'r' in fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh)", "Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr, Ytr = Xtr[:m], Ytr[:m] if da:", "weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else: raise ValueError(f'Invalid weak learner name: \"{wl}\".') logging.info(f'Weak learner:", "= AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label in encoder.labels_encoding): encoder", "quadboost.datasets import MNISTDataset from quadboost.utils import parse, timed from quadboost.data_preprocessing.data_augmentation import extend_mnist from", "recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%} | Risk:", "quadboost.callbacks import * from quadboost.datasets import MNISTDataset from quadboost.utils import parse, timed from", "if encodings == 'onehot': encoder = OneHotEncoder(Ytr) elif encodings == 'allpairs': encoder =", "mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val)", "nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed) ### Data loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr),", "'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename", "QuadBoostMHCR from quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import * from quadboost.callbacks", "from quadboost.weak_learner import * from quadboost.callbacks import * from quadboost.datasets import MNISTDataset from", "nl: filename += f'-relu' activation = torch.nn.functional.relu elif 'sigmoid' in nl: filename +=", "elif wl in ['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr)))", "learner: {type(weak_learner).__name__}') ### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log')", "dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0,", "callbacks = [ckpt, logger, zero_risk, ] logging.info(f'Filename: {filename}') ### Fitting the model if", "weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename +=", "Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else: raise ValueError(f'Invalid bank_size", "= f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak learner kwargs = {} if wl in", "if wl in ['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr)))", "Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback()", "= Xtr[:m], Ytr[:m] if da: logging.info(f'Adding {da} examples with data augmentation.') Xtr, Ytr", "= n_jobs filename += f'{max_n_leaves}' elif wl == 'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif", "resume fitting a model else: logging.info(f'Resuming fit with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr,", "dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks = [ckpt, logger, zero_risk, ] logging.info(f'Filename: {filename}') ###", "center=False, reduce=False, shuffle=seed) Xtr, Ytr = Xtr[:m], Ytr[:m] if da: logging.info(f'Adding {da} examples", "patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool',", "f_proc.append(center_weight) if 'n' in fn: f_proc.append(normalize_weight) if 'r' in fn: f_proc.append(reduce_weight) w_gen =", "= [] if 'c' in fn: f_proc.append(center_weight) if 'n' in fn: f_proc.append(normalize_weight) if", "encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak learner", "Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset} (center:", "torch.sigmoid filename += f'-{init_filters}' if degrees: filename += f'-deg={degrees}' if scale: filename +=", "if 0 < bank_ratio < 1: bank_size = int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr,", "logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks = [ckpt, logger, zero_risk, ]", "= CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks = [ckpt, logger, zero_risk, ] logging.info(f'Filename:", "{qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy", "Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts =", "LabelEncoder({int(label):encoding for label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice", "if fn: filename += f'_{fn}' f_proc = [] if 'c' in fn: f_proc.append(center_weight)", "MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr,", "if seed: torch.manual_seed(seed) np.random.seed(seed) ### Data loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val,", "name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger", "Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on last", "= RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if fsh: filename += f'_to_{fsh}' if wl.startswith('rlc'): filename", "MNISTDataset from quadboost.utils import parse, timed from quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution import", "torch.manual_seed(seed) np.random.seed(seed) ### Data loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val), (Xts,", "= extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr", "= Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen,", "kwargs['n_jobs'] = n_jobs filename += f'{max_n_leaves}' elif wl == 'ridge': weak_learner = WLThresholdedRidge(threshold=.5)", "fsh: filename += f'_to_{fsh}' if wl.startswith('rlc'): filename += f'-loc={locality}' activation = None if", "None if 'maxpool' in nl: filename += f'-maxpool{maxpool}' if 'relu' in nl: filename", "= ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks =", "'c' in fn: f_proc.append(center_weight) if 'n' in fn: f_proc.append(normalize_weight) if 'r' in fn:", "AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label in encoder.labels_encoding): encoder =", "import MNISTDataset from quadboost.utils import parse, timed from quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution", "= WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val =", "+= f'-relu' activation = torch.nn.functional.relu elif 'sigmoid' in nl: filename += f'-sigmoid' activation", "None filter_bank = None if init_filters == 'from_bank': if 0 < bank_ratio <", "fsh) if fsh else None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear, ) if wl.startswith('rcc'):", "round {qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}')", "import * from quadboost.callbacks import * from quadboost.datasets import MNISTDataset from quadboost.utils import", "f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak learner kwargs = {} if wl in ['ds',", "= OneHotEncoder(Ytr) elif encodings == 'allpairs': encoder = AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings)", "callbacks=callbacks, **kwargs) ### Or resume fitting a model else: logging.info(f'Resuming fit with max_round_number={max_round}.')", "filename += f'-nf={n_filters}-fs={fs}' if fsh: filename += f'_to_{fsh}' if wl.startswith('rlc'): filename += f'-loc={locality}'", "if not resume: logging.info(f'Beginning fit with max_round_number={max_round} and patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder)", "dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks = [ckpt, logger,", "filename += f'_to_{fsh}' if wl.startswith('rlc'): filename += f'-loc={locality}' activation = None if 'maxpool'", "import QuadBoostMHCR from quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import * from", "import plot_images @timed @parse def main(m=60_000, val=10_000, da=0, dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge',", "scale = None if shear: filename += f'-shear={shear}' else: shear = None filter_bank", "examples - train: {len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}') ### Choice of encoder if", "+= f'-nf={n_filters}-fs={fs}' if fsh: filename += f'_to_{fsh}' if wl.startswith('rlc'): filename += f'-loc={locality}' activation", "= BreakOnZeroRiskCallback() callbacks = [ckpt, logger, zero_risk, ] logging.info(f'Filename: {filename}') ### Fitting the", "logger, zero_risk, ] logging.info(f'Filename: {filename}') ### Fitting the model if not resume: logging.info(f'Beginning", "+= f'{max_n_leaves}' elif wl == 'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'):", "a model else: logging.info(f'Resuming fit with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val,", "{bank_size}') else: raise ValueError(f'Invalid bank_size {bank_size}.') filename += f'_br={bank_ratio}' elif init_filters == 'from_data':", "fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0, margin=2, nt=1): if seed: torch.manual_seed(seed)", "from quadboost.callbacks import * from quadboost.datasets import MNISTDataset from quadboost.utils import parse, timed", "mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded", "f'-sigmoid' activation = torch.sigmoid filename += f'-{init_filters}' if degrees: filename += f'-deg={degrees}' if", "Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset} (center: {center}, reduce: {reduce})') logging.info(f'Number of", "shear: filename += f'-shear={shear}' else: shear = None filter_bank = None if init_filters", "### Data loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val), (Xts, Yts) =", "Xts = RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if fsh: filename += f'_to_{fsh}' if wl.startswith('rlc'):", "bank_size {bank_size}.') filename += f'_br={bank_ratio}' elif init_filters == 'from_data': filter_bank = Xtr if", "model if not resume: logging.info(f'Beginning fit with max_round_number={max_round} and patience={patience}.') qb = QuadBoostMHCR(weak_learner,", "RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if fsh: filename", "weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs", "None if init_filters == 'from_bank': if 0 < bank_ratio < 1: bank_size =", "print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%}", "activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool,", "augmentation.') Xtr, Ytr = extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center,", "loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False,", "import extend_mnist from quadboost.weak_learner.random_convolution import plot_images @timed @parse def main(m=60_000, val=10_000, da=0, dataset='mnist',", "= mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset} (center: {center},", "logging.info(f'Beginning fit with max_round_number={max_round} and patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round,", "learner name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True)", "shuffle=seed) Xtr, Ytr = Xtr[:m], Ytr[:m] if da: logging.info(f'Adding {da} examples with data", "val=10_000, da=0, dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10,", "elif 'sigmoid' in nl: filename += f'-sigmoid' activation = torch.sigmoid filename += f'-{init_filters}'", "Xtr, Ytr = Xtr[:m], Ytr[:m] if da: logging.info(f'Adding {da} examples with data augmentation.')", "Or resume fitting a model else: logging.info(f'Resuming fit with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt')", "f'-deg={degrees}' if scale: filename += f'-scale={scale}' scale = (1-scale, 1/(1-scale)) else: scale =", "= None if init_filters == 'from_bank': if 0 < bank_ratio < 1: bank_size", "+= f'-deg={degrees}' if scale: filename += f'-scale={scale}' scale = (1-scale, 1/(1-scale)) else: scale", "shear=.0, margin=2, nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed) ### Data loading mnist = MNISTDataset.load(dataset+'.pkl')", "center=center, reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts,", "encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename =", "fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0,", "nl: filename += f'-maxpool{maxpool}' if 'relu' in nl: filename += f'-relu' activation =", "= Xtr if fn: filename += f'_{fn}' f_proc = [] if 'c' in", "scale = (1-scale, 1/(1-scale)) else: scale = None if shear: filename += f'-shear={shear}'", "@parse def main(m=60_000, val=10_000, da=0, dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0,", "weak learner kwargs = {} if wl in ['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump()", "weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if nt > 1: filename += f'-nt={nt}' if", "filename += f'-nt={nt}' if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner =", "of examples - train: {len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}') ### Choice of encoder", "model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if __name__", "= QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d}", "f'{max_n_leaves}' elif wl == 'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'): if", "degrees: filename += f'-deg={degrees}' if scale: filename += f'-scale={scale}' scale = (1-scale, 1/(1-scale))", "maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0, margin=2, nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed) ### Data", "= MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed)", "ValueError(f'Invalid weak learner name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt',", "else: raise ValueError(f'Invalid bank_size {bank_size}.') filename += f'_br={bank_ratio}' elif init_filters == 'from_data': filter_bank", "if nt > 1: filename += f'-nt={nt}' if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge)", "f'-nf={n_filters}-fs={fs}' if fsh: filename += f'_to_{fsh}' if wl.startswith('rlc'): filename += f'-loc={locality}' activation =", "LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import * from quadboost.callbacks import * from quadboost.datasets", "size: {bank_size}') else: raise ValueError(f'Invalid bank_size {bank_size}.') filename += f'_br={bank_ratio}' elif init_filters ==", "= torch.nn.functional.relu elif 'sigmoid' in nl: filename += f'-sigmoid' activation = torch.sigmoid filename", "in nl: filename += f'-maxpool{maxpool}' if 'relu' in nl: filename += f'-relu' activation", "@timed @parse def main(m=60_000, val=10_000, da=0, dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000,", "bank_size = int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size:", "valid: {len(X_val)}, test: {len(Xts)}') ### Choice of encoder if encodings == 'onehot': encoder", "encoder if encodings == 'onehot': encoder = OneHotEncoder(Ytr) elif encodings == 'allpairs': encoder", "(center: {center}, reduce: {reduce})') logging.info(f'Number of examples - train: {len(Xtr)}, valid: {len(X_val)}, test:", "import logging from quadboost import QuadBoostMHCR from quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from", "= mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts)", "= Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else: raise ValueError(f'Invalid bank_size {bank_size}.') filename +=", "n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu',", "nt > 1: filename += f'-nt={nt}' if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if", "bank_ratio < 1: bank_size = int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:],", "acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test", ") if wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'):", "Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset} (center: {center}, reduce: {reduce})')", "not resume: logging.info(f'Beginning fit with max_round_number={max_round} and patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr,", "activation = torch.sigmoid filename += f'-{init_filters}' if degrees: filename += f'-deg={degrees}' if scale:", "f'_br={bank_ratio}' elif init_filters == 'from_data': filter_bank = Xtr if fn: filename += f'_{fn}'", "from quadboost.datasets import MNISTDataset from quadboost.utils import parse, timed from quadboost.data_preprocessing.data_augmentation import extend_mnist", "encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak learner kwargs =", "{reduce})') logging.info(f'Number of examples - train: {len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}') ### Choice", "margin=2, nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed) ### Data loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr,", "filename += f'-relu' activation = torch.nn.functional.relu elif 'sigmoid' in nl: filename += f'-sigmoid'", "f'-shear={shear}' else: shear = None filter_bank = None if init_filters == 'from_bank': if", "zero_risk, ] logging.info(f'Filename: {filename}') ### Fitting the model if not resume: logging.info(f'Beginning fit", "**kwargs) print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%} | Valid acc:", "= RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if fsh:", "RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else: raise", "max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or resume fitting a model else:", "fit with max_round_number={max_round} and patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience,", "1: bank_size = int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank", "from quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution import plot_images @timed @parse def main(m=60_000, val=10_000,", "label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak", "fitting a model else: logging.info(f'Resuming fit with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr,", "for label in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding:", "X_val = RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if fsh: filename +=", "Yts) logging.info(f'Loaded dataset: {dataset} (center: {center}, reduce: {reduce})') logging.info(f'Number of examples - train:", "filename += f'-shear={shear}' else: shear = None filter_bank = None if init_filters ==", "Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset} (center: {center}, reduce: {reduce})') logging.info(f'Number", "BreakOnZeroRiskCallback() callbacks = [ckpt, logger, zero_risk, ] logging.info(f'Filename: {filename}') ### Fitting the model", "- train: {len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}') ### Choice of encoder if encodings", "shear = None filter_bank = None if init_filters == 'from_bank': if 0 <", "{da} examples with data augmentation.') Xtr, Ytr = extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale,", "if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else: raise ValueError(f'Invalid weak", "from quadboost.utils import parse, timed from quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution import plot_images", "w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if fsh else None, filter_processing=f_proc, margin=margin,", "f_proc = [] if 'c' in fn: f_proc.append(center_weight) if 'n' in fn: f_proc.append(normalize_weight)", "= Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else: raise ValueError(f'Invalid", "fn: f_proc.append(center_weight) if 'n' in fn: f_proc.append(normalize_weight) if 'r' in fn: f_proc.append(reduce_weight) w_gen", "center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4,", "if shear: filename += f'-shear={shear}' else: shear = None filter_bank = None if", "activation = None if 'maxpool' in nl: filename += f'-maxpool{maxpool}' if 'relu' in", "with max_round_number={max_round} and patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val,", "= int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}')", "'n' in fn: f_proc.append(normalize_weight) if 'r' in fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs,", "else: shear = None filter_bank = None if init_filters == 'from_bank': if 0", "quadboost import QuadBoostMHCR from quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import *", "reduce: {reduce})') logging.info(f'Number of examples - train: {len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}') ###", "+= f'_to_{fsh}' if wl.startswith('rlc'): filename += f'-loc={locality}' activation = None if 'maxpool' in", "in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename", "raise ValueError(f'Invalid bank_size {bank_size}.') filename += f'_br={bank_ratio}' elif init_filters == 'from_data': filter_bank =", "WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device)", "if fsh else None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear, ) if wl.startswith('rcc'): filters", "MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename += f'{max_n_leaves}' elif", "weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename += f'{max_n_leaves}' elif wl == 'ridge': weak_learner =", "nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0, margin=2, nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed) ###", "Ytr = Xtr[:m], Ytr[:m] if da: logging.info(f'Adding {da} examples with data augmentation.') Xtr,", "kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename += f'{max_n_leaves}' elif wl", "if scale: filename += f'-scale={scale}' scale = (1-scale, 1/(1-scale)) else: scale = None", "from quadboost.weak_learner.random_convolution import plot_images @timed @parse def main(m=60_000, val=10_000, da=0, dataset='mnist', center=True, reduce=True,", "Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else: raise ValueError(f'Invalid bank_size {bank_size}.') filename", "+= f'-shear={shear}' else: shear = None filter_bank = None if init_filters == 'from_bank':", "| Train acc: {qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy", "* from quadboost.callbacks import * from quadboost.datasets import MNISTDataset from quadboost.utils import parse,", "MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif wl in ['dt',", "n_jobs filename += f'{max_n_leaves}' elif wl == 'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc')", "elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if nt >", "None if shear: filename += f'-shear={shear}' else: shear = None filter_bank = None", "{bank_size}.') filename += f'_br={bank_ratio}' elif init_filters == 'from_data': filter_bank = Xtr if fn:", "else: raise ValueError(f'Invalid weak learner name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks ckpt", "the model if not resume: logging.info(f'Beginning fit with max_round_number={max_round} and patience={patience}.') qb =", "{len(X_val)}, test: {len(Xts)}') ### Choice of encoder if encodings == 'onehot': encoder =", "quadboost.weak_learner.random_convolution import plot_images @timed @parse def main(m=60_000, val=10_000, da=0, dataset='mnist', center=True, reduce=True, encodings='onehot',", "= None if 'maxpool' in nl: filename += f'-maxpool{maxpool}' if 'relu' in nl:", "= mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr, Ytr = Xtr[:m], Ytr[:m] if da: logging.info(f'Adding", "kwargs = {} if wl in ['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs =", "### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk =", "else None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear, ) if wl.startswith('rcc'): filters = Filters(n_filters=n_filters,", "encoder = LabelEncoder({int(label):encoding for label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}'", "= torch.sigmoid filename += f'-{init_filters}' if degrees: filename += f'-deg={degrees}' if scale: filename", "logging.info(f'Bank size: {bank_size}') else: raise ValueError(f'Invalid bank_size {bank_size}.') filename += f'_br={bank_ratio}' elif init_filters", "import torch import logging from quadboost import QuadBoostMHCR from quadboost.label_encoder import LabelEncoder, OneHotEncoder,", "weak_learner = MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif wl", "OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import * from quadboost.callbacks import * from quadboost.datasets import", "margin=margin, degrees=degrees, scale=scale, shear=shear, ) if wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt,", "== 'from_data': filter_bank = Xtr if fn: filename += f'_{fn}' f_proc = []", "model else: logging.info(f'Resuming fit with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val,", "### Choice of encoder if encodings == 'onehot': encoder = OneHotEncoder(Ytr) elif encodings", "n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0,", "data augmentation.') Xtr, Ytr = extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr,", "maxpool, maxpool)) if nt > 1: filename += f'-nt={nt}' if wl.endswith('ridge'): weak_learner =", "torch.nn.functional.relu elif 'sigmoid' in nl: filename += f'-sigmoid' activation = torch.sigmoid filename +=", "reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts", "**kwargs) ### Or resume fitting a model else: logging.info(f'Resuming fit with max_round_number={max_round}.') qb", "or wl.startswith('rlc'): if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device)", "examples with data augmentation.') Xtr, Ytr = extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)),", "elif wl == 'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'):", "qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting round", "logging.info(f'Loaded dataset: {dataset} (center: {center}, reduce: {reduce})') logging.info(f'Number of examples - train: {len(Xtr)},", "{qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if __name__ ==", "locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if nt > 1: filename += f'-nt={nt}' if wl.endswith('ridge'):", "reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank',", "if degrees: filename += f'-deg={degrees}' if scale: filename += f'-scale={scale}' scale = (1-scale,", "+= f'_{fn}' f_proc = [] if 'c' in fn: f_proc.append(center_weight) if 'n' in", "Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality,", "== 'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'): Xtr =", "### Choice of weak learner kwargs = {} if wl in ['ds', 'decision-stump']:", "test: {len(Xts)}') ### Choice of encoder if encodings == 'onehot': encoder = OneHotEncoder(Ytr)", "wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts =", "ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks", "elif wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts", "filename += f'{max_n_leaves}' elif wl == 'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or", "Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or resume fitting a model", "{filename}') ### Fitting the model if not resume: logging.info(f'Beginning fit with max_round_number={max_round} and", "shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1),", "torch import logging from quadboost import QuadBoostMHCR from quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder", "if 'c' in fn: f_proc.append(center_weight) if 'n' in fn: f_proc.append(normalize_weight) if 'r' in", "Valid acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on best model: {qb.evaluate(Xts, Yts):.3%}')", "wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else: raise ValueError(f'Invalid weak learner", "1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val =", "Xtr, Ytr = extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce)", "of weak learner kwargs = {} if wl in ['ds', 'decision-stump']: weak_learner =", "patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs)", "filename += f'-maxpool{maxpool}' if 'relu' in nl: filename += f'-relu' activation = torch.nn.functional.relu", "= dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif wl in ['dt', 'decision-tree']: weak_learner", "degrees=.0, scale=.0, shear=.0, margin=2, nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed) ### Data loading mnist", "ValueError(f'Invalid bank_size {bank_size}.') filename += f'_br={bank_ratio}' elif init_filters == 'from_data': filter_bank = Xtr", "all(label.isdigit() for label in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for label, encoding in encoder.labels_encoding.items()})", "= mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset} (center: {center}, reduce: {reduce})') logging.info(f'Number of examples", "filename += f'-loc={locality}' activation = None if 'maxpool' in nl: filename += f'-maxpool{maxpool}'", "else: logging.info(f'Resuming fit with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round,", "LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if nt > 1: filename += f'-nt={nt}'", "nl: filename += f'-sigmoid' activation = torch.sigmoid filename += f'-{init_filters}' if degrees: filename", "< 1: bank_size = int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:]", "filename += f'-{init_filters}' if degrees: filename += f'-deg={degrees}' if scale: filename += f'-scale={scale}'", "= LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for label,", "import * from quadboost.datasets import MNISTDataset from quadboost.utils import parse, timed from quadboost.data_preprocessing.data_augmentation", "logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak learner kwargs = {}", "weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else: raise ValueError(f'Invalid weak learner name:", "if wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'): filters", "activation = torch.nn.functional.relu elif 'sigmoid' in nl: filename += f'-sigmoid' activation = torch.sigmoid", "if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs']", "'r' in fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if fsh", "kwargs['n_jobs'] = n_jobs else: raise ValueError(f'Invalid weak learner name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}')", "Data loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val,", "+= f'-{init_filters}' if degrees: filename += f'-deg={degrees}' if scale: filename += f'-scale={scale}' scale", "logging.info(f'Adding {da} examples with data augmentation.') Xtr, Ytr = extend_mnist(Xtr, Ytr, N=da, degrees=degrees,", "filename += f'_br={bank_ratio}' elif init_filters == 'from_data': filter_bank = Xtr if fn: filename", "| Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on", "+= f'-maxpool{maxpool}' if 'relu' in nl: filename += f'-relu' activation = torch.nn.functional.relu elif", "Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr, Ytr = Xtr[:m], Ytr[:m]", "extend_mnist from quadboost.weak_learner.random_convolution import plot_images @timed @parse def main(m=60_000, val=10_000, da=0, dataset='mnist', center=True,", "X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset}", "+= f'-nt={nt}' if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters,", "Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train acc:", "['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs", "filename += f'_{fn}' f_proc = [] if 'c' in fn: f_proc.append(center_weight) if 'n'", "Ytr[:m] if da: logging.info(f'Adding {da} examples with data augmentation.') Xtr, Ytr = extend_mnist(Xtr,", "weak_learner=Ridge) if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else: raise ValueError(f'Invalid", "if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename +=", "{} if wl in ['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'),", "== 'allpairs': encoder = AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label", "Choice of weak learner kwargs = {} if wl in ['ds', 'decision-stump']: weak_learner", "dataset: {dataset} (center: {center}, reduce: {reduce})') logging.info(f'Number of examples - train: {len(Xtr)}, valid:", "= {} if wl in ['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs = dict(zip(('sorted_X',", "encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for", "filters_shape_high=(fsh, fsh) if fsh else None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear, ) if", "Xtr if fn: filename += f'_{fn}' f_proc = [] if 'c' in fn:", "'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif", "init_filters == 'from_data': filter_bank = Xtr if fn: filename += f'_{fn}' f_proc =", "filename += f'-deg={degrees}' if scale: filename += f'-scale={scale}' scale = (1-scale, 1/(1-scale)) else:", "parse, timed from quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution import plot_images @timed @parse def", "== 'from_bank': if 0 < bank_ratio < 1: bank_size = int(m*bank_ratio) filter_bank =", "Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else: raise ValueError(f'Invalid bank_size {bank_size}.') filename += f'_br={bank_ratio}'", "| Valid acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on best model: {qb.evaluate(Xts,", "main(m=60_000, val=10_000, da=0, dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4,", "'allpairs': encoder = AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label in", "+= f'-loc={locality}' activation = None if 'maxpool' in nl: filename += f'-maxpool{maxpool}' if", "1/(1-scale)) else: scale = None if shear: filename += f'-shear={shear}' else: shear =", "in fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if fsh else", "fn: filename += f'_{fn}' f_proc = [] if 'c' in fn: f_proc.append(center_weight) if", "f'-loc={locality}' activation = None if 'maxpool' in nl: filename += f'-maxpool{maxpool}' if 'relu'", "device='cpu', degrees=.0, scale=.0, shear=.0, margin=2, nt=1): if seed: torch.manual_seed(seed) np.random.seed(seed) ### Data loading", "{len(Xts)}') ### Choice of encoder if encodings == 'onehot': encoder = OneHotEncoder(Ytr) elif", "max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0,", "{type(weak_learner).__name__}') ### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk", "Ytr), (X_val, Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr, Ytr =", "da=0, dataset='mnist', center=True, reduce=True, encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11,", "f'-maxpool{maxpool}' if 'relu' in nl: filename += f'-relu' activation = torch.nn.functional.relu elif 'sigmoid'", "encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or resume fitting", "fn: f_proc.append(normalize_weight) if 'r' in fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh,", "weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif wl in ['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs", "+= f'-scale={scale}' scale = (1-scale, 1/(1-scale)) else: scale = None if shear: filename", "QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d} |", "[ckpt, logger, zero_risk, ] logging.info(f'Filename: {filename}') ### Fitting the model if not resume:", "= RandomConvolution(filters=filters, weak_learner=Ridge) if wl.endswith('ds'): weak_learner = RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else:", "in fn: f_proc.append(center_weight) if 'n' in fn: f_proc.append(normalize_weight) if 'r' in fn: f_proc.append(reduce_weight)", "X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or resume fitting a model else: logging.info(f'Resuming fit", "mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1), Yts) logging.info(f'Loaded dataset: {dataset} (center: {center}, reduce:", "+= f'-sigmoid' activation = torch.sigmoid filename += f'-{init_filters}' if degrees: filename += f'-deg={degrees}'", "'from_data': filter_bank = Xtr if fn: filename += f'_{fn}' f_proc = [] if", "in fn: f_proc.append(normalize_weight) if 'r' in fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs),", "= dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename += f'{max_n_leaves}' elif wl ==", "f'-scale={scale}' scale = (1-scale, 1/(1-scale)) else: scale = None if shear: filename +=", "patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or resume fitting a model else: logging.info(f'Resuming", "== 'onehot': encoder = OneHotEncoder(Ytr) elif encodings == 'allpairs': encoder = AllPairsEncoder(Ytr) else:", "f'-{init_filters}' if degrees: filename += f'-deg={degrees}' if scale: filename += f'-scale={scale}' scale =", "['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs", "(1-scale, 1/(1-scale)) else: scale = None if shear: filename += f'-shear={shear}' else: shear", "{len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}') ### Choice of encoder if encodings == 'onehot':", "save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks = [ckpt, logger, zero_risk,", "qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ###", "scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val", "(Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr, Ytr = Xtr[:m], Ytr[:m] if", "None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear, ) if wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen,", "in ['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] =", "RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}' if fsh: filename += f'_to_{fsh}' if wl.startswith('rlc'): filename +=", "wl == 'ridge': weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'): Xtr", "f'_to_{fsh}' if wl.startswith('rlc'): filename += f'-loc={locality}' activation = None if 'maxpool' in nl:", "elif encodings == 'allpairs': encoder = AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit()", "RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else: raise ValueError(f'Invalid weak learner name: \"{wl}\".') logging.info(f'Weak", "\"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks ckpt = ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger =", "{dataset} (center: {center}, reduce: {reduce})') logging.info(f'Number of examples - train: {len(Xtr)}, valid: {len(X_val)},", "quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import * from quadboost.callbacks import *", "encoder = OneHotEncoder(Ytr) elif encodings == 'allpairs': encoder = AllPairsEncoder(Ytr) else: encoder =", "wl.startswith('rlc'): filename += f'-loc={locality}' activation = None if 'maxpool' in nl: filename +=", "if init_filters == 'from_bank': if 0 < bank_ratio < 1: bank_size = int(m*bank_ratio)", "ModelCheckpoint(filename=filename+'-{round}.ckpt', dirname='./results', save_last=True) logger = CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks = [ckpt,", "learner kwargs = {} if wl in ['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs", "+= f'_br={bank_ratio}' elif init_filters == 'from_data': filter_bank = Xtr if fn: filename +=", "model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if __name__ == '__main__': logging.basicConfig(level=logging.INFO, style='{', format='[{levelname}] {message}') main()", "filename += f'-sigmoid' activation = torch.sigmoid filename += f'-{init_filters}' if degrees: filename +=", "scale: filename += f'-scale={scale}' scale = (1-scale, 1/(1-scale)) else: scale = None if", "logging.info(f'Resuming fit with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs)", "logging.info(f'Filename: {filename}') ### Fitting the model if not resume: logging.info(f'Beginning fit with max_round_number={max_round}", "init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0, margin=2, nt=1): if", "Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else: raise ValueError(f'Invalid bank_size {bank_size}.') filename += f'_br={bank_ratio}' elif", "n_jobs elif wl in ['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'),", "= QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or", "qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train", "dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename += f'{max_n_leaves}' elif wl == 'ridge':", "train: {len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}') ### Choice of encoder if encodings ==", "Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1),", "if 'n' in fn: f_proc.append(normalize_weight) if 'r' in fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank,", "if fsh: filename += f'_to_{fsh}' if wl.startswith('rlc'): filename += f'-loc={locality}' activation = None", "wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'): filters =", "f'-relu' activation = torch.nn.functional.relu elif 'sigmoid' in nl: filename += f'-sigmoid' activation =", "filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak learner kwargs = {} if wl", "'from_bank': if 0 < bank_ratio < 1: bank_size = int(m*bank_ratio) filter_bank = Xtr[:bank_size]", "fit with max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best", "locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0, margin=2, nt=1):", "= LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if nt > 1: filename +=", "= MulticlassDecisionTree(max_n_leaves=max_n_leaves) kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename += f'{max_n_leaves}'", "WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if fsh else None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale,", "raise ValueError(f'Invalid weak learner name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ### Callbacks ckpt =", "max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42,", "label in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}')", "filter_bank = Xtr if fn: filename += f'_{fn}' f_proc = [] if 'c'", "zero_risk = BreakOnZeroRiskCallback() callbacks = [ckpt, logger, zero_risk, ] logging.info(f'Filename: {filename}') ### Fitting", "f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if fsh else None, filter_processing=f_proc,", "(Xtr, Ytr), (X_val, Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False, shuffle=seed) Xtr, Ytr", "da: logging.info(f'Adding {da} examples with data augmentation.') Xtr, Ytr = extend_mnist(Xtr, Ytr, N=da,", "Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%} |", "int(m*bank_ratio) filter_bank = Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else:", "LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for label, encoding", "fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if fsh else None,", "accuracy on last model: {qb.evaluate(Xts, Yts, mode=\"last\"):.3%}') if __name__ == '__main__': logging.basicConfig(level=logging.INFO, style='{',", "max_round_number={max_round} and patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val,", "weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt,", "max_round_number={max_round}.') qb = QuadBoostMHCR.load(f'results/{filename}-{resume}.ckpt') qb.resume_fit(Xtr, Ytr, X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting", "maxpool_shape=(nt, maxpool, maxpool)) elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool))", "fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0, margin=2,", "] logging.info(f'Filename: {filename}') ### Fitting the model if not resume: logging.info(f'Beginning fit with", "if 'r' in fn: f_proc.append(reduce_weight) w_gen = WeightFromBankGenerator(filter_bank=filter_bank, filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if", "else: encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit() for label in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding", "X_val=X_val, Y_val=Y_val, max_round_number=max_round, **kwargs) print(f'Best round recap:\\nBoosting round {qb.best_round.step_number+1:03d} | Train acc: {qb.best_round.train_acc:.3%}", "if all(label.isdigit() for label in encoder.labels_encoding): encoder = LabelEncoder({int(label):encoding for label, encoding in", "= LabelEncoder({int(label):encoding for label, encoding in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ###", "device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename += f'-nf={n_filters}-fs={fs}'", "shear=shear, ) if wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool)) elif", "{qb.best_round.risk:.3f}') print(f'Test accuracy on best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on last model:", "= MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif wl in", "acc: {qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on best", "Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or resume fitting a model else: logging.info(f'Resuming fit with", "maxpool)) elif wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if nt", "elif init_filters == 'from_data': filter_bank = Xtr if fn: filename += f'_{fn}' f_proc", "and patience={patience}.') qb = QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks,", "timed from quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution import plot_images @timed @parse def main(m=60_000,", "if 'maxpool' in nl: filename += f'-maxpool{maxpool}' if 'relu' in nl: filename +=", "init_filters == 'from_bank': if 0 < bank_ratio < 1: bank_size = int(m*bank_ratio) filter_bank", "maxpool)) if nt > 1: filename += f'-nt={nt}' if wl.endswith('ridge'): weak_learner = RandomConvolution(filters=filters,", "if 'relu' in nl: filename += f'-relu' activation = torch.nn.functional.relu elif 'sigmoid' in", "import LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import * from quadboost.callbacks import * from", "if da: logging.info(f'Adding {da} examples with data augmentation.') Xtr, Ytr = extend_mnist(Xtr, Ytr,", "= None if shear: filename += f'-shear={shear}' else: shear = None filter_bank =", "print(f'Test accuracy on best model: {qb.evaluate(Xts, Yts):.3%}') print(f'Test accuracy on last model: {qb.evaluate(Xts,", "bank_ratio=.05, fn='c', seed=42, nl='maxpool', maxpool=3, device='cpu', degrees=.0, scale=.0, shear=.0, margin=2, nt=1): if seed:", "encodings == 'allpairs': encoder = AllPairsEncoder(Ytr) else: encoder = LabelEncoder.load_encodings(encodings) if all(label.isdigit() for", "from quadboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from quadboost.weak_learner import * from quadboost.callbacks import", "Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val, Y_val = mnist.transform_data(X_val.reshape(X_val.shape[0],-1), Y_val) Xts, Yts = mnist.transform_data(Xts.reshape(Xts.shape[0],-1),", "QuadBoostMHCR(weak_learner, encoder=encoder) qb.fit(Xtr, Ytr, max_round_number=max_round, patience=patience, X_val=X_val, Y_val=Y_val, callbacks=callbacks, **kwargs) ### Or resume", "wl.startswith('rlc'): if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val = RandomConvolution.format_data(X_val).to(device=device) Xts = RandomConvolution.format_data(Xts).to(device=device) filename", "degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear) mnist.fit_scaler(Xtr, center=center, reduce=reduce) Xtr, Ytr = mnist.transform_data(Xtr.reshape(Xtr.shape[0],-1), Ytr) X_val,", "import parse, timed from quadboost.data_preprocessing.data_augmentation import extend_mnist from quadboost.weak_learner.random_convolution import plot_images @timed @parse", "{center}, reduce: {reduce})') logging.info(f'Number of examples - train: {len(Xtr)}, valid: {len(X_val)}, test: {len(Xts)}')", "CSVLogger(filename=filename+'-log.csv', dirname='./results/log') zero_risk = BreakOnZeroRiskCallback() callbacks = [ckpt, logger, zero_risk, ] logging.info(f'Filename: {filename}')", "scale=scale, shear=shear, ) if wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation, maxpool_shape=(nt, maxpool, maxpool))", "= [ckpt, logger, zero_risk, ] logging.info(f'Filename: {filename}') ### Fitting the model if not", "encodings='onehot', wl='rccridge', max_round=1000, patience=1000, resume=0, n_jobs=1, max_n_leaves=4, n_filters=10, fs=11, fsh=0, locality=4, init_filters='from_bank', bank_ratio=.05,", "filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear, ) if wl.startswith('rcc'): filters = Filters(n_filters=n_filters, weights_generator=w_gen, activation=activation,", "with data augmentation.') Xtr, Ytr = extend_mnist(Xtr, Ytr, N=da, degrees=degrees, scale=(1-scale, 1/(1-scale)), shear=shear)", "maxpool_shape=(nt, maxpool, maxpool)) if nt > 1: filename += f'-nt={nt}' if wl.endswith('ridge'): weak_learner", "'relu' in nl: filename += f'-relu' activation = torch.nn.functional.relu elif 'sigmoid' in nl:", "else: scale = None if shear: filename += f'-shear={shear}' else: shear = None", "= RandomConvolution(filters=filters, weak_learner=MulticlassDecisionStump) kwargs['n_jobs'] = n_jobs else: raise ValueError(f'Invalid weak learner name: \"{wl}\".')", "np.random.seed(seed) ### Data loading mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val), (Xts, Yts)", "wl.startswith('rlc'): filters = LocalFilters(n_filters=n_filters, weights_generator=w_gen, locality=locality, maxpool_shape=(nt, maxpool, maxpool)) if nt > 1:", "= n_jobs else: raise ValueError(f'Invalid weak learner name: \"{wl}\".') logging.info(f'Weak learner: {type(weak_learner).__name__}') ###", "Fitting the model if not resume: logging.info(f'Beginning fit with max_round_number={max_round} and patience={patience}.') qb", "'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs elif wl in ['dt', 'decision-tree']: weak_learner = MulticlassDecisionTree(max_n_leaves=max_n_leaves)", "'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs'] = n_jobs filename += f'{max_n_leaves}' elif wl == 'ridge': weak_learner", "wl in ['ds', 'decision-stump']: weak_learner = MulticlassDecisionStump() kwargs = dict(zip(('sorted_X', 'sorted_X_idx'), weak_learner.sort_data(Xtr))) kwargs['n_jobs']", "in nl: filename += f'-relu' activation = torch.nn.functional.relu elif 'sigmoid' in nl: filename", "filter_bank = Xtr[:bank_size] Xtr, Ytr = Xtr[bank_size:], Ytr[bank_size:] logging.info(f'Bank size: {bank_size}') else: raise", "{qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on best model:", "in encoder.labels_encoding.items()}) logging.info(f'Encoding: {encodings}') filename = f'd={dataset}-e={encodings}-wl={wl}' ### Choice of weak learner kwargs", "filters_shape=(fs, fs), filters_shape_high=(fsh, fsh) if fsh else None, filter_processing=f_proc, margin=margin, degrees=degrees, scale=scale, shear=shear,", "weak_learner = WLThresholdedRidge(threshold=.5) elif wl.startswith('rcc') or wl.startswith('rlc'): if device.startswith('cuda'): Xtr = RandomConvolution.format_data(Xtr).to(device=device) X_val", "mnist = MNISTDataset.load(dataset+'.pkl') (Xtr, Ytr), (X_val, Y_val), (Xts, Yts) = mnist.get_train_valid_test(valid=val, center=False, reduce=False,", "Train acc: {qb.best_round.train_acc:.3%} | Valid acc: {qb.best_round.valid_acc:.3%} | Risk: {qb.best_round.risk:.3f}') print(f'Test accuracy on" ]
[ "print min([1,2,3,4]) print min([2,1],[1,2],[1,1],[1,1,0]) # tuples print \"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0)) #", "lists print \"\\nlists\" print min([1,2,3,4]) print min([2,1],[1,2],[1,1],[1,1,0]) # tuples print \"\\ntuples\" print min((1,2,3,4))", "print \"\\nlists\" print min([1,2,3,4]) print min([2,1],[1,2],[1,1],[1,1,0]) # tuples print \"\\ntuples\" print min((1,2,3,4)) print", "min([2,1],[1,2],[1,1],[1,1,0]) # tuples print \"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0)) # dictionaries print \"\\ndictionaries\"", "\"\\nlists\" print min([1,2,3,4]) print min([2,1],[1,2],[1,1],[1,1,0]) # tuples print \"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0))", "min([1,2,3,4]) print min([2,1],[1,2],[1,1],[1,1,0]) # tuples print \"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0)) # dictionaries", "tuples print \"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0)) # dictionaries print \"\\ndictionaries\" print min({1:2,3:4,5:6})", "\"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0)) # dictionaries print \"\\ndictionaries\" print min({1:2,3:4,5:6}) print min({1:6,3:4,5:2})", "# lists print \"\\nlists\" print min([1,2,3,4]) print min([2,1],[1,2],[1,1],[1,1,0]) # tuples print \"\\ntuples\" print", "# tuples print \"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0)) # dictionaries print \"\\ndictionaries\" print", "print min([2,1],[1,2],[1,1],[1,1,0]) # tuples print \"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0)) # dictionaries print", "print \"\\ntuples\" print min((1,2,3,4)) print min((2,1),(1,2),(1,1),(1,1,0)) # dictionaries print \"\\ndictionaries\" print min({1:2,3:4,5:6}) print" ]
[]
[ "futures import grpc import relationExtractService_pb2 import relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context):", "request.sentence triples = tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for triple in triples: data =", "triples: data = response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response def serve(): server =", "serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server) server.add_insecure_port(\"[::]:4232\") server.start() server.wait_for_termination() if __name__ == '__main__': serve()", "import grpc import relationExtractService_pb2 import relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence", "in triples: data = response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response def serve(): server", "ExtractTriple(self,request,context): sentence = request.sentence triples = tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for triple in", "import futures import grpc import relationExtractService_pb2 import relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def", "triples = tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for triple in triples: data = response.triples.add()", "= tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for triple in triples: data = response.triples.add() data.sub=triple[0]", "triple in triples: data = response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response def serve():", "grpc import relationExtractService_pb2 import relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence =", "import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence = request.sentence triples = tools.extract_items(sentence) response", "tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence = request.sentence triples = tools.extract_items(sentence) response =", "= request.sentence triples = tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for triple in triples: data", "relationExtractService_pb2.relationExtractResponse() for triple in triples: data = response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response", "data.pred=triple[1] data.obj=triple[2] return response def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server) server.add_insecure_port(\"[::]:4232\") server.start() server.wait_for_termination()", "import relationExtractService_pb2 import relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence = request.sentence", "sentence = request.sentence triples = tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for triple in triples:", "response def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server) server.add_insecure_port(\"[::]:4232\") server.start() server.wait_for_termination() if __name__ ==", "def ExtractTriple(self,request,context): sentence = request.sentence triples = tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for triple", "def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server) server.add_insecure_port(\"[::]:4232\") server.start() server.wait_for_termination() if __name__ == '__main__':", "concurrent import futures import grpc import relationExtractService_pb2 import relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer):", "response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server) server.add_insecure_port(\"[::]:4232\")", "data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server) server.add_insecure_port(\"[::]:4232\") server.start()", "tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for triple in triples: data = response.triples.add() data.sub=triple[0] data.pred=triple[1]", "= relationExtractService_pb2.relationExtractResponse() for triple in triples: data = response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return", "class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence = request.sentence triples = tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse()", "for triple in triples: data = response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response def", "return response def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server) server.add_insecure_port(\"[::]:4232\") server.start() server.wait_for_termination() if __name__", "data.obj=triple[2] return response def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server) server.add_insecure_port(\"[::]:4232\") server.start() server.wait_for_termination() if", "relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence = request.sentence triples = tools.extract_items(sentence) response = relationExtractService_pb2.relationExtractResponse() for", "= response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) relationExtractService_pb2_grpc.add_relationExtractServiceServicer_to_server(relationExtractService(),server)", "data = response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2] return response def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=8))", "relationExtractService_pb2 import relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence = request.sentence triples", "import relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence = request.sentence triples =", "relationExtractService_pb2_grpc import tools class relationExtractService(relationExtractService_pb2_grpc.relationExtractServiceServicer): def ExtractTriple(self,request,context): sentence = request.sentence triples = tools.extract_items(sentence)", "from concurrent import futures import grpc import relationExtractService_pb2 import relationExtractService_pb2_grpc import tools class", "response = relationExtractService_pb2.relationExtractResponse() for triple in triples: data = response.triples.add() data.sub=triple[0] data.pred=triple[1] data.obj=triple[2]" ]
[ "import torch.nn.functional as F from torch_geometric.data import Data, Batch from . import base_networks", "nc, components = cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1, nc):", "1), device=constants.DEVICE) * -100, node_delete_logits], dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if", "dim=0) return masks def delete_scores(self, graph): \"\"\"Compute delete scores for each node in", "# [N-1, 1] delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100, node_delete_logits], dim=0) return", "= base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet forward pass. Note: Assume that the graph", "= torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1, nc): mask = components == j component_size", "The first logit (background) is always low, so BG is never deleted. \"\"\"", "dictionary concat_features = torch.cat([encodings[key] for key in encodings], dim=1) # [N, \\sum_i d_i]", "self.node_encoder(graph) # dictionary concat_features = torch.cat([encodings[key] for key in encodings], dim=1) # [N,", "for each node in the graph. Args: graph: a torch_geometric.Data instance Returns: a", "[N, 4] torch.LongTensor. xmin, ymin, xmax, ymax. Returns: a [N] torch.FloatTensor of delete", "from .util import utilities as util_ class DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet, self).__init__()", "torch.FloatTensor. XYZ image - mask: a [N, h, w] torch.FloatTensor of values in", "deleted. \"\"\" encodings = self.node_encoder(graph) # dictionary concat_features = torch.cat([encodings[key] for key in", "util_ class DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module =", "cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components = cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for j", "torch.LongTensor. xmin, ymin, xmax, ymax. Returns: a [N] torch.FloatTensor of delete score logits.", "concat_features[0:1] # [1, \\sum_i d_i] node_features = concat_features[1:] # [N-1, \\sum_i d_i] node_minus_bg_features", "mask. Concatenate them to masks. Args: masks: a [N, H, W] torch.Tensor with", "w] torch.FloatTensor of values in {0, 1} - orig_masks: a [N, H, W]", "return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model' in self.config: self.model = self.config['deletenet_model']", "a [N, H, W] torch.Tensor with values in {0, 1}. fg_mask: a [H,", "bg_feature # [N-1, \\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits =", "masks def delete_scores(self, graph): \"\"\"Compute delete scores for each node in the graph.", "cv2 import torch import torch.nn as nn from torch.nn import Sequential as Seq,", ".util import utilities as util_ class DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet, self).__init__() self.node_encoder", "a [N, h, w] torch.FloatTensor of values in {0, 1} - orig_masks: a", "import utilities as util_ class DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet, self).__init__() self.node_encoder =", "of new masks. delta = #new_masks. \"\"\" occupied_mask = masks.sum(dim=0) > 0.5 fg_mask", "else: self.model = DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new potential masks.", "d_i] node_minus_bg_features = node_features - bg_feature # [N-1, \\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features)", "\\sum_i d_i] bg_feature = concat_features[0:1] # [1, \\sum_i d_i] node_features = concat_features[1:] #", "from collections import OrderedDict import numpy as np import cv2 import torch import", "from . import graph_construction as gc from . import constants from .util import", "= fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components =", "values in {0, 1} - orig_masks: a [N, H, W] torch.FloatTensor of values", "def forward(self, graph): \"\"\"DeleteNet forward pass. Note: Assume that the graph contains the", "from torch.nn import Sequential as Seq, Linear, ReLU import torch.nn.functional as F from", "node as the first node. Args: graph: a torch_geometric.Data instance with attributes: -", "so BG is never deleted. \"\"\" encodings = self.node_encoder(graph) # dictionary concat_features =", "Seq, Linear, ReLU import torch.nn.functional as F from torch_geometric.data import Data, Batch from", "a [H, W] torch.Tensor with values in {0, 1}. Returns: a [N +", "j in range(1, nc): mask = components == j component_size = mask.sum().float() if", "graph: a torch_geometric.Data instance with attributes: - rgb: a [N, 256, h, w]", "h, w] torch.FloatTensor of values in {0, 1} - orig_masks: a [N, H,", "torch.nn.functional as F from torch_geometric.data import Data, Batch from . import base_networks from", "import numpy as np import cv2 import torch import torch.nn as nn from", "node in the graph. Args: graph: a torch_geometric.Data instance Returns: a [N] torch.Tensor", "[N-1, \\sum_i d_i] node_minus_bg_features = node_features - bg_feature # [N-1, \\sum_i d_i] node_delete_logits", "F from torch_geometric.data import Data, Batch from . import base_networks from . import", "new masks. delta = #new_masks. \"\"\" occupied_mask = masks.sum(dim=0) > 0.5 fg_mask =", "See if any connected components of fg_mask _setminus_ mask can be considered as", "\\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE)", "torch.FloatTensor of values in {0, 1}. Original image size. - crop_indices: a [N,", "config): super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet", "forward(self, graph): \"\"\"DeleteNet forward pass. Note: Assume that the graph contains the background", "> self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()], dim=0) return masks def delete_scores(self, graph): \"\"\"Compute", "graph): \"\"\"Compute delete scores for each node in the graph. Args: graph: a", "dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model' in self.config: self.model =", "[N, 256, h, w] torch.FloatTensor of ResnNet50+FPN rgb image features - depth: a", ". import graph_construction as gc from . import constants from .util import utilities", "as nn from torch.nn import Sequential as Seq, Linear, ReLU import torch.nn.functional as", "logits. The first logit (background) is always low, so BG is never deleted.", "super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet forward", "class DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config'])", "masks: a [N, H, W] torch.Tensor with values in {0, 1}. fg_mask: a", "= torch.cat([masks, mask[None].float()], dim=0) return masks def delete_scores(self, graph): \"\"\"Compute delete scores for", "import Sequential as Seq, Linear, ReLU import torch.nn.functional as F from torch_geometric.data import", "first node. Args: graph: a torch_geometric.Data instance with attributes: - rgb: a [N,", "[N, H, W] torch.Tensor with values in {0, 1}. fg_mask: a [H, W]", "constants from .util import utilities as util_ class DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet,", "delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100, node_delete_logits], dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper):", "as a new mask. Concatenate them to masks. Args: masks: a [N, H,", "d_i] node_features = concat_features[1:] # [N-1, \\sum_i d_i] node_minus_bg_features = node_features - bg_feature", "H, W] torch.FloatTensor of values in {0, 1}. Original image size. - crop_indices:", "delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model' in self.config: self.model = self.config['deletenet_model'] else:", "ResnNet50+FPN rgb image features - depth: a [N, 3, h, w] torch.FloatTensor. XYZ", "low, so BG is never deleted. \"\"\" encodings = self.node_encoder(graph) # dictionary concat_features", ". import constants from .util import utilities as util_ class DeleteNet(nn.Module): def __init__(self,", "[N + delta, H, W] np.ndarray of new masks. delta = #new_masks. \"\"\"", "if 'deletenet_model' in self.config: self.model = self.config['deletenet_model'] else: self.model = DeleteNet(self.config) self.model.to(self.device) def", "1] delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100, node_delete_logits], dim=0) return delete_logits[:,0] class", "Note: Assume that the graph contains the background node as the first node.", "def __init__(self, config): super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self,", "ReLU import torch.nn.functional as F from torch_geometric.data import Data, Batch from . import", "\"\"\"Compute delete scores for each node in the graph. Args: graph: a torch_geometric.Data", "'deletenet_model' in self.config: self.model = self.config['deletenet_model'] else: self.model = DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self,", "cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1, nc): mask = components", "in the graph. Args: graph: a torch_geometric.Data instance Returns: a [N] torch.Tensor with", "graph. Args: graph: a torch_geometric.Data instance Returns: a [N] torch.Tensor with values in", "torch.cat([masks, mask[None].float()], dim=0) return masks def delete_scores(self, graph): \"\"\"Compute delete scores for each", "torch_geometric.Data instance Returns: a [N] torch.Tensor with values in [0, 1] \"\"\" return", "first logit (background) is always low, so BG is never deleted. \"\"\" encodings", "forward pass. Note: Assume that the graph contains the background node as the", "nn from torch.nn import Sequential as Seq, Linear, ReLU import torch.nn.functional as F", "d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE) *", "rgb image features - depth: a [N, 3, h, w] torch.FloatTensor. XYZ image", "= torch.cat([encodings[key] for key in encodings], dim=1) # [N, \\sum_i d_i] bg_feature =", "ymin, xmax, ymax. Returns: a [N] torch.FloatTensor of delete score logits. The first", "self.model = self.config['deletenet_model'] else: self.model = DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute", "# [N-1, \\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits = torch.cat([torch.ones((1,", "import itertools from collections import OrderedDict import numpy as np import cv2 import", "- orig_masks: a [N, H, W] torch.FloatTensor of values in {0, 1}. Original", "the graph contains the background node as the first node. Args: graph: a", "new mask. Concatenate them to masks. Args: masks: a [N, H, W] torch.Tensor", "base_networks from . import graph_construction as gc from . import constants from .util", "[N, 3, h, w] torch.FloatTensor. XYZ image - mask: a [N, h, w]", "256, h, w] torch.FloatTensor of ResnNet50+FPN rgb image features - depth: a [N,", "as np import cv2 import torch import torch.nn as nn from torch.nn import", "Assume that the graph contains the background node as the first node. Args:", "Original image size. - crop_indices: a [N, 4] torch.LongTensor. xmin, ymin, xmax, ymax.", "values in {0, 1}. Returns: a [N + delta, H, W] np.ndarray of", "of ResnNet50+FPN rgb image features - depth: a [N, 3, h, w] torch.FloatTensor.", "values in {0, 1}. Original image size. - crop_indices: a [N, 4] torch.LongTensor.", "= concat_features[1:] # [N-1, \\sum_i d_i] node_minus_bg_features = node_features - bg_feature # [N-1,", "a new mask. Concatenate them to masks. Args: masks: a [N, H, W]", "import constants from .util import utilities as util_ class DeleteNet(nn.Module): def __init__(self, config):", "= self.node_encoder(graph) # dictionary concat_features = torch.cat([encodings[key] for key in encodings], dim=1) #", "{0, 1} - orig_masks: a [N, H, W] torch.FloatTensor of values in {0,", "if any connected components of fg_mask _setminus_ mask can be considered as a", "masks = torch.cat([masks, mask[None].float()], dim=0) return masks def delete_scores(self, graph): \"\"\"Compute delete scores", "\"\"\" encodings = self.node_encoder(graph) # dictionary concat_features = torch.cat([encodings[key] for key in encodings],", "DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model' in self.config: self.model = self.config['deletenet_model'] else: self.model =", "[N, h, w] torch.FloatTensor of values in {0, 1} - orig_masks: a [N,", "a [N, H, W] torch.FloatTensor of values in {0, 1}. Original image size.", "self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100, node_delete_logits], dim=0)", "xmin, ymin, xmax, ymax. Returns: a [N] torch.FloatTensor of delete score logits. The", "be considered as a new mask. Concatenate them to masks. Args: masks: a", "image - mask: a [N, h, w] torch.FloatTensor of values in {0, 1}", "ymax. Returns: a [N] torch.FloatTensor of delete score logits. The first logit (background)", "1}. Returns: a [N + delta, H, W] np.ndarray of new masks. delta", "new potential masks. See if any connected components of fg_mask _setminus_ mask can", "component_size = mask.sum().float() if component_size > self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()], dim=0) return", "fg_mask: a [H, W] torch.Tensor with values in {0, 1}. Returns: a [N", "as gc from . import constants from .util import utilities as util_ class", "for key in encodings], dim=1) # [N, \\sum_i d_i] bg_feature = concat_features[0:1] #", "Args: masks: a [N, H, W] torch.Tensor with values in {0, 1}. fg_mask:", "xmax, ymax. Returns: a [N] torch.FloatTensor of delete score logits. The first logit", "[N-1, 1] delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100, node_delete_logits], dim=0) return delete_logits[:,0]", "components = torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1, nc): mask = components == j", "values in {0, 1}. fg_mask: a [H, W] torch.Tensor with values in {0,", "self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new potential masks. See if any connected", "def delete_scores(self, graph): \"\"\"Compute delete scores for each node in the graph. Args:", "as Seq, Linear, ReLU import torch.nn.functional as F from torch_geometric.data import Data, Batch", "h, w] torch.FloatTensor. XYZ image - mask: a [N, h, w] torch.FloatTensor of", "masks. delta = #new_masks. \"\"\" occupied_mask = masks.sum(dim=0) > 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8)", "from . import constants from .util import utilities as util_ class DeleteNet(nn.Module): def", "- mask: a [N, h, w] torch.FloatTensor of values in {0, 1} -", "rgb: a [N, 256, h, w] torch.FloatTensor of ResnNet50+FPN rgb image features -", "encodings], dim=1) # [N, \\sum_i d_i] bg_feature = concat_features[0:1] # [1, \\sum_i d_i]", "torch.nn as nn from torch.nn import Sequential as Seq, Linear, ReLU import torch.nn.functional", "torch_geometric.Data instance with attributes: - rgb: a [N, 256, h, w] torch.FloatTensor of", "a [N + delta, H, W] np.ndarray of new masks. delta = #new_masks.", "is never deleted. \"\"\" encodings = self.node_encoder(graph) # dictionary concat_features = torch.cat([encodings[key] for", "node_features = concat_features[1:] # [N-1, \\sum_i d_i] node_minus_bg_features = node_features - bg_feature #", "torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1, nc): mask = components == j component_size =", "potential masks. See if any connected components of fg_mask _setminus_ mask can be", "[H, W] torch.Tensor with values in {0, 1}. Returns: a [N + delta,", "the background node as the first node. Args: graph: a torch_geometric.Data instance with", "component_size > self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()], dim=0) return masks def delete_scores(self, graph):", "delete scores for each node in the graph. Args: graph: a torch_geometric.Data instance", "= cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components = cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for", "of values in {0, 1}. Original image size. - crop_indices: a [N, 4]", "- depth: a [N, 3, h, w] torch.FloatTensor. XYZ image - mask: a", "4] torch.LongTensor. xmin, ymin, xmax, ymax. Returns: a [N] torch.FloatTensor of delete score", "bg_feature = concat_features[0:1] # [1, \\sum_i d_i] node_features = concat_features[1:] # [N-1, \\sum_i", "of fg_mask _setminus_ mask can be considered as a new mask. Concatenate them", "graph_construction as gc from . import constants from .util import utilities as util_", "DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def", "{0, 1}. Returns: a [N + delta, H, W] np.ndarray of new masks.", "graph: a torch_geometric.Data instance Returns: a [N] torch.Tensor with values in [0, 1]", "= base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet forward pass. Note: Assume", "get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new potential masks. See if any connected components of", "import Data, Batch from . import base_networks from . import graph_construction as gc", "components of fg_mask _setminus_ mask can be considered as a new mask. Concatenate", "np.ndarray of new masks. delta = #new_masks. \"\"\" occupied_mask = masks.sum(dim=0) > 0.5", "[N, H, W] torch.FloatTensor of values in {0, 1}. Original image size. -", "#new_masks. \"\"\" occupied_mask = masks.sum(dim=0) > 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0", "of delete score logits. The first logit (background) is always low, so BG", "masks. See if any connected components of fg_mask _setminus_ mask can be considered", "node_minus_bg_features = node_features - bg_feature # [N-1, \\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) #", "torch_geometric.data import Data, Batch from . import base_networks from . import graph_construction as", "fg_mask): \"\"\"Compute new potential masks. See if any connected components of fg_mask _setminus_", "DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new potential masks. See if any", "torch.Tensor with values in {0, 1}. Returns: a [N + delta, H, W]", "graph contains the background node as the first node. Args: graph: a torch_geometric.Data", "base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet forward pass. Note: Assume that", "Sequential as Seq, Linear, ReLU import torch.nn.functional as F from torch_geometric.data import Data,", "mask can be considered as a new mask. Concatenate them to masks. Args:", "attributes: - rgb: a [N, 256, h, w] torch.FloatTensor of ResnNet50+FPN rgb image", "node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100,", "Data, Batch from . import base_networks from . import graph_construction as gc from", "import cv2 import torch import torch.nn as nn from torch.nn import Sequential as", "torch.Tensor with values in {0, 1}. fg_mask: a [H, W] torch.Tensor with values", "in {0, 1} - orig_masks: a [N, H, W] torch.FloatTensor of values in", "of values in {0, 1} - orig_masks: a [N, H, W] torch.FloatTensor of", "the first node. Args: graph: a torch_geometric.Data instance with attributes: - rgb: a", "# dictionary concat_features = torch.cat([encodings[key] for key in encodings], dim=1) # [N, \\sum_i", "Args: graph: a torch_geometric.Data instance Returns: a [N] torch.Tensor with values in [0,", "torch.FloatTensor of values in {0, 1} - orig_masks: a [N, H, W] torch.FloatTensor", "== j component_size = mask.sum().float() if component_size > self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()],", "them to masks. Args: masks: a [N, H, W] torch.Tensor with values in", "H, W] torch.Tensor with values in {0, 1}. fg_mask: a [H, W] torch.Tensor", "self.config['deletenet_model'] else: self.model = DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new potential", "= #new_masks. \"\"\" occupied_mask = masks.sum(dim=0) > 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] =", "= concat_features[0:1] # [1, \\sum_i d_i] node_features = concat_features[1:] # [N-1, \\sum_i d_i]", "W] torch.Tensor with values in {0, 1}. fg_mask: a [H, W] torch.Tensor with", "can be considered as a new mask. Concatenate them to masks. Args: masks:", "self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()], dim=0) return masks def delete_scores(self, graph): \"\"\"Compute delete", "= masks.sum(dim=0) > 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask = cv2.erode(fg_mask,", "torch.cat([encodings[key] for key in encodings], dim=1) # [N, \\sum_i d_i] bg_feature = concat_features[0:1]", "{0, 1}. Original image size. - crop_indices: a [N, 4] torch.LongTensor. xmin, ymin,", "1}. Original image size. - crop_indices: a [N, 4] torch.LongTensor. xmin, ymin, xmax,", "image size. - crop_indices: a [N, 4] torch.LongTensor. xmin, ymin, xmax, ymax. Returns:", "0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc,", "= self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits = torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100, node_delete_logits],", "import base_networks from . import graph_construction as gc from . import constants from", "return masks def delete_scores(self, graph): \"\"\"Compute delete scores for each node in the", "torch.FloatTensor of delete score logits. The first logit (background) is always low, so", "= torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100, node_delete_logits], dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def", ". import base_networks from . import graph_construction as gc from . import constants", "fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components = cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE)", "in self.config: self.model = self.config['deletenet_model'] else: self.model = DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks,", "torch.FloatTensor of ResnNet50+FPN rgb image features - depth: a [N, 3, h, w]", "self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet forward pass. Note: Assume that the", "BG is never deleted. \"\"\" encodings = self.node_encoder(graph) # dictionary concat_features = torch.cat([encodings[key]", "a torch_geometric.Data instance with attributes: - rgb: a [N, 256, h, w] torch.FloatTensor", "Concatenate them to masks. Args: masks: a [N, H, W] torch.Tensor with values", "the graph. Args: graph: a torch_geometric.Data instance Returns: a [N] torch.Tensor with values", "setup(self): if 'deletenet_model' in self.config: self.model = self.config['deletenet_model'] else: self.model = DeleteNet(self.config) self.model.to(self.device)", "import torch.nn as nn from torch.nn import Sequential as Seq, Linear, ReLU import", "itertools from collections import OrderedDict import numpy as np import cv2 import torch", "node_features - bg_feature # [N-1, \\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1, 1]", "# [N-1, \\sum_i d_i] node_minus_bg_features = node_features - bg_feature # [N-1, \\sum_i d_i]", "as util_ class DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module", "-100, node_delete_logits], dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model' in self.config:", "W] torch.FloatTensor of values in {0, 1}. Original image size. - crop_indices: a", "depth: a [N, 3, h, w] torch.FloatTensor. XYZ image - mask: a [N,", "a torch_geometric.Data instance Returns: a [N] torch.Tensor with values in [0, 1] \"\"\"", "w] torch.FloatTensor of ResnNet50+FPN rgb image features - depth: a [N, 3, h,", "Linear, ReLU import torch.nn.functional as F from torch_geometric.data import Data, Batch from .", "def setup(self): if 'deletenet_model' in self.config: self.model = self.config['deletenet_model'] else: self.model = DeleteNet(self.config)", "- crop_indices: a [N, 4] torch.LongTensor. xmin, ymin, xmax, ymax. Returns: a [N]", "with attributes: - rgb: a [N, 256, h, w] torch.FloatTensor of ResnNet50+FPN rgb", "w] torch.FloatTensor. XYZ image - mask: a [N, h, w] torch.FloatTensor of values", "components = cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1, nc): mask", "numpy as np import cv2 import torch import torch.nn as nn from torch.nn", "\\sum_i d_i] node_features = concat_features[1:] # [N-1, \\sum_i d_i] node_minus_bg_features = node_features -", "scores for each node in the graph. Args: graph: a torch_geometric.Data instance Returns:", "[N-1, \\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits = torch.cat([torch.ones((1, 1),", "delta, H, W] np.ndarray of new masks. delta = #new_masks. \"\"\" occupied_mask =", "if component_size > self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()], dim=0) return masks def delete_scores(self,", "never deleted. \"\"\" encodings = self.node_encoder(graph) # dictionary concat_features = torch.cat([encodings[key] for key", "\"\"\"DeleteNet forward pass. Note: Assume that the graph contains the background node as", "from torch_geometric.data import Data, Batch from . import base_networks from . import graph_construction", "mask: a [N, h, w] torch.FloatTensor of values in {0, 1} - orig_masks:", "base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet forward pass. Note: Assume that the graph contains", "image features - depth: a [N, 3, h, w] torch.FloatTensor. XYZ image -", "# [1, \\sum_i d_i] node_features = concat_features[1:] # [N-1, \\sum_i d_i] node_minus_bg_features =", "np.ones((3,3)), iterations=1) nc, components = cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for j in", "_setminus_ mask can be considered as a new mask. Concatenate them to masks.", "utilities as util_ class DeleteNet(nn.Module): def __init__(self, config): super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config'])", "is always low, so BG is never deleted. \"\"\" encodings = self.node_encoder(graph) #", "occupied_mask = masks.sum(dim=0) > 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask =", "graph): \"\"\"DeleteNet forward pass. Note: Assume that the graph contains the background node", "to masks. Args: masks: a [N, H, W] torch.Tensor with values in {0,", "torch.cat([torch.ones((1, 1), device=constants.DEVICE) * -100, node_delete_logits], dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self):", "(background) is always low, so BG is never deleted. \"\"\" encodings = self.node_encoder(graph)", "self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet forward pass. Note:", "OrderedDict import numpy as np import cv2 import torch import torch.nn as nn", "as F from torch_geometric.data import Data, Batch from . import base_networks from .", "Batch from . import base_networks from . import graph_construction as gc from .", "key in encodings], dim=1) # [N, \\sum_i d_i] bg_feature = concat_features[0:1] # [1,", "masks. Args: masks: a [N, H, W] torch.Tensor with values in {0, 1}.", "masks, fg_mask): \"\"\"Compute new potential masks. See if any connected components of fg_mask", "j component_size = mask.sum().float() if component_size > self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()], dim=0)", "any connected components of fg_mask _setminus_ mask can be considered as a new", "that the graph contains the background node as the first node. Args: graph:", "- bg_feature # [N-1, \\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1, 1] delete_logits", "iterations=1) nc, components = cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1,", "> 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1)", "concat_features = torch.cat([encodings[key] for key in encodings], dim=1) # [N, \\sum_i d_i] bg_feature", "delete score logits. The first logit (background) is always low, so BG is", "instance with attributes: - rgb: a [N, 256, h, w] torch.FloatTensor of ResnNet50+FPN", "encodings = self.node_encoder(graph) # dictionary concat_features = torch.cat([encodings[key] for key in encodings], dim=1)", "in {0, 1}. Returns: a [N + delta, H, W] np.ndarray of new", "pass. Note: Assume that the graph contains the background node as the first", "in {0, 1}. fg_mask: a [H, W] torch.Tensor with values in {0, 1}.", "a [N, 3, h, w] torch.FloatTensor. XYZ image - mask: a [N, h,", "W] torch.Tensor with values in {0, 1}. Returns: a [N + delta, H,", "import torch import torch.nn as nn from torch.nn import Sequential as Seq, Linear,", "background node as the first node. Args: graph: a torch_geometric.Data instance with attributes:", "[1, \\sum_i d_i] node_features = concat_features[1:] # [N-1, \\sum_i d_i] node_minus_bg_features = node_features", "fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components", "= components == j component_size = mask.sum().float() if component_size > self.config['min_pixels_thresh']: masks =", "W] np.ndarray of new masks. delta = #new_masks. \"\"\" occupied_mask = masks.sum(dim=0) >", "= self.config['deletenet_model'] else: self.model = DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new", "0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components = cv2.connectedComponents(fg_mask, connectivity=8) components =", "* -100, node_delete_logits], dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model' in", "h, w] torch.FloatTensor of ResnNet50+FPN rgb image features - depth: a [N, 3,", "instance Returns: a [N] torch.Tensor with values in [0, 1] \"\"\" return torch.sigmoid(self.model(graph))", "a [N] torch.FloatTensor of delete score logits. The first logit (background) is always", "d_i] bg_feature = concat_features[0:1] # [1, \\sum_i d_i] node_features = concat_features[1:] # [N-1,", "device=constants.DEVICE) * -100, node_delete_logits], dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model'", "\\sum_i d_i] node_minus_bg_features = node_features - bg_feature # [N-1, \\sum_i d_i] node_delete_logits =", "{0, 1}. fg_mask: a [H, W] torch.Tensor with values in {0, 1}. Returns:", "+ delta, H, W] np.ndarray of new masks. delta = #new_masks. \"\"\" occupied_mask", "# [N, \\sum_i d_i] bg_feature = concat_features[0:1] # [1, \\sum_i d_i] node_features =", "1} - orig_masks: a [N, H, W] torch.FloatTensor of values in {0, 1}.", "Returns: a [N + delta, H, W] np.ndarray of new masks. delta =", "class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model' in self.config: self.model = self.config['deletenet_model'] else: self.model", "[N] torch.FloatTensor of delete score logits. The first logit (background) is always low,", "a [N, 256, h, w] torch.FloatTensor of ResnNet50+FPN rgb image features - depth:", "masks.sum(dim=0) > 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)),", "mask.sum().float() if component_size > self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()], dim=0) return masks def", "in range(1, nc): mask = components == j component_size = mask.sum().float() if component_size", "node. Args: graph: a torch_geometric.Data instance with attributes: - rgb: a [N, 256,", "import OrderedDict import numpy as np import cv2 import torch import torch.nn as", "considered as a new mask. Concatenate them to masks. Args: masks: a [N,", "np import cv2 import torch import torch.nn as nn from torch.nn import Sequential", "connected components of fg_mask _setminus_ mask can be considered as a new mask.", "dim=1) # [N, \\sum_i d_i] bg_feature = concat_features[0:1] # [1, \\sum_i d_i] node_features", "H, W] np.ndarray of new masks. delta = #new_masks. \"\"\" occupied_mask = masks.sum(dim=0)", "range(1, nc): mask = components == j component_size = mask.sum().float() if component_size >", "orig_masks: a [N, H, W] torch.FloatTensor of values in {0, 1}. Original image", "\"\"\" occupied_mask = masks.sum(dim=0) > 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask", "gc from . import constants from .util import utilities as util_ class DeleteNet(nn.Module):", "with values in {0, 1}. Returns: a [N + delta, H, W] np.ndarray", "fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components = cv2.connectedComponents(fg_mask,", "= DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new potential masks. See if", "= mask.sum().float() if component_size > self.config['min_pixels_thresh']: masks = torch.cat([masks, mask[None].float()], dim=0) return masks", "a [N, 4] torch.LongTensor. xmin, ymin, xmax, ymax. Returns: a [N] torch.FloatTensor of", "self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph): \"\"\"DeleteNet forward pass.", "1}. fg_mask: a [H, W] torch.Tensor with values in {0, 1}. Returns: a", "Returns: a [N] torch.FloatTensor of delete score logits. The first logit (background) is", "mask[None].float()], dim=0) return masks def delete_scores(self, graph): \"\"\"Compute delete scores for each node", "import graph_construction as gc from . import constants from .util import utilities as", "def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new potential masks. See if any connected components", "each node in the graph. Args: graph: a torch_geometric.Data instance Returns: a [N]", "torch.nn import Sequential as Seq, Linear, ReLU import torch.nn.functional as F from torch_geometric.data", "nc): mask = components == j component_size = mask.sum().float() if component_size > self.config['min_pixels_thresh']:", "for j in range(1, nc): mask = components == j component_size = mask.sum().float()", "self.model = DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask): \"\"\"Compute new potential masks. See", "3, h, w] torch.FloatTensor. XYZ image - mask: a [N, h, w] torch.FloatTensor", "in {0, 1}. Original image size. - crop_indices: a [N, 4] torch.LongTensor. xmin,", "= node_features - bg_feature # [N-1, \\sum_i d_i] node_delete_logits = self.bg_fusion_module(node_minus_bg_features) # [N-1,", "connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1, nc): mask = components ==", "delta = #new_masks. \"\"\" occupied_mask = masks.sum(dim=0) > 0.5 fg_mask = fg_mask.cpu().numpy().astype(np.uint8) fg_mask[occupied_mask.cpu().numpy()]", "collections import OrderedDict import numpy as np import cv2 import torch import torch.nn", "with values in {0, 1}. fg_mask: a [H, W] torch.Tensor with values in", "= 0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components = cv2.connectedComponents(fg_mask, connectivity=8) components", "crop_indices: a [N, 4] torch.LongTensor. xmin, ymin, xmax, ymax. Returns: a [N] torch.FloatTensor", "fg_mask _setminus_ mask can be considered as a new mask. Concatenate them to", "size. - crop_indices: a [N, 4] torch.LongTensor. xmin, ymin, xmax, ymax. Returns: a", "Args: graph: a torch_geometric.Data instance with attributes: - rgb: a [N, 256, h,", "__init__(self, config): super(DeleteNet, self).__init__() self.node_encoder = base_networks.NodeEncoder(config['node_encoder_config']) self.bg_fusion_module = base_networks.LinearEncoder(config['bg_fusion_module_config']) def forward(self, graph):", "torch import torch.nn as nn from torch.nn import Sequential as Seq, Linear, ReLU", "from . import base_networks from . import graph_construction as gc from . import", "- rgb: a [N, 256, h, w] torch.FloatTensor of ResnNet50+FPN rgb image features", "delete_scores(self, graph): \"\"\"Compute delete scores for each node in the graph. Args: graph:", "\"\"\"Compute new potential masks. See if any connected components of fg_mask _setminus_ mask", "fg_mask[occupied_mask.cpu().numpy()] = 0 fg_mask = cv2.erode(fg_mask, np.ones((3,3)), iterations=1) nc, components = cv2.connectedComponents(fg_mask, connectivity=8)", "contains the background node as the first node. Args: graph: a torch_geometric.Data instance", "node_delete_logits], dim=0) return delete_logits[:,0] class DeleteNetWrapper(base_networks.NetworkWrapper): def setup(self): if 'deletenet_model' in self.config: self.model", "= cv2.connectedComponents(fg_mask, connectivity=8) components = torch.from_numpy(components).float().to(constants.DEVICE) for j in range(1, nc): mask =", "in encodings], dim=1) # [N, \\sum_i d_i] bg_feature = concat_features[0:1] # [1, \\sum_i", "self.config: self.model = self.config['deletenet_model'] else: self.model = DeleteNet(self.config) self.model.to(self.device) def get_new_potential_masks(self, masks, fg_mask):", "components == j component_size = mask.sum().float() if component_size > self.config['min_pixels_thresh']: masks = torch.cat([masks,", "concat_features[1:] # [N-1, \\sum_i d_i] node_minus_bg_features = node_features - bg_feature # [N-1, \\sum_i", "XYZ image - mask: a [N, h, w] torch.FloatTensor of values in {0,", "features - depth: a [N, 3, h, w] torch.FloatTensor. XYZ image - mask:", "always low, so BG is never deleted. \"\"\" encodings = self.node_encoder(graph) # dictionary", "score logits. The first logit (background) is always low, so BG is never", "as the first node. Args: graph: a torch_geometric.Data instance with attributes: - rgb:", "[N, \\sum_i d_i] bg_feature = concat_features[0:1] # [1, \\sum_i d_i] node_features = concat_features[1:]", "mask = components == j component_size = mask.sum().float() if component_size > self.config['min_pixels_thresh']: masks", "logit (background) is always low, so BG is never deleted. \"\"\" encodings =" ]
[ "in range(10, num_proc * 100, 10)] ret = [] for x in util:", "for x in util: if len(x) == 2: ret.append('0.' + x) else: ret.append(x[:len(x)", "+ x) else: ret.append(x[:len(x) - 2] + '.' + x[len(x) - 2:]) return", "== 2: ret.append('0.' + x) else: ret.append(x[:len(x) - 2] + '.' + x[len(x)", "util = [str(x) for x in range(10, num_proc * 100, 10)] ret =", "[] for x in util: if len(x) == 2: ret.append('0.' + x) else:", "util: if len(x) == 2: ret.append('0.' + x) else: ret.append(x[:len(x) - 2] +", "* 100, 10)] ret = [] for x in util: if len(x) ==", "if len(x) == 2: ret.append('0.' + x) else: ret.append(x[:len(x) - 2] + '.'", "ret.append('0.' + x) else: ret.append(x[:len(x) - 2] + '.' + x[len(x) - 2:])", "def get_util_range(num_proc): util = [str(x) for x in range(10, num_proc * 100, 10)]", "2: ret.append('0.' + x) else: ret.append(x[:len(x) - 2] + '.' + x[len(x) -", "[str(x) for x in range(10, num_proc * 100, 10)] ret = [] for", "x) else: ret.append(x[:len(x) - 2] + '.' + x[len(x) - 2:]) return ret", "100, 10)] ret = [] for x in util: if len(x) == 2:", "range(10, num_proc * 100, 10)] ret = [] for x in util: if", "num_proc * 100, 10)] ret = [] for x in util: if len(x)", "len(x) == 2: ret.append('0.' + x) else: ret.append(x[:len(x) - 2] + '.' +", "= [str(x) for x in range(10, num_proc * 100, 10)] ret = []", "ret = [] for x in util: if len(x) == 2: ret.append('0.' +", "x in util: if len(x) == 2: ret.append('0.' + x) else: ret.append(x[:len(x) -", "x in range(10, num_proc * 100, 10)] ret = [] for x in", "get_util_range(num_proc): util = [str(x) for x in range(10, num_proc * 100, 10)] ret", "for x in range(10, num_proc * 100, 10)] ret = [] for x", "in util: if len(x) == 2: ret.append('0.' + x) else: ret.append(x[:len(x) - 2]", "= [] for x in util: if len(x) == 2: ret.append('0.' + x)", "10)] ret = [] for x in util: if len(x) == 2: ret.append('0.'" ]
[ "resources import get_subreddits, update_subreddits \"\"\" subreddits: { '<subreddit name>': { 'phrases': [ '<phrases>'", "... } \"\"\" subreddits = get_subreddits() def list(): return subreddits.keys() def add(name): subreddits[name]", "'include': <boolean>, 'unflaired': <boolean> }, ... } \"\"\" subreddits = get_subreddits() def list():", "'<flairs>' ], 'include': <boolean>, 'unflaired': <boolean> }, ... } \"\"\" subreddits = get_subreddits()", "False, 'unflaired': True } update_subreddits(subreddits) def remove(name): del subreddits[name] update_subreddits(subreddits) def clear(): subreddits.clear()", "], 'flairs': [ '<flairs>' ], 'include': <boolean>, 'unflaired': <boolean> }, ... } \"\"\"", "'flairs': [], 'include': False, 'unflaired': True } update_subreddits(subreddits) def remove(name): del subreddits[name] update_subreddits(subreddits)", "[ '<phrases>' ], 'flairs': [ '<flairs>' ], 'include': <boolean>, 'unflaired': <boolean> }, ...", "<boolean> }, ... } \"\"\" subreddits = get_subreddits() def list(): return subreddits.keys() def", "subreddits.keys() def add(name): subreddits[name] = { 'phrases': [], 'flairs': [], 'include': False, 'unflaired':", "= { 'phrases': [], 'flairs': [], 'include': False, 'unflaired': True } update_subreddits(subreddits) def", "{ 'phrases': [], 'flairs': [], 'include': False, 'unflaired': True } update_subreddits(subreddits) def remove(name):", "{ 'phrases': [ '<phrases>' ], 'flairs': [ '<flairs>' ], 'include': <boolean>, 'unflaired': <boolean>", "} \"\"\" subreddits = get_subreddits() def list(): return subreddits.keys() def add(name): subreddits[name] =", "'phrases': [], 'flairs': [], 'include': False, 'unflaired': True } update_subreddits(subreddits) def remove(name): del", "[], 'include': False, 'unflaired': True } update_subreddits(subreddits) def remove(name): del subreddits[name] update_subreddits(subreddits) def", "'unflaired': True } update_subreddits(subreddits) def remove(name): del subreddits[name] update_subreddits(subreddits) def clear(): subreddits.clear() update_subreddits(subreddits)", "get_subreddits, update_subreddits \"\"\" subreddits: { '<subreddit name>': { 'phrases': [ '<phrases>' ], 'flairs':", "list(): return subreddits.keys() def add(name): subreddits[name] = { 'phrases': [], 'flairs': [], 'include':", "\"\"\" subreddits: { '<subreddit name>': { 'phrases': [ '<phrases>' ], 'flairs': [ '<flairs>'", "subreddits = get_subreddits() def list(): return subreddits.keys() def add(name): subreddits[name] = { 'phrases':", "def list(): return subreddits.keys() def add(name): subreddits[name] = { 'phrases': [], 'flairs': [],", "= get_subreddits() def list(): return subreddits.keys() def add(name): subreddits[name] = { 'phrases': [],", "'phrases': [ '<phrases>' ], 'flairs': [ '<flairs>' ], 'include': <boolean>, 'unflaired': <boolean> },", "import get_subreddits, update_subreddits \"\"\" subreddits: { '<subreddit name>': { 'phrases': [ '<phrases>' ],", "update_subreddits \"\"\" subreddits: { '<subreddit name>': { 'phrases': [ '<phrases>' ], 'flairs': [", "\"\"\" subreddits = get_subreddits() def list(): return subreddits.keys() def add(name): subreddits[name] = {", "subreddits: { '<subreddit name>': { 'phrases': [ '<phrases>' ], 'flairs': [ '<flairs>' ],", "'<phrases>' ], 'flairs': [ '<flairs>' ], 'include': <boolean>, 'unflaired': <boolean> }, ... }", "name>': { 'phrases': [ '<phrases>' ], 'flairs': [ '<flairs>' ], 'include': <boolean>, 'unflaired':", "'<subreddit name>': { 'phrases': [ '<phrases>' ], 'flairs': [ '<flairs>' ], 'include': <boolean>,", "get_subreddits() def list(): return subreddits.keys() def add(name): subreddits[name] = { 'phrases': [], 'flairs':", "{ '<subreddit name>': { 'phrases': [ '<phrases>' ], 'flairs': [ '<flairs>' ], 'include':", "return subreddits.keys() def add(name): subreddits[name] = { 'phrases': [], 'flairs': [], 'include': False,", "[ '<flairs>' ], 'include': <boolean>, 'unflaired': <boolean> }, ... } \"\"\" subreddits =", "from resources import get_subreddits, update_subreddits \"\"\" subreddits: { '<subreddit name>': { 'phrases': [", "'flairs': [ '<flairs>' ], 'include': <boolean>, 'unflaired': <boolean> }, ... } \"\"\" subreddits", "], 'include': <boolean>, 'unflaired': <boolean> }, ... } \"\"\" subreddits = get_subreddits() def", "subreddits[name] = { 'phrases': [], 'flairs': [], 'include': False, 'unflaired': True } update_subreddits(subreddits)", "'unflaired': <boolean> }, ... } \"\"\" subreddits = get_subreddits() def list(): return subreddits.keys()", "def add(name): subreddits[name] = { 'phrases': [], 'flairs': [], 'include': False, 'unflaired': True", "[], 'flairs': [], 'include': False, 'unflaired': True } update_subreddits(subreddits) def remove(name): del subreddits[name]", "<boolean>, 'unflaired': <boolean> }, ... } \"\"\" subreddits = get_subreddits() def list(): return", "add(name): subreddits[name] = { 'phrases': [], 'flairs': [], 'include': False, 'unflaired': True }", "'include': False, 'unflaired': True } update_subreddits(subreddits) def remove(name): del subreddits[name] update_subreddits(subreddits) def clear():", "}, ... } \"\"\" subreddits = get_subreddits() def list(): return subreddits.keys() def add(name):" ]
[ "-*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import", "django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [", "-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations", "django.conf import settings class Migration(migrations.Migration): dependencies = [ ('events', '0005_auto_20150809_0203'), ] operations =", "import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('events',", "migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('events', '0005_auto_20150809_0203'), ]", "class Migration(migrations.Migration): dependencies = [ ('events', '0005_auto_20150809_0203'), ] operations = [ migrations.RemoveField( model_name='team',", "unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies", "name='members', ), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True, to='events.Team'), ), migrations.AlterField( model_name='teammembership', name='user', field=models.OneToOneField(to=settings.AUTH_USER_MODEL),", "] operations = [ migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True,", "= [ migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True, to='events.Team'), ),", "= [ ('events', '0005_auto_20150809_0203'), ] operations = [ migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField(", "coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from", "models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('events', '0005_auto_20150809_0203'),", "model_name='team', name='members', ), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True, to='events.Team'), ), migrations.AlterField( model_name='teammembership', name='user',", "operations = [ migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True, to='events.Team'),", "import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration):", "from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('events', '0005_auto_20150809_0203'), ] operations", "import settings class Migration(migrations.Migration): dependencies = [ ('events', '0005_auto_20150809_0203'), ] operations = [", "dependencies = [ ('events', '0005_auto_20150809_0203'), ] operations = [ migrations.RemoveField( model_name='team', name='members', ),", "migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True, to='events.Team'), ), migrations.AlterField( model_name='teammembership', name='user', field=models.OneToOneField(to=settings.AUTH_USER_MODEL), ), ]", "from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings", "('events', '0005_auto_20150809_0203'), ] operations = [ migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField( model_name='teammembership', name='team',", "utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf", "), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True, to='events.Team'), ), migrations.AlterField( model_name='teammembership', name='user', field=models.OneToOneField(to=settings.AUTH_USER_MODEL), ),", "__future__ import unicode_literals from django.db import models, migrations from django.conf import settings class", "from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies =", "[ migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True, to='events.Team'), ), migrations.AlterField(", "[ ('events', '0005_auto_20150809_0203'), ] operations = [ migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField( model_name='teammembership',", "migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True, blank=True, to='events.Team'), ), migrations.AlterField( model_name='teammembership',", "<filename>events/migrations/0006_auto_20150811_1213.py<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import", "'0005_auto_20150809_0203'), ] operations = [ migrations.RemoveField( model_name='team', name='members', ), migrations.AlterField( model_name='teammembership', name='team', field=models.ForeignKey(null=True,", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models,", "Migration(migrations.Migration): dependencies = [ ('events', '0005_auto_20150809_0203'), ] operations = [ migrations.RemoveField( model_name='team', name='members',", "settings class Migration(migrations.Migration): dependencies = [ ('events', '0005_auto_20150809_0203'), ] operations = [ migrations.RemoveField(" ]
[ "test_attributes(): NS = shared['NS'] sp = NS.sampled_parameters assert sp == sampled_parameters lnl =", "range(ndim)] # Set the active point population size population_size = 20 sampler =", "i in range(ndim)] # Set the active point population size population_size = 20", "width = 10.0 def analytic_log_evidence(ndim, width): lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim", "NS.evidence Z_err = NS.evidence_error H = NS.information def test_func_posteriors(): NS = shared['NS'] posteriors", "width) lnZ = NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err = NS.log_evidence_error Z =", "Tests using an implementation of a 5-dimensional Gaussian problem and its Nested Sampling", "posteriors = NS.posteriors() keys = list(posteriors.keys()) assert len(keys) == len(sampled_parameters) def test_func_akaike_ic(): NS", "<filename>tests/test_nested_sampling.py \"\"\" Tests using an implementation of a 5-dimensional Gaussian problem and its", "from gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import", "erf from gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection", "using an implementation of a 5-dimensional Gaussian problem and its Nested Sampling using", "= MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120) # Define the loglikelihood function def loglikelihood(sampled_parameter_vector):", "np.log(width)) return lZ shared = {'NS': None} def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood,", "NS = shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width) print(analytic, log_evidence)", "lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width)) return lZ shared =", "= NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv) pop = NS.population_size assert", "NS.deviance_ic() if __name__ == '__main__': test_initialization() test_attributes() test_func_run() test_properties() test_func_posteriors() test_func_akaike_ic() test_func_bayesian_ic() test_func_deviance_ic()", "shared['NS'] = NS def test_attributes(): NS = shared['NS'] sp = NS.sampled_parameters assert sp", "NS.sampled_parameters assert sp == sampled_parameters lnl = NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv)", "prior from scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)] # Set", "= 10.0 def analytic_log_evidence(ndim, width): lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim *", "test_func_akaike_ic(): NS = shared['NS'] aic = NS.akaike_ic() def test_func_bayesian_ic(): NS = shared['NS'] bic", "-0.5*np.sum(sampled_parameter_vector**2) + ndim * const width = 10.0 def analytic_log_evidence(ndim, width): lZ =", "Nested Sampling using via Gleipnir's built-in Nested Sampler. Adapted from the DNest4 python", "-- # we are using a fixed uniform prior from scipy.stats sampled_parameters =", "NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os import glob", "gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os import glob # Number", "H = NS.information def test_func_posteriors(): NS = shared['NS'] posteriors = NS.posteriors() keys =", "= [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)] # Set the active point population", "= 5 # Set up the list of sampled parameters: the prior is", "= {'NS': None} def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler, population_size=population_size,", "Nested Sampler. Adapted from the DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest", "import pytest import numpy as np from numpy import exp, log, pi from", "scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)] # Set the active", "population size population_size = 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120) #", "we are using a fixed uniform prior from scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0))", "= NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err = NS.log_evidence_error Z = NS.evidence Z_err", "NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] =", "log_evidence_error = NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.)", "aic = NS.akaike_ic() def test_func_bayesian_ic(): NS = shared['NS'] bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic():", "sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)] # Set the active point", "def analytic_log_evidence(ndim, width): lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width)) return", "= NS.sampled_parameters assert sp == sampled_parameters lnl = NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert", "# Set the active point population size population_size = 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10,", "Uniform(-5:5) -- # we are using a fixed uniform prior from scipy.stats sampled_parameters", "assert lnl(spv) == loglikelihood(spv) pop = NS.population_size assert pop == population_size def test_func_run():", "[SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)] # Set the active point population size", "NS def test_properties(): NS = shared['NS'] analytic = analytic_log_evidence(ndim, width) lnZ = NS.log_evidence", "Sampler. Adapted from the DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import", "* np.log(width)) return lZ shared = {'NS': None} def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters,", "rtol=1.) lnZ_err = NS.log_evidence_error Z = NS.evidence Z_err = NS.evidence_error H = NS.information", "10.0 def analytic_log_evidence(ndim, width): lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width))", "test_func_bayesian_ic(): NS = shared['NS'] bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS = shared['NS'] dic", "NS = shared['NS'] dic = NS.deviance_ic() if __name__ == '__main__': test_initialization() test_attributes() test_func_run()", "lnl(spv) == loglikelihood(spv) pop = NS.population_size assert pop == population_size def test_func_run(): NS", "= analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] = NS def", "sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120) # Define the loglikelihood function def", "NS = shared['NS'] aic = NS.akaike_ic() def test_func_bayesian_ic(): NS = shared['NS'] bic =", "= shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert", "= NS.population_size assert pop == population_size def test_func_run(): NS = shared['NS'] log_evidence, log_evidence_error", "as np from numpy import exp, log, pi from scipy.stats import uniform from", "import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os import glob # Number of", "= np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv) pop = NS.population_size assert pop == population_size", "prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)] # Set the active point population size population_size", "DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import numpy as np from", "import numpy as np from numpy import exp, log, pi from scipy.stats import", "using a fixed uniform prior from scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i", "5 ndim = 5 # Set up the list of sampled parameters: the", "scipy.stats import uniform from scipy.special import erf from gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling", "population_size = 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120) # Define the", "test_func_posteriors(): NS = shared['NS'] posteriors = NS.posteriors() keys = list(posteriors.keys()) assert len(keys) ==", "NS.information def test_func_posteriors(): NS = shared['NS'] posteriors = NS.posteriors() keys = list(posteriors.keys()) assert", "bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS = shared['NS'] dic = NS.deviance_ic() if __name__", "Gleipnir's built-in Nested Sampler. Adapted from the DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\"", "def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim * const width =", "+ ndim * const width = 10.0 def analytic_log_evidence(ndim, width): lZ = (ndim", "Adapted from the DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import numpy", "(ndim * np.log(width)) return lZ shared = {'NS': None} def test_initialization(): NS =", "return lZ shared = {'NS': None} def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler", "NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS def test_attributes(): NS", "NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS def", "shared['NS'] sp = NS.sampled_parameters assert sp == sampled_parameters lnl = NS.loglikelihood spv =", "NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv) pop = NS.population_size assert pop", "= NS.posteriors() keys = list(posteriors.keys()) assert len(keys) == len(sampled_parameters) def test_func_akaike_ic(): NS =", "len(keys) == len(sampled_parameters) def test_func_akaike_ic(): NS = shared['NS'] aic = NS.akaike_ic() def test_func_bayesian_ic():", "def test_func_bayesian_ic(): NS = shared['NS'] bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS = shared['NS']", "import erf from gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers import", "sample is 5 ndim = 5 # Set up the list of sampled", "* const width = 10.0 def analytic_log_evidence(ndim, width): lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2))))", "test_func_run(): NS = shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width) print(analytic,", "analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] = NS def test_properties():", "shared['NS'] aic = NS.akaike_ic() def test_func_bayesian_ic(): NS = shared['NS'] bic = NS.bayesian_ic(n_data=5) def", "= shared['NS'] bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS = shared['NS'] dic = NS.deviance_ic()", "implementation of a 5-dimensional Gaussian problem and its Nested Sampling using via Gleipnir's", "paramters to sample is 5 ndim = 5 # Set up the list", "{'NS': None} def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion)", "gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os", "uniform prior from scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)] #", "for i in range(ndim)] # Set the active point population size population_size =", "\"\"\" import pytest import numpy as np from numpy import exp, log, pi", "def test_attributes(): NS = shared['NS'] sp = NS.sampled_parameters assert sp == sampled_parameters lnl", "5 # Set up the list of sampled parameters: the prior is Uniform(-5:5)", "20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120) # Define the loglikelihood function", "SampledParameter from gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations", "from gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from", "from scipy.special import erf from gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling import NestedSampling from", "NS.population_size assert pop == population_size def test_func_run(): NS = shared['NS'] log_evidence, log_evidence_error =", "pytest import numpy as np from numpy import exp, log, pi from scipy.stats", "of sampled parameters: the prior is Uniform(-5:5) -- # we are using a", "assert pop == population_size def test_func_run(): NS = shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False)", "analytic, rtol=1.) shared['NS'] = NS def test_properties(): NS = shared['NS'] analytic = analytic_log_evidence(ndim,", "= NS.evidence_error H = NS.information def test_func_posteriors(): NS = shared['NS'] posteriors = NS.posteriors()", "analytic_log_evidence(ndim, width) lnZ = NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err = NS.log_evidence_error Z", "assert len(keys) == len(sampled_parameters) def test_func_akaike_ic(): NS = shared['NS'] aic = NS.akaike_ic() def", "NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err = NS.log_evidence_error Z = NS.evidence Z_err =", "the loglikelihood function def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim *", "is Uniform(-5:5) -- # we are using a fixed uniform prior from scipy.stats", "lZ shared = {'NS': None} def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler =", "= NumberOfIterations(120) # Define the loglikelihood function def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return", "lnl = NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv) pop = NS.population_size", "NS = shared['NS'] analytic = analytic_log_evidence(ndim, width) lnZ = NS.log_evidence assert np.isclose(lnZ, analytic,", "from scipy.stats import uniform from scipy.special import erf from gleipnir.sampled_parameter import SampledParameter from", "np from numpy import exp, log, pi from scipy.stats import uniform from scipy.special", "- (ndim * np.log(width)) return lZ shared = {'NS': None} def test_initialization(): NS", "== sampled_parameters lnl = NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv) pop", "\"\"\" Tests using an implementation of a 5-dimensional Gaussian problem and its Nested", "exp, log, pi from scipy.stats import uniform from scipy.special import erf from gleipnir.sampled_parameter", "tuning_cycles=1) stopping_criterion = NumberOfIterations(120) # Define the loglikelihood function def loglikelihood(sampled_parameter_vector): const =", "shared['NS'] = NS def test_properties(): NS = shared['NS'] analytic = analytic_log_evidence(ndim, width) lnZ", "import SampledParameter from gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import", "= NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS']", "= list(posteriors.keys()) assert len(keys) == len(sampled_parameters) def test_func_akaike_ic(): NS = shared['NS'] aic =", "is 5 ndim = 5 # Set up the list of sampled parameters:", "import NumberOfIterations import os import glob # Number of paramters to sample is", "fixed uniform prior from scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)]", "5-dimensional Gaussian problem and its Nested Sampling using via Gleipnir's built-in Nested Sampler.", "up the list of sampled parameters: the prior is Uniform(-5:5) -- # we", "const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim * const width = 10.0 def", "def test_func_posteriors(): NS = shared['NS'] posteriors = NS.posteriors() keys = list(posteriors.keys()) assert len(keys)", "NS.akaike_ic() def test_func_bayesian_ic(): NS = shared['NS'] bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS =", "= NS.akaike_ic() def test_func_bayesian_ic(): NS = shared['NS'] bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS", "lnZ = NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err = NS.log_evidence_error Z = NS.evidence", "shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert np.isclose(log_evidence,", "# we are using a fixed uniform prior from scipy.stats sampled_parameters = [SampledParameter(name=i,", "= (ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width)) return lZ shared = {'NS':", "NS = shared['NS'] posteriors = NS.posteriors() keys = list(posteriors.keys()) assert len(keys) == len(sampled_parameters)", "in range(ndim)] # Set the active point population size population_size = 20 sampler", "# Define the loglikelihood function def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) +", "pop = NS.population_size assert pop == population_size def test_func_run(): NS = shared['NS'] log_evidence,", "of a 5-dimensional Gaussian problem and its Nested Sampling using via Gleipnir's built-in", "NS.posteriors() keys = list(posteriors.keys()) assert len(keys) == len(sampled_parameters) def test_func_akaike_ic(): NS = shared['NS']", "analytic = analytic_log_evidence(ndim, width) lnZ = NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err =", "gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import numpy as np from numpy import", "import glob # Number of paramters to sample is 5 ndim = 5", "np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] = NS def test_properties(): NS = shared['NS'] analytic =", "import exp, log, pi from scipy.stats import uniform from scipy.special import erf from", "list of sampled parameters: the prior is Uniform(-5:5) -- # we are using", "np.isclose(lnZ, analytic, rtol=1.) lnZ_err = NS.log_evidence_error Z = NS.evidence Z_err = NS.evidence_error H", "= shared['NS'] sp = NS.sampled_parameters assert sp == sampled_parameters lnl = NS.loglikelihood spv", "= shared['NS'] aic = NS.akaike_ic() def test_func_bayesian_ic(): NS = shared['NS'] bic = NS.bayesian_ic(n_data=5)", "from the DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import numpy as", "from numpy import exp, log, pi from scipy.stats import uniform from scipy.special import", "Z_err = NS.evidence_error H = NS.information def test_func_posteriors(): NS = shared['NS'] posteriors =", "spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv) pop = NS.population_size assert pop ==", "# Number of paramters to sample is 5 ndim = 5 # Set", "= -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim * const width = 10.0 def analytic_log_evidence(ndim,", "width): lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width)) return lZ shared", "= NS.deviance_ic() if __name__ == '__main__': test_initialization() test_attributes() test_func_run() test_properties() test_func_posteriors() test_func_akaike_ic() test_func_bayesian_ic()", "os import glob # Number of paramters to sample is 5 ndim =", "import uniform from scipy.special import erf from gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling import", "log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] = NS def test_properties(): NS = shared['NS']", "gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion", "np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width)) return lZ shared = {'NS': None} def test_initialization():", "scipy.special import erf from gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling import NestedSampling from gleipnir.nestedsampling.samplers", "= NS.information def test_func_posteriors(): NS = shared['NS'] posteriors = NS.posteriors() keys = list(posteriors.keys())", "numpy as np from numpy import exp, log, pi from scipy.stats import uniform", "Z = NS.evidence Z_err = NS.evidence_error H = NS.information def test_func_posteriors(): NS =", "dic = NS.deviance_ic() if __name__ == '__main__': test_initialization() test_attributes() test_func_run() test_properties() test_func_posteriors() test_func_akaike_ic()", "of paramters to sample is 5 ndim = 5 # Set up the", "Set up the list of sampled parameters: the prior is Uniform(-5:5) -- #", "gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os import glob # Number of paramters to sample", "parameters: the prior is Uniform(-5:5) -- # we are using a fixed uniform", "NS = shared['NS'] bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS = shared['NS'] dic =", "= shared['NS'] analytic = analytic_log_evidence(ndim, width) lnZ = NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.)", "pi from scipy.stats import uniform from scipy.special import erf from gleipnir.sampled_parameter import SampledParameter", "via Gleipnir's built-in Nested Sampler. Adapted from the DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py", "shared['NS'] bic = NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS = shared['NS'] dic = NS.deviance_ic() if", "sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS def test_attributes(): NS = shared['NS']", "from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os import glob # Number of paramters to", "test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS", "def test_func_run(): NS = shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width)", "width) print(analytic, log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] = NS def test_properties(): NS", "Set the active point population size population_size = 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1)", "a 5-dimensional Gaussian problem and its Nested Sampling using via Gleipnir's built-in Nested", "glob # Number of paramters to sample is 5 ndim = 5 #", "list(posteriors.keys()) assert len(keys) == len(sampled_parameters) def test_func_akaike_ic(): NS = shared['NS'] aic = NS.akaike_ic()", "Sampling using via Gleipnir's built-in Nested Sampler. Adapted from the DNest4 python gaussian", "numpy import exp, log, pi from scipy.stats import uniform from scipy.special import erf", "MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os import glob # Number of paramters", "= 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120) # Define the loglikelihood", "stopping_criterion = NumberOfIterations(120) # Define the loglikelihood function def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi)", "const width = 10.0 def analytic_log_evidence(ndim, width): lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2)))) -", "= shared['NS'] posteriors = NS.posteriors() keys = list(posteriors.keys()) assert len(keys) == len(sampled_parameters) def", "the prior is Uniform(-5:5) -- # we are using a fixed uniform prior", "test_properties(): NS = shared['NS'] analytic = analytic_log_evidence(ndim, width) lnZ = NS.log_evidence assert np.isclose(lnZ,", "# Set up the list of sampled parameters: the prior is Uniform(-5:5) --", "sampled parameters: the prior is Uniform(-5:5) -- # we are using a fixed", "sp == sampled_parameters lnl = NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv)", "an implementation of a 5-dimensional Gaussian problem and its Nested Sampling using via", "= shared['NS'] dic = NS.deviance_ic() if __name__ == '__main__': test_initialization() test_attributes() test_func_run() test_properties()", "loglikelihood function def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim * const", "stopping_criterion=stopping_criterion) shared['NS'] = NS def test_attributes(): NS = shared['NS'] sp = NS.sampled_parameters assert", "= sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS def test_attributes(): NS = shared['NS'] sp", "NS.log_evidence_error Z = NS.evidence Z_err = NS.evidence_error H = NS.information def test_func_posteriors(): NS", "def test_func_akaike_ic(): NS = shared['NS'] aic = NS.akaike_ic() def test_func_bayesian_ic(): NS = shared['NS']", "def test_func_deviance_ic(): NS = shared['NS'] dic = NS.deviance_ic() if __name__ == '__main__': test_initialization()", "built-in Nested Sampler. Adapted from the DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import", "= NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS def test_attributes():", "loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim * const width = 10.0", "from scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in range(ndim)] # Set the", "point population size population_size = 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120)", "function def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim * const width", "prior is Uniform(-5:5) -- # we are using a fixed uniform prior from", "example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import numpy as np from numpy import exp,", "ndim = 5 # Set up the list of sampled parameters: the prior", "problem and its Nested Sampling using via Gleipnir's built-in Nested Sampler. Adapted from", "python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import numpy as np from numpy", "= NS def test_attributes(): NS = shared['NS'] sp = NS.sampled_parameters assert sp ==", "NS.evidence_error H = NS.information def test_func_posteriors(): NS = shared['NS'] posteriors = NS.posteriors() keys", "and its Nested Sampling using via Gleipnir's built-in Nested Sampler. Adapted from the", "uniform from scipy.special import erf from gleipnir.sampled_parameter import SampledParameter from gleipnir.nestedsampling import NestedSampling", "assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] = NS def test_properties(): NS = shared['NS'] analytic", "log_evidence, log_evidence_error = NS.run(verbose=False) analytic = analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert np.isclose(log_evidence, analytic,", "keys = list(posteriors.keys()) assert len(keys) == len(sampled_parameters) def test_func_akaike_ic(): NS = shared['NS'] aic", "from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os import glob #", "= NS.evidence Z_err = NS.evidence_error H = NS.information def test_func_posteriors(): NS = shared['NS']", "shared = {'NS': None} def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler,", "sp = NS.sampled_parameters assert sp == sampled_parameters lnl = NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.])", "sampled_parameters lnl = NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv) pop =", "Gaussian problem and its Nested Sampling using via Gleipnir's built-in Nested Sampler. Adapted", "len(sampled_parameters) def test_func_akaike_ic(): NS = shared['NS'] aic = NS.akaike_ic() def test_func_bayesian_ic(): NS =", "the DNest4 python gaussian example: https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import numpy as np", "import os import glob # Number of paramters to sample is 5 ndim", "np.array([5.,5.,5.,5.,5.]) assert lnl(spv) == loglikelihood(spv) pop = NS.population_size assert pop == population_size def", "shared['NS'] analytic = analytic_log_evidence(ndim, width) lnZ = NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err", "def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] =", "size population_size = 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120) # Define", "NS = shared['NS'] sp = NS.sampled_parameters assert sp == sampled_parameters lnl = NS.loglikelihood", "the list of sampled parameters: the prior is Uniform(-5:5) -- # we are", "(ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width)) return lZ shared = {'NS': None}", "population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS def test_attributes(): NS = shared['NS'] sp = NS.sampled_parameters", "loglikelihood(spv) pop = NS.population_size assert pop == population_size def test_func_run(): NS = shared['NS']", "NS def test_attributes(): NS = shared['NS'] sp = NS.sampled_parameters assert sp == sampled_parameters", "population_size def test_func_run(): NS = shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False) analytic = analytic_log_evidence(ndim,", "are using a fixed uniform prior from scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for", "rtol=1.) shared['NS'] = NS def test_properties(): NS = shared['NS'] analytic = analytic_log_evidence(ndim, width)", "test_func_deviance_ic(): NS = shared['NS'] dic = NS.deviance_ic() if __name__ == '__main__': test_initialization() test_attributes()", "= NS def test_properties(): NS = shared['NS'] analytic = analytic_log_evidence(ndim, width) lnZ =", "import NestedSampling from gleipnir.nestedsampling.samplers import MetropolisComponentWiseHardNSRejection from gleipnir.nestedsampling.stopping_criterion import NumberOfIterations import os import", "Number of paramters to sample is 5 ndim = 5 # Set up", "loglikelihood=loglikelihood, sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS def test_attributes(): NS =", "== loglikelihood(spv) pop = NS.population_size assert pop == population_size def test_func_run(): NS =", "= analytic_log_evidence(ndim, width) lnZ = NS.log_evidence assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err = NS.log_evidence_error", "== population_size def test_func_run(): NS = shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False) analytic =", "NumberOfIterations(120) # Define the loglikelihood function def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2)", "active point population size population_size = 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion =", "analytic_log_evidence(ndim, width): lZ = (ndim * np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width)) return lZ", "return -0.5*np.sum(sampled_parameter_vector**2) + ndim * const width = 10.0 def analytic_log_evidence(ndim, width): lZ", "None} def test_initialization(): NS = NestedSampling(sampled_parameters=sampled_parameters, loglikelihood=loglikelihood, sampler = sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS']", "Define the loglikelihood function def loglikelihood(sampled_parameter_vector): const = -0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim", "sampler, population_size=population_size, stopping_criterion=stopping_criterion) shared['NS'] = NS def test_attributes(): NS = shared['NS'] sp =", "https://github.com/eggplantbren/DNest4/blob/master/python/examples/gaussian/gaussian.py \"\"\" import pytest import numpy as np from numpy import exp, log,", "def test_properties(): NS = shared['NS'] analytic = analytic_log_evidence(ndim, width) lnZ = NS.log_evidence assert", "assert sp == sampled_parameters lnl = NS.loglikelihood spv = np.array([5.,5.,5.,5.,5.]) assert lnl(spv) ==", "shared['NS'] posteriors = NS.posteriors() keys = list(posteriors.keys()) assert len(keys) == len(sampled_parameters) def test_func_akaike_ic():", "a fixed uniform prior from scipy.stats sampled_parameters = [SampledParameter(name=i, prior=uniform(loc=-5.0,scale=10.0)) for i in", "* np.log(erf(0.5*width/np.sqrt(2)))) - (ndim * np.log(width)) return lZ shared = {'NS': None} def", "to sample is 5 ndim = 5 # Set up the list of", "analytic = analytic_log_evidence(ndim, width) print(analytic, log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] = NS", "NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS = shared['NS'] dic = NS.deviance_ic() if __name__ == '__main__':", "= NS.log_evidence_error Z = NS.evidence Z_err = NS.evidence_error H = NS.information def test_func_posteriors():", "= NS.bayesian_ic(n_data=5) def test_func_deviance_ic(): NS = shared['NS'] dic = NS.deviance_ic() if __name__ ==", "== len(sampled_parameters) def test_func_akaike_ic(): NS = shared['NS'] aic = NS.akaike_ic() def test_func_bayesian_ic(): NS", "its Nested Sampling using via Gleipnir's built-in Nested Sampler. Adapted from the DNest4", "shared['NS'] dic = NS.deviance_ic() if __name__ == '__main__': test_initialization() test_attributes() test_func_run() test_properties() test_func_posteriors()", "log, pi from scipy.stats import uniform from scipy.special import erf from gleipnir.sampled_parameter import", "lnZ_err = NS.log_evidence_error Z = NS.evidence Z_err = NS.evidence_error H = NS.information def", "assert np.isclose(lnZ, analytic, rtol=1.) lnZ_err = NS.log_evidence_error Z = NS.evidence Z_err = NS.evidence_error", "pop == population_size def test_func_run(): NS = shared['NS'] log_evidence, log_evidence_error = NS.run(verbose=False) analytic", "NumberOfIterations import os import glob # Number of paramters to sample is 5", "analytic, rtol=1.) lnZ_err = NS.log_evidence_error Z = NS.evidence Z_err = NS.evidence_error H =", "MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion = NumberOfIterations(120) # Define the loglikelihood function def loglikelihood(sampled_parameter_vector): const", "using via Gleipnir's built-in Nested Sampler. Adapted from the DNest4 python gaussian example:", "-0.5*np.log(2*np.pi) return -0.5*np.sum(sampled_parameter_vector**2) + ndim * const width = 10.0 def analytic_log_evidence(ndim, width):", "ndim * const width = 10.0 def analytic_log_evidence(ndim, width): lZ = (ndim *", "the active point population size population_size = 20 sampler = MetropolisComponentWiseHardNSRejection(iterations=10, tuning_cycles=1) stopping_criterion", "print(analytic, log_evidence) assert np.isclose(log_evidence, analytic, rtol=1.) shared['NS'] = NS def test_properties(): NS =" ]
[ "var_type_index == 0: self.var_value = 0 elif var_type_index == 1: self.var_value = False", "self.var_value = var_value def set_defualt_value(self, var_type): var_type = var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None)", "= var_value if var_value == \"\": self.set_defualt_value(var_type) else: self.var_value = var_value def set_defualt_value(self,", "else: print(\"Variable type error\") def set_variable_type(self, type): self.var_type = type def set_variable_name(self, name):", "var_type_index == 1: self.var_value = False elif var_type_index == 2: self.var_value = 0.0", "1, 'boolean' : 1, 'float' : 2, 'double' : 2, 'string' : 3,", "var_value if var_value == \"\": self.set_defualt_value(var_type) else: self.var_value = var_value def set_defualt_value(self, var_type):", "Variable.var_type_dic.get(var_type, None) if var_type_index == 0: self.var_value = 0 elif var_type_index == 1:", "value): self.var_value = value def get_variable_type(self): return self.var_type def get_variable_name(self): return self.var_name def", "0.0 elif var_type_index == 3: self.var_value = \"\" else: print(\"Variable type error\") def", "= var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None) if var_type_index == 0: self.var_value = 0", "var_type_index == 2: self.var_value = 0.0 elif var_type_index == 3: self.var_value = \"\"", "== 3: self.var_value = \"\" else: print(\"Variable type error\") def set_variable_type(self, type): self.var_type", "0 elif var_type_index == 1: self.var_value = False elif var_type_index == 2: self.var_value", "elif var_type_index == 2: self.var_value = 0.0 elif var_type_index == 3: self.var_value =", ": 1, 'float' : 2, 'double' : 2, 'string' : 3, 'str' :", "type def set_variable_name(self, name): self.var_name = name def set_variable_value(self, value): self.var_value = value", "'float' : 2, 'double' : 2, 'string' : 3, 'str' : 3} def", "name): self.var_name = name def set_variable_value(self, value): self.var_value = value def get_variable_type(self): return", "type): self.var_type = type def set_variable_name(self, name): self.var_name = name def set_variable_value(self, value):", "= type def set_variable_name(self, name): self.var_name = name def set_variable_value(self, value): self.var_value =", "2, 'double' : 2, 'string' : 3, 'str' : 3} def __init__(self, var_type,", "False elif var_type_index == 2: self.var_value = 0.0 elif var_type_index == 3: self.var_value", "set_defualt_value(self, var_type): var_type = var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None) if var_type_index == 0:", "\"\": self.set_defualt_value(var_type) else: self.var_value = var_value def set_defualt_value(self, var_type): var_type = var_type.lower() var_type_index", "var_type self.var_name = var_name self.var_value = var_value if var_value == \"\": self.set_defualt_value(var_type) else:", "def set_defualt_value(self, var_type): var_type = var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None) if var_type_index ==", ": 3, 'str' : 3} def __init__(self, var_type, var_name, var_value): self.var_type = var_type", "set_variable_value(self, value): self.var_value = value def get_variable_type(self): return self.var_type def get_variable_name(self): return self.var_name", "= var_value def set_defualt_value(self, var_type): var_type = var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None) if", "3, 'str' : 3} def __init__(self, var_type, var_name, var_value): self.var_type = var_type self.var_name", "var_name self.var_value = var_value if var_value == \"\": self.set_defualt_value(var_type) else: self.var_value = var_value", "self.var_value = var_value if var_value == \"\": self.set_defualt_value(var_type) else: self.var_value = var_value def", "set_variable_name(self, name): self.var_name = name def set_variable_value(self, value): self.var_value = value def get_variable_type(self):", "self.var_name = name def set_variable_value(self, value): self.var_value = value def get_variable_type(self): return self.var_type", "= var_type self.var_name = var_name self.var_value = var_value if var_value == \"\": self.set_defualt_value(var_type)", "= 0 elif var_type_index == 1: self.var_value = False elif var_type_index == 2:", "== \"\": self.set_defualt_value(var_type) else: self.var_value = var_value def set_defualt_value(self, var_type): var_type = var_type.lower()", "= value def get_variable_type(self): return self.var_type def get_variable_name(self): return self.var_name def get_variable_value(self): return", "else: self.var_value = var_value def set_defualt_value(self, var_type): var_type = var_type.lower() var_type_index = Variable.var_type_dic.get(var_type,", "var_type, var_name, var_value): self.var_type = var_type self.var_name = var_name self.var_value = var_value if", "class Variable: var_type_dic = {'int' : 0, 'bool' : 1, 'boolean' : 1,", ": 1, 'boolean' : 1, 'float' : 2, 'double' : 2, 'string' :", "== 2: self.var_value = 0.0 elif var_type_index == 3: self.var_value = \"\" else:", "'boolean' : 1, 'float' : 2, 'double' : 2, 'string' : 3, 'str'", "var_name, var_value): self.var_type = var_type self.var_name = var_name self.var_value = var_value if var_value", "self.var_value = value def get_variable_type(self): return self.var_type def get_variable_name(self): return self.var_name def get_variable_value(self):", "print(\"Variable type error\") def set_variable_type(self, type): self.var_type = type def set_variable_name(self, name): self.var_name", "0: self.var_value = 0 elif var_type_index == 1: self.var_value = False elif var_type_index", "var_type_index == 3: self.var_value = \"\" else: print(\"Variable type error\") def set_variable_type(self, type):", "value def get_variable_type(self): return self.var_type def get_variable_name(self): return self.var_name def get_variable_value(self): return self.var_value", "'str' : 3} def __init__(self, var_type, var_name, var_value): self.var_type = var_type self.var_name =", "def set_variable_name(self, name): self.var_name = name def set_variable_value(self, value): self.var_value = value def", "var_value): self.var_type = var_type self.var_name = var_name self.var_value = var_value if var_value ==", "= var_name self.var_value = var_value if var_value == \"\": self.set_defualt_value(var_type) else: self.var_value =", "'bool' : 1, 'boolean' : 1, 'float' : 2, 'double' : 2, 'string'", "= \"\" else: print(\"Variable type error\") def set_variable_type(self, type): self.var_type = type def", "set_variable_type(self, type): self.var_type = type def set_variable_name(self, name): self.var_name = name def set_variable_value(self,", "None) if var_type_index == 0: self.var_value = 0 elif var_type_index == 1: self.var_value", ": 2, 'double' : 2, 'string' : 3, 'str' : 3} def __init__(self,", "Variable: var_type_dic = {'int' : 0, 'bool' : 1, 'boolean' : 1, 'float'", "var_type_dic = {'int' : 0, 'bool' : 1, 'boolean' : 1, 'float' :", "error\") def set_variable_type(self, type): self.var_type = type def set_variable_name(self, name): self.var_name = name", "== 0: self.var_value = 0 elif var_type_index == 1: self.var_value = False elif", "= 0.0 elif var_type_index == 3: self.var_value = \"\" else: print(\"Variable type error\")", "__init__(self, var_type, var_name, var_value): self.var_type = var_type self.var_name = var_name self.var_value = var_value", "self.var_value = False elif var_type_index == 2: self.var_value = 0.0 elif var_type_index ==", "var_value def set_defualt_value(self, var_type): var_type = var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None) if var_type_index", "2: self.var_value = 0.0 elif var_type_index == 3: self.var_value = \"\" else: print(\"Variable", "== 1: self.var_value = False elif var_type_index == 2: self.var_value = 0.0 elif", "'string' : 3, 'str' : 3} def __init__(self, var_type, var_name, var_value): self.var_type =", "var_type_index = Variable.var_type_dic.get(var_type, None) if var_type_index == 0: self.var_value = 0 elif var_type_index", "self.var_value = 0 elif var_type_index == 1: self.var_value = False elif var_type_index ==", "self.var_value = \"\" else: print(\"Variable type error\") def set_variable_type(self, type): self.var_type = type", "self.var_name = var_name self.var_value = var_value if var_value == \"\": self.set_defualt_value(var_type) else: self.var_value", "if var_value == \"\": self.set_defualt_value(var_type) else: self.var_value = var_value def set_defualt_value(self, var_type): var_type", "type error\") def set_variable_type(self, type): self.var_type = type def set_variable_name(self, name): self.var_name =", "1, 'float' : 2, 'double' : 2, 'string' : 3, 'str' : 3}", ": 3} def __init__(self, var_type, var_name, var_value): self.var_type = var_type self.var_name = var_name", "self.set_defualt_value(var_type) else: self.var_value = var_value def set_defualt_value(self, var_type): var_type = var_type.lower() var_type_index =", "\"\" else: print(\"Variable type error\") def set_variable_type(self, type): self.var_type = type def set_variable_name(self,", "elif var_type_index == 3: self.var_value = \"\" else: print(\"Variable type error\") def set_variable_type(self,", "name def set_variable_value(self, value): self.var_value = value def get_variable_type(self): return self.var_type def get_variable_name(self):", "2, 'string' : 3, 'str' : 3} def __init__(self, var_type, var_name, var_value): self.var_type", "def __init__(self, var_type, var_name, var_value): self.var_type = var_type self.var_name = var_name self.var_value =", "if var_type_index == 0: self.var_value = 0 elif var_type_index == 1: self.var_value =", ": 2, 'string' : 3, 'str' : 3} def __init__(self, var_type, var_name, var_value):", "= {'int' : 0, 'bool' : 1, 'boolean' : 1, 'float' : 2,", "self.var_type = type def set_variable_name(self, name): self.var_name = name def set_variable_value(self, value): self.var_value", "def set_variable_value(self, value): self.var_value = value def get_variable_type(self): return self.var_type def get_variable_name(self): return", "self.var_value = 0.0 elif var_type_index == 3: self.var_value = \"\" else: print(\"Variable type", "3: self.var_value = \"\" else: print(\"Variable type error\") def set_variable_type(self, type): self.var_type =", "= Variable.var_type_dic.get(var_type, None) if var_type_index == 0: self.var_value = 0 elif var_type_index ==", "var_type = var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None) if var_type_index == 0: self.var_value =", "= name def set_variable_value(self, value): self.var_value = value def get_variable_type(self): return self.var_type def", "var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None) if var_type_index == 0: self.var_value = 0 elif", "= False elif var_type_index == 2: self.var_value = 0.0 elif var_type_index == 3:", ": 0, 'bool' : 1, 'boolean' : 1, 'float' : 2, 'double' :", "{'int' : 0, 'bool' : 1, 'boolean' : 1, 'float' : 2, 'double'", "var_type): var_type = var_type.lower() var_type_index = Variable.var_type_dic.get(var_type, None) if var_type_index == 0: self.var_value", "self.var_type = var_type self.var_name = var_name self.var_value = var_value if var_value == \"\":", "3} def __init__(self, var_type, var_name, var_value): self.var_type = var_type self.var_name = var_name self.var_value", "def set_variable_type(self, type): self.var_type = type def set_variable_name(self, name): self.var_name = name def", "0, 'bool' : 1, 'boolean' : 1, 'float' : 2, 'double' : 2,", "'double' : 2, 'string' : 3, 'str' : 3} def __init__(self, var_type, var_name,", "var_value == \"\": self.set_defualt_value(var_type) else: self.var_value = var_value def set_defualt_value(self, var_type): var_type =", "1: self.var_value = False elif var_type_index == 2: self.var_value = 0.0 elif var_type_index", "elif var_type_index == 1: self.var_value = False elif var_type_index == 2: self.var_value =" ]
[ "how much specified in min_start_goal_dist for obj in final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]):", "keep orientation...\") continue for obj in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1", "and z > 0.55 - 0.15: return True if obj == 'mustard' and", "failed: print(\"{} changed pos by {} and orientation by {}\" .format(obj, posDiff, orientDiff))", "objOnTable=None): failed = True while failed: # skip 1st object, i.e the table", "goal.initial_state) objects = [o for o in goal.initial_state] p0 = np.vstack([goal.initial_state[o] for o", "at_least_two_near_objects = True else: at_least_two_near_objects = False for obj1 in initial.fixed_state.keys(): for obj2", "it, mask = runEnv(env) return actual_image, actual_position, failed, it, mask def checkMinSeparation(state): positions", "print(\"Failed image generation...\") continue clearance = checkMinSeparation(actual_position) if clearance < minSeparation: failed =", "> 0.55 - 0.15: return True if obj == 'tomato' and z >", "True: table = None if objOnTable is not None: if obj in objOnTable:", "them in a file.\\n The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are", "drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether at least two objects are close", "({}), draw again {}..\" .format(clearance, obj)) (a, p, f, it, m) = generateRealPosition(env,", "obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type != '3D' or len(initial.fixed_state.keys()) ==", "position = Position() startPositions = {} for obj in fixedObjects: startPositions[obj] = fixedPositions[obj]", "on the table. This only if in the initial positions it is not", "if objOnTable is not None: if obj in objOnTable: table = objOnTable[obj] startPose", "whether at least two objects are close together as specified in max_objects_dist if", "0.49 - 0.15: return True if obj == 'mustard' and z < 0.48", "3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos,", "True if obj == 'mustard' and z > 0.545 - 0.15: return True", "== 2 for goal in goals]) mustards = sum([goal.mask == 3 for goal", "generation, \" \"draw again everything..\".format(clearance)) continue if fixedOrientation: for obj in objects: q1", "(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or the default value. \"\"\" np.random.seed(seed) allgoals =", "could add some progress bar... for _ in range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj,", "after {} timesteps..\".format(t)) if not still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'],", "again {}..\" .format(clearance, obj)) (a, p, f, it, m) = generateRealPosition(env, startPositions) actual_image", "at_least_one_on_shelf = False for obj in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or goal_type ==", "# checks if at least one object is on the table at_least_one_on_shelf =", "clearance >= minSeparation: break print(\"Failed minimum separation ({}), draw again {}..\" .format(clearance, obj))", "goal.retina = final.retina goal.mask = final.mask print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type)) return goal", "- 0.15: return True return False def isOnTable(obj, state): z = state[obj][2] if", "= np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if x <= 0.05: z = 0.40 else:", "1: break clearance = checkMinSeparation(startPositions) if clearance >= minSeparation: break print(\"Failed minimum separation", "None: if obj in objOnTable: table = objOnTable[obj] startPose = generatePosition(env, obj, fixedOrientation,", "_, _ = runEnv(env) # In these for loops, we could add some", "in all_goals if goal.challenge == challenge] if len(goals) > 0: if images: #", "env.robot.used_objects[1:] objOnTable = {} for obj in objects: objOnTable[obj] = True if goal_type", "failed: print(\"{} changed orientation by {}\" .format(obj, orientDiff)) break else: print(\"{} kept orientation.\".format(obj))", "positions of the objects is at least how much specified in min_start_goal_dist for", "if found: break # checks if at least one object is on the", "objOnTable = None if not on_shelf: objects = env.robot.used_objects[1:] objOnTable = {} for", "in objects]) p1 = np.vstack([pos[o] for o in objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:,", "least one object is on the table. This only if in the initial", "np.array(orientation).tolist() return pose def generateRealPosition(env, startPositions): env.reset() runEnv(env) # Generate Images for obj", "True break # checks if the distance between initial and final positions of", "specified number of goals and saves them in a file.\\n The file is", "done = False render = slow action = {'joint_command': np.zeros(9), 'render': render} objects", "{}..\" .format(clearance, obj)) (a, p, f, it, m) = generateRealPosition(env, startPositions) actual_image =", "obj1 == obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found = True break if", "startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed, it, mask = runEnv(env) return actual_image, actual_position,", "this SEED for numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='# of 2D goals (default 25)')", "- we had to rise it many times failed = failed or orientDiff", "i, obj in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 = old_positions[i][3:] q2", "= state[obj][2] if obj == 'cube' and z < 0.48 - 0.15: return", "generation of GOAL {}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as plt", "fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found = True # checks whether at least two objects", "+= [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_25d_goals): allgoals +=", "= True break if at_least_two_near_objects: break # checks if at least one object", "This - we had to rise it many times failed = failed or", "positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) still = False stable = 0", "sum([goal.mask == 3 for goal in goals]) cubes = sum([goal.mask == 4 for", "not(found): found = True final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether", "on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals) checkRepeatability(env, allgoals) visualizeGoalDistribution(allgoals)", "sum([goal.mask == 2 for goal in goals]) mustards = sum([goal.mask == 3 for", "break pos_dict = {} for obj in objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment", "obj == 'tomato' and z > 0.55 - 0.15: return True if obj", "render} objects = env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) still =", "render = slow action = {'joint_command': np.zeros(9), 'render': render} objects = env.robot.used_objects[1:] positions", "plt challenges = np.unique([goal.challenge for goal in all_goals]) fig, axes = plt.subplots(max(2, len(challenges)),", "0.05: z = 0.40 else: z = 0.50 if fixed: orientation = basePosition[obj][3:]", "final.fixed_state goal.retina_before = initial.retina goal.retina = final.retina goal.mask = final.mask print(\"SUCCESSFULL generation of", "This only if in the initial positions it is not true if found", "1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else: # Positions scatter view for i, o", "= str(n_obj) goal.initial_state = initial.fixed_state goal.final_state = final.fixed_state goal.retina_before = initial.retina goal.retina =", "1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def runEnv(env, max_t=1000): reward = 0", "for goal in goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0], positions[:, 1])", "failed: print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos, maxDiffOr def isOnShelf(obj, state): z = state[obj][2]", "mask def checkMinSeparation(state): positions = np.vstack([state[obj][:3] for obj in state]) if len(positions) >", "a-b, a-b)) def runEnv(env, max_t=1000): reward = 0 done = False render =", "axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else: # Positions scatter", "axes[c, i].hist2d(positions[:, 0], positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command()", "# -*- coding: utf-8 -*- \"\"\"Console script to generate goals for real_robots\"\"\" import", "= False break goal = Goal() goal.challenge = goal_type goal.subtype = str(n_obj) goal.initial_state", "startPositions[obj] = startPose if len(startPositions) == 1: break clearance = checkMinSeparation(startPositions) if clearance", "actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed = failed or posDiff >", "q2), np.linalg.norm(q1+q2)) # TODO CHECK This - we had to rise it many", "= False render = slow action = {'joint_command': np.zeros(9), 'render': render} objects =", "image generation...\") continue clearance = checkMinSeparation(actual_position) if clearance < minSeparation: failed = True", "= initial.fixed_state goal.final_state = final.fixed_state goal.retina_before = initial.retina goal.retina = final.retina goal.mask =", "generateRealPosition(env, startPositions) actual_image = a actual_mask = m actual_position = p failed =", "n_obj=3): \"\"\" Generates the specified number of goals and saves them in a", "initial.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type !=", "numpy as np from real_robots.envs import Goal import gym import math basePosition =", "in goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0], positions[:, 1]) axes[c, i].set_xlim([-0.3,", "the table objects = env.robot.used_objects[1:] position = Position() startPositions = {} for obj", "it is not true if not at_least_two_near_objects: found = False for obj1 in", "0.15: return True return False def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2):", "stable > 20: still = True break pos_dict = {} for obj in", "{}\" .format(obj, orientDiff)) break else: print(\"{} kept orientation.\".format(obj)) if failed: print(\"Failed to keep", "progress bar... for _ in range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2,", "obj == 'mustard' and z < 0.48 - 0.15: return True return False", "= False while not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found = True", "type=int, help='Generate goals using this SEED for numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='# of", "obj)) (a, p, f, it, m) = generateRealPosition(env, startPositions) actual_image = a actual_mask", "help='# of 2.5D goals (default 15)') @click.option('--n_3d_goals', type=int, default=10, help='# of 3D goals", "obj in objects: q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 -", "we could add some progress bar... for _ in range(n_2d_goals): allgoals += [generateGoalREAL2020(env,", "obj in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found = True break # checks if", "again everything..\".format(clearance)) continue if fixedOrientation: for obj in objects: q1 = startPositions[obj][3:] q2", "pairwise_distances(positions) clearance = distances[distances > 0].min() else: clearance = np.inf return clearance def", "goal.subtype = str(n_obj) goal.initial_state = initial.fixed_state goal.final_state = final.fixed_state goal.retina_before = initial.retina goal.retina", "np.random.rand()*(max_y-min_y)+min_y if x <= 0.05: z = 0.40 else: z = 0.50 if", "initial.retina goal.retina = final.retina goal.mask = final.mask print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type)) return", "tomatos = sum([goal.mask == 2 for goal in goals]) mustards = sum([goal.mask ==", "0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed', type=int, help='Generate goals using this SEED", "10: stable += 1 else: stable = 0 action['render'] = slow if stable", "= p failed = f if failed: print(\"Failed image generation...\") continue clearance =", "z > 0.55 - 0.15: return True if obj == 'orange' and z", "at least two objects are close together as specified in max_objects_dist if n_obj", "max_x = .25 elif tablePlane: min_x = -.25 max_x = .05 else: min_x", "print(\"Failed to keep orientation...\") continue for obj in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] -", "slow action = {'joint_command': np.zeros(9), 'render': render} objects = env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj)", "the table. This only if in the initial positions it is not true", "True return False def isOnTable(obj, state): z = state[obj][2] if obj == 'cube'", "tablePlane is None: min_x = -.25 max_x = .25 elif tablePlane: min_x =", "min_x = -.25 max_x = .05 else: min_x = .10 max_x = .25", "failed, it, mask def checkMinSeparation(state): positions = np.vstack([state[obj][:3] for obj in state]) if", "goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable = None if not on_shelf:", "loops, we could add some progress bar... for _ in range(n_2d_goals): allgoals +=", "tablePlane=None): if tablePlane is None: min_x = -.25 max_x = .25 elif tablePlane:", "stable = 0 action['render'] = slow if stable > 19: action['render'] = True", "if stable > 20: still = True break pos_dict = {} for obj", "break # checks if at least one object is on the table at_least_one_on_shelf", "_ in range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed,", "obj2 in final.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found", "minSeparation: break print(\"Failed minimum separation ({}), draw again {}..\" .format(clearance, obj)) (a, p,", "This only if in the initial positions it is not true if not", "return observation['retina'], pos_dict, not still, t, observation['mask'] class Position: def __init__(self, start_state=None, fixed_state=None,", "in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found = True break # checks if the", "the distance between initial and final positions of the objects is at least", "table. This only if in the initial positions it is not true if", "min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos,", "orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if failed: print(\"Failed to keep objects fixed...\") continue position.start_state", "if obj == 'cube' and z < 0.48 - 0.15: return True if", "objects = env.robot.used_objects[1:] objOnTable = {} for obj in objects: objOnTable[obj] = True", "elif tablePlane: min_x = -.25 max_x = .05 else: min_x = .10 max_x", "_, pos, failed, _, _ = generateRealPosition(env, goal.initial_state) objects = [o for o", "start_state=None, fixed_state=None, retina=None, mask=None): self.start_state = start_state self.fixed_state = fixed_state self.retina = retina", "to rise it many times failed = failed or orientDiff > 0.041 if", "changed orientation by {}\" .format(obj, orientDiff)) break else: print(\"{} kept orientation.\".format(obj)) if failed:", "found = False for obj in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found = True", "in the initial positions it is not true if found and not at_least_one_on_shelf:", "actual_image, actual_position, failed, it, mask = runEnv(env) return actual_image, actual_position, failed, it, mask", "fixed_state=None, retina=None, mask=None): self.start_state = start_state self.fixed_state = fixed_state self.retina = retina self.mask", "objects is at least how much specified in min_start_goal_dist for obj in final.fixed_state.keys():", "while not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found = True # checks", "z = state[obj][2] if obj == 'cube' and z > 0.55 - 0.15:", "_ in range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _", "np.vstack([env.get_obj_pose(obj) for obj in objects]) still = False stable = 0 for t", "= False for obj in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or goal_type == '2D':", "__init__(self, start_state=None, fixed_state=None, retina=None, mask=None): self.start_state = start_state self.fixed_state = fixed_state self.retina =", "if failed: print(\"{} changed orientation by {}\" .format(obj, orientDiff)) break else: print(\"{} kept", "n_obj) or the default value. \"\"\" np.random.seed(seed) allgoals = [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj))", "return False def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable", "failed = True print(\"Failed minimum separation ({}) after real generation, \" \"draw again", "enclosed brackets are replaced with the supplied options (seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj)", "actual_image = a actual_mask = m actual_position = p failed = f if", "tablePlane=table) startPositions[obj] = startPose if len(startPositions) == 1: break clearance = checkMinSeparation(startPositions) if", "objects]) p1 = np.vstack([pos[o] for o in objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3])", "<= max_objects_dist or goal_type != '3D' or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects = True", "orientDiff) if maxPosDiff < 0.0001 and maxOrientDiff < 0.001 and t > 10:", "{}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0], positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6])", "cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else: # Positions scatter view for i, o in", "position.start_state = startPositions position.fixed_state = actual_position position.retina = actual_image position.mask = actual_mask return", "goals and saves them in a file.\\n The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where", "# TODO CHECK This - we had to rise it many times failed", "state): z = state[obj][2] if obj == 'cube' and z > 0.55 -", "True break if at_least_two_near_objects: break # checks if at least one object is", "by {}\" .format(obj, orientDiff)) break else: print(\"{} kept orientation.\".format(obj)) if failed: print(\"Failed to", "# Generate Images for obj in startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image,", "we had to rise it many times failed = failed or orientDiff >", "reward, done, _ = env.step(action) positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) maxPosDiff", "found = False while not(found): found = True final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable,", "0.48 - 0.15: return True if obj == 'orange' and z < 0.48", "obj == 'mustard' and z > 0.545 - 0.15: return True return False", "= {} for obj in objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment after {}", "n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals) checkRepeatability(env, allgoals) visualizeGoalDistribution(allgoals) if __name__ == \"__main__\": main()", "for obj in fixedObjects: startPositions[obj] = fixedPositions[obj] for obj in np.random.permutation(objects): if obj", "True break if found: break # checks if at least one object is", "np.random.permutation(objects): if obj in fixedObjects: continue while True: table = None if objOnTable", "table at_least_one_on_shelf = False for obj in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or goal_type", "True else: at_least_two_near_objects = False for obj1 in initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys():", "separation ({}), draw again {}..\" .format(clearance, obj)) (a, p, f, it, m) =", "utf-8 -*- \"\"\"Console script to generate goals for real_robots\"\"\" import click import numpy", "posDiff > 0.002 or orientDiff > 0.041 if failed: print(\"{} changed pos by", "== 1: at_least_two_near_objects = True else: at_least_two_near_objects = False for obj1 in initial.fixed_state.keys():", "= True while failed: # skip 1st object, i.e the table objects =", "in range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in", "goals (default 10)') @click.option('--n_obj', type=int, default=3, help='# of objects (default 3)') def main(seed=None,", "actual_mask = m actual_position = p failed = f if failed: print(\"Failed image", "else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose = [x, y, z] +", "False render = False def pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk,", "> 0.545 - 0.15: return True return False def isOnTable(obj, state): z =", "z > 0.55 - 0.15: return True if obj == 'tomato' and z", "None if not on_shelf: objects = env.robot.used_objects[1:] objOnTable = {} for obj in", "print(\"Generating GOAL..\") objOnTable = None if not on_shelf: objects = env.robot.used_objects[1:] objOnTable =", "'mustard' and z > 0.545 - 0.15: return True return False def isOnTable(obj,", "= True # checks whether at least two objects are close together as", "= generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj] = startPose if len(startPositions) == 1: break", "def isOnTable(obj, state): z = state[obj][2] if obj == 'cube' and z <", "using this SEED for numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='# of 2D goals (default", "# Positions scatter view for i, o in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for", "def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as plt challenges = np.unique([goal.challenge for goal in", "= True if stable > 20: still = True break pos_dict = {}", "0.15: return True if obj == 'tomato' and z < 0.49 - 0.15:", "n_3d_goals, n_obj) or the default value. \"\"\" np.random.seed(seed) allgoals = [] env =", "return clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed = True while", "obj in startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed, it, mask", "False break goal = Goal() goal.challenge = goal_type goal.subtype = str(n_obj) goal.initial_state =", "o in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for goal in goals]) axes[c, i].set_title(\"{} {}\".format(o,", "return True if obj == 'tomato' and z < 0.49 - 0.15: return", "fixedOrientation = True found = False while not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable,", "many times failed = failed or orientDiff > 0.041 if failed: print(\"{} changed", "break goal = Goal() goal.challenge = goal_type goal.subtype = str(n_obj) goal.initial_state = initial.fixed_state", "= startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed, it, mask = runEnv(env) return actual_image,", "@click.option('--seed', type=int, help='Generate goals using this SEED for numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='#", "objects]) maxPosDiff = 0 maxOrientDiff = 0 for i, obj in enumerate(objects): posDiff", "at_least_two_near_objects = False for obj1 in initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys(): if obj1", "continue position.start_state = startPositions position.fixed_state = actual_position position.retina = actual_image position.mask = actual_mask", "real generation, \" \"draw again everything..\".format(clearance)) continue if fixedOrientation: for obj in objects:", "in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or goal_type == '2D': at_least_one_on_shelf = True break", "if at least one object is on the table. This only if in", "failed or posDiff > 0.002 or orientDiff > 0.041 if failed: print(\"{} changed", "in objects: q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2),", "not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found = True # checks whether", "checks if at least one object is on the table. This only if", "to keep orientation...\") continue for obj in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3])", "t, observation['mask'] class Position: def __init__(self, start_state=None, fixed_state=None, retina=None, mask=None): self.start_state = start_state", "0.15: return True if obj == 'mustard' and z > 0.545 - 0.15:", "n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable = None if not", "fixedOrientation: for obj in objects: q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff =", "the specified number of goals and saves them in a file.\\n The file", "for obj in state]) if len(positions) > 1: distances = pairwise_distances(positions) clearance =", "z > 0.55 - 0.15: return True if obj == 'mustard' and z", "actual_position, failed, it, mask = runEnv(env) return actual_image, actual_position, failed, it, mask def", "mask def generatePosition(env, obj, fixed=False, tablePlane=None): if tablePlane is None: min_x = -.25", "= final.mask print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals, images=True): import", "- 0.15: return True if obj == 'tomato' and z < 0.49 -", "diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos, maxDiffOr", "scatter view for i, o in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for goal in", "of 2D goals (default 25)') @click.option('--n_25d_goals', type=int, default=15, help='# of 2.5D goals (default", "fixedObjects: continue while True: table = None if objOnTable is not None: if", "action['render'] = slow if stable > 19: action['render'] = True if stable >", "goals]) mustards = sum([goal.mask == 3 for goal in goals]) cubes = sum([goal.mask", "np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 -", "+= [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_3d_goals): allgoals +=", "np.vstack([pos[o] for o in objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:,", "for obj in objects]) maxPosDiff = 0 maxOrientDiff = 0 for i, obj", "print(\"Exiting environment after {} timesteps..\".format(t)) if not still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff))", "= -.25 max_x = .25 elif tablePlane: min_x = -.25 max_x = .05", "for o in goal.initial_state] p0 = np.vstack([goal.initial_state[o] for o in objects]) p1 =", "0 done = False render = slow action = {'joint_command': np.zeros(9), 'render': render}", "# checks if at least one object is on the table. This only", "= old_positions[i][3:] q2 = positions[i][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff =", "< 0.48 - 0.15: return True if obj == 'tomato' and z <", "it, m) = generateRealPosition(env, startPositions) actual_image = a actual_mask = m actual_position =", "0 for goal in goals: _, pos, failed, _, _ = generateRealPosition(env, goal.initial_state)", "def checkMinSeparation(state): positions = np.vstack([state[obj][:3] for obj in state]) if len(positions) > 1:", "== obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found = True break if found:", "= a actual_mask = m actual_position = p failed = f if failed:", "or the default value. \"\"\" np.random.seed(seed) allgoals = [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if", "bar... for _ in range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)]", "break # checks if the distance between initial and final positions of the", "else: fixedOrientation = True found = False while not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation,", "q2 = positions[i][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff)", "break # checks if at least one object is on the table. This", "while failed: # skip 1st object, i.e the table objects = env.robot.used_objects[1:] position", "max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff) if maxPosDiff < 0.0001 and maxOrientDiff <", "default=15, help='# of 2.5D goals (default 15)') @click.option('--n_3d_goals', type=int, default=10, help='# of 3D", "maxDiffPos, maxDiffOr def isOnShelf(obj, state): z = state[obj][2] if obj == 'cube' and", "- 0.15: return True if obj == 'orange' and z > 0.55 -", "q2), np.linalg.norm(q1+q2)) failed = failed or posDiff > 0.002 or orientDiff > 0.041", "not still, t, observation['mask'] class Position: def __init__(self, start_state=None, fixed_state=None, retina=None, mask=None): self.start_state", "False for obj1 in final.fixed_state.keys(): for obj2 in final.fixed_state.keys(): if obj1 == obj2:", "if found and not at_least_one_on_shelf: found = False for obj in final.fixed_state.keys(): if", "0.0001 and maxOrientDiff < 0.001 and t > 10: stable += 1 else:", "4 for goal in goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes,", "if isOnShelf(obj, initial.fixed_state) or goal_type == '2D': at_least_one_on_shelf = True break found =", "# Superimposed images view tomatos = sum([goal.mask == 2 for goal in goals])", "number of goals and saves them in a file.\\n The file is called", "and z > 0.55 - 0.15: return True if obj == 'tomato' and", "= plt.subplots(max(2, len(challenges)), 3) for c, challenge in enumerate(challenges): goals = [goal for", "positions[i][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff =", "= True print(\"Failed minimum separation ({}) after real generation, \" \"draw again everything..\".format(clearance))", "== 'tomato' and z < 0.49 - 0.15: return True if obj ==", "[generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_3d_goals): allgoals += [generateGoalREAL2020(env,", "GOAL {}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as plt challenges =", "in objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:,", "if len(goals) > 0: if images: # Superimposed images view tomatos = sum([goal.mask", "failed: # skip 1st object, i.e the table objects = env.robot.used_objects[1:] position =", "'render': render} objects = env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) still", "on the table at_least_one_on_shelf = False for obj in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state)", "stable = 0 for t in range(max_t): old_positions = positions observation, reward, done,", "0.545 - 0.15: return True return False def isOnTable(obj, state): z = state[obj][2]", "allgoals += [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals,", "return actual_image, actual_position, failed, it, mask def checkMinSeparation(state): positions = np.vstack([state[obj][:3] for obj", "for obj in objects: q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1", "3 for goal in goals]) cubes = sum([goal.mask == 4 for goal in", "== 'orange' and z < 0.48 - 0.15: return True if obj ==", "\"\"\" np.random.seed(seed) allgoals = [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset() global", "maxDiffPos = 0 maxDiffOr = 0 for goal in goals: _, pos, failed,", "import gym import math basePosition = None slow = False render = False", "clearance = np.inf return clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed", "if obj == 'mustard' and z > 0.545 - 0.15: return True return", "is None: min_x = -.25 max_x = .25 elif tablePlane: min_x = -.25", "replaced with the supplied options (seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or the default", "self.mask = mask def generatePosition(env, obj, fixed=False, tablePlane=None): if tablePlane is None: min_x", "in goals]) mustards = sum([goal.mask == 3 for goal in goals]) cubes =", "it is not true if found and not at_least_one_on_shelf: found = False for", "had to rise it many times failed = failed or orientDiff > 0.041", "default=25, help='# of 2D goals (default 25)') @click.option('--n_25d_goals', type=int, default=15, help='# of 2.5D", "def checkRepeatability(env, goals): maxDiffPos = 0 maxDiffOr = 0 for goal in goals:", "goal.initial_state = initial.fixed_state goal.final_state = final.fixed_state goal.retina_before = initial.retina goal.retina = final.retina goal.mask", "positions observation, reward, done, _ = env.step(action) positions = np.vstack([env.get_obj_pose(obj) for obj in", "= .25 elif tablePlane: min_x = -.25 max_x = .05 else: min_x =", "as np from real_robots.envs import Goal import gym import math basePosition = None", "specified in max_objects_dist if n_obj == 1: at_least_two_near_objects = True else: at_least_two_near_objects =", "t in range(max_t): old_positions = positions observation, reward, done, _ = env.step(action) positions", "break if found: break # checks if at least one object is on", "pos, failed, _, _ = generateRealPosition(env, goal.initial_state) objects = [o for o in", "Generates the specified number of goals and saves them in a file.\\n The", "'cube' and z > 0.55 - 0.15: return True if obj == 'orange'", "if obj == 'orange' and z < 0.48 - 0.15: return True if", ".05 else: min_x = .10 max_x = .25 min_y = -.45 max_y =", "a file.\\n The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are replaced with", "for _ in range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy'", "= fixed_state self.retina = retina self.mask = mask def generatePosition(env, obj, fixed=False, tablePlane=None):", "str(n_obj) goal.initial_state = initial.fixed_state goal.final_state = final.fixed_state goal.retina_before = initial.retina goal.retina = final.retina", "at_least_two_near_objects: break # checks if at least one object is on the table", "0 action['render'] = slow if stable > 19: action['render'] = True if stable", "whether at least two objects are close together as specified in max_objects_dist. This", "actual_image position.mask = actual_mask return position def checkRepeatability(env, goals): maxDiffPos = 0 maxDiffOr", "minimum separation ({}), draw again {}..\" .format(clearance, obj)) (a, p, f, it, m)", "{}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as plt challenges = np.unique([goal.challenge", "continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found = True break if found: break #", "numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='# of 2D goals (default 25)') @click.option('--n_25d_goals', type=int, default=15,", "two objects are close together as specified in max_objects_dist. This only if in", "<= max_objects_dist: found = True break if found: break # checks if at", "return False def isOnTable(obj, state): z = state[obj][2] if obj == 'cube' and", "to keep objects fixed...\") continue position.start_state = startPositions position.fixed_state = actual_position position.retina =", "checks whether at least two objects are close together as specified in max_objects_dist", ".format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals) checkRepeatability(env, allgoals) visualizeGoalDistribution(allgoals) if __name__ == \"__main__\":", "= actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) # TODO CHECK This -", "np.linalg.norm(q1+q2)) failed = failed or posDiff > 0.002 or orientDiff > 0.041 if", "_, _ = generateRealPosition(env, goal.initial_state) objects = [o for o in goal.initial_state] p0", "if obj in fixedObjects: continue while True: table = None if objOnTable is", "for goal in goals: _, pos, failed, _, _ = generateRealPosition(env, goal.initial_state) objects", "= runEnv(env) return actual_image, actual_position, failed, it, mask def checkMinSeparation(state): positions = np.vstack([state[obj][:3]", "still = True break pos_dict = {} for obj in objects: pos_dict[obj] =", "- 0.15: return True if obj == 'mustard' and z > 0.545 -", "found = False for obj1 in final.fixed_state.keys(): for obj2 in final.fixed_state.keys(): if obj1", "because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict, not still, t, observation['mask'] class Position:", "if len(startPositions) == 1: break clearance = checkMinSeparation(startPositions) if clearance >= minSeparation: break", "0 for t in range(max_t): old_positions = positions observation, reward, done, _ =", "help='# of 3D goals (default 10)') @click.option('--n_obj', type=int, default=3, help='# of objects (default", "for o in objects]) p1 = np.vstack([pos[o] for o in objects]) diffPos =", "q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed = failed or", "self.fixed_state = fixed_state self.retina = retina self.mask = mask def generatePosition(env, obj, fixed=False,", "final.retina goal.mask = final.mask print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals,", "x = np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if x <= 0.05: z = 0.40", "= [o for o in goal.initial_state] p0 = np.vstack([goal.initial_state[o] for o in objects])", "In these for loops, we could add some progress bar... for _ in", "challenge] if len(goals) > 0: if images: # Superimposed images view tomatos =", "obj == 'tomato' and z < 0.49 - 0.15: return True if obj", "1: at_least_two_near_objects = True break if at_least_two_near_objects: break # checks if at least", "obj2 in initial.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or", "'mustard' and z < 0.48 - 0.15: return True return False def generateGoalREAL2020(env,", "def generateRealPosition(env, startPositions): env.reset() runEnv(env) # Generate Images for obj in startPositions: pos", "in range(max_t): old_positions = positions observation, reward, done, _ = env.step(action) positions =", "render = False def pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij',", "of 3D goals (default 10)') @click.option('--n_obj', type=int, default=3, help='# of objects (default 3)')", "a-b)) def runEnv(env, max_t=1000): reward = 0 done = False render = slow", "with the supplied options (seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or the default value.", "skip 1st object, i.e the table objects = env.robot.used_objects[1:] position = Position() startPositions", "return True if obj == 'tomato' and z > 0.55 - 0.15: return", "matplotlib.pyplot as plt challenges = np.unique([goal.challenge for goal in all_goals]) fig, axes =", "observation['retina'], pos_dict, not still, t, observation['mask'] class Position: def __init__(self, start_state=None, fixed_state=None, retina=None,", "= np.vstack([goal.initial_state[o] for o in objects]) p1 = np.vstack([pos[o] for o in objects])", "print(actual_position[obj]) break if failed: print(\"Failed to keep objects fixed...\") continue position.start_state = startPositions", "= True break # checks if the distance between initial and final positions", "orientation = basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose = [x,", "= max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff) if maxPosDiff < 0.0001 and maxOrientDiff", "type=int, default=3, help='# of objects (default 3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3):", "def isOnShelf(obj, state): z = state[obj][2] if obj == 'cube' and z >", "in state]) if len(positions) > 1: distances = pairwise_distances(positions) clearance = distances[distances >", "= positions[i][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff", "{} for obj in objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment after {} timesteps..\".format(t))", "position def checkRepeatability(env, goals): maxDiffPos = 0 maxDiffOr = 0 for goal in", "if not at_least_two_near_objects: found = False for obj1 in final.fixed_state.keys(): for obj2 in", "checkRepeatability(env, goals): maxDiffPos = 0 maxDiffOr = 0 for goal in goals: _,", "goals for real_robots\"\"\" import click import numpy as np from real_robots.envs import Goal", "= .05 else: min_x = .10 max_x = .25 min_y = -.45 max_y", "pos[3:]) actual_image, actual_position, failed, it, mask = runEnv(env) return actual_image, actual_position, failed, it,", "def __init__(self, start_state=None, fixed_state=None, retina=None, mask=None): self.start_state = start_state self.fixed_state = fixed_state self.retina", "generation...\") continue clearance = checkMinSeparation(actual_position) if clearance < minSeparation: failed = True print(\"Failed", "object is on the table. This only if in the initial positions it", "default=3, help='# of objects (default 3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\"", "- q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff) if maxPosDiff", "else: stable = 0 action['render'] = slow if stable > 19: action['render'] =", "final.fixed_state): found = True break # checks if the distance between initial and", "None slow = False render = False def pairwise_distances(a): b = a.reshape(a.shape[0], 1,", "obj1 in initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys(): if obj1 == obj2: continue if", "= Goal() goal.challenge = goal_type goal.subtype = str(n_obj) goal.initial_state = initial.fixed_state goal.final_state =", "position.mask = actual_mask return position def checkRepeatability(env, goals): maxDiffPos = 0 maxDiffOr =", "3) for c, challenge in enumerate(challenges): goals = [goal for goal in all_goals", "for loops, we could add some progress bar... for _ in range(n_2d_goals): allgoals", "minSeparation=0, objOnTable=None): failed = True while failed: # skip 1st object, i.e the", "= .10 max_x = .25 min_y = -.45 max_y = .45 x =", "value. \"\"\" np.random.seed(seed) allgoals = [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset()", "np.vstack([goal.final_state[o] for goal in goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0], positions[:,", "old_positions[i][3:] q2 = positions[i][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff,", "m actual_position = p failed = f if failed: print(\"Failed image generation...\") continue", "if obj == 'cube' and z > 0.55 - 0.15: return True if", "failed: print(\"Failed to keep objects fixed...\") continue position.start_state = startPositions position.fixed_state = actual_position", "or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects = True break if at_least_two_near_objects: break # checks", "i].hist2d(positions[:, 0], positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed',", "objects]) still = False stable = 0 for t in range(max_t): old_positions =", "the default value. \"\"\" np.random.seed(seed) allgoals = [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render:", "pos_dict, not still, t, observation['mask'] class Position: def __init__(self, start_state=None, fixed_state=None, retina=None, mask=None):", "i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed', type=int, help='Generate goals using this SEED for numpy.random')", "objects: q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2))", "at least how much specified in min_start_goal_dist for obj in final.fixed_state.keys(): if min_start_goal_dist", "diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos, maxDiffOr def isOnShelf(obj, state):", "print(\"{} changed pos by {} and orientation by {}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj])", "Superimposed images view tomatos = sum([goal.mask == 2 for goal in goals]) mustards", "fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff", "n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or the default value. \"\"\" np.random.seed(seed) allgoals = []", "np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 = old_positions[i][3:] q2 = positions[i][3:] orientDiff = min(np.linalg.norm(q1 -", "True final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether at least two", "1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed', type=int, help='Generate goals", "= -.25 max_x = .05 else: min_x = .10 max_x = .25 min_y", "z < 0.49 - 0.15: return True if obj == 'mustard' and z", "objOnTable[obj] = True if goal_type == '3D': fixedOrientation = False else: fixedOrientation =", "obj == 'orange' and z < 0.48 - 0.15: return True if obj", "type=int, default=25, help='# of 2D goals (default 25)') @click.option('--n_25d_goals', type=int, default=15, help='# of", "_ = env.step(action) positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) maxPosDiff = 0", "goal def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as plt challenges = np.unique([goal.challenge for goal", "> 10: stable += 1 else: stable = 0 action['render'] = slow if", "maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict, not still, t, observation['mask'] class Position: def", "{'joint_command': np.zeros(9), 'render': render} objects = env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for obj in", "actual_position, failed, it, mask def checkMinSeparation(state): positions = np.vstack([state[obj][:3] for obj in state])", "final.fixed_state.keys(): for obj2 in final.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <=", "# checks if the distance between initial and final positions of the objects", "max_x = .05 else: min_x = .10 max_x = .25 min_y = -.45", "startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed, it, mask = runEnv(env)", "= True if goal_type == '3D': fixedOrientation = False else: fixedOrientation = True", "in objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment after {} timesteps..\".format(t)) if not still:", "for obj1 in final.fixed_state.keys(): for obj2 in final.fixed_state.keys(): if obj1 == obj2: continue", "final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break goal = Goal() goal.challenge", "as plt challenges = np.unique([goal.challenge for goal in all_goals]) fig, axes = plt.subplots(max(2,", "and maxOrientDiff < 0.001 and t > 10: stable += 1 else: stable", "in final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break goal = Goal()", "together as specified in max_objects_dist. This only if in the initial positions it", "if obj1 == obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found = True break", "checks if at least one object is on the table at_least_one_on_shelf = False", "= env.get_obj_pose(obj) print(\"Exiting environment after {} timesteps..\".format(t)) if not still: print(\"Failed because maxPosDiff:{:.6f},\"", "= distances[distances > 0].min() else: clearance = np.inf return clearance def drawPosition(env, fixedOrientation=False,", "if images: # Superimposed images view tomatos = sum([goal.mask == 2 for goal", "for _ in range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for", "None: min_x = -.25 max_x = .25 elif tablePlane: min_x = -.25 max_x", "of GOAL {}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as plt challenges", "0 maxDiffOr = 0 for goal in goals: _, pos, failed, _, _", "- 0.15: return True return False def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05,", "= np.random.rand()*(max_y-min_y)+min_y if x <= 0.05: z = 0.40 else: z = 0.50", "obj in np.random.permutation(objects): if obj in fixedObjects: continue while True: table = None", "or posDiff > 0.002 or orientDiff > 0.041 if failed: print(\"{} changed pos", "goal = Goal() goal.challenge = goal_type goal.subtype = str(n_obj) goal.initial_state = initial.fixed_state goal.final_state", "continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type != '3D' or len(initial.fixed_state.keys()) == 1:", "obj, fixed=False, tablePlane=None): if tablePlane is None: min_x = -.25 max_x = .25", "after real generation, \" \"draw again everything..\".format(clearance)) continue if fixedOrientation: for obj in", "-.25 max_x = .25 elif tablePlane: min_x = -.25 max_x = .05 else:", "posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if failed: print(\"Failed to keep objects fixed...\") continue", ".10 max_x = .25 min_y = -.45 max_y = .45 x = np.random.rand()*(max_x-min_x)+min_x", "generatePosition(env, obj, fixed=False, tablePlane=None): if tablePlane is None: min_x = -.25 max_x =", "not true if found and not at_least_one_on_shelf: found = False for obj in", "orientDiff > 0.041 if failed: print(\"{} changed pos by {} and orientation by", "return True return False def isOnTable(obj, state): z = state[obj][2] if obj ==", "0.001 and t > 10: stable += 1 else: stable = 0 action['render']", "close together as specified in max_objects_dist if n_obj == 1: at_least_two_near_objects = True", "actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) # TODO CHECK This - we", "_, basePosition, _, _, _ = runEnv(env) # In these for loops, we", "q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) # TODO CHECK This", "0.15: return True if obj == 'tomato' and z > 0.55 - 0.15:", "- positions[i][:3]) q1 = old_positions[i][3:] q2 = positions[i][3:] orientDiff = min(np.linalg.norm(q1 - q2),", "== '3D': fixedOrientation = False else: fixedOrientation = True found = False while", "is on the table at_least_one_on_shelf = False for obj in initial.fixed_state.keys(): if isOnShelf(obj,", "np from real_robots.envs import Goal import gym import math basePosition = None slow", "import math basePosition = None slow = False render = False def pairwise_distances(a):", "print(startPositions[obj]) print(actual_position[obj]) break if failed: print(\"Failed to keep objects fixed...\") continue position.start_state =", "else: min_x = .10 max_x = .25 min_y = -.45 max_y = .45", "< 0.48 - 0.15: return True if obj == 'orange' and z <", "max_x = .25 min_y = -.45 max_y = .45 x = np.random.rand()*(max_x-min_x)+min_x y", "on_shelf: objects = env.robot.used_objects[1:] objOnTable = {} for obj in objects: objOnTable[obj] =", "continue while True: table = None if objOnTable is not None: if obj", "> 0.041 if failed: print(\"{} changed pos by {} and orientation by {}\"", "and final positions of the objects is at least how much specified in", "= drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether at least two objects are", "if x <= 0.05: z = 0.40 else: z = 0.50 if fixed:", "= np.vstack([goal.final_state[o] for goal in goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0],", "actual_position position.retina = actual_image position.mask = actual_mask return position def checkRepeatability(env, goals): maxDiffPos", "[x, y, z] + np.array(orientation).tolist() return pose def generateRealPosition(env, startPositions): env.reset() runEnv(env) #", "sum([goal.mask == 4 for goal in goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray')", "True if obj == 'orange' and z > 0.55 - 0.15: return True", "goals = [goal for goal in all_goals if goal.challenge == challenge] if len(goals)", "= {} for obj in fixedObjects: startPositions[obj] = fixedPositions[obj] for obj in np.random.permutation(objects):", "return True if obj == 'orange' and z > 0.55 - 0.15: return", "objOnTable = {} for obj in objects: objOnTable[obj] = True if goal_type ==", "keep objects fixed...\") continue position.start_state = startPositions position.fixed_state = actual_position position.retina = actual_image", "Positions scatter view for i, o in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for goal", "True found = False while not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found", "fixed=False, tablePlane=None): if tablePlane is None: min_x = -.25 max_x = .25 elif", "is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are replaced with the supplied options (seed,", "gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset() global basePosition _, basePosition, _, _, _ =", "or orientDiff > 0.041 if failed: print(\"{} changed pos by {} and orientation", "positions = np.vstack([state[obj][:3] for obj in state]) if len(positions) > 1: distances =", "objects are close together as specified in max_objects_dist if n_obj == 1: at_least_two_near_objects", "env.render('human') env.reset() global basePosition _, basePosition, _, _, _ = runEnv(env) # In", "= positions observation, reward, done, _ = env.step(action) positions = np.vstack([env.get_obj_pose(obj) for obj", "goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else: # Positions", "view tomatos = sum([goal.mask == 2 for goal in goals]) mustards = sum([goal.mask", "separation ({}) after real generation, \" \"draw again everything..\".format(clearance)) continue if fixedOrientation: for", "min_y = -.45 max_y = .45 x = np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if", "in a file.\\n The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are replaced", "orientation...\") continue for obj in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 =", "maxDiffOr = 0 for goal in goals: _, pos, failed, _, _ =", "for obj1 in initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys(): if obj1 == obj2: continue", "in range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals,", "\"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals) checkRepeatability(env, allgoals)", "< 0.0001 and maxOrientDiff < 0.001 and t > 10: stable += 1", "t > 10: stable += 1 else: stable = 0 action['render'] = slow", "action = {'joint_command': np.zeros(9), 'render': render} objects = env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for", "axes[c, 2].imshow(cubes, cmap='gray') else: # Positions scatter view for i, o in enumerate(goals[0].final_state.keys()):", "= f if failed: print(\"Failed image generation...\") continue clearance = checkMinSeparation(actual_position) if clearance", "state[obj][2] if obj == 'cube' and z > 0.55 - 0.15: return True", "= np.inf return clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed =", "b = a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def runEnv(env, max_t=1000):", "goals: _, pos, failed, _, _ = generateRealPosition(env, goal.initial_state) objects = [o for", "3:])) maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr))", "in objects]) still = False stable = 0 for t in range(max_t): old_positions", "2 for goal in goals]) mustards = sum([goal.mask == 3 for goal in", "y = np.random.rand()*(max_y-min_y)+min_y if x <= 0.05: z = 0.40 else: z =", "for t in range(max_t): old_positions = positions observation, reward, done, _ = env.step(action)", "axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed', type=int, help='Generate goals using this SEED for", "final.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found = True", "obj in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 = old_positions[i][3:] q2 =", "objOnTable=objOnTable, minSeparation=min_objects_dist) found = True # checks whether at least two objects are", "runEnv(env) return actual_image, actual_position, failed, it, mask def checkMinSeparation(state): positions = np.vstack([state[obj][:3] for", "at_least_two_near_objects = True break if at_least_two_near_objects: break # checks if at least one", "goal.initial_state] p0 = np.vstack([goal.initial_state[o] for o in objects]) p1 = np.vstack([pos[o] for o", "@click.command() @click.option('--seed', type=int, help='Generate goals using this SEED for numpy.random') @click.option('--n_2d_goals', type=int, default=25,", "= min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff)", "o in objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]),", "max_objects_dist=2): print(\"Generating GOAL..\") objOnTable = None if not on_shelf: objects = env.robot.used_objects[1:] objOnTable", "pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def runEnv(env,", "for i, obj in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 = old_positions[i][3:]", "in final.fixed_state.keys(): for obj2 in final.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3])", "\"draw again everything..\".format(clearance)) continue if fixedOrientation: for obj in objects: q1 = startPositions[obj][3:]", "env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset() global basePosition _, basePosition, _, _,", "for obj2 in initial.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist", "= False def pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b,", "np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found = True break if found: break # checks if", "if in the initial positions it is not true if found and not", "if maxPosDiff < 0.0001 and maxOrientDiff < 0.001 and t > 10: stable", "False for obj in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or goal_type == '2D': at_least_one_on_shelf", "for obj2 in final.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist:", "= True break if found: break # checks if at least one object", "range(max_t): old_positions = positions observation, reward, done, _ = env.step(action) positions = np.vstack([env.get_obj_pose(obj)", "_, _, _ = runEnv(env) # In these for loops, we could add", "0.55 - 0.15: return True if obj == 'tomato' and z > 0.55", "min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break goal = Goal() goal.challenge = goal_type", "diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr", "axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed', type=int, help='Generate goals using", "minSeparation: failed = True print(\"Failed minimum separation ({}) after real generation, \" \"draw", "= False render = False def pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1]) return", "else: print(\"{} kept orientation.\".format(obj)) if failed: print(\"Failed to keep orientation...\") continue for obj", "= 0 for i, obj in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1", "distances[distances > 0].min() else: clearance = np.inf return clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[],", "for goal in goals]) cubes = sum([goal.mask == 4 for goal in goals])", "supplied options (seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or the default value. \"\"\" np.random.seed(seed)", "diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:]))", "max_objects_dist if n_obj == 1: at_least_two_near_objects = True else: at_least_two_near_objects = False for", "found = True break # checks if the distance between initial and final", "= start_state self.fixed_state = fixed_state self.retina = retina self.mask = mask def generatePosition(env,", "(default 15)') @click.option('--n_3d_goals', type=int, default=10, help='# of 3D goals (default 10)') @click.option('--n_obj', type=int,", "= checkMinSeparation(actual_position) if clearance < minSeparation: failed = True print(\"Failed minimum separation ({})", "np.random.seed(seed) allgoals = [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset() global basePosition", "drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed = True while failed: # skip", "= a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def runEnv(env, max_t=1000): reward", "posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff =", "> 0].min() else: clearance = np.inf return clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None,", "failed, it, mask = runEnv(env) return actual_image, actual_position, failed, it, mask def checkMinSeparation(state):", "startPositions = {} for obj in fixedObjects: startPositions[obj] = fixedPositions[obj] for obj in", "while True: table = None if objOnTable is not None: if obj in", "p failed = f if failed: print(\"Failed image generation...\") continue clearance = checkMinSeparation(actual_position)", "positions it is not true if found and not at_least_one_on_shelf: found = False", "obj in objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment after {} timesteps..\".format(t)) if not", "range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_3d_goals):", "p1 = np.vstack([pos[o] for o in objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr", "'orange' and z > 0.55 - 0.15: return True if obj == 'tomato'", "= 0 action['render'] = slow if stable > 19: action['render'] = True if", "obj in final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break goal =", "env.robot.used_objects[1:] position = Position() startPositions = {} for obj in fixedObjects: startPositions[obj] =", "max(maxOrientDiff, orientDiff) if maxPosDiff < 0.0001 and maxOrientDiff < 0.001 and t >", "break else: print(\"{} kept orientation.\".format(obj)) if failed: print(\"Failed to keep orientation...\") continue for", "goal.challenge = goal_type goal.subtype = str(n_obj) goal.initial_state = initial.fixed_state goal.final_state = final.fixed_state goal.retina_before", "= (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose = [x, y, z] + np.array(orientation).tolist() return", "in startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed, it, mask =", "z < 0.48 - 0.15: return True if obj == 'tomato' and z", "Position: def __init__(self, start_state=None, fixed_state=None, retina=None, mask=None): self.start_state = start_state self.fixed_state = fixed_state", "math basePosition = None slow = False render = False def pairwise_distances(a): b", "= False for obj in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found = True break", "= env.step(action) positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) maxPosDiff = 0 maxOrientDiff", "+= 1 else: stable = 0 action['render'] = slow if stable > 19:", "= startPositions position.fixed_state = actual_position position.retina = actual_image position.mask = actual_mask return position", "False while not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found = True #", "or orientDiff > 0.041 if failed: print(\"{} changed orientation by {}\" .format(obj, orientDiff))", "startPositions) actual_image = a actual_mask = m actual_position = p failed = f", "return True if obj == 'mustard' and z > 0.545 - 0.15: return", "obj, fixedOrientation, tablePlane=table) startPositions[obj] = startPose if len(startPositions) == 1: break clearance =", "type=int, default=10, help='# of 3D goals (default 10)') @click.option('--n_obj', type=int, default=3, help='# of", "np.zeros(9), 'render': render} objects = env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for obj in objects])", "in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 = old_positions[i][3:] q2 = positions[i][3:]", "diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos, maxDiffOr def isOnShelf(obj,", "orientation by {}\" .format(obj, orientDiff)) break else: print(\"{} kept orientation.\".format(obj)) if failed: print(\"Failed", "True print(\"Failed minimum separation ({}) after real generation, \" \"draw again everything..\".format(clearance)) continue", "objects are close together as specified in max_objects_dist. This only if in the", "True if goal_type == '3D': fixedOrientation = False else: fixedOrientation = True found", "obj in fixedObjects: startPositions[obj] = fixedPositions[obj] for obj in np.random.permutation(objects): if obj in", "fixedObjects: startPositions[obj] = fixedPositions[obj] for obj in np.random.permutation(objects): if obj in fixedObjects: continue", "< 0.49 - 0.15: return True if obj == 'mustard' and z <", "close together as specified in max_objects_dist. This only if in the initial positions", "minSeparation=min_objects_dist) # checks whether at least two objects are close together as specified", "print(\"Failed to keep objects fixed...\") continue position.start_state = startPositions position.fixed_state = actual_position position.retina", "clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed = True while failed:", "cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else: # Positions scatter view for", "runEnv(env) # Generate Images for obj in startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:])", "final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether at least two objects", "import numpy as np from real_robots.envs import Goal import gym import math basePosition", "specified in min_start_goal_dist for obj in final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found =", "= -.45 max_y = .45 x = np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if x", "+ np.array(orientation).tolist() return pose def generateRealPosition(env, startPositions): env.reset() runEnv(env) # Generate Images for", "z < 0.48 - 0.15: return True return False def generateGoalREAL2020(env, n_obj, goal_type,", "at least one object is on the table. This only if in the", "# skip 1st object, i.e the table objects = env.robot.used_objects[1:] position = Position()", "c, challenge in enumerate(challenges): goals = [goal for goal in all_goals if goal.challenge", ".format(obj, orientDiff)) break else: print(\"{} kept orientation.\".format(obj)) if failed: print(\"Failed to keep orientation...\")", "\"\"\"Console script to generate goals for real_robots\"\"\" import click import numpy as np", "objects = [o for o in goal.initial_state] p0 = np.vstack([goal.initial_state[o] for o in", "initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found = True # checks whether at", "generateRealPosition(env, goal.initial_state) objects = [o for o in goal.initial_state] p0 = np.vstack([goal.initial_state[o] for", "range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_25d_goals):", "< 0.001 and t > 10: stable += 1 else: stable = 0", "at_least_two_near_objects: found = False for obj1 in final.fixed_state.keys(): for obj2 in final.fixed_state.keys(): if", "False for obj in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found = True break #", "return position def checkRepeatability(env, goals): maxDiffPos = 0 maxDiffOr = 0 for goal", "goal in goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else:", "file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are replaced with the supplied options", "[goal for goal in all_goals if goal.challenge == challenge] if len(goals) > 0:", "only if in the initial positions it is not true if found and", "np.vstack([state[obj][:3] for obj in state]) if len(positions) > 1: distances = pairwise_distances(positions) clearance", "failed, _, _ = generateRealPosition(env, goal.initial_state) objects = [o for o in goal.initial_state]", "= {} for obj in objects: objOnTable[obj] = True if goal_type == '3D':", "is on the table. This only if in the initial positions it is", "= None if objOnTable is not None: if obj in objOnTable: table =", "break found = False while not(found): found = True final = drawPosition(env, fixedOrientation=fixedOrientation,", "= Position() startPositions = {} for obj in fixedObjects: startPositions[obj] = fixedPositions[obj] for", "goal in goals: _, pos, failed, _, _ = generateRealPosition(env, goal.initial_state) objects =", ".45 x = np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if x <= 0.05: z =", "goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0], positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3])", "Generate Images for obj in startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position,", "object is on the table at_least_one_on_shelf = False for obj in initial.fixed_state.keys(): if", "None if objOnTable is not None: if obj in objOnTable: table = objOnTable[obj]", "= np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1", "for obj in objects: objOnTable[obj] = True if goal_type == '3D': fixedOrientation =", "table objects = env.robot.used_objects[1:] position = Position() startPositions = {} for obj in", "if obj == 'tomato' and z < 0.49 - 0.15: return True if", "state): z = state[obj][2] if obj == 'cube' and z < 0.48 -", "in max_objects_dist if n_obj == 1: at_least_two_near_objects = True else: at_least_two_near_objects = False", "= actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed = failed or posDiff", "0].min() else: clearance = np.inf return clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0,", "obj in fixedObjects: continue while True: table = None if objOnTable is not", "enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for goal in goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c,", "goal in goals]) mustards = sum([goal.mask == 3 for goal in goals]) cubes", "False while not(found): found = True final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) #", "min_start_goal_dist for obj in final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break", "env.get_obj_pose(obj) print(\"Exiting environment after {} timesteps..\".format(t)) if not still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff,", "fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed = True while failed: # skip 1st", "= False for obj1 in initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys(): if obj1 ==", "click import numpy as np from real_robots.envs import Goal import gym import math", "in goal.initial_state] p0 = np.vstack([goal.initial_state[o] for o in objects]) p1 = np.vstack([pos[o] for", "np.vstack([goal.initial_state[o] for o in objects]) p1 = np.vstack([pos[o] for o in objects]) diffPos", "= 0.50 if fixed: orientation = basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation =", "0.15: return True if obj == 'mustard' and z < 0.48 - 0.15:", "= True break pos_dict = {} for obj in objects: pos_dict[obj] = env.get_obj_pose(obj)", "False def pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b))", "0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else: # Positions scatter view", "positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) maxPosDiff = 0 maxOrientDiff = 0", "orientDiff)) break else: print(\"{} kept orientation.\".format(obj)) if failed: print(\"Failed to keep orientation...\") continue", "z > 0.545 - 0.15: return True return False def isOnTable(obj, state): z", "least one object is on the table at_least_one_on_shelf = False for obj in", "in initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3])", "if failed: print(\"Failed to keep objects fixed...\") continue position.start_state = startPositions position.fixed_state =", "= 0 for t in range(max_t): old_positions = positions observation, reward, done, _", "for o in objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:,", "old_positions = positions observation, reward, done, _ = env.step(action) positions = np.vstack([env.get_obj_pose(obj) for", "if tablePlane is None: min_x = -.25 max_x = .25 elif tablePlane: min_x", "min_x = .10 max_x = .25 min_y = -.45 max_y = .45 x", "[o for o in goal.initial_state] p0 = np.vstack([goal.initial_state[o] for o in objects]) p1", "{} for obj in fixedObjects: startPositions[obj] = fixedPositions[obj] for obj in np.random.permutation(objects): if", "False stable = 0 for t in range(max_t): old_positions = positions observation, reward,", "GOAL..\") objOnTable = None if not on_shelf: objects = env.robot.used_objects[1:] objOnTable = {}", "reward = 0 done = False render = slow action = {'joint_command': np.zeros(9),", "(np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose = [x, y, z] + np.array(orientation).tolist() return pose", "pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment after {} timesteps..\".format(t)) if not still: print(\"Failed because", "for goal in all_goals]) fig, axes = plt.subplots(max(2, len(challenges)), 3) for c, challenge", "main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates the specified number of goals and", "of the objects is at least how much specified in min_start_goal_dist for obj", "def runEnv(env, max_t=1000): reward = 0 done = False render = slow action", "= goal_type goal.subtype = str(n_obj) goal.initial_state = initial.fixed_state goal.final_state = final.fixed_state goal.retina_before =", "# checks whether at least two objects are close together as specified in", "> 20: still = True break pos_dict = {} for obj in objects:", "runEnv(env, max_t=1000): reward = 0 done = False render = slow action =", "0.48 - 0.15: return True return False def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1,", "obj in objOnTable: table = objOnTable[obj] startPose = generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj]", "@click.option('--n_obj', type=int, default=3, help='# of objects (default 3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10,", "= startPose if len(startPositions) == 1: break clearance = checkMinSeparation(startPositions) if clearance >=", "SEED for numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='# of 2D goals (default 25)') @click.option('--n_25d_goals',", "maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if", "print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos, maxDiffOr def isOnShelf(obj, state): z = state[obj][2] if", "objects: objOnTable[obj] = True if goal_type == '3D': fixedOrientation = False else: fixedOrientation", "env._p.getQuaternionFromEuler(orientation) pose = [x, y, z] + np.array(orientation).tolist() return pose def generateRealPosition(env, startPositions):", "- 0.15: return True if obj == 'orange' and z < 0.48 -", "= gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset() global basePosition _, basePosition, _, _, _", "max_objects_dist. This only if in the initial positions it is not true if", "q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff) if maxPosDiff <", "n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj,", "view for i, o in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for goal in goals])", "clearance < minSeparation: failed = True print(\"Failed minimum separation ({}) after real generation,", "0.48 - 0.15: return True if obj == 'tomato' and z < 0.49", "\"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"3D\",", "min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals) checkRepeatability(env, allgoals) visualizeGoalDistribution(allgoals) if __name__", "not still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict, not still, t,", "= initial.retina goal.retina = final.retina goal.mask = final.mask print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type))", "or goal_type != '3D' or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects = True break if", "in fixedObjects: startPositions[obj] = fixedPositions[obj] for obj in np.random.permutation(objects): if obj in fixedObjects:", "positions it is not true if not at_least_two_near_objects: found = False for obj1", "position.retina = actual_image position.mask = actual_mask return position def checkRepeatability(env, goals): maxDiffPos =", "on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable = None if not on_shelf: objects", "min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) # TODO CHECK This - we had to rise", "= actual_image position.mask = actual_mask return position def checkRepeatability(env, goals): maxDiffPos = 0", ".25 min_y = -.45 max_y = .45 x = np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y", "> 0: if images: # Superimposed images view tomatos = sum([goal.mask == 2", "1: at_least_two_near_objects = True else: at_least_two_near_objects = False for obj1 in initial.fixed_state.keys(): for", "goal_type == '2D': at_least_one_on_shelf = True break found = False while not(found): found", "in max_objects_dist. This only if in the initial positions it is not true", "found: break # checks if at least one object is on the table.", "!= '3D' or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects = True break if at_least_two_near_objects: break", "not at_least_one_on_shelf: found = False for obj in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found", "= env.robot.used_objects[1:] position = Position() startPositions = {} for obj in fixedObjects: startPositions[obj]", "if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type != '3D' or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects", "z = state[obj][2] if obj == 'cube' and z < 0.48 - 0.15:", "orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed = failed or posDiff > 0.002", "np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated diffPos:{}", "still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict, not still, t, observation['mask']", "maxOrientDiff = max(maxOrientDiff, orientDiff) if maxPosDiff < 0.0001 and maxOrientDiff < 0.001 and", "fixedOrientation, tablePlane=table) startPositions[obj] = startPose if len(startPositions) == 1: break clearance = checkMinSeparation(startPositions)", "is not true if found and not at_least_one_on_shelf: found = False for obj", "1 else: stable = 0 action['render'] = slow if stable > 19: action['render']", "def generatePosition(env, obj, fixed=False, tablePlane=None): if tablePlane is None: min_x = -.25 max_x", "in range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in", "default value. \"\"\" np.random.seed(seed) allgoals = [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human')", "cubes = sum([goal.mask == 4 for goal in goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c,", "obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found = True break if found: break", "goal_type != '3D' or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects = True break if at_least_two_near_objects:", "images=True): import matplotlib.pyplot as plt challenges = np.unique([goal.challenge for goal in all_goals]) fig,", "in goals]) cubes = sum([goal.mask == 4 for goal in goals]) axes[c, 0].imshow(tomatos,", "fig, axes = plt.subplots(max(2, len(challenges)), 3) for c, challenge in enumerate(challenges): goals =", "for obj in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or goal_type == '2D': at_least_one_on_shelf =", "Images for obj in startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed,", "obj1 in final.fixed_state.keys(): for obj2 in final.fixed_state.keys(): if obj1 == obj2: continue if", "min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2,", "still, t, observation['mask'] class Position: def __init__(self, start_state=None, fixed_state=None, retina=None, mask=None): self.start_state =", "tablePlane: min_x = -.25 max_x = .05 else: min_x = .10 max_x =", "== 'mustard' and z > 0.545 - 0.15: return True return False def", "axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else: # Positions scatter view for i,", "goal.retina_before = initial.retina goal.retina = final.retina goal.mask = final.mask print(\"SUCCESSFULL generation of GOAL", "z = 0.40 else: z = 0.50 if fixed: orientation = basePosition[obj][3:] else:", "for goal in goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray')", "'orange' and z < 0.48 - 0.15: return True if obj == 'tomato'", "== challenge] if len(goals) > 0: if images: # Superimposed images view tomatos", "much specified in min_start_goal_dist for obj in final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found", "0: if images: # Superimposed images view tomatos = sum([goal.mask == 2 for", "_ = runEnv(env) # In these for loops, we could add some progress", "\"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\",", "to generate goals for real_robots\"\"\" import click import numpy as np from real_robots.envs", "break if failed: print(\"Failed to keep objects fixed...\") continue position.start_state = startPositions position.fixed_state", "= slow action = {'joint_command': np.zeros(9), 'render': render} objects = env.robot.used_objects[1:] positions =", "= np.vstack([pos[o] for o in objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr =", "found = True break if found: break # checks if at least one", "help='# of 2D goals (default 25)') @click.option('--n_25d_goals', type=int, default=15, help='# of 2.5D goals", "done, _ = env.step(action) positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) maxPosDiff =", "print(\"Failed minimum separation ({}) after real generation, \" \"draw again everything..\".format(clearance)) continue if", "= generateRealPosition(env, goal.initial_state) objects = [o for o in goal.initial_state] p0 = np.vstack([goal.initial_state[o]", ":3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos, diffPos)", "n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj,", "orientation = (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose = [x, y, z] + np.array(orientation).tolist()", "for numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='# of 2D goals (default 25)') @click.option('--n_25d_goals', type=int,", "if obj in objOnTable: table = objOnTable[obj] startPose = generatePosition(env, obj, fixedOrientation, tablePlane=table)", "= final.retina goal.mask = final.mask print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type)) return goal def", "basePosition _, basePosition, _, _, _ = runEnv(env) # In these for loops,", "slow = False render = False def pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1])", "= sum([goal.mask == 2 for goal in goals]) mustards = sum([goal.mask == 3", "0 for i, obj in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 =", "Goal() goal.challenge = goal_type goal.subtype = str(n_obj) goal.initial_state = initial.fixed_state goal.final_state = final.fixed_state", "20: still = True break pos_dict = {} for obj in objects: pos_dict[obj]", "all_goals if goal.challenge == challenge] if len(goals) > 0: if images: # Superimposed", "goals (default 15)') @click.option('--n_3d_goals', type=int, default=10, help='# of 3D goals (default 10)') @click.option('--n_obj',", "startPose = generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj] = startPose if len(startPositions) == 1:", ".format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if failed: print(\"Failed to keep objects fixed...\")", "env.reset() runEnv(env) # Generate Images for obj in startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3],", "f if failed: print(\"Failed image generation...\") continue clearance = checkMinSeparation(actual_position) if clearance <", "for i, o in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for goal in goals]) axes[c,", "n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals) checkRepeatability(env,", "({}) after real generation, \" \"draw again everything..\".format(clearance)) continue if fixedOrientation: for obj", "= startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed =", "the initial positions it is not true if found and not at_least_one_on_shelf: found", "= np.unique([goal.challenge for goal in all_goals]) fig, axes = plt.subplots(max(2, len(challenges)), 3) for", "found = False break goal = Goal() goal.challenge = goal_type goal.subtype = str(n_obj)", "i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0], positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6,", "on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True,", "in goals: _, pos, failed, _, _ = generateRealPosition(env, goal.initial_state) objects = [o", "o in objects]) p1 = np.vstack([pos[o] for o in objects]) diffPos = np.linalg.norm(p1[:,", "if failed: print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos, maxDiffOr def isOnShelf(obj, state): z =", "state[obj][2] if obj == 'cube' and z < 0.48 - 0.15: return True", "0.55 - 0.15: return True if obj == 'mustard' and z > 0.545", "of 2.5D goals (default 15)') @click.option('--n_3d_goals', type=int, default=10, help='# of 3D goals (default", "objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether at least two objects are close together as", "objOnTable[obj] startPose = generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj] = startPose if len(startPositions) ==", "break print(\"Failed minimum separation ({}), draw again {}..\" .format(clearance, obj)) (a, p, f,", "- 0.15: return True if obj == 'tomato' and z > 0.55 -", "return goal def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as plt challenges = np.unique([goal.challenge for", "final positions of the objects is at least how much specified in min_start_goal_dist", "goal.final_state = final.fixed_state goal.retina_before = initial.retina goal.retina = final.retina goal.mask = final.mask print(\"SUCCESSFULL", "@click.option('--n_3d_goals', type=int, default=10, help='# of 3D goals (default 10)') @click.option('--n_obj', type=int, default=3, help='#", "== 'cube' and z > 0.55 - 0.15: return True if obj ==", "and z > 0.545 - 0.15: return True return False def isOnTable(obj, state):", "enumerate(challenges): goals = [goal for goal in all_goals if goal.challenge == challenge] if", "@click.option('--n_2d_goals', type=int, default=25, help='# of 2D goals (default 25)') @click.option('--n_25d_goals', type=int, default=15, help='#", "25)') @click.option('--n_25d_goals', type=int, default=15, help='# of 2.5D goals (default 15)') @click.option('--n_3d_goals', type=int, default=10,", "type=int, default=15, help='# of 2.5D goals (default 15)') @click.option('--n_3d_goals', type=int, default=10, help='# of", "{} for obj in objects: objOnTable[obj] = True if goal_type == '3D': fixedOrientation", "and z > 0.55 - 0.15: return True if obj == 'orange' and", "{} and orientation by {}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if failed:", "goals (default 25)') @click.option('--n_25d_goals', type=int, default=15, help='# of 2.5D goals (default 15)') @click.option('--n_3d_goals',", "for _ in range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for", "continue if fixedOrientation: for obj in objects: q1 = startPositions[obj][3:] q2 = actual_position[obj][3:]", "and not at_least_one_on_shelf: found = False for obj in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state):", "np.linalg.norm(q1+q2)) # TODO CHECK This - we had to rise it many times", "Position() startPositions = {} for obj in fixedObjects: startPositions[obj] = fixedPositions[obj] for obj", "cmap='gray') else: # Positions scatter view for i, o in enumerate(goals[0].final_state.keys()): positions =", "> np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break goal = Goal() goal.challenge = goal_type goal.subtype", "real_robots.envs import Goal import gym import math basePosition = None slow = False", "= actual_position position.retina = actual_image position.mask = actual_mask return position def checkRepeatability(env, goals):", "if render: env.render('human') env.reset() global basePosition _, basePosition, _, _, _ = runEnv(env)", "q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) #", "if goal_type == '3D': fixedOrientation = False else: fixedOrientation = True found =", "times failed = failed or orientDiff > 0.041 if failed: print(\"{} changed orientation", "for goal in all_goals if goal.challenge == challenge] if len(goals) > 0: if", "fixedPositions=None, minSeparation=0, objOnTable=None): failed = True while failed: # skip 1st object, i.e", "z] + np.array(orientation).tolist() return pose def generateRealPosition(env, startPositions): env.reset() runEnv(env) # Generate Images", "and t > 10: stable += 1 else: stable = 0 action['render'] =", "the initial positions it is not true if not at_least_two_near_objects: found = False", "if isOnShelf(obj, final.fixed_state): found = True break # checks if the distance between", "default=10, help='# of 3D goals (default 10)') @click.option('--n_obj', type=int, default=3, help='# of objects", "obj in objects: objOnTable[obj] = True if goal_type == '3D': fixedOrientation = False", "len(positions) > 1: distances = pairwise_distances(positions) clearance = distances[distances > 0].min() else: clearance", "not at_least_two_near_objects: found = False for obj1 in final.fixed_state.keys(): for obj2 in final.fixed_state.keys():", "= max(maxOrientDiff, orientDiff) if maxPosDiff < 0.0001 and maxOrientDiff < 0.001 and t", "(default 10)') @click.option('--n_obj', type=int, default=3, help='# of objects (default 3)') def main(seed=None, n_2d_goals=25,", "objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment after {} timesteps..\".format(t)) if not still: print(\"Failed", "= False while not(found): found = True final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist)", "for real_robots\"\"\" import click import numpy as np from real_robots.envs import Goal import", "continue for obj in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 = startPositions[obj][3:]", "observation, reward, done, _ = env.step(action) positions = np.vstack([env.get_obj_pose(obj) for obj in objects])", "isOnTable(obj, state): z = state[obj][2] if obj == 'cube' and z < 0.48", "0.50 if fixed: orientation = basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation)", "= min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr =", "if fixedOrientation: for obj in objects: q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff", "= m actual_position = p failed = f if failed: print(\"Failed image generation...\")", "orientation = env._p.getQuaternionFromEuler(orientation) pose = [x, y, z] + np.array(orientation).tolist() return pose def", "least two objects are close together as specified in max_objects_dist. This only if", ":3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos,", "positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed', type=int, help='Generate", "np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def runEnv(env, max_t=1000): reward = 0 done = False", "coding: utf-8 -*- \"\"\"Console script to generate goals for real_robots\"\"\" import click import", "Goal import gym import math basePosition = None slow = False render =", "return True if obj == 'mustard' and z < 0.48 - 0.15: return", "called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are replaced with the supplied options (seed, n_2d_goals,", "rise it many times failed = failed or orientDiff > 0.041 if failed:", "= env._p.getQuaternionFromEuler(orientation) pose = [x, y, z] + np.array(orientation).tolist() return pose def generateRealPosition(env,", "== 1: break clearance = checkMinSeparation(startPositions) if clearance >= minSeparation: break print(\"Failed minimum", "== 'cube' and z < 0.48 - 0.15: return True if obj ==", "def pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def", "initial.fixed_state goal.final_state = final.fixed_state goal.retina_before = initial.retina goal.retina = final.retina goal.mask = final.mask", "and z < 0.48 - 0.15: return True return False def generateGoalREAL2020(env, n_obj,", "max_y = .45 x = np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if x <= 0.05:", "if the distance between initial and final positions of the objects is at", "1: distances = pairwise_distances(positions) clearance = distances[distances > 0].min() else: clearance = np.inf", "True if obj == 'tomato' and z > 0.55 - 0.15: return True", "if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break goal = Goal() goal.challenge =", "are replaced with the supplied options (seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or the", "specified in max_objects_dist. This only if in the initial positions it is not", "final.mask print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot", "maxOrientDiff)) return observation['retina'], pos_dict, not still, t, observation['mask'] class Position: def __init__(self, start_state=None,", "n_obj == 1: at_least_two_near_objects = True else: at_least_two_near_objects = False for obj1 in", "startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) # TODO CHECK", "drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found = True # checks whether at least two", "= fixedPositions[obj] for obj in np.random.permutation(objects): if obj in fixedObjects: continue while True:", "- 0.15: return True if obj == 'mustard' and z < 0.48 -", "if failed: print(\"Failed image generation...\") continue clearance = checkMinSeparation(actual_position) if clearance < minSeparation:", "allgoals += [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_25d_goals): allgoals", "if obj == 'orange' and z > 0.55 - 0.15: return True if", "stable > 19: action['render'] = True if stable > 20: still = True", "0 maxOrientDiff = 0 for i, obj in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] -", "n_3d_goals=10, n_obj=3): \"\"\" Generates the specified number of goals and saves them in", "at_least_one_on_shelf = True break found = False while not(found): found = True final", "for obj in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 = startPositions[obj][3:] q2", "z = 0.50 if fixed: orientation = basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation", "generate goals for real_robots\"\"\" import click import numpy as np from real_robots.envs import", "isOnShelf(obj, initial.fixed_state) or goal_type == '2D': at_least_one_on_shelf = True break found = False", "True if obj == 'tomato' and z < 0.49 - 0.15: return True", "obj == 'cube' and z < 0.48 - 0.15: return True if obj", "final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found = True break # checks if the distance", "two objects are close together as specified in max_objects_dist if n_obj == 1:", "== 'orange' and z > 0.55 - 0.15: return True if obj ==", "not on_shelf: objects = env.robot.used_objects[1:] objOnTable = {} for obj in objects: objOnTable[obj]", "basePosition, _, _, _ = runEnv(env) # In these for loops, we could", "= failed or posDiff > 0.002 or orientDiff > 0.041 if failed: print(\"{}", "0.6]) plt.show() @click.command() @click.option('--seed', type=int, help='Generate goals using this SEED for numpy.random') @click.option('--n_2d_goals',", "< 0.48 - 0.15: return True return False def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False,", "basePosition = None slow = False render = False def pairwise_distances(a): b =", "draw again {}..\" .format(clearance, obj)) (a, p, f, it, m) = generateRealPosition(env, startPositions)", "startPose if len(startPositions) == 1: break clearance = checkMinSeparation(startPositions) if clearance >= minSeparation:", "import Goal import gym import math basePosition = None slow = False render", "= True found = False while not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist)", "in final.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found =", "0.041 if failed: print(\"{} changed orientation by {}\" .format(obj, orientDiff)) break else: print(\"{}", "is not None: if obj in objOnTable: table = objOnTable[obj] startPose = generatePosition(env,", "return True return False def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating", "one object is on the table. This only if in the initial positions", "def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates the specified number of goals", "one object is on the table at_least_one_on_shelf = False for obj in initial.fixed_state.keys():", "goals]) cubes = sum([goal.mask == 4 for goal in goals]) axes[c, 0].imshow(tomatos, cmap='gray')", "0.15: return True return False def isOnTable(obj, state): z = state[obj][2] if obj", "failed: print(\"Failed to keep orientation...\") continue for obj in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3]", "maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff) if maxPosDiff < 0.0001 and", "> 0.002 or orientDiff > 0.041 if failed: print(\"{} changed pos by {}", "posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 = old_positions[i][3:] q2 = positions[i][3:] orientDiff =", "> 19: action['render'] = True if stable > 20: still = True break", "True break found = False while not(found): found = True final = drawPosition(env,", "x <= 0.05: z = 0.40 else: z = 0.50 if fixed: orientation", "if clearance >= minSeparation: break print(\"Failed minimum separation ({}), draw again {}..\" .format(clearance,", "= np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 = old_positions[i][3:] q2 = positions[i][3:] orientDiff = min(np.linalg.norm(q1", "actual_position[obj][:3]) q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2))", "goal in goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0], positions[:, 1]) axes[c,", "False def isOnTable(obj, state): z = state[obj][2] if obj == 'cube' and z", "goals using this SEED for numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='# of 2D goals", "2D goals (default 25)') @click.option('--n_25d_goals', type=int, default=15, help='# of 2.5D goals (default 15)')", "timesteps..\".format(t)) if not still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict, not", "import click import numpy as np from real_robots.envs import Goal import gym import", "env.reset() global basePosition _, basePosition, _, _, _ = runEnv(env) # In these", "= None slow = False render = False def pairwise_distances(a): b = a.reshape(a.shape[0],", "2.5D goals (default 15)') @click.option('--n_3d_goals', type=int, default=10, help='# of 3D goals (default 10)')", "if at least one object is on the table at_least_one_on_shelf = False for", "isOnShelf(obj, state): z = state[obj][2] if obj == 'cube' and z > 0.55", "action['render'] = True if stable > 20: still = True break pos_dict =", "print(\"{} changed orientation by {}\" .format(obj, orientDiff)) break else: print(\"{} kept orientation.\".format(obj)) if", "position.fixed_state = actual_position position.retina = actual_image position.mask = actual_mask return position def checkRepeatability(env,", "maxOrientDiff = 0 for i, obj in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3])", "if at_least_two_near_objects: break # checks if at least one object is on the", "10)') @click.option('--n_obj', type=int, default=3, help='# of objects (default 3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15,", "orientDiff > 0.041 if failed: print(\"{} changed orientation by {}\" .format(obj, orientDiff)) break", "clearance = distances[distances > 0].min() else: clearance = np.inf return clearance def drawPosition(env,", "pos_dict = {} for obj in objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment after", "2].imshow(cubes, cmap='gray') else: # Positions scatter view for i, o in enumerate(goals[0].final_state.keys()): positions", "= np.vstack([env.get_obj_pose(obj) for obj in objects]) maxPosDiff = 0 maxOrientDiff = 0 for", "= checkMinSeparation(startPositions) if clearance >= minSeparation: break print(\"Failed minimum separation ({}), draw again", "distances = pairwise_distances(positions) clearance = distances[distances > 0].min() else: clearance = np.inf return", "for c, challenge in enumerate(challenges): goals = [goal for goal in all_goals if", "len(goals) > 0: if images: # Superimposed images view tomatos = sum([goal.mask ==", "a actual_mask = m actual_position = p failed = f if failed: print(\"Failed", "pose = [x, y, z] + np.array(orientation).tolist() return pose def generateRealPosition(env, startPositions): env.reset()", "state]) if len(positions) > 1: distances = pairwise_distances(positions) clearance = distances[distances > 0].min()", "{}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if failed: print(\"Failed to keep objects", "as specified in max_objects_dist if n_obj == 1: at_least_two_near_objects = True else: at_least_two_near_objects", "= max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed:", "render: env.render('human') env.reset() global basePosition _, basePosition, _, _, _ = runEnv(env) #", "still = False stable = 0 for t in range(max_t): old_positions = positions", "at_least_one_on_shelf: found = False for obj in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found =", ".format(clearance, obj)) (a, p, f, it, m) = generateRealPosition(env, startPositions) actual_image = a", "some progress bar... for _ in range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False,", "= True else: at_least_two_near_objects = False for obj1 in initial.fixed_state.keys(): for obj2 in", "0], positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed', type=int,", "for obj in startPositions: pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed, it,", "True if obj == 'orange' and z < 0.48 - 0.15: return True", "goal.mask = final.mask print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals, images=True):", "[generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals)", "= False for obj1 in final.fixed_state.keys(): for obj2 in final.fixed_state.keys(): if obj1 ==", "_ = generateRealPosition(env, goal.initial_state) objects = [o for o in goal.initial_state] p0 =", "in objects]) maxPosDiff = 0 maxOrientDiff = 0 for i, obj in enumerate(objects):", "np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff) if maxPosDiff < 0.0001", "axes = plt.subplots(max(2, len(challenges)), 3) for c, challenge in enumerate(challenges): goals = [goal", "images view tomatos = sum([goal.mask == 2 for goal in goals]) mustards =", "= [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset() global basePosition _, basePosition,", "if not still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict, not still,", "goal.challenge == challenge] if len(goals) > 0: if images: # Superimposed images view", "if obj1 == obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type != '3D'", "'tomato' and z > 0.55 - 0.15: return True if obj == 'mustard'", "maxPosDiff < 0.0001 and maxOrientDiff < 0.001 and t > 10: stable +=", "len(challenges)), 3) for c, challenge in enumerate(challenges): goals = [goal for goal in", "print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos, maxDiffOr def", "visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as plt challenges = np.unique([goal.challenge for goal in all_goals])", "between initial and final positions of the objects is at least how much", "3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated", "break if at_least_two_near_objects: break # checks if at least one object is on", "pos by {} and orientation by {}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break", "if fixed: orientation = basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose", "saves them in a file.\\n The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets", "global basePosition _, basePosition, _, _, _ = runEnv(env) # In these for", "max_objects_dist: found = True break if found: break # checks if at least", "max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos,", "= min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed = failed or posDiff > 0.002 or", "(default 3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates the specified number", "# In these for loops, we could add some progress bar... for _", "> 0.55 - 0.15: return True if obj == 'mustard' and z >", "fixedPositions[obj] for obj in np.random.permutation(objects): if obj in fixedObjects: continue while True: table", "found = True final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether at", "return maxDiffPos, maxDiffOr def isOnShelf(obj, state): z = state[obj][2] if obj == 'cube'", "together as specified in max_objects_dist if n_obj == 1: at_least_two_near_objects = True else:", "if len(positions) > 1: distances = pairwise_distances(positions) clearance = distances[distances > 0].min() else:", "n_25d_goals, n_3d_goals, n_obj) or the default value. \"\"\" np.random.seed(seed) allgoals = [] env", "objOnTable is not None: if obj in objOnTable: table = objOnTable[obj] startPose =", "if clearance < minSeparation: failed = True print(\"Failed minimum separation ({}) after real", "found and not at_least_one_on_shelf: found = False for obj in final.fixed_state.keys(): if isOnShelf(obj,", "if failed: print(\"{} changed pos by {} and orientation by {}\" .format(obj, posDiff,", "= False stable = 0 for t in range(max_t): old_positions = positions observation,", "= generateRealPosition(env, startPositions) actual_image = a actual_mask = m actual_position = p failed", "= actual_mask return position def checkRepeatability(env, goals): maxDiffPos = 0 maxDiffOr = 0", "by {} and orientation by {}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if", "maxOrientDiff < 0.001 and t > 10: stable += 1 else: stable =", "= min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) # TODO CHECK This - we had to", "(default 25)') @click.option('--n_25d_goals', type=int, default=15, help='# of 2.5D goals (default 15)') @click.option('--n_3d_goals', type=int,", "= 0.40 else: z = 0.50 if fixed: orientation = basePosition[obj][3:] else: orientation", "self.retina = retina self.mask = mask def generatePosition(env, obj, fixed=False, tablePlane=None): if tablePlane", "in enumerate(challenges): goals = [goal for goal in all_goals if goal.challenge == challenge]", "fixedOrientation = False else: fixedOrientation = True found = False while not(found): initial", "kept orientation.\".format(obj)) if failed: print(\"Failed to keep orientation...\") continue for obj in fixedObjects:", "brackets are replaced with the supplied options (seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or", "actual_image, actual_position, failed, it, mask def checkMinSeparation(state): positions = np.vstack([state[obj][:3] for obj in", "maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\") return 1000000", "{} timesteps..\".format(t)) if not still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict,", "in min_start_goal_dist for obj in final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False", "n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates the specified number of goals and saves them", "= drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found = True # checks whether at least", "orientation by {}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if failed: print(\"Failed to", "ijk->ij', a-b, a-b)) def runEnv(env, max_t=1000): reward = 0 done = False render", "0.40 else: z = 0.50 if fixed: orientation = basePosition[obj][3:] else: orientation =", "return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def runEnv(env, max_t=1000): reward = 0 done =", "these for loops, we could add some progress bar... for _ in range(n_2d_goals):", "np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break goal = Goal() goal.challenge = goal_type goal.subtype =", "= objOnTable[obj] startPose = generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj] = startPose if len(startPositions)", "actual_mask return position def checkRepeatability(env, goals): maxDiffPos = 0 maxDiffOr = 0 for", "enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3] - positions[i][:3]) q1 = old_positions[i][3:] q2 = positions[i][3:] orientDiff", "it many times failed = failed or orientDiff > 0.041 if failed: print(\"{}", "y, z] + np.array(orientation).tolist() return pose def generateRealPosition(env, startPositions): env.reset() runEnv(env) # Generate", "= 0 done = False render = slow action = {'joint_command': np.zeros(9), 'render':", "obj in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or goal_type == '2D': at_least_one_on_shelf = True", "0.15: return True if obj == 'orange' and z > 0.55 - 0.15:", "runEnv(env) # In these for loops, we could add some progress bar... for", "\"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict, not still, t, observation['mask'] class Position: def __init__(self,", "initial and final positions of the objects is at least how much specified", "min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable = None if not on_shelf: objects =", "i, o in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for goal in goals]) axes[c, i].set_title(\"{}", "in fixedObjects: continue while True: table = None if objOnTable is not None:", "TODO CHECK This - we had to rise it many times failed =", "print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return observation['retina'], pos_dict, not still, t, observation['mask'] class", "p0 = np.vstack([goal.initial_state[o] for o in objects]) p1 = np.vstack([pos[o] for o in", "fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether at least two objects are close together", "= max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\") return 1000000 return", "in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o] for goal in goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge))", "pos = startPositions[obj] env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed, it, mask = runEnv(env) return", "in np.random.permutation(objects): if obj in fixedObjects: continue while True: table = None if", "file.\\n The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are replaced with the", "@click.option('--n_25d_goals', type=int, default=15, help='# of 2.5D goals (default 15)') @click.option('--n_3d_goals', type=int, default=10, help='#", "checkMinSeparation(startPositions) if clearance >= minSeparation: break print(\"Failed minimum separation ({}), draw again {}..\"", "plt.show() @click.command() @click.option('--seed', type=int, help='Generate goals using this SEED for numpy.random') @click.option('--n_2d_goals', type=int,", "1000000 return maxDiffPos, maxDiffOr def isOnShelf(obj, state): z = state[obj][2] if obj ==", "-.25 max_x = .05 else: min_x = .10 max_x = .25 min_y =", "obj in objects]) maxPosDiff = 0 maxOrientDiff = 0 for i, obj in", "goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are replaced with the supplied options (seed, n_2d_goals, n_25d_goals,", "np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if x <= 0.05: z = 0.40 else: z", "objects fixed...\") continue position.start_state = startPositions position.fixed_state = actual_position position.retina = actual_image position.mask", "minSeparation=min_objects_dist) found = True # checks whether at least two objects are close", "return 1000000 return maxDiffPos, maxDiffOr def isOnShelf(obj, state): z = state[obj][2] if obj", "as specified in max_objects_dist. This only if in the initial positions it is", "'tomato' and z < 0.49 - 0.15: return True if obj == 'mustard'", "= pairwise_distances(positions) clearance = distances[distances > 0].min() else: clearance = np.inf return clearance", "in objects: objOnTable[obj] = True if goal_type == '3D': fixedOrientation = False else:", "objects = env.robot.used_objects[1:] position = Position() startPositions = {} for obj in fixedObjects:", "it, mask def checkMinSeparation(state): positions = np.vstack([state[obj][:3] for obj in state]) if len(positions)", "max_t=1000): reward = 0 done = False render = slow action = {'joint_command':", "= np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos", "add some progress bar... for _ in range(n_2d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2D\",", ".25 elif tablePlane: min_x = -.25 max_x = .05 else: min_x = .10", "max_objects_dist or goal_type != '3D' or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects = True break", "19: action['render'] = True if stable > 20: still = True break pos_dict", "maxDiffOr def isOnShelf(obj, state): z = state[obj][2] if obj == 'cube' and z", "fixed...\") continue position.start_state = startPositions position.fixed_state = actual_position position.retina = actual_image position.mask =", "for goal in goals]) mustards = sum([goal.mask == 3 for goal in goals])", "changed pos by {} and orientation by {}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj])", "= sum([goal.mask == 4 for goal in goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards,", "and z < 0.48 - 0.15: return True if obj == 'orange' and", "actual_position = p failed = f if failed: print(\"Failed image generation...\") continue clearance", "in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 = startPositions[obj][3:] q2 = actual_position[obj][3:]", "real_robots\"\"\" import click import numpy as np from real_robots.envs import Goal import gym", "self.start_state = start_state self.fixed_state = fixed_state self.retina = retina self.mask = mask def", "== 'mustard' and z < 0.48 - 0.15: return True return False def", "clearance = checkMinSeparation(startPositions) if clearance >= minSeparation: break print(\"Failed minimum separation ({}), draw", "minimum separation ({}) after real generation, \" \"draw again everything..\".format(clearance)) continue if fixedOrientation:", "where enclosed brackets are replaced with the supplied options (seed, n_2d_goals, n_25d_goals, n_3d_goals,", "failed: print(\"Failed image generation...\") continue clearance = checkMinSeparation(actual_position) if clearance < minSeparation: failed", "if obj == 'tomato' and z > 0.55 - 0.15: return True if", "obj1 == obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type != '3D' or", "len(initial.fixed_state.keys()) == 1: at_least_two_near_objects = True break if at_least_two_near_objects: break # checks if", "= .25 min_y = -.45 max_y = .45 x = np.random.rand()*(max_x-min_x)+min_x y =", "1st object, i.e the table objects = env.robot.used_objects[1:] position = Position() startPositions =", "checks if the distance between initial and final positions of the objects is", "'3D' or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects = True break if at_least_two_near_objects: break #", "positions[i][:3]) q1 = old_positions[i][3:] q2 = positions[i][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2))", "= 0 maxDiffOr = 0 for goal in goals: _, pos, failed, _,", "mustards = sum([goal.mask == 3 for goal in goals]) cubes = sum([goal.mask ==", "else: # Positions scatter view for i, o in enumerate(goals[0].final_state.keys()): positions = np.vstack([goal.final_state[o]", "o in goal.initial_state] p0 = np.vstack([goal.initial_state[o] for o in objects]) p1 = np.vstack([pos[o]", "the objects is at least how much specified in min_start_goal_dist for obj in", "all_goals]) fig, axes = plt.subplots(max(2, len(challenges)), 3) for c, challenge in enumerate(challenges): goals", "obj == 'cube' and z > 0.55 - 0.15: return True if obj", "checks whether at least two objects are close together as specified in max_objects_dist.", "clearance = checkMinSeparation(actual_position) if clearance < minSeparation: failed = True print(\"Failed minimum separation", "= True final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks whether at least", "for obj in np.random.permutation(objects): if obj in fixedObjects: continue while True: table =", "and z < 0.49 - 0.15: return True if obj == 'mustard' and", "= env.robot.used_objects[1:] objOnTable = {} for obj in objects: objOnTable[obj] = True if", "initial.fixed_state) or goal_type == '2D': at_least_one_on_shelf = True break found = False while", "failed = failed or orientDiff > 0.041 if failed: print(\"{} changed orientation by", "min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed = failed or posDiff > 0.002 or orientDiff", "+= [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj),", "i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show() @click.command() @click.option('--seed', type=int, help='Generate goals using this", "true if found and not at_least_one_on_shelf: found = False for obj in final.fixed_state.keys():", "'2D': at_least_one_on_shelf = True break found = False while not(found): found = True", "= sum([goal.mask == 3 for goal in goals]) cubes = sum([goal.mask == 4", "while not(found): found = True final = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) # checks", "initial positions it is not true if found and not at_least_one_on_shelf: found =", "goals): maxDiffPos = 0 maxDiffOr = 0 for goal in goals: _, pos,", "of objects (default 3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates the", "startPositions): env.reset() runEnv(env) # Generate Images for obj in startPositions: pos = startPositions[obj]", "in initial.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type", "table = None if objOnTable is not None: if obj in objOnTable: table", "p, f, it, m) = generateRealPosition(env, startPositions) actual_image = a actual_mask = m", "maxPosDiff = 0 maxOrientDiff = 0 for i, obj in enumerate(objects): posDiff =", "'3D': fixedOrientation = False else: fixedOrientation = True found = False while not(found):", "fixed_state self.retina = retina self.mask = mask def generatePosition(env, obj, fixed=False, tablePlane=None): if", "= slow if stable > 19: action['render'] = True if stable > 20:", "-*- coding: utf-8 -*- \"\"\"Console script to generate goals for real_robots\"\"\" import click", "help='Generate goals using this SEED for numpy.random') @click.option('--n_2d_goals', type=int, default=25, help='# of 2D", "max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\")", "stable += 1 else: stable = 0 action['render'] = slow if stable >", "= True break found = False while not(found): found = True final =", "challenge in enumerate(challenges): goals = [goal for goal in all_goals if goal.challenge ==", "are close together as specified in max_objects_dist if n_obj == 1: at_least_two_near_objects =", "np.vstack([env.get_obj_pose(obj) for obj in objects]) maxPosDiff = 0 maxOrientDiff = 0 for i,", "3D goals (default 10)') @click.option('--n_obj', type=int, default=3, help='# of objects (default 3)') def", "the table at_least_one_on_shelf = False for obj in initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or", "print(\"SUCCESSFULL generation of GOAL {}!\".format(goal_type)) return goal def visualizeGoalDistribution(all_goals, images=True): import matplotlib.pyplot as", "[generateGoalREAL2020(env, n_obj, \"2D\", on_shelf=False, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_25d_goals): allgoals += [generateGoalREAL2020(env,", "true if not at_least_two_near_objects: found = False for obj1 in final.fixed_state.keys(): for obj2", "The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed brackets are replaced with the supplied", "min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable = None if not on_shelf: objects = env.robot.used_objects[1:]", "q1 = old_positions[i][3:] q2 = positions[i][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff", "env.step(action) positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) maxPosDiff = 0 maxOrientDiff =", ">= minSeparation: break print(\"Failed minimum separation ({}), draw again {}..\" .format(clearance, obj)) (a,", "np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals) checkRepeatability(env, allgoals) visualizeGoalDistribution(allgoals) if __name__ ==", "goal_type == '3D': fixedOrientation = False else: fixedOrientation = True found = False", "allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_3d_goals): allgoals", "help='# of objects (default 3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates", "= .45 x = np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if x <= 0.05: z", "min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff) if", "True while failed: # skip 1st object, i.e the table objects = env.robot.used_objects[1:]", "if not on_shelf: objects = env.robot.used_objects[1:] objOnTable = {} for obj in objects:", "m) = generateRealPosition(env, startPositions) actual_image = a actual_mask = m actual_position = p", "checkMinSeparation(actual_position) if clearance < minSeparation: failed = True print(\"Failed minimum separation ({}) after", "are close together as specified in max_objects_dist. This only if in the initial", "allgoals = [] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset() global basePosition _,", "== 4 for goal in goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c,", "everything..\".format(clearance)) continue if fixedOrientation: for obj in objects: q1 = startPositions[obj][3:] q2 =", "startPositions position.fixed_state = actual_position position.retina = actual_image position.mask = actual_mask return position def", "fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed = True while failed: # skip 1st object,", "for obj in final.fixed_state.keys(): if min_start_goal_dist > np.linalg.norm(final.fixed_state[obj][:2]-initial.fixed_state[obj][:2]): found = False break goal", "== 'tomato' and z > 0.55 - 0.15: return True if obj ==", "the supplied options (seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or the default value. \"\"\"", "True if obj == 'mustard' and z < 0.48 - 0.15: return True", "if n_obj == 1: at_least_two_near_objects = True else: at_least_two_near_objects = False for obj1", "< minSeparation: failed = True print(\"Failed minimum separation ({}) after real generation, \"", "goal in all_goals if goal.challenge == challenge] if len(goals) > 0: if images:", "if goal.challenge == challenge] if len(goals) > 0: if images: # Superimposed images", "= 0 for goal in goals: _, pos, failed, _, _ = generateRealPosition(env,", "True break pos_dict = {} for obj in objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting", "checkMinSeparation(state): positions = np.vstack([state[obj][:3] for obj in state]) if len(positions) > 1: distances", "== obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type != '3D' or len(initial.fixed_state.keys())", "-.45 max_y = .45 x = np.random.rand()*(max_x-min_x)+min_x y = np.random.rand()*(max_y-min_y)+min_y if x <=", "range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals,", "if obj == 'mustard' and z < 0.48 - 0.15: return True return", "of goals and saves them in a file.\\n The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz", "== 3 for goal in goals]) cubes = sum([goal.mask == 4 for goal", "posDiff) maxOrientDiff = max(maxOrientDiff, orientDiff) if maxPosDiff < 0.0001 and maxOrientDiff < 0.001", "np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <= max_objects_dist or goal_type != '3D' or len(initial.fixed_state.keys()) == 1: at_least_two_near_objects =", "= failed or orientDiff > 0.041 if failed: print(\"{} changed orientation by {}\"", "else: clearance = np.inf return clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None):", "False render = slow action = {'joint_command': np.zeros(9), 'render': render} objects = env.robot.used_objects[1:]", "plt.subplots(max(2, len(challenges)), 3) for c, challenge in enumerate(challenges): goals = [goal for goal", "obj in objects]) still = False stable = 0 for t in range(max_t):", "env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) still = False stable =", "initial positions it is not true if not at_least_two_near_objects: found = False for", "positions = np.vstack([goal.final_state[o] for goal in goals]) axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:,", "in the initial positions it is not true if not at_least_two_near_objects: found =", "= np.vstack([env.get_obj_pose(obj) for obj in objects]) still = False stable = 0 for", "False def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable =", "min_objects_dist=0.25)] for _ in range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0)]", "\"\"\" Generates the specified number of goals and saves them in a file.\\n", "obj == 'orange' and z > 0.55 - 0.15: return True if obj", "min_x = -.25 max_x = .25 elif tablePlane: min_x = -.25 max_x =", "failed or orientDiff > 0.041 if failed: print(\"{} changed orientation by {}\" .format(obj,", "'cube' and z < 0.48 - 0.15: return True if obj == 'orange'", "if in the initial positions it is not true if not at_least_two_near_objects: found", "objects = env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) still = False", "np.inf return clearance def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed = True", "from real_robots.envs import Goal import gym import math basePosition = None slow =", "and orientation by {}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if failed: print(\"Failed", "failed = f if failed: print(\"Failed image generation...\") continue clearance = checkMinSeparation(actual_position) if", "0.041 if failed: print(\"{} changed pos by {} and orientation by {}\" .format(obj,", "<= 0.05: z = 0.40 else: z = 0.50 if fixed: orientation =", "= {'joint_command': np.zeros(9), 'render': render} objects = env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for obj", "def drawPosition(env, fixedOrientation=False, fixedObjects=[], fixedPositions=None, minSeparation=0, objOnTable=None): failed = True while failed: #", "return True if obj == 'orange' and z < 0.48 - 0.15: return", "script to generate goals for real_robots\"\"\" import click import numpy as np from", "15)') @click.option('--n_3d_goals', type=int, default=10, help='# of 3D goals (default 10)') @click.option('--n_obj', type=int, default=3,", "3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates the specified number of", "min_start_goal_dist=0.2, min_objects_dist=0)] np.savez_compressed('goals-REAL2020-s{}-{}-{}-{}-{}.npy' .format(seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj), allgoals) checkRepeatability(env, allgoals) visualizeGoalDistribution(allgoals) if", "3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos = max(maxDiffPos, diffPos) maxDiffOr = max(maxDiffPos, diffOr)", "diffPos) maxDiffOr = max(maxDiffPos, diffOr) print(\"Replicated diffPos:{} diffOr:{}\".format(diffPos, diffOr)) if failed: print(\"*****************FAILED************!!!!\") return", "= startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) # TODO", "challenge)) axes[c, i].hist2d(positions[:, 0], positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c, i].set_ylim([-0.6, 0.6]) plt.show()", "False else: fixedOrientation = True found = False while not(found): initial = drawPosition(env,", "fixed: orientation = basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose =", "[] env = gym.make('REALRobot2020-R1J{}-v0'.format(n_obj)) if render: env.render('human') env.reset() global basePosition _, basePosition, _,", "not None: if obj in objOnTable: table = objOnTable[obj] startPose = generatePosition(env, obj,", "- q2), np.linalg.norm(q1+q2)) failed = failed or posDiff > 0.002 or orientDiff >", "- actual_position[obj][:3]) q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2),", "== '2D': at_least_one_on_shelf = True break found = False while not(found): found =", "distance between initial and final positions of the objects is at least how", "a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def runEnv(env, max_t=1000): reward = 0 done", "import matplotlib.pyplot as plt challenges = np.unique([goal.challenge for goal in all_goals]) fig, axes", "obj in fixedObjects: posDiff = np.linalg.norm(startPositions[obj][:3] - actual_position[obj][:3]) q1 = startPositions[obj][3:] q2 =", "env.robot.object_bodies[obj].reset_pose(pos[:3], pos[3:]) actual_image, actual_position, failed, it, mask = runEnv(env) return actual_image, actual_position, failed,", "= env.robot.used_objects[1:] positions = np.vstack([env.get_obj_pose(obj) for obj in objects]) still = False stable", "return pose def generateRealPosition(env, startPositions): env.reset() runEnv(env) # Generate Images for obj in", "min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True, min_start_goal_dist=0.2,", "print(\"Failed minimum separation ({}), draw again {}..\" .format(clearance, obj)) (a, p, f, it,", "0.15: return True if obj == 'orange' and z < 0.48 - 0.15:", "by {}\" .format(obj, posDiff, orientDiff)) print(startPositions[obj]) print(actual_position[obj]) break if failed: print(\"Failed to keep", "> 0.041 if failed: print(\"{} changed orientation by {}\" .format(obj, orientDiff)) break else:", "goal_type goal.subtype = str(n_obj) goal.initial_state = initial.fixed_state goal.final_state = final.fixed_state goal.retina_before = initial.retina", "if stable > 19: action['render'] = True if stable > 20: still =", "pose def generateRealPosition(env, startPositions): env.reset() runEnv(env) # Generate Images for obj in startPositions:", "class Position: def __init__(self, start_state=None, fixed_state=None, retina=None, mask=None): self.start_state = start_state self.fixed_state =", "is not true if not at_least_two_near_objects: found = False for obj1 in final.fixed_state.keys():", "orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) maxPosDiff = max(maxPosDiff, posDiff) maxOrientDiff = max(maxOrientDiff,", "and z < 0.48 - 0.15: return True if obj == 'tomato' and", "= None if not on_shelf: objects = env.robot.used_objects[1:] objOnTable = {} for obj", "- q2), np.linalg.norm(q1+q2)) # TODO CHECK This - we had to rise it", "retina self.mask = mask def generatePosition(env, obj, fixed=False, tablePlane=None): if tablePlane is None:", "is at least how much specified in min_start_goal_dist for obj in final.fixed_state.keys(): if", "_ in range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _", "a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b)) def runEnv(env, max_t=1000): reward =", "observation['mask'] class Position: def __init__(self, start_state=None, fixed_state=None, retina=None, mask=None): self.start_state = start_state self.fixed_state", "= mask def generatePosition(env, obj, fixed=False, tablePlane=None): if tablePlane is None: min_x =", "np.unique([goal.challenge for goal in all_goals]) fig, axes = plt.subplots(max(2, len(challenges)), 3) for c,", "== 1: at_least_two_near_objects = True break if at_least_two_near_objects: break # checks if at", "CHECK This - we had to rise it many times failed = failed", "retina=None, mask=None): self.start_state = start_state self.fixed_state = fixed_state self.retina = retina self.mask =", "\" \"draw again everything..\".format(clearance)) continue if fixedOrientation: for obj in objects: q1 =", "failed = failed or posDiff > 0.002 or orientDiff > 0.041 if failed:", "= retina self.mask = mask def generatePosition(env, obj, fixed=False, tablePlane=None): if tablePlane is", "least how much specified in min_start_goal_dist for obj in final.fixed_state.keys(): if min_start_goal_dist >", "on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)] for _ in range(n_3d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"3D\", on_shelf=True,", "axes[c, i].set_title(\"{} {}\".format(o, challenge)) axes[c, i].hist2d(positions[:, 0], positions[:, 1]) axes[c, i].set_xlim([-0.3, 0.3]) axes[c,", "object, i.e the table objects = env.robot.used_objects[1:] position = Position() startPositions = {}", "orientation.\".format(obj)) if failed: print(\"Failed to keep orientation...\") continue for obj in fixedObjects: posDiff", "challenges = np.unique([goal.challenge for goal in all_goals]) fig, axes = plt.subplots(max(2, len(challenges)), 3)", "generateRealPosition(env, startPositions): env.reset() runEnv(env) # Generate Images for obj in startPositions: pos =", "in objOnTable: table = objOnTable[obj] startPose = generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj] =", "True if stable > 20: still = True break pos_dict = {} for", "initial.fixed_state.keys(): if isOnShelf(obj, initial.fixed_state) or goal_type == '2D': at_least_one_on_shelf = True break found", "generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj] = startPose if len(startPositions) == 1: break clearance", "0.55 - 0.15: return True if obj == 'orange' and z > 0.55", "objects (default 3)') def main(seed=None, n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates the specified", "= 0 maxOrientDiff = 0 for i, obj in enumerate(objects): posDiff = np.linalg.norm(old_positions[i][:3]", "= False else: fixedOrientation = True found = False while not(found): initial =", "= runEnv(env) # In these for loops, we could add some progress bar...", "np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:, 3:])) maxDiffPos =", "generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable = None if", "options (seed, n_2d_goals, n_25d_goals, n_3d_goals, n_obj) or the default value. \"\"\" np.random.seed(seed) allgoals", "gym import math basePosition = None slow = False render = False def", "for obj in objects: pos_dict[obj] = env.get_obj_pose(obj) print(\"Exiting environment after {} timesteps..\".format(t)) if", "0.002 or orientDiff > 0.041 if failed: print(\"{} changed pos by {} and", "found = True # checks whether at least two objects are close together", "in all_goals]) fig, axes = plt.subplots(max(2, len(challenges)), 3) for c, challenge in enumerate(challenges):", "images: # Superimposed images view tomatos = sum([goal.mask == 2 for goal in", "or goal_type == '2D': at_least_one_on_shelf = True break found = False while not(found):", "n_2d_goals=25, n_25d_goals=15, n_3d_goals=10, n_obj=3): \"\"\" Generates the specified number of goals and saves", "obj in state]) if len(positions) > 1: distances = pairwise_distances(positions) clearance = distances[distances", "basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose = [x, y, z]", "in goals]) axes[c, 0].imshow(tomatos, cmap='gray') axes[c, 1].imshow(mustards, cmap='gray') axes[c, 2].imshow(cubes, cmap='gray') else: #", "> 1: distances = pairwise_distances(positions) clearance = distances[distances > 0].min() else: clearance =", "= final.fixed_state goal.retina_before = initial.retina goal.retina = final.retina goal.mask = final.mask print(\"SUCCESSFULL generation", "def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\") objOnTable = None", "only if in the initial positions it is not true if not at_least_two_near_objects:", "slow if stable > 19: action['render'] = True if stable > 20: still", "-*- \"\"\"Console script to generate goals for real_robots\"\"\" import click import numpy as", "= basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist() orientation = env._p.getQuaternionFromEuler(orientation) pose = [x, y,", "orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) # TODO CHECK This - we had", "True return False def generateGoalREAL2020(env, n_obj, goal_type, on_shelf=False, min_start_goal_dist=0.1, min_objects_dist=0.05, max_objects_dist=2): print(\"Generating GOAL..\")", "isOnShelf(obj, final.fixed_state): found = True break # checks if the distance between initial", "else: at_least_two_near_objects = False for obj1 in initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys(): if", "i.e the table objects = env.robot.used_objects[1:] position = Position() startPositions = {} for", "break clearance = checkMinSeparation(startPositions) if clearance >= minSeparation: break print(\"Failed minimum separation ({}),", "environment after {} timesteps..\".format(t)) if not still: print(\"Failed because maxPosDiff:{:.6f},\" \"maxOrientDiff:{:.6f}\".format(maxPosDiff, maxOrientDiff)) return", "continue clearance = checkMinSeparation(actual_position) if clearance < minSeparation: failed = True print(\"Failed minimum", "q1 = startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed", "diffOr)) if failed: print(\"*****************FAILED************!!!!\") return 1000000 return maxDiffPos, maxDiffOr def isOnShelf(obj, state): z", "True # checks whether at least two objects are close together as specified", "False for obj1 in initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys(): if obj1 == obj2:", "mask = runEnv(env) return actual_image, actual_position, failed, it, mask def checkMinSeparation(state): positions =", "objects]) diffPos = np.linalg.norm(p1[:, :3]-p0[:, :3]) diffOr = min(np.linalg.norm(p1[:, 3:]-p0[:, 3:]), np.linalg.norm(p1[:, 3:]+p0[:,", "else: z = 0.50 if fixed: orientation = basePosition[obj][3:] else: orientation = (np.random.rand(3)*math.pi*2).tolist()", "if failed: print(\"Failed to keep orientation...\") continue for obj in fixedObjects: posDiff =", "startPositions[obj] = fixedPositions[obj] for obj in np.random.permutation(objects): if obj in fixedObjects: continue while", "table = objOnTable[obj] startPose = generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj] = startPose if", "least two objects are close together as specified in max_objects_dist if n_obj ==", "at least two objects are close together as specified in max_objects_dist. This only", "= [x, y, z] + np.array(orientation).tolist() return pose def generateRealPosition(env, startPositions): env.reset() runEnv(env)", "and saves them in a file.\\n The file is called goals-REAL2020-s{}-{}-{}-{}-{}.npy.npz where enclosed", "z < 0.48 - 0.15: return True if obj == 'orange' and z", "not true if not at_least_two_near_objects: found = False for obj1 in final.fixed_state.keys(): for", "if np.linalg.norm(final.fixed_state[obj1][:3]-final.fixed_state[obj2][:3]) <= max_objects_dist: found = True break if found: break # checks", "for obj in final.fixed_state.keys(): if isOnShelf(obj, final.fixed_state): found = True break # checks", "startPositions[obj][3:] q2 = actual_position[obj][3:] orientDiff = min(np.linalg.norm(q1 - q2), np.linalg.norm(q1+q2)) failed = failed", "f, it, m) = generateRealPosition(env, startPositions) actual_image = a actual_mask = m actual_position", "objOnTable: table = objOnTable[obj] startPose = generatePosition(env, obj, fixedOrientation, tablePlane=table) startPositions[obj] = startPose", "(a, p, f, it, m) = generateRealPosition(env, startPositions) actual_image = a actual_mask =", "goal in goals]) cubes = sum([goal.mask == 4 for goal in goals]) axes[c,", "failed = True while failed: # skip 1st object, i.e the table objects", "= np.vstack([state[obj][:3] for obj in state]) if len(positions) > 1: distances = pairwise_distances(positions)", "print(\"{} kept orientation.\".format(obj)) if failed: print(\"Failed to keep orientation...\") continue for obj in", "for obj in objects]) still = False stable = 0 for t in", "min_objects_dist=0.25)] for _ in range(n_25d_goals): allgoals += [generateGoalREAL2020(env, n_obj, \"2.5D\", on_shelf=True, min_start_goal_dist=0.2, min_objects_dist=0.25)]", "initial.fixed_state.keys(): for obj2 in initial.fixed_state.keys(): if obj1 == obj2: continue if np.linalg.norm(initial.fixed_state[obj1][:3]-initial.fixed_state[obj2][:3]) <=", "> 0.55 - 0.15: return True if obj == 'orange' and z >", "= state[obj][2] if obj == 'cube' and z > 0.55 - 0.15: return", "= [goal for goal in all_goals if goal.challenge == challenge] if len(goals) >", "mask=None): self.start_state = start_state self.fixed_state = fixed_state self.retina = retina self.mask = mask", "found = False while not(found): initial = drawPosition(env, fixedOrientation=fixedOrientation, objOnTable=objOnTable, minSeparation=min_objects_dist) found =", "at least one object is on the table at_least_one_on_shelf = False for obj", "start_state self.fixed_state = fixed_state self.retina = retina self.mask = mask def generatePosition(env, obj,", "goal in all_goals]) fig, axes = plt.subplots(max(2, len(challenges)), 3) for c, challenge in", "len(startPositions) == 1: break clearance = checkMinSeparation(startPositions) if clearance >= minSeparation: break print(\"Failed" ]
[ "encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to format the", "options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if ret.returncode != 0:", "self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args =", "self.name = name def __str__(self): return self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self):", "2021 Qualcomm Innovation Center, Inc. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from", "used to generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to file\")", "{'object_list': object_list} output += str(Template(file=options.template, searchList=ns)) if options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE)", "not modify.\\n\" output += \"\\n\" ns = {'object_list': object_list} output += str(Template(file=options.template, searchList=ns))", "rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import Template import argparse import", "type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args = argparse.ArgumentParser() mode_args", "# # SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import Template import argparse import subprocess import", "__str__(self): return self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main():", "import sys class Object: def __init__(self, name): self.name = name def __str__(self): return", "object_list = [Object(o) for group in options.input for o in group] output =", "= args.parse_args() object_list = [Object(o) for group in options.input for o in group]", "output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify", "\"--formatter\", help=\"specify clang-format to format the code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List of", "# # © 2021 Qualcomm Innovation Center, Inc. All rights reserved. # #", "help=\"List of objects to process\") options = args.parse_args() object_list = [Object(o) for group", "\"\\n\" ns = {'object_list': object_list} output += str(Template(file=options.template, searchList=ns)) if options.formatter: ret =", "!= 0: raise Exception(\"failed to format output:\\n \", ret.stderr) options.output.write(output) if __name__ ==", "mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used to generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w',", "sys class Object: def __init__(self, name): self.name = name def __str__(self): return self.name", "clang-format to format the code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List of objects to", "args.parse_args() object_list = [Object(o) for group in options.input for o in group] output", "'--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used to generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"),", "\"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args = argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"),", "in group] output = \"// Automatically generated. Do not modify.\\n\" output += \"\\n\"", "generated. Do not modify.\\n\" output += \"\\n\" ns = {'object_list': object_list} output +=", "in options.input for o in group] output = \"// Automatically generated. Do not", "ret.returncode != 0: raise Exception(\"failed to format output:\\n \", ret.stderr) options.output.write(output) if __name__", "raise Exception(\"failed to format output:\\n \", ret.stderr) options.output.write(output) if __name__ == '__main__': main()", "# SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import Template import argparse import subprocess import sys", "= args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used to generate output\") args.add_argument('-o',", "© 2021 Qualcomm Innovation Center, Inc. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause", "return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args = argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r',", "output = ret.stdout.decode(\"utf-8\") if ret.returncode != 0: raise Exception(\"failed to format output:\\n \",", "# © 2021 Qualcomm Innovation Center, Inc. All rights reserved. # # SPDX-License-Identifier:", "import argparse import subprocess import sys class Object: def __init__(self, name): self.name =", "if ret.returncode != 0: raise Exception(\"failed to format output:\\n \", ret.stderr) options.output.write(output) if", "output to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to format the code\") args.add_argument('input', metavar='INPUT',", "encoding=\"utf-8\"), help=\"Template file used to generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write", "reserved. # # SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import Template import argparse import subprocess", "objects to process\") options = args.parse_args() object_list = [Object(o) for group in options.input", "SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import Template import argparse import subprocess import sys class", "args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used to generate output\") args.add_argument('-o', '--output',", "output = \"// Automatically generated. Do not modify.\\n\" output += \"\\n\" ns =", "help=\"Write output to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to format the code\") args.add_argument('input',", "argparse import subprocess import sys class Object: def __init__(self, name): self.name = name", "BSD-3-Clause from Cheetah.Template import Template import argparse import subprocess import sys class Object:", "#!/usr/bin/env python3 # # © 2021 Qualcomm Innovation Center, Inc. All rights reserved.", "ns = {'object_list': object_list} output += str(Template(file=options.template, searchList=ns)) if options.formatter: ret = subprocess.run([options.formatter],", "def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args = argparse.ArgumentParser()", "object_list} output += str(Template(file=options.template, searchList=ns)) if options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output", "rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args = argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template',", "metavar='INPUT', nargs='+', action='append', help=\"List of objects to process\") options = args.parse_args() object_list =", "group in options.input for o in group] output = \"// Automatically generated. Do", "modify.\\n\" output += \"\\n\" ns = {'object_list': object_list} output += str(Template(file=options.template, searchList=ns)) if", "if options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if ret.returncode !=", "All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import Template import argparse", "= [Object(o) for group in options.input for o in group] output = \"//", "= argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used to", "Innovation Center, Inc. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import", "Inc. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import Template import", "of objects to process\") options = args.parse_args() object_list = [Object(o) for group in", "= {'object_list': object_list} output += str(Template(file=options.template, searchList=ns)) if options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"),", "return self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args", "to format the code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List of objects to process\")", "help=\"Template file used to generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output", "to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to format the code\") args.add_argument('input', metavar='INPUT', nargs='+',", "[Object(o) for group in options.input for o in group] output = \"// Automatically", "__init__(self, name): self.name = name def __str__(self): return self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper())", "python3 # # © 2021 Qualcomm Innovation Center, Inc. All rights reserved. #", "'--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to", "import subprocess import sys class Object: def __init__(self, name): self.name = name def", "args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to format the code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List", "def __str__(self): return self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def", "file used to generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to", "Cheetah.Template import Template import argparse import subprocess import sys class Object: def __init__(self,", "action='append', help=\"List of objects to process\") options = args.parse_args() object_list = [Object(o) for", "subprocess import sys class Object: def __init__(self, name): self.name = name def __str__(self):", "+= str(Template(file=options.template, searchList=ns)) if options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\")", "options.input for o in group] output = \"// Automatically generated. Do not modify.\\n\"", "nargs='+', action='append', help=\"List of objects to process\") options = args.parse_args() object_list = [Object(o)", "format the code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List of objects to process\") options", "def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args = argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t',", "ret.stdout.decode(\"utf-8\") if ret.returncode != 0: raise Exception(\"failed to format output:\\n \", ret.stderr) options.output.write(output)", "the code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List of objects to process\") options =", "def __init__(self, name): self.name = name def __str__(self): return self.name def type_enum(self): return", "args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format", "<gh_stars>10-100 #!/usr/bin/env python3 # # © 2021 Qualcomm Innovation Center, Inc. All rights", "main(): args = argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file", "for group in options.input for o in group] output = \"// Automatically generated.", "input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if ret.returncode != 0: raise Exception(\"failed to format", "= ret.stdout.decode(\"utf-8\") if ret.returncode != 0: raise Exception(\"failed to format output:\\n \", ret.stderr)", "str(Template(file=options.template, searchList=ns)) if options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if", "to generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to file\") args.add_argument(\"-f\",", "= \"// Automatically generated. Do not modify.\\n\" output += \"\\n\" ns = {'object_list':", "stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if ret.returncode != 0: raise Exception(\"failed to format output:\\n", "args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List of objects to process\") options = args.parse_args() object_list", "from Cheetah.Template import Template import argparse import subprocess import sys class Object: def", "for o in group] output = \"// Automatically generated. Do not modify.\\n\" output", "Qualcomm Innovation Center, Inc. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template", "Object: def __init__(self, name): self.name = name def __str__(self): return self.name def type_enum(self):", "generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to file\") args.add_argument(\"-f\", \"--formatter\",", "name def __str__(self): return self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper())", "\"// Automatically generated. Do not modify.\\n\" output += \"\\n\" ns = {'object_list': object_list}", "options = args.parse_args() object_list = [Object(o) for group in options.input for o in", "return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args = argparse.ArgumentParser() mode_args =", "0: raise Exception(\"failed to format output:\\n \", ret.stderr) options.output.write(output) if __name__ == '__main__':", "o in group] output = \"// Automatically generated. Do not modify.\\n\" output +=", "Template import argparse import subprocess import sys class Object: def __init__(self, name): self.name", "subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if ret.returncode != 0: raise Exception(\"failed to", "group] output = \"// Automatically generated. Do not modify.\\n\" output += \"\\n\" ns", "+= \"\\n\" ns = {'object_list': object_list} output += str(Template(file=options.template, searchList=ns)) if options.formatter: ret", "Center, Inc. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from Cheetah.Template import Template", "\"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return \"RCU_UPDATE_CLASS_{:s}_DESTROY\".format(self.name.upper()) def main(): args = argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True)", "type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used to generate output\") args.add_argument('-o', '--output', type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout,", "Automatically generated. Do not modify.\\n\" output += \"\\n\" ns = {'object_list': object_list} output", "output += str(Template(file=options.template, searchList=ns)) if options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output =", "code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List of objects to process\") options = args.parse_args()", "output += \"\\n\" ns = {'object_list': object_list} output += str(Template(file=options.template, searchList=ns)) if options.formatter:", "def main(): args = argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template", "= subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if ret.returncode != 0: raise Exception(\"failed", "mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used to generate output\")", "help=\"specify clang-format to format the code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append', help=\"List of objects", "searchList=ns)) if options.formatter: ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if ret.returncode", "class Object: def __init__(self, name): self.name = name def __str__(self): return self.name def", "file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to format the code\") args.add_argument('input', metavar='INPUT', nargs='+', action='append',", "process\") options = args.parse_args() object_list = [Object(o) for group in options.input for o", "Do not modify.\\n\" output += \"\\n\" ns = {'object_list': object_list} output += str(Template(file=options.template,", "to process\") options = args.parse_args() object_list = [Object(o) for group in options.input for", "import Template import argparse import subprocess import sys class Object: def __init__(self, name):", "ret = subprocess.run([options.formatter], input=output.encode(\"utf-8\"), stdout=subprocess.PIPE) output = ret.stdout.decode(\"utf-8\") if ret.returncode != 0: raise", "argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used to generate", "default=sys.stdout, help=\"Write output to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to format the code\")", "args = argparse.ArgumentParser() mode_args = args.add_mutually_exclusive_group(required=True) mode_args.add_argument('-t', '--template', type=argparse.FileType('r', encoding=\"utf-8\"), help=\"Template file used", "type=argparse.FileType('w', encoding=\"utf-8\"), default=sys.stdout, help=\"Write output to file\") args.add_argument(\"-f\", \"--formatter\", help=\"specify clang-format to format", "= name def __str__(self): return self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def rcu_destroy_enum(self): return", "name): self.name = name def __str__(self): return self.name def type_enum(self): return \"OBJECT_TYPE_{:s}\".format(self.name.upper()) def" ]
[ "hàm canvas_merge_union là canvas_compose truyền vào tham số đầu tiên, Mặc định là", "print(path,\"\\n\") opts.bg = svg_color(\"white\") if opts.bg is None else opts.bg opts.fg = svg_color(\"black\")", "Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is not None: output = output.background(opts.bg)", "parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB", "np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\", help=\"output", "closefd=closefd) as file: output.write_png(file) #path.fill trả về vùng ảnh, offset của ảnh lớn.", "output = Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is not None: output", "parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG files containing all fonts\") opts = parser.parse_args() if", "size is not None: w, h = size result = scene.render( transform, viewport=[0,", "opts.bg is not None: output = output.background(opts.bg) filename = opts.output if opts.output !=", "if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not exsits: {opts.svg}\\n\") sys.exit(1) fonts = FontsDB()", "file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground color\")", "numpy as np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG", "file does not exsits: {opts.svg}\\n\") sys.exit(1) fonts = FontsDB() for font in opts.fonts", "RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG files containing all fonts\") opts", "nhất. # canvas_compose cho biết cách mà blend tam giác vào ảnh. #", "ngoài tam giác là 0 # còn các cạnh của tam giác sẽ", "parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render", "parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set", "if opts.bg is None else opts.bg opts.fg = svg_color(\"black\") if opts.fg is None", "os import argparse from svgrasterize import * import numpy as np np.set_printoptions(formatter={'float': lambda", "parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default background", "= output.background(opts.bg) filename = opts.output if opts.output != \"-\" else 1 closefd =", "{}, None else: scene, ids, size = svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts )", "foreground color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render single element with specified", "trả về vùng ảnh và offset, trả về ảnh lớn nhất. # canvas_compose", "ảnh lớn. #hàm gộp là Layer.compose trả về vùng ảnh và offset, trả", "scene.render( transform, viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb ) else: result = scene.render(transform, linear_rgb=opts.linear_rgb)", "open(filename, \"wb\", closefd=closefd) as file: output.write_png(file) #path.fill trả về vùng ảnh, offset của", "0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is not None: output = output.background(opts.bg) filename =", "None: w, h = size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w),", "argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default", "lambda x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\", help=\"output PNG", "sys.stderr.write(f\"[error] file does not exsits: {opts.svg}\\n\") sys.exit(1) fonts = FontsDB() for font in", "not exsits: {opts.svg}\\n\") sys.exit(1) fonts = FontsDB() for font in opts.fonts or [DEFAULT_FONTS]:", "int(w), 4), dtype=FLOAT) image = canvas_merge_at(base, output.image, output.offset) output = Layer(image, (0, 0),", "in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0, 1, 0, 1, 0, 0)", "còn các cạnh của tam giác sẽ được là có giá trị trong", "0, 0) if opts.transform: transform @= opts.transform if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\")", "= time.time() if size is not None: w, h = size result =", "with open(filename, \"wb\", closefd=closefd) as file: output.write_png(file) #path.fill trả về vùng ảnh, offset", "= Scene.fill(path, opts.fg) ids, size = {}, None else: scene, ids, size =", "opts.id is not None: size = None scene = ids.get(opts.id) if scene is", "tiên, Mặc định là COMPOSE_OVER # Path.mask trả về mass của tam giác.", "= svg_color(\"white\") if opts.bg is None else opts.bg opts.fg = svg_color(\"black\") if opts.fg", "containing all fonts\") opts = parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not", "not None: output = output.background(opts.bg) filename = opts.output if opts.output != \"-\" else", "width\") parser.add_argument(\"-id\", help=\"render single element with specified `id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply", "fonts\") opts = parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not exsits: {opts.svg}\\n\")", "Mặc định là COMPOSE_OVER # Path.mask trả về mass của tam giác. bên", "None else opts.fg scene = Scene.fill(path, opts.fg) ids, size = {}, None else:", "SVG files containing all fonts\") opts = parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file", "parser.add_argument(\"-id\", help=\"render single element with specified `id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply additional", "start = time.time() if size is not None: w, h = size result", "mà blend tam giác vào ảnh. # blend của hàm canvas_merge_union là canvas_compose", "help=\"output width\") parser.add_argument(\"-id\", help=\"render single element with specified `id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform,", "sys.exit(1) output, _convex_hull = result if size is not None: w, h =", "opts.fg = svg_color(\"black\") if opts.fg is None else opts.fg scene = Scene.fill(path, opts.fg)", "parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not exsits: {opts.svg}\\n\") sys.exit(1) fonts =", "fonts.register_file(font) transform = Transform().matrix(0, 1, 0, 1, 0, 0) if opts.transform: transform @=", "transform = Transform().matrix(0, 1, 0, 1, 0, 0) if opts.transform: transform @= opts.transform", "opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\") if opts.bg is None else", "fonts=fonts ) if scene is None: sys.stderr.write(\"[error] nothing to render\\n\") else: pass if", "canvas_compose truyền vào tham số đầu tiên, Mặc định là COMPOSE_OVER # Path.mask", "cạnh của tam giác sẽ được là có giá trị trong khoảng từ", "None: sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1) output, _convex_hull = result if size is", "sys.stderr.flush() if result is None: sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1) output, _convex_hull =", "trị trong khoảng từ 0 đến 1. # còn trả về offset nữa.", "not None: size = None scene = ids.get(opts.id) if scene is None: sys.stderr.write(f\"[error]", ") else: result = scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop", "là có giá trị trong khoảng từ 0 đến 1. # còn trả", "font in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0, 1, 0, 1, 0,", "argparse from svgrasterize import * import numpy as np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)})", "from svgrasterize import * import numpy as np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser", "all fonts\") opts = parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not exsits:", "specified `id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use", "viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb ) else: result = scene.render(transform, linear_rgb=opts.linear_rgb) stop =", "linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w), 4), dtype=FLOAT) image = canvas_merge_at(base, output.image, output.offset) output", "của ảnh lớn. #hàm gộp là Layer.compose trả về vùng ảnh và offset,", "= scene.render( transform, viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb ) else: result = scene.render(transform,", "= scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop - start)) sys.stderr.flush()", "cách mà blend tam giác vào ảnh. # blend của hàm canvas_merge_union là", "* import numpy as np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\",", "#hàm gộp là Layer.compose trả về vùng ảnh và offset, trả về ảnh", "0, int(h), int(w)], linear_rgb=opts.linear_rgb ) else: result = scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time()", "size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w), 4), dtype=FLOAT) image =", "type=svg_color, help=\"set default foreground color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render single", "size result = scene.render( transform, viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb ) else: result", "is None: sys.stderr.write(\"[error] nothing to render\\n\") else: pass if opts.id is not None:", "sys.stderr.write(\"[error] nothing to render\\n\") else: pass if opts.id is not None: size =", "additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths", "{opts.id}\\n\") sys.exit(1) start = time.time() if size is not None: w, h =", ") if scene is None: sys.stderr.write(\"[error] nothing to render\\n\") else: pass if opts.id", "pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is not None: output = output.background(opts.bg) filename = opts.output", "giác vào ảnh. # blend của hàm canvas_merge_union là canvas_compose truyền vào tham", "if scene is None: sys.stderr.write(f\"[error] no object with id: {opts.id}\\n\") sys.exit(1) start =", "output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w), 4), dtype=FLOAT) image = canvas_merge_at(base,", "= svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts ) if scene is None: sys.stderr.write(\"[error] nothing", "opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0, 1, 0, 1, 0, 0) if", "giác. bên trong tam giác là 1, ngoài tam giác là 0 #", "None else: scene, ids, size = svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts ) if", "is None: sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1) output, _convex_hull = result if size", "sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop - start)) sys.stderr.flush() if result is None: sys.stderr.write(\"[error] nothing", "svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts ) if scene is None: sys.stderr.write(\"[error] nothing to", "giác là 0 # còn các cạnh của tam giác sẽ được là", "nargs=\"*\", help=\"paths to SVG files containing all fonts\") opts = parser.parse_args() if not", "\"-\" else 1 closefd = opts.output != \"-\" with open(filename, \"wb\", closefd=closefd) as", "import * import numpy as np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser()", "with specified `id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\",", "Path.mask trả về mass của tam giác. bên trong tam giác là 1,", "# blend của hàm canvas_merge_union là canvas_compose truyền vào tham số đầu tiên,", "rendered in {:.2f}\\n\".format(stop - start)) sys.stderr.flush() if result is None: sys.stderr.write(\"[error] nothing to", "opts.transform: transform @= opts.transform if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\")", "None: w, h = size result = scene.render( transform, viewport=[0, 0, int(h), int(w)],", "opts.fg) ids, size = {}, None else: scene, ids, size = svg_scene_from_filepath( opts.svg,", "opts = parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not exsits: {opts.svg}\\n\") sys.exit(1)", "time.time() if size is not None: w, h = size result = scene.render(", "output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w), 4), dtype=FLOAT) image = canvas_merge_at(base, output.image, output.offset)", "= output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w), 4), dtype=FLOAT) image = canvas_merge_at(base, output.image,", "blend tam giác vào ảnh. # blend của hàm canvas_merge_union là canvas_compose truyền", "help=\"render single element with specified `id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply additional transformation\"", "if opts.output != \"-\" else 1 closefd = opts.output != \"-\" with open(filename,", "x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\", help=\"output PNG file\")", "if opts.transform: transform @= opts.transform if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg =", "= Transform().matrix(0, 1, 0, 1, 0, 0) if opts.transform: transform @= opts.transform if", "trả về mass của tam giác. bên trong tam giác là 1, ngoài", "bên trong tam giác là 1, ngoài tam giác là 0 # còn", "color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\",", "ảnh. # blend của hàm canvas_merge_union là canvas_compose truyền vào tham số đầu", "time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop - start)) sys.stderr.flush() if result is None: sys.stderr.write(\"[error]", "= ids.get(opts.id) if scene is None: sys.stderr.write(f\"[error] no object with id: {opts.id}\\n\") sys.exit(1)", "canvas_merge_at(base, output.image, output.offset) output = Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is", "vào tham số đầu tiên, Mặc định là COMPOSE_OVER # Path.mask trả về", "size = svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts ) if scene is None: sys.stderr.write(\"[error]", "output = output.background(opts.bg) filename = opts.output if opts.output != \"-\" else 1 closefd", "canvas_compose cho biết cách mà blend tam giác vào ảnh. # blend của", "exsits: {opts.svg}\\n\") sys.exit(1) fonts = FontsDB() for font in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font)", "!= \"-\" else 1 closefd = opts.output != \"-\" with open(filename, \"wb\", closefd=closefd)", "type=svg_color, help=\"set default background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground color\") parser.add_argument(\"-w\", \"--width\",", "`id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear", "scene = Scene.fill(path, opts.fg) ids, size = {}, None else: scene, ids, size", "về vùng ảnh và offset, trả về ảnh lớn nhất. # canvas_compose cho", "help=\"set default foreground color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render single element", "type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render single element with specified `id`\") parser.add_argument( \"-t\", \"--transform\",", "dtype=FLOAT) image = canvas_merge_at(base, output.image, output.offset) output = Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb)", "help=\"use linear RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG files containing all", "action=\"store_true\", help=\"use linear RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG files containing", "lớn. #hàm gộp là Layer.compose trả về vùng ảnh và offset, trả về", "background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\")", "or [DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0, 1, 0, 1, 0, 0) if opts.transform:", "vùng ảnh và offset, trả về ảnh lớn nhất. # canvas_compose cho biết", "default foreground color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render single element with", "= size result = scene.render( transform, viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb ) else:", "svg_color(\"white\") if opts.bg is None else opts.bg opts.fg = svg_color(\"black\") if opts.fg is", "gộp là Layer.compose trả về vùng ảnh và offset, trả về ảnh lớn", "svgrasterize import * import numpy as np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser =", "giác sẽ được là có giá trị trong khoảng từ 0 đến 1.", "fonts = FontsDB() for font in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0,", "Transform().matrix(0, 1, 0, 1, 0, 0) if opts.transform: transform @= opts.transform if opts.svg.endswith(\".path\"):", "path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\") if opts.bg is None else opts.bg", "type=svg_transform, help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB for rendering\") parser.add_argument(\"--fonts\",", "Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\") if opts.bg is None else opts.bg opts.fg =", "help=\"set default background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground color\") parser.add_argument(\"-w\", \"--width\", type=int,", "được là có giá trị trong khoảng từ 0 đến 1. # còn", "is None else opts.bg opts.fg = svg_color(\"black\") if opts.fg is None else opts.fg", "= parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not exsits: {opts.svg}\\n\") sys.exit(1) fonts", "0) if opts.transform: transform @= opts.transform if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg", "if scene is None: sys.stderr.write(\"[error] nothing to render\\n\") else: pass if opts.id is", "parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color,", "# Path.mask trả về mass của tam giác. bên trong tam giác là", "else: pass if opts.id is not None: size = None scene = ids.get(opts.id)", "int(h), int(w)], linear_rgb=opts.linear_rgb ) else: result = scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info]", "linear RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG files containing all fonts\")", "!= \"-\" with open(filename, \"wb\", closefd=closefd) as file: output.write_png(file) #path.fill trả về vùng", "object with id: {opts.id}\\n\") sys.exit(1) start = time.time() if size is not None:", "ảnh, offset của ảnh lớn. #hàm gộp là Layer.compose trả về vùng ảnh", "sys.stderr.write(f\"[error] no object with id: {opts.id}\\n\") sys.exit(1) start = time.time() if size is", "giác là 1, ngoài tam giác là 0 # còn các cạnh của", "in {:.2f}\\n\".format(stop - start)) sys.stderr.flush() if result is None: sys.stderr.write(\"[error] nothing to render\\n\")", "= time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop - start)) sys.stderr.flush() if result is None:", "render\\n\") sys.exit(1) output, _convex_hull = result if size is not None: w, h", "import os import argparse from svgrasterize import * import numpy as np np.set_printoptions(formatter={'float':", "có giá trị trong khoảng từ 0 đến 1. # còn trả về", "Layer.compose trả về vùng ảnh và offset, trả về ảnh lớn nhất. #", "\"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\",", "id: {opts.id}\\n\") sys.exit(1) start = time.time() if size is not None: w, h", "= {}, None else: scene, ids, size = svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts", "parser.add_argument(\"-bg\", type=svg_color, help=\"set default background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground color\") parser.add_argument(\"-w\",", "if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\") if opts.bg is None", "base = np.zeros((int(h), int(w), 4), dtype=FLOAT) image = canvas_merge_at(base, output.image, output.offset) output =", "not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not exsits: {opts.svg}\\n\") sys.exit(1) fonts = FontsDB() for", "sys.exit(1) fonts = FontsDB() for font in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform =", "None scene = ids.get(opts.id) if scene is None: sys.stderr.write(f\"[error] no object with id:", "mass của tam giác. bên trong tam giác là 1, ngoài tam giác", "# còn các cạnh của tam giác sẽ được là có giá trị", "color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render single element with specified `id`\")", "result if size is not None: w, h = size output = output.convert(pre_alpha=True,", "\"--transform\", type=svg_transform, help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB for rendering\")", "if size is not None: w, h = size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb)", "is None else opts.fg scene = Scene.fill(path, opts.fg) ids, size = {}, None", "của tam giác sẽ được là có giá trị trong khoảng từ 0", "help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default", "is not None: size = None scene = ids.get(opts.id) if scene is None:", "size = None scene = ids.get(opts.id) if scene is None: sys.stderr.write(f\"[error] no object", "image = canvas_merge_at(base, output.image, output.offset) output = Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if", "pass if opts.id is not None: size = None scene = ids.get(opts.id) if", "scene, ids, size = svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts ) if scene is", "ảnh và offset, trả về ảnh lớn nhất. # canvas_compose cho biết cách", "ids.get(opts.id) if scene is None: sys.stderr.write(f\"[error] no object with id: {opts.id}\\n\") sys.exit(1) start", "= opts.output if opts.output != \"-\" else 1 closefd = opts.output != \"-\"", "về mass của tam giác. bên trong tam giác là 1, ngoài tam", "opts.bg = svg_color(\"white\") if opts.bg is None else opts.bg opts.fg = svg_color(\"black\") if", "scene is None: sys.stderr.write(\"[error] nothing to render\\n\") else: pass if opts.id is not", "None: output = output.background(opts.bg) filename = opts.output if opts.output != \"-\" else 1", "else: result = scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop -", "= Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is not None: output =", "định là COMPOSE_OVER # Path.mask trả về mass của tam giác. bên trong", "for font in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0, 1, 0, 1,", "output, _convex_hull = result if size is not None: w, h = size", "và offset, trả về ảnh lớn nhất. # canvas_compose cho biết cách mà", "[DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0, 1, 0, 1, 0, 0) if opts.transform: transform", "= Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\") if opts.bg is None else opts.bg opts.fg", "element with specified `id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\",", "\"-\" with open(filename, \"wb\", closefd=closefd) as file: output.write_png(file) #path.fill trả về vùng ảnh,", "not None: w, h = size result = scene.render( transform, viewport=[0, 0, int(h),", "tham số đầu tiên, Mặc định là COMPOSE_OVER # Path.mask trả về mass", "if size is not None: w, h = size result = scene.render( transform,", "file\") parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default background color\") parser.add_argument(\"-fg\", type=svg_color,", "default background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground color\") parser.add_argument(\"-w\", \"--width\", type=int, help=\"output", "result = scene.render( transform, viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb ) else: result =", "offset của ảnh lớn. #hàm gộp là Layer.compose trả về vùng ảnh và", "về vùng ảnh, offset của ảnh lớn. #hàm gộp là Layer.compose trả về", "file: output.write_png(file) #path.fill trả về vùng ảnh, offset của ảnh lớn. #hàm gộp", "stop = time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop - start)) sys.stderr.flush() if result is", "np.zeros((int(h), int(w), 4), dtype=FLOAT) image = canvas_merge_at(base, output.image, output.offset) output = Layer(image, (0,", "4), dtype=FLOAT) image = canvas_merge_at(base, output.image, output.offset) output = Layer(image, (0, 0), pre_alpha=True,", "trong tam giác là 1, ngoài tam giác là 0 # còn các", "# canvas_compose cho biết cách mà blend tam giác vào ảnh. # blend", "output.write_png(file) #path.fill trả về vùng ảnh, offset của ảnh lớn. #hàm gộp là", "{opts.svg}\\n\") sys.exit(1) fonts = FontsDB() for font in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform", "parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG files", "closefd = opts.output != \"-\" with open(filename, \"wb\", closefd=closefd) as file: output.write_png(file) #path.fill", "= opts.output != \"-\" with open(filename, \"wb\", closefd=closefd) as file: output.write_png(file) #path.fill trả", "sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1) output, _convex_hull = result if size is not", "tam giác là 0 # còn các cạnh của tam giác sẽ được", "else opts.bg opts.fg = svg_color(\"black\") if opts.fg is None else opts.fg scene =", "tam giác là 1, ngoài tam giác là 0 # còn các cạnh", "opts.bg opts.fg = svg_color(\"black\") if opts.fg is None else opts.fg scene = Scene.fill(path,", "None: sys.stderr.write(\"[error] nothing to render\\n\") else: pass if opts.id is not None: size", "của hàm canvas_merge_union là canvas_compose truyền vào tham số đầu tiên, Mặc định", "1 closefd = opts.output != \"-\" with open(filename, \"wb\", closefd=closefd) as file: output.write_png(file)", "các cạnh của tam giác sẽ được là có giá trị trong khoảng", "import numpy as np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input", "svg_color(\"black\") if opts.fg is None else opts.fg scene = Scene.fill(path, opts.fg) ids, size", ") parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG", "là 1, ngoài tam giác là 0 # còn các cạnh của tam", "linear_rgb=opts.linear_rgb) if opts.bg is not None: output = output.background(opts.bg) filename = opts.output if", "canvas_merge_union là canvas_compose truyền vào tham số đầu tiên, Mặc định là COMPOSE_OVER", "single element with specified `id`\") parser.add_argument( \"-t\", \"--transform\", type=svg_transform, help=\"apply additional transformation\" )", "else: scene, ids, size = svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts ) if scene", "else opts.fg scene = Scene.fill(path, opts.fg) ids, size = {}, None else: scene,", "là 0 # còn các cạnh của tam giác sẽ được là có", "blend của hàm canvas_merge_union là canvas_compose truyền vào tham số đầu tiên, Mặc", "result = scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop - start))", "tam giác vào ảnh. # blend của hàm canvas_merge_union là canvas_compose truyền vào", "nothing to render\\n\") else: pass if opts.id is not None: size = None", "của tam giác. bên trong tam giác là 1, ngoài tam giác là", "help=\"input SVG file\") parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default background color\")", "là COMPOSE_OVER # Path.mask trả về mass của tam giác. bên trong tam", "số đầu tiên, Mặc định là COMPOSE_OVER # Path.mask trả về mass của", "else 1 closefd = opts.output != \"-\" with open(filename, \"wb\", closefd=closefd) as file:", "if opts.fg is None else opts.fg scene = Scene.fill(path, opts.fg) ids, size =", "w, h = size result = scene.render( transform, viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb", "output.image, output.offset) output = Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is not", "về ảnh lớn nhất. # canvas_compose cho biết cách mà blend tam giác", "as file: output.write_png(file) #path.fill trả về vùng ảnh, offset của ảnh lớn. #hàm", "Scene.fill(path, opts.fg) ids, size = {}, None else: scene, ids, size = svg_scene_from_filepath(", "if result is None: sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1) output, _convex_hull = result", "import argparse from svgrasterize import * import numpy as np np.set_printoptions(formatter={'float': lambda x:", "0, 1, 0, 0) if opts.transform: transform @= opts.transform if opts.svg.endswith(\".path\"): path =", "None: size = None scene = ids.get(opts.id) if scene is None: sys.stderr.write(f\"[error] no", "{:.2f}\\n\".format(stop - start)) sys.stderr.flush() if result is None: sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1)", "FontsDB() for font in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0, 1, 0,", "render\\n\") else: pass if opts.id is not None: size = None scene =", "trả về ảnh lớn nhất. # canvas_compose cho biết cách mà blend tam", "#path.fill trả về vùng ảnh, offset của ảnh lớn. #hàm gộp là Layer.compose", "start)) sys.stderr.flush() if result is None: sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1) output, _convex_hull", "= FontsDB() for font in opts.fonts or [DEFAULT_FONTS]: fonts.register_file(font) transform = Transform().matrix(0, 1,", "opts.output != \"-\" with open(filename, \"wb\", closefd=closefd) as file: output.write_png(file) #path.fill trả về", "np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\",", "1, 0, 0) if opts.transform: transform @= opts.transform if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read())", "linear_rgb=opts.linear_rgb ) else: result = scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info] rendered in", "is not None: output = output.background(opts.bg) filename = opts.output if opts.output != \"-\"", "giá trị trong khoảng từ 0 đến 1. # còn trả về offset", "output.offset) output = Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is not None:", "os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does not exsits: {opts.svg}\\n\") sys.exit(1) fonts = FontsDB() for font", "scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop - start)) sys.stderr.flush() if", "lớn nhất. # canvas_compose cho biết cách mà blend tam giác vào ảnh.", "to render\\n\") else: pass if opts.id is not None: size = None scene", "nothing to render\\n\") sys.exit(1) output, _convex_hull = result if size is not None:", "\"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render single element with specified `id`\") parser.add_argument( \"-t\",", "ids, size = svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width, fonts=fonts ) if scene is None:", "transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to", "is not None: w, h = size result = scene.render( transform, viewport=[0, 0,", "opts.fg is None else opts.fg scene = Scene.fill(path, opts.fg) ids, size = {},", "scene is None: sys.stderr.write(f\"[error] no object with id: {opts.id}\\n\") sys.exit(1) start = time.time()", "đầu tiên, Mặc định là COMPOSE_OVER # Path.mask trả về mass của tam", "for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG files containing all fonts\") opts =", "opts.svg, fg=opts.fg, width=opts.width, fonts=fonts ) if scene is None: sys.stderr.write(\"[error] nothing to render\\n\")", "files containing all fonts\") opts = parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error] file does", "if opts.bg is not None: output = output.background(opts.bg) filename = opts.output if opts.output", "None else opts.bg opts.fg = svg_color(\"black\") if opts.fg is None else opts.fg scene", "not None: w, h = size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h),", "@= opts.transform if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\") if opts.bg", "ids, size = {}, None else: scene, ids, size = svg_scene_from_filepath( opts.svg, fg=opts.fg,", "scene = ids.get(opts.id) if scene is None: sys.stderr.write(f\"[error] no object with id: {opts.id}\\n\")", "= argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\") parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set", "= np.zeros((int(h), int(w), 4), dtype=FLOAT) image = canvas_merge_at(base, output.image, output.offset) output = Layer(image,", "\"wb\", closefd=closefd) as file: output.write_png(file) #path.fill trả về vùng ảnh, offset của ảnh", "w, h = size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w), 4),", "parser.add_argument(\"-w\", \"--width\", type=int, help=\"output width\") parser.add_argument(\"-id\", help=\"render single element with specified `id`\") parser.add_argument(", "trả về vùng ảnh, offset của ảnh lớn. #hàm gộp là Layer.compose trả", "does not exsits: {opts.svg}\\n\") sys.exit(1) fonts = FontsDB() for font in opts.fonts or", "biết cách mà blend tam giác vào ảnh. # blend của hàm canvas_merge_union", "PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default background color\") parser.add_argument(\"-fg\", type=svg_color, help=\"set default foreground", "opts.output != \"-\" else 1 closefd = opts.output != \"-\" with open(filename, \"wb\",", "COMPOSE_OVER # Path.mask trả về mass của tam giác. bên trong tam giác", "(0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg is not None: output = output.background(opts.bg) filename", "if opts.id is not None: size = None scene = ids.get(opts.id) if scene", "as np np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)}) parser = argparse.ArgumentParser() parser.add_argument(\"svg\", help=\"input SVG file\")", "\"-t\", \"--transform\", type=svg_transform, help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB for", "SVG file\") parser.add_argument(\"output\", help=\"output PNG file\") parser.add_argument(\"-bg\", type=svg_color, help=\"set default background color\") parser.add_argument(\"-fg\",", "to render\\n\") sys.exit(1) output, _convex_hull = result if size is not None: w,", "_convex_hull = result if size is not None: w, h = size output", "filename = opts.output if opts.output != \"-\" else 1 closefd = opts.output !=", "transform @= opts.transform if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\") if", "1, ngoài tam giác là 0 # còn các cạnh của tam giác", "truyền vào tham số đầu tiên, Mặc định là COMPOSE_OVER # Path.mask trả", "= result if size is not None: w, h = size output =", "vào ảnh. # blend của hàm canvas_merge_union là canvas_compose truyền vào tham số", "cho biết cách mà blend tam giác vào ảnh. # blend của hàm", "= None scene = ids.get(opts.id) if scene is None: sys.stderr.write(f\"[error] no object with", "ảnh lớn nhất. # canvas_compose cho biết cách mà blend tam giác vào", "size is not None: w, h = size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base", "= svg_color(\"black\") if opts.fg is None else opts.fg scene = Scene.fill(path, opts.fg) ids,", "0 # còn các cạnh của tam giác sẽ được là có giá", "opts.transform if opts.svg.endswith(\".path\"): path = Path.from_svg(open(opts.svg).read()) print(path,\"\\n\") opts.bg = svg_color(\"white\") if opts.bg is", "fg=opts.fg, width=opts.width, fonts=fonts ) if scene is None: sys.stderr.write(\"[error] nothing to render\\n\") else:", "- start)) sys.stderr.flush() if result is None: sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1) output,", "= canvas_merge_at(base, output.image, output.offset) output = Layer(image, (0, 0), pre_alpha=True, linear_rgb=opts.linear_rgb) if opts.bg", "to SVG files containing all fonts\") opts = parser.parse_args() if not os.path.exists(opts.svg): sys.stderr.write(f\"[error]", "None: sys.stderr.write(f\"[error] no object with id: {opts.id}\\n\") sys.exit(1) start = time.time() if size", "sys.exit(1) start = time.time() if size is not None: w, h = size", "int(w)], linear_rgb=opts.linear_rgb ) else: result = scene.render(transform, linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info] rendered", "là Layer.compose trả về vùng ảnh và offset, trả về ảnh lớn nhất.", "is not None: w, h = size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base =", "help=\"apply additional transformation\" ) parser.add_argument(\"--linear-rgb\", action=\"store_true\", help=\"use linear RGB for rendering\") parser.add_argument(\"--fonts\", nargs=\"*\",", "rendering\") parser.add_argument(\"--fonts\", nargs=\"*\", help=\"paths to SVG files containing all fonts\") opts = parser.parse_args()", "transform, viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb ) else: result = scene.render(transform, linear_rgb=opts.linear_rgb) stop", "linear_rgb=opts.linear_rgb) stop = time.time() sys.stderr.write(\"[info] rendered in {:.2f}\\n\".format(stop - start)) sys.stderr.flush() if result", "opts.fg scene = Scene.fill(path, opts.fg) ids, size = {}, None else: scene, ids,", "offset, trả về ảnh lớn nhất. # canvas_compose cho biết cách mà blend", "is None: sys.stderr.write(f\"[error] no object with id: {opts.id}\\n\") sys.exit(1) start = time.time() if", "help=\"paths to SVG files containing all fonts\") opts = parser.parse_args() if not os.path.exists(opts.svg):", "vùng ảnh, offset của ảnh lớn. #hàm gộp là Layer.compose trả về vùng", "opts.output if opts.output != \"-\" else 1 closefd = opts.output != \"-\" with", "width=opts.width, fonts=fonts ) if scene is None: sys.stderr.write(\"[error] nothing to render\\n\") else: pass", "result is None: sys.stderr.write(\"[error] nothing to render\\n\") sys.exit(1) output, _convex_hull = result if", "opts.bg is None else opts.bg opts.fg = svg_color(\"black\") if opts.fg is None else", "h = size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w), 4), dtype=FLOAT)", "= size output = output.convert(pre_alpha=True, linear_rgb=opts.linear_rgb) base = np.zeros((int(h), int(w), 4), dtype=FLOAT) image", "1, 0, 1, 0, 0) if opts.transform: transform @= opts.transform if opts.svg.endswith(\".path\"): path", "h = size result = scene.render( transform, viewport=[0, 0, int(h), int(w)], linear_rgb=opts.linear_rgb )", "size = {}, None else: scene, ids, size = svg_scene_from_filepath( opts.svg, fg=opts.fg, width=opts.width,", "with id: {opts.id}\\n\") sys.exit(1) start = time.time() if size is not None: w,", "tam giác. bên trong tam giác là 1, ngoài tam giác là 0", "là canvas_compose truyền vào tham số đầu tiên, Mặc định là COMPOSE_OVER #", "no object with id: {opts.id}\\n\") sys.exit(1) start = time.time() if size is not", "tam giác sẽ được là có giá trị trong khoảng từ 0 đến", "sẽ được là có giá trị trong khoảng từ 0 đến 1. #", "output.background(opts.bg) filename = opts.output if opts.output != \"-\" else 1 closefd = opts.output" ]
[ "args.dev_file args.test_file = DATA_PATH / args.dataset / args.test_file if args.replace_word_dict == 'False': args.replace_word_dict", "default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512,", "default=0, type=int) args = parser.parse_args() args.train_file = DATA_PATH / args.dataset / args.train_file args.dev_file", "parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict',", "type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int)", "default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int) args = parser.parse_args() args.train_file = DATA_PATH / args.dataset", "parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file',", "True if args.retrain_model == 'False': args.retrain_model = False else: args.retrain_model = True (DATA_PATH", "/ args.test_file if args.replace_word_dict == 'False': args.replace_word_dict = False else: args.replace_word_dict = True", "args.train_file = DATA_PATH / args.dataset / args.train_file args.dev_file = DATA_PATH / args.dataset /", "= False else: args.retrain_model = True (DATA_PATH / 'model' / args.dataset).mkdir(parents = True,", "'model' / args.dataset).mkdir(parents = True, exist_ok=True) args.model_file = DATA_PATH / 'model' / args.dataset", "= True, exist_ok=True) args.model_file = DATA_PATH / 'model' / args.dataset / args.model_file train_language_model(args)", "args.test_file = DATA_PATH / args.dataset / args.test_file if args.replace_word_dict == 'False': args.replace_word_dict =", "args.train_file args.dev_file = DATA_PATH / args.dataset / args.dev_file args.test_file = DATA_PATH / args.dataset", "/ args.dev_file args.test_file = DATA_PATH / args.dataset / args.test_file if args.replace_word_dict == 'False':", "default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2,", "parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file',", "from DenoiseSum.LanguageModel.training import train_language_model if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten',", "type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int)", "default=16, type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20,", "default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False',", "type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int)", "default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500,", "default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3,", "type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str)", "else: args.replace_word_dict = True if args.retrain_model == 'False': args.retrain_model = False else: args.retrain_model", "== 'False': args.retrain_model = False else: args.retrain_model = True (DATA_PATH / 'model' /", "DenoiseSum import DATA_PATH from DenoiseSum.LanguageModel.training import train_language_model if __name__ == '__main__': parser =", "== '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16,", "parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim',", "/ 'model' / args.dataset).mkdir(parents = True, exist_ok=True) args.model_file = DATA_PATH / 'model' /", "DATA_PATH / args.dataset / args.dev_file args.test_file = DATA_PATH / args.dataset / args.test_file if", "parser.add_argument('--coverage_rate', default=0, type=int) args = parser.parse_args() args.train_file = DATA_PATH / args.dataset / args.train_file", "parser.parse_args() args.train_file = DATA_PATH / args.dataset / args.train_file args.dev_file = DATA_PATH / args.dataset", "parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos',", "type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str)", "args.dataset / args.test_file if args.replace_word_dict == 'False': args.replace_word_dict = False else: args.replace_word_dict =", "default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model',", "type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int)", "import argparse from DenoiseSum import DATA_PATH from DenoiseSum.LanguageModel.training import train_language_model if __name__ ==", "default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv',", "parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int) args", "== 'False': args.replace_word_dict = False else: args.replace_word_dict = True if args.retrain_model == 'False':", "= True (DATA_PATH / 'model' / args.dataset).mkdir(parents = True, exist_ok=True) args.model_file = DATA_PATH", "'__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16, type=int)", "parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch',", "type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50, type=int)", "import train_language_model if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance',", "default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv',", "type=int) args = parser.parse_args() args.train_file = DATA_PATH / args.dataset / args.train_file args.dev_file =", "'False': args.retrain_model = False else: args.retrain_model = True (DATA_PATH / 'model' / args.dataset).mkdir(parents", "parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos',", "/ args.dataset / args.dev_file args.test_file = DATA_PATH / args.dataset / args.test_file if args.replace_word_dict", "= parser.parse_args() args.train_file = DATA_PATH / args.dataset / args.train_file args.dev_file = DATA_PATH /", "if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int)", "parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim',", "<gh_stars>0 import argparse from DenoiseSum import DATA_PATH from DenoiseSum.LanguageModel.training import train_language_model if __name__", "type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str)", "parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate',", "DATA_PATH / args.dataset / args.train_file args.dev_file = DATA_PATH / args.dataset / args.dev_file args.test_file", "type=str) parser.add_argument('--retrain_model', default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3, type=int)", "type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str)", "default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False',", "if args.retrain_model == 'False': args.retrain_model = False else: args.retrain_model = True (DATA_PATH /", "args.replace_word_dict == 'False': args.replace_word_dict = False else: args.replace_word_dict = True if args.retrain_model ==", "(DATA_PATH / 'model' / args.dataset).mkdir(parents = True, exist_ok=True) args.model_file = DATA_PATH / 'model'", "__name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size',", "parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int) args = parser.parse_args() args.train_file = DATA_PATH /", "default=512, type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5,", "args.replace_word_dict = False else: args.replace_word_dict = True if args.retrain_model == 'False': args.retrain_model =", "parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file',", "default=2, type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int) args = parser.parse_args() args.train_file =", "False else: args.replace_word_dict = True if args.retrain_model == 'False': args.retrain_model = False else:", "import DATA_PATH from DenoiseSum.LanguageModel.training import train_language_model if __name__ == '__main__': parser = argparse.ArgumentParser()", "parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after',", "train_language_model if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40,", "/ args.train_file args.dev_file = DATA_PATH / args.dataset / args.dev_file args.test_file = DATA_PATH /", "type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int) args = parser.parse_args()", "default=40, type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50,", "DenoiseSum.LanguageModel.training import train_language_model if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str)", "argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300, type=int)", "type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int)", "args.retrain_model == 'False': args.retrain_model = False else: args.retrain_model = True (DATA_PATH / 'model'", "True (DATA_PATH / 'model' / args.dataset).mkdir(parents = True, exist_ok=True) args.model_file = DATA_PATH /", "else: args.retrain_model = True (DATA_PATH / 'model' / args.dataset).mkdir(parents = True, exist_ok=True) args.model_file", "/ args.dataset / args.test_file if args.replace_word_dict == 'False': args.replace_word_dict = False else: args.replace_word_dict", "args.test_file if args.replace_word_dict == 'False': args.replace_word_dict = False else: args.replace_word_dict = True if", "args.dataset / args.dev_file args.test_file = DATA_PATH / args.dataset / args.test_file if args.replace_word_dict ==", "args.dev_file = DATA_PATH / args.dataset / args.dev_file args.test_file = DATA_PATH / args.dataset /", "parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every',", "parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int) args = parser.parse_args() args.train_file", "= DATA_PATH / args.dataset / args.test_file if args.replace_word_dict == 'False': args.replace_word_dict = False", "DATA_PATH from DenoiseSum.LanguageModel.training import train_language_model if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset',", "type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str)", "from DenoiseSum import DATA_PATH from DenoiseSum.LanguageModel.training import train_language_model if __name__ == '__main__': parser", "args.replace_word_dict = True if args.retrain_model == 'False': args.retrain_model = False else: args.retrain_model =", "= True if args.retrain_model == 'False': args.retrain_model = False else: args.retrain_model = True", "type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str)", "'False': args.replace_word_dict = False else: args.replace_word_dict = True if args.retrain_model == 'False': args.retrain_model", "if args.replace_word_dict == 'False': args.replace_word_dict = False else: args.replace_word_dict = True if args.retrain_model", "default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv',", "parser.add_argument('--disc_size', default=50, type=int) parser.add_argument('--num_epoch', default=20, type=int) parser.add_argument('--eval_every', default=2500, type=int) parser.add_argument('--stop_after', default=5, type=int) parser.add_argument('--train_file',", "args.retrain_model = False else: args.retrain_model = True (DATA_PATH / 'model' / args.dataset).mkdir(parents =", "/ args.dataset).mkdir(parents = True, exist_ok=True) args.model_file = DATA_PATH / 'model' / args.dataset /", "type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int)", "default='False', type=str) parser.add_argument('--model_file', default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0,", "= DATA_PATH / args.dataset / args.train_file args.dev_file = DATA_PATH / args.dataset / args.dev_file", "args = parser.parse_args() args.train_file = DATA_PATH / args.dataset / args.train_file args.dev_file = DATA_PATH", "args.dataset).mkdir(parents = True, exist_ok=True) args.model_file = DATA_PATH / 'model' / args.dataset / args.model_file", "argparse from DenoiseSum import DATA_PATH from DenoiseSum.LanguageModel.training import train_language_model if __name__ == '__main__':", "= DATA_PATH / args.dataset / args.dev_file args.test_file = DATA_PATH / args.dataset / args.test_file", "parser.add_argument('--train_file', default='reviews_large_train.csv', type=str) parser.add_argument('--dev_file', default='reviews_large_validation.csv', type=str) parser.add_argument('--test_file', default='reviews_large_test.csv', type=str) parser.add_argument('--replace_word_dict', default='False', type=str) parser.add_argument('--retrain_model',", "args.dataset / args.train_file args.dev_file = DATA_PATH / args.dataset / args.dev_file args.test_file = DATA_PATH", "default='lm.model', type=str) parser.add_argument('--sos', default=2, type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int) args =", "type=int) parser.add_argument('--coverage_rate', default=0, type=int) args = parser.parse_args() args.train_file = DATA_PATH / args.dataset /", "/ args.dataset / args.train_file args.dev_file = DATA_PATH / args.dataset / args.dev_file args.test_file =", "type=int) parser.add_argument('--eos', default=3, type=int) parser.add_argument('--coverage_rate', default=0, type=int) args = parser.parse_args() args.train_file = DATA_PATH", "DATA_PATH / args.dataset / args.test_file if args.replace_word_dict == 'False': args.replace_word_dict = False else:", "False else: args.retrain_model = True (DATA_PATH / 'model' / args.dataset).mkdir(parents = True, exist_ok=True)", "parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300, type=int) parser.add_argument('--hidden_dim', default=512, type=int) parser.add_argument('--disc_size',", "= argparse.ArgumentParser() parser.add_argument('--dataset', default='rotten', type=str) parser.add_argument('--no_instance', default=40, type=int) parser.add_argument('--batch_size', default=16, type=int) parser.add_argument('--word_dim', default=300,", "= False else: args.replace_word_dict = True if args.retrain_model == 'False': args.retrain_model = False", "args.retrain_model = True (DATA_PATH / 'model' / args.dataset).mkdir(parents = True, exist_ok=True) args.model_file =" ]
[ "self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c'))", "ramda as R \"\"\" https://github.com/ramda/ramda/blob/master/test/head.js \"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2,", "class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3]))", "\"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3,", "R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self): with self.assertRaises(TypeError):", "3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c',", "R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self): with self.assertRaises(TypeError): R.head(None) if __name__ ==", "unittest import ramda as R \"\"\" https://github.com/ramda/ramda/blob/master/test/head.js \"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1,", "def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([]))", "test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a',", "R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self):", "self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self): with self.assertRaises(TypeError): R.head(None) if __name__", "R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self): with self.assertRaises(TypeError): R.head(None) if __name__ == '__main__': unittest.main()", "as R \"\"\" https://github.com/ramda/ramda/blob/master/test/head.js \"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3]))", "2, 3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc'))", "self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc'))", "\"\"\" https://github.com/ramda/ramda/blob/master/test/head.js \"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2, R.head([2,", "R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self): with self.assertRaises(TypeError): R.head(None) if", "self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self): with self.assertRaises(TypeError): R.head(None) if __name__ == '__main__':", "3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head(''))", "self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self): with", "R \"\"\" https://github.com/ramda/ramda/blob/master/test/head.js \"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2,", "self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def test_throws_if_applied_to_None(self): with self.assertRaises(TypeError): R.head(None)", "import unittest import ramda as R \"\"\" https://github.com/ramda/ramda/blob/master/test/head.js \"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self):", "import ramda as R \"\"\" https://github.com/ramda/ramda/blob/master/test/head.js \"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1,", "https://github.com/ramda/ramda/blob/master/test/head.js \"\"\" class TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2, R.head([2, 3]))", "self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('', R.head('')) def", "R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b', R.head('bc')) self.assertEqual('c', R.head('c')) self.assertEqual('',", "R.head([1, 2, 3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None, R.head([])) self.assertEqual('a', R.head('abc')) self.assertEqual('b',", "TestHead(unittest.TestCase): def test_returns_the_first_element_of_an_ordered_collection(self): self.assertEqual(1, R.head([1, 2, 3])) self.assertEqual(2, R.head([2, 3])) self.assertEqual(3, R.head([3])) self.assertEqual(None," ]
[ "name='django.contrib.sitemaps.views.sitemap'), # Error page styling tests. It's OK to have these outside of", "urlpatterns = [ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/',", "from django.contrib.sitemaps.views import sitemap from django.urls import include, path from django.views.generic import TemplateView", "from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from", "include, path from django.views.generic import TemplateView from markdownx.views import MarkdownifyView from exhaust.posts.sitemaps import", "path from django.views.generic import TemplateView from markdownx.views import MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS", "django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views", "import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import", "from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.urls import include, path", "TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static( settings.STATIC_URL, document_root=settings.STATIC_ROOT", "they're having a 500 they're more than welcome # to). It means there's", "import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.urls import", "more than welcome # to). It means there's one less branch to test", "settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap", "MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page styling tests. It's", "include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps':", "path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static( settings.STATIC_URL,", "path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page", "TemplateView from markdownx.views import MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns = [ path('',", "from django.views.generic import TemplateView from markdownx.views import MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns", "a 500 they're more than welcome # to). It means there's one less", "Error page styling tests. It's OK to have these outside of DEBUG (if", "TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), #", "MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns = [ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls',", "django.urls import include, path from django.views.generic import TemplateView from markdownx.views import MarkdownifyView from", "wants to pretend they're having a 500 they're more than welcome # to).", "namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml',", "django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.urls", "to pretend they're having a 500 they're more than welcome # to). It", "one less branch to test in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] +", "means there's one less branch to test in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')),", "django.views.generic import TemplateView from markdownx.views import MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns =", "import TemplateView from markdownx.views import MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns = [", "admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page styling", "include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'),", "to have these outside of DEBUG (if # someone wants to pretend they're", "markdownx.views import MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns = [ path('', include('exhaust.posts.urls', namespace='posts')),", "from django.urls import include, path from django.views.generic import TemplateView from markdownx.views import MarkdownifyView", "OK to have these outside of DEBUG (if # someone wants to pretend", "outside of DEBUG (if # someone wants to pretend they're having a 500", "It's OK to have these outside of DEBUG (if # someone wants to", "less branch to test in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] + static(", "settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(", "branch to test in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] + static( settings.MEDIA_URL,", "than welcome # to). It means there's one less branch to test in", "to). It means there's one less branch to test in settings. path('404/', TemplateView.as_view(template_name='404.html')),", "DEBUG (if # someone wants to pretend they're having a 500 they're more", "name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page styling tests. It's OK", "in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) +", "import admin from django.contrib.sitemaps.views import sitemap from django.urls import include, path from django.views.generic", "import POSTS_SITE_MAPS urlpatterns = [ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt',", "having a 500 they're more than welcome # to). It means there's one", "500 they're more than welcome # to). It means there's one less branch", "# to). It means there's one less branch to test in settings. path('404/',", "POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page styling tests. It's OK to have these outside", "styling tests. It's OK to have these outside of DEBUG (if # someone", "[ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/',", "of DEBUG (if # someone wants to pretend they're having a 500 they're", "import MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns = [ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/',", "from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from", "django.contrib.sitemaps.views import sitemap from django.urls import include, path from django.views.generic import TemplateView from", "there's one less branch to test in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ]", "from markdownx.views import MarkdownifyView from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns = [ path('', include('exhaust.posts.urls',", "welcome # to). It means there's one less branch to test in settings.", "sitemap from django.urls import include, path from django.views.generic import TemplateView from markdownx.views import", "sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page styling tests. It's OK to have", "content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error", "path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page styling tests.", "someone wants to pretend they're having a 500 they're more than welcome #", "test in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT )", "path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap,", "they're more than welcome # to). It means there's one less branch to", "namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS},", "path('500/', TemplateView.as_view(template_name='500.html')), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static( settings.STATIC_URL, document_root=settings.STATIC_ROOT )", "admin from django.contrib.sitemaps.views import sitemap from django.urls import include, path from django.views.generic import", "page styling tests. It's OK to have these outside of DEBUG (if #", "to test in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/', TemplateView.as_view(template_name='500.html')), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT", "POSTS_SITE_MAPS urlpatterns = [ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),", "path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page styling tests. It's OK to", "exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns = [ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt',", "have these outside of DEBUG (if # someone wants to pretend they're having", "pretend they're having a 500 they're more than welcome # to). It means", "path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(),", "path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls), path('markdownx/markdownify/', MarkdownifyView.as_view(), name='markdownx_markdownify'), path('sitemap.xml', sitemap, {'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'),", "import sitemap from django.urls import include, path from django.views.generic import TemplateView from markdownx.views", "django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.urls import include, path from", "from exhaust.posts.sitemaps import POSTS_SITE_MAPS urlpatterns = [ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')),", "(if # someone wants to pretend they're having a 500 they're more than", "It means there's one less branch to test in settings. path('404/', TemplateView.as_view(template_name='404.html')), path('500/',", "these outside of DEBUG (if # someone wants to pretend they're having a", "= [ path('', include('exhaust.posts.urls', namespace='posts')), path('exogram/', include('exhaust.exogram.urls', namespace='exogram')), path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), path('admin/', admin.site.urls),", "tests. It's OK to have these outside of DEBUG (if # someone wants", "static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.urls import include,", "import include, path from django.views.generic import TemplateView from markdownx.views import MarkdownifyView from exhaust.posts.sitemaps", "# Error page styling tests. It's OK to have these outside of DEBUG", "# someone wants to pretend they're having a 500 they're more than welcome", "{'sitemaps': POSTS_SITE_MAPS}, name='django.contrib.sitemaps.views.sitemap'), # Error page styling tests. It's OK to have these" ]
[ "import unittest class TeskKey(unittest.TestCase): def test_key(self): a = ['a', 'b'] b = ['b']", "<filename>Python3/tests/test_key.py<gh_stars>1-10 import unittest class TeskKey(unittest.TestCase): def test_key(self): a = ['a', 'b'] b =", "unittest class TeskKey(unittest.TestCase): def test_key(self): a = ['a', 'b'] b = ['b'] self.assertEqual(a,b)" ]
[ "logging.getLogger(__name__) class SystemContext: def __init__(self): self.config = conf.cnf self.ds: DataStoreMongo = None self.ds_client:", ") from quakestats.system import ( conf, ) logger = logging.getLogger(__name__) class SystemContext: def", "conf.cnf self.ds: DataStoreMongo = None self.ds_client: pymongo.MongoClient = None self.configure() def configure(self): uri", "None self.ds_client: pymongo.MongoClient = None self.configure() def configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client =", "quakestats.system import ( conf, ) logger = logging.getLogger(__name__) class SystemContext: def __init__(self): self.config", "self.ds: DataStoreMongo = None self.ds_client: pymongo.MongoClient = None self.configure() def configure(self): uri =", "None self.configure() def configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri = pymongo.uri_parser.parse_uri(uri)", "= None self.ds_client: pymongo.MongoClient = None self.configure() def configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client", "__init__(self): self.config = conf.cnf self.ds: DataStoreMongo = None self.ds_client: pymongo.MongoClient = None self.configure()", "from quakestats.datasource.mongo2 import ( DataStoreMongo, ) from quakestats.system import ( conf, ) logger", "self.config = conf.cnf self.ds: DataStoreMongo = None self.ds_client: pymongo.MongoClient = None self.configure() def", "SystemContext: def __init__(self): self.config = conf.cnf self.ds: DataStoreMongo = None self.ds_client: pymongo.MongoClient =", "= logging.getLogger(__name__) class SystemContext: def __init__(self): self.config = conf.cnf self.ds: DataStoreMongo = None", "quakestats.datasource.mongo2 import ( DataStoreMongo, ) from quakestats.system import ( conf, ) logger =", "pymongo.MongoClient = None self.configure() def configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri", "configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri = pymongo.uri_parser.parse_uri(uri) database_name = parsed_uri[\"database\"]", "conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri = pymongo.uri_parser.parse_uri(uri) database_name = parsed_uri[\"database\"] self.ds = DataStoreMongo(self.ds_client.get_database(database_name))", "class SystemContext: def __init__(self): self.config = conf.cnf self.ds: DataStoreMongo = None self.ds_client: pymongo.MongoClient", "import pymongo from quakestats.datasource.mongo2 import ( DataStoreMongo, ) from quakestats.system import ( conf,", "def __init__(self): self.config = conf.cnf self.ds: DataStoreMongo = None self.ds_client: pymongo.MongoClient = None", "= conf.cnf self.ds: DataStoreMongo = None self.ds_client: pymongo.MongoClient = None self.configure() def configure(self):", "= None self.configure() def configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri =", "logging import pymongo from quakestats.datasource.mongo2 import ( DataStoreMongo, ) from quakestats.system import (", "import ( DataStoreMongo, ) from quakestats.system import ( conf, ) logger = logging.getLogger(__name__)", "conf, ) logger = logging.getLogger(__name__) class SystemContext: def __init__(self): self.config = conf.cnf self.ds:", "def configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri = pymongo.uri_parser.parse_uri(uri) database_name =", "( conf, ) logger = logging.getLogger(__name__) class SystemContext: def __init__(self): self.config = conf.cnf", "logger = logging.getLogger(__name__) class SystemContext: def __init__(self): self.config = conf.cnf self.ds: DataStoreMongo =", "= conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri = pymongo.uri_parser.parse_uri(uri) database_name = parsed_uri[\"database\"] self.ds =", "import ( conf, ) logger = logging.getLogger(__name__) class SystemContext: def __init__(self): self.config =", "import logging import pymongo from quakestats.datasource.mongo2 import ( DataStoreMongo, ) from quakestats.system import", "DataStoreMongo = None self.ds_client: pymongo.MongoClient = None self.configure() def configure(self): uri = conf.get_conf_val('MONGO_URI')", "uri = conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri = pymongo.uri_parser.parse_uri(uri) database_name = parsed_uri[\"database\"] self.ds", "DataStoreMongo, ) from quakestats.system import ( conf, ) logger = logging.getLogger(__name__) class SystemContext:", "self.ds_client: pymongo.MongoClient = None self.configure() def configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri)", ") logger = logging.getLogger(__name__) class SystemContext: def __init__(self): self.config = conf.cnf self.ds: DataStoreMongo", "self.configure() def configure(self): uri = conf.get_conf_val('MONGO_URI') self.ds_client = pymongo.MongoClient(uri) parsed_uri = pymongo.uri_parser.parse_uri(uri) database_name", "pymongo from quakestats.datasource.mongo2 import ( DataStoreMongo, ) from quakestats.system import ( conf, )", "( DataStoreMongo, ) from quakestats.system import ( conf, ) logger = logging.getLogger(__name__) class", "from quakestats.system import ( conf, ) logger = logging.getLogger(__name__) class SystemContext: def __init__(self):" ]
[ "= \"174379\" phone_number = \"254746468686\" lipa_na_mpesa_passkey = \"<KEY>\" consumer_key = \"ryHq5u8TIFcyps7lIYQThAP1Al0zXAcU\" consumer_secrete =", "business_shortCode = \"174379\" phone_number = \"254746468686\" lipa_na_mpesa_passkey = \"<KEY>\" consumer_key = \"ryHq5u8TIFcyps7lIYQThAP1Al0zXAcU\" consumer_secrete", "phone_number = \"254746468686\" lipa_na_mpesa_passkey = \"<KEY>\" consumer_key = \"ryHq5u8TIFcyps7lIYQThAP1Al0zXAcU\" consumer_secrete = \"O9kOqvHmN5sGViKI \"", "\"174379\" phone_number = \"254746468686\" lipa_na_mpesa_passkey = \"<KEY>\" consumer_key = \"ryHq5u8TIFcyps7lIYQThAP1Al0zXAcU\" consumer_secrete = \"O9kOqvHmN5sGViKI" ]
[ "strony źródłowej ?!\",\"public\":\"\"} if lenT2 > lenT1 and lenT1==0: return {\"private\":\"Dopisano nowy przedmiot:", "subject msg['From'] = eml_from msg['To'] = eml_to # Send the message via SMTP", "secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\") except: #raise print(\"...sending email: somethin went wrong:(\") def", "if lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn. Być może zmeniła", "L = len(T1) for i in range(0,L): if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\"", "INFO EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING", "lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn. Być może zmeniła się struktura strony", "return str(grade) def compareT(T1,T2): #T1,T2 krotka z wierszem z bazy danych (wiersz tabeli", "compareT(T1,T2): #T1,T2 krotka z wierszem z bazy danych (wiersz tabeli z ocenami starymi/nowymi)", "zm = zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z przedmiotu:", "= smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\") except: #raise print(\"...sending", "try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\") except:", "smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\") except: #raise print(\"...sending email:", "nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 == lenT2 and lenT1 == 9: zm=\"\" L", "= eml_to # Send the message via SMTP server. print(\"SENDING INFO EMAIL...\") try:", "{\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn. Być może zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"}", "może zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"} if lenT2 > lenT1 and lenT1==0:", "załadowane zostały przedmioty z nowego semestru lub zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"}", "Nieodpowiednia ilość kolumn. Być może zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"} if lenT2", "went wrong:(\") def preetyGrade(grade): if grade==\"-\": return \"brak\" else: return str(grade) def compareT(T1,T2):", "oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd.", "def compareT(T1,T2): #T1,T2 krotka z wierszem z bazy danych (wiersz tabeli z ocenami", "+\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm = zm[:-2] return", "struktura strony źródłowej ?!\",\"public\":\"\"} if lenT2 > lenT1 and lenT1==0: return {\"private\":\"Dopisano nowy", "server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\") except: #raise print(\"...sending email: somethin went wrong:(\")", "= subject msg['From'] = eml_from msg['To'] = eml_to # Send the message via", "return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")", "SMTP server. print(\"SENDING INFO EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"])", "(\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa", "except: #raise print(\"...sending email: somethin went wrong:(\") def preetyGrade(grade): if grade==\"-\": return \"brak\"", "się struktura strony źródłowej ?!\",\"public\":\"\"} if lenT2 > lenT1 and lenT1==0: return {\"private\":\"Dopisano", "krotka z wierszem z bazy danych (wiersz tabeli z ocenami starymi/nowymi) lenT1 =", "grade==\"-\": return \"brak\" else: return str(grade) def compareT(T1,T2): #T1,T2 krotka z wierszem z", "server.send_message(msg) server.quit() print(\"SENDING OK!\") except: #raise print(\"...sending email: somethin went wrong:(\") def preetyGrade(grade):", "moze załadowane zostały przedmioty z nowego semestru lub zmeniła się struktura strony źródłowej", "\" if len(zm)>1: zm = zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe", "zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm", "import smtplib from email.message import EmailMessage from credent import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message):", "\"public\":\"Możliwa nowe oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return", "len(zm)>1: zm = zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z", "zm=\"\" L = len(T1) for i in range(0,L): if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana", "tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message) msg['Subject'] = subject msg['From'] = eml_from", "if lenT2 > lenT1 and lenT1==0: return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1", "EmailMessage from credent import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message) msg['Subject']", "lenT2 and lenT1 == 9: zm=\"\" L = len(T1) for i in range(0,L):", "from email.message import EmailMessage from credent import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg =", "if grade==\"-\": return \"brak\" else: return str(grade) def compareT(T1,T2): #T1,T2 krotka z wierszem", "smtplib from email.message import EmailMessage from credent import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg", "msg['Subject'] = subject msg['From'] = eml_from msg['To'] = eml_to # Send the message", "message via SMTP server. print(\"SENDING INFO EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo()", "lenT1 and lenT1==0: return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 == lenT2 and", "= len(T1) lenT2 = len(T2) if lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia", "Być moze załadowane zostały przedmioty z nowego semestru lub zmeniła się struktura strony", "źródłowej ?!\",\"public\":\"\"} if lenT2 > lenT1 and lenT1==0: return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"}", "lenT1==0: return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 == lenT2 and lenT1 ==", "automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być moze załadowane zostały przedmioty z nowego", "Być może zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"} if lenT2 > lenT1 and", "the message via SMTP server. print(\"SENDING INFO EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"])", "msg.set_content(message) msg['Subject'] = subject msg['From'] = eml_from msg['To'] = eml_to # Send the", "z ocenami starymi/nowymi) lenT1 = len(T1) lenT2 = len(T2) if lenT1!=9 and lenT2!=9:", "in range(0,L): if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \"", "z wierszem z bazy danych (wiersz tabeli z ocenami starymi/nowymi) lenT1 = len(T1)", "bazy danych (wiersz tabeli z ocenami starymi/nowymi) lenT1 = len(T1) lenT2 = len(T2)", "import EmailMessage from credent import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message)", "lenT2 = len(T2) if lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn.", "lenT2 > lenT1 and lenT1==0: return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 ==", "eml_from msg['To'] = eml_to # Send the message via SMTP server. print(\"SENDING INFO", "EmailMessage() msg.set_content(message) msg['Subject'] = subject msg['From'] = eml_from msg['To'] = eml_to # Send", "z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być", "# Send the message via SMTP server. print(\"SENDING INFO EMAIL...\") try: server =", "zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm = zm[:-2]", "msg = EmailMessage() msg.set_content(message) msg['Subject'] = subject msg['From'] = eml_from msg['To'] = eml_to", "{\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 == lenT2 and lenT1 == 9: zm=\"\"", "len(T1) lenT2 = len(T2) if lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia ilość", "{\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie", "== lenT2 and lenT1 == 9: zm=\"\" L = len(T1) for i in", "server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\") except: #raise", "Send the message via SMTP server. print(\"SENDING INFO EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"],", "secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message) msg['Subject'] = subject msg['From'] =", "zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"} if lenT2 > lenT1 and lenT1==0: return", "OK!\") except: #raise print(\"...sending email: somethin went wrong:(\") def preetyGrade(grade): if grade==\"-\": return", "msg['To'] = eml_to # Send the message via SMTP server. print(\"SENDING INFO EMAIL...\")", "return {\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn. Być może zmeniła się struktura strony źródłowej", "if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if len(zm)>1:", "and lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn. Być może zmeniła się struktura", "lenT1 = len(T1) lenT2 = len(T2) if lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd E1.", "= zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z przedmiotu: \"+T1[1]+\"", "(wiersz tabeli z ocenami starymi/nowymi) lenT1 = len(T1) lenT2 = len(T2) if lenT1!=9", "and lenT1 == 9: zm=\"\" L = len(T1) for i in range(0,L): if(T1[i]!=T2[i]):", "return {\"private\":\"Nieokreślony błąd. Być moze załadowane zostały przedmioty z nowego semestru lub zmeniła", "preetyGrade(grade): if grade==\"-\": return \"brak\" else: return str(grade) def compareT(T1,T2): #T1,T2 krotka z", "= len(T1) for i in range(0,L): if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z", "z bazy danych (wiersz tabeli z ocenami starymi/nowymi) lenT1 = len(T1) lenT2 =", "sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message) msg['Subject'] = subject msg['From'] = eml_from msg['To'] =", "starymi/nowymi) lenT1 = len(T1) lenT2 = len(T2) if lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd", "len(T2) if lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn. Być może", "przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 == lenT2 and lenT1 == 9: zm=\"\" L =", "= eml_from msg['To'] = eml_to # Send the message via SMTP server. print(\"SENDING", "wierszem z bazy danych (wiersz tabeli z ocenami starymi/nowymi) lenT1 = len(T1) lenT2", "print(\"...sending email: somethin went wrong:(\") def preetyGrade(grade): if grade==\"-\": return \"brak\" else: return", "?!\",\"public\":\"\"} if lenT2 > lenT1 and lenT1==0: return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if", "email.message import EmailMessage from credent import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage()", "\"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne,", "def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message) msg['Subject'] = subject msg['From'] = eml_from msg['To']", "tabeli z ocenami starymi/nowymi) lenT1 = len(T1) lenT2 = len(T2) if lenT1!=9 and", "9: zm=\"\" L = len(T1) for i in range(0,L): if(T1[i]!=T2[i]): zm = zm", "= EmailMessage() msg.set_content(message) msg['Subject'] = subject msg['From'] = eml_from msg['To'] = eml_to #", "print(\"SENDING INFO EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit()", "for i in range(0,L): if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na", "kolumn. Być może zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"} if lenT2 > lenT1", "przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być moze", "\"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być moze załadowane zostały przedmioty", "WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być moze załadowane zostały przedmioty z nowego semestru lub", "from credent import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message) msg['Subject'] =", "if len(zm)>1: zm = zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny", "via SMTP server. print(\"SENDING INFO EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"],", "danych (wiersz tabeli z ocenami starymi/nowymi) lenT1 = len(T1) lenT2 = len(T2) if", "else: return str(grade) def compareT(T1,T2): #T1,T2 krotka z wierszem z bazy danych (wiersz", "return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 == lenT2 and lenT1 == 9:", "#T1,T2 krotka z wierszem z bazy danych (wiersz tabeli z ocenami starymi/nowymi) lenT1", "if lenT1 == lenT2 and lenT1 == 9: zm=\"\" L = len(T1) for", "lenT1 == 9: zm=\"\" L = len(T1) for i in range(0,L): if(T1[i]!=T2[i]): zm", "z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm = zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\"", "\"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm = zm[:-2] return {\"private\":\"Przedmiot:", "msg['From'] = eml_from msg['To'] = eml_to # Send the message via SMTP server.", "print(\"SENDING OK!\") except: #raise print(\"...sending email: somethin went wrong:(\") def preetyGrade(grade): if grade==\"-\":", "\"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm = zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\",", "len(T1) for i in range(0,L): if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\"", "\"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm = zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa", "(\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być moze załadowane zostały", "i in range(0,L): if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\",", "\"+T2[1],\"public\":\"\"} if lenT1 == lenT2 and lenT1 == 9: zm=\"\" L = len(T1)", "import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message) msg['Subject'] = subject msg['From']", "somethin went wrong:(\") def preetyGrade(grade): if grade==\"-\": return \"brak\" else: return str(grade) def", "lenT1 == lenT2 and lenT1 == 9: zm=\"\" L = len(T1) for i", "na \"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm = zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm,", "\"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"}", "def preetyGrade(grade): if grade==\"-\": return \"brak\" else: return str(grade) def compareT(T1,T2): #T1,T2 krotka", "[powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być moze załadowane zostały przedmioty z", "{\"private\":\"Nieokreślony błąd. Być moze załadowane zostały przedmioty z nowego semestru lub zmeniła się", "#raise print(\"...sending email: somethin went wrong:(\") def preetyGrade(grade): if grade==\"-\": return \"brak\" else:", "\"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być moze załadowane", "str(grade) def compareT(T1,T2): #T1,T2 krotka z wierszem z bazy danych (wiersz tabeli z", "eml_to # Send the message via SMTP server. print(\"SENDING INFO EMAIL...\") try: server", "credent import secret tb_headers=[\"id\",\"przedmiot\",\"wykladowca\",\"forma_zaliczenia\",\"rodz_zajec\",\"ocena1\",\"data1\",\"ocena2\",\"data2\"] def sendEmail(subject,eml_from,eml_to,message): msg = EmailMessage() msg.set_content(message) msg['Subject'] = subject", "= len(T2) if lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn. Być", "grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony błąd. Być moze załadowane zostały przedmioty z nowego semestru", "range(0,L): if(T1[i]!=T2[i]): zm = zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if", "ocenami starymi/nowymi) lenT1 = len(T1) lenT2 = len(T2) if lenT1!=9 and lenT2!=9: return", "and lenT1==0: return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 == lenT2 and lenT1", "wrong:(\") def preetyGrade(grade): if grade==\"-\": return \"brak\" else: return str(grade) def compareT(T1,T2): #T1,T2", "= zm +\"\\r\\nZmiana \"+tb_headers[i]+\" z \"+preetyGrade(T1[i])+\" na \"+preetyGrade(T2[i])+\", \" if len(zm)>1: zm =", "nowe oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\") [powiadomienie automatyczne, grupa WZ_INiN3_PG2]\"} return {\"private\":\"Nieokreślony", "zm[:-2] return {\"private\":\"Przedmiot: \"+T1[1]+\" (\"+T1[3]+\", \"+T1[2]+\")\"+zm, \"public\":\"Możliwa nowe oceny z przedmiotu: \"+T1[1]+\" (\"+T1[3]+\",", "secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\") except: #raise print(\"...sending email: somethin", "\"brak\" else: return str(grade) def compareT(T1,T2): #T1,T2 krotka z wierszem z bazy danych", "server.quit() print(\"SENDING OK!\") except: #raise print(\"...sending email: somethin went wrong:(\") def preetyGrade(grade): if", "EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\")", "== 9: zm=\"\" L = len(T1) for i in range(0,L): if(T1[i]!=T2[i]): zm =", "E1. Nieodpowiednia ilość kolumn. Być może zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"} if", "email: somethin went wrong:(\") def preetyGrade(grade): if grade==\"-\": return \"brak\" else: return str(grade)", "ilość kolumn. Być może zmeniła się struktura strony źródłowej ?!\",\"public\":\"\"} if lenT2 >", "> lenT1 and lenT1==0: return {\"private\":\"Dopisano nowy przedmiot: \"+T2[1],\"public\":\"\"} if lenT1 == lenT2", "błąd. Być moze załadowane zostały przedmioty z nowego semestru lub zmeniła się struktura", "server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg) server.quit() print(\"SENDING OK!\") except: #raise print(\"...sending email: somethin went", "lenT1!=9 and lenT2!=9: return {\"private\":\"Błąd E1. Nieodpowiednia ilość kolumn. Być może zmeniła się", "return \"brak\" else: return str(grade) def compareT(T1,T2): #T1,T2 krotka z wierszem z bazy", "server. print(\"SENDING INFO EMAIL...\") try: server = smtplib.SMTP(secret[\"smtp_host\"], secret[\"smtp_port\"]) server.ehlo() server.login(secret[\"smtp_login\"], secret[\"smtp_password\"]) server.send_message(msg)" ]
[ "node's NodeSet with the owner of this NodeSet. :type value: Node \"\"\" if", "root and each subsequent Node is a child. Any existing parents or children", "int :type raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\" return helpers.find_node(node=self,", "direction=direction) def find(self, condition, direction=None, raise_on_empty=False): \"\"\" Returns a single node which matches", "NodeSet and removes this NodeSet's owner from the node's NodeSets. :type value: Node", "int :type obj: Any :return: Returns `obj` (or None if no `obj` is", "and each subsequent Node is a child. Any existing parents or children will", "direction. :type direction: int :rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None):", "is supplied). :rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self, callback,", "direction, obj=None): \"\"\" Executes a depth-first traversal from this node in a given", "{}>'.format(type(self).__name__, self.data) @property def connections(self): \"\"\" Returns all parents and children associated with", "Node(object): __slots__ = ('parents', 'children', 'data') def __init__(self, data=None, parents=None, children=None): self.parents =", "root. :rtype: Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition, direction=None): \"\"\" Returns", "self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ = ('parents', 'children', 'data') def", "direction=direction, obj=obj) def root(self): \"\"\" Returns the root node of this node if", "list is the root and each subsequent Node is a child. Any existing", "owner, items, direction): \"\"\" :type owner: Node :type items: set[Node] :type direction: int", "If direction is given, only remove the node from the connected nodes in", "with no children) of this node. :rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self) def delete(self,", "is supplied). :rtype: Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def root(self): \"\"\"", "parents is None else parents, BACKWARD) self.children = NodeSet(self, [] if children is", "flatten(self, direction=None): \"\"\" Returns a list of node lists representing a path on", "-> (Any) | None :rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def", "of Nodes, with the return value being the root node. :param tree_dict: dict", "\"\"\" Returns all parents and children associated with this Node. :rtype: set[Node] \"\"\"", "given direction. :type direction: int :rtype: Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def clone(self):", "dict :type data_converter: (Any) -> (Any) | None :rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict,", "'<{} {}>'.format(type(self).__name__, self.data) @property def connections(self): \"\"\" Returns all parents and children associated", "obj=obj) def walk_links(self, callback, direction, obj=None): \"\"\" Walks the each link for this", "Converts a dict into a tree of Nodes, with the return value being", "if no `obj` is supplied). :rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj)", "__iter__(self): return iter(self.items) def __len__(self): return len(self.items) def add(self, value): \"\"\" Adds the", "from_nodes(cls, nodes): \"\"\" Creates a flat tree structure from a list of nodes.", "\"\"\" return self.parents if direction == BACKWARD else self.children def depth_first_traversal(self, callback, direction,", "`parent` NodeSet will automatically be populated with the owner of this NodeSet. \"\"\"", "it only has one root node. :rtype: Node :raises: ValueError \"\"\" roots =", "direction=direction) def roots(self): \"\"\" Returns all roots (any parent nodes with no parents)", "parent nodes with no parents) of this node. :rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self)", "self.children def depth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a depth-first traversal from this", "this NodeSet. :type value: Node \"\"\" if value not in self: value.direction(self.direction *", "(or None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback,", "populates the node's NodeSet with the owner of this NodeSet. :type value: Node", "def from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts a dict into a tree of Nodes,", "\"\"\" return helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None): \"\"\" Returns a list of node", "the node has multiple roots') return next(iter(roots)) def gather_nodes(self, direction=None): \"\"\" Returns all", "node's NodeSets. :type value: Node \"\"\" if value in self: value.direction(self.direction * -1).items.discard(self.owner)", "is supplied). :rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def walk_links(self, callback,", "\"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\" Clones the node and all its", ":rtype: Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\" Clones the node and", "__contains__(self, x): return self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ = ('parents',", "Node :raises: ValueError \"\"\" roots = self.roots() if len(roots) > 1: raise ValueError('Node.root", "Clones the node and all its child nodes and forms a new root.", "Node, object) -> () :type direction: int :type obj: Any :return: Returns `obj`", "\"\"\" A mutable set which automatically populates parent/child node sets. For example, if", "in nodes: self.add(node) def discard_many(self, nodes): for node in nodes: self.discard(node) def one(self,", "a tree of Nodes, with the return value being the root node. :param", "applicable when the node has multiple roots') return next(iter(roots)) def gather_nodes(self, direction=None): \"\"\"", "helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\" Converts this node's complete structure", "will automatically be populated with the owner of this NodeSet. \"\"\" __slots__ =", "> 1: raise ValueError('Node.root is not applicable when the node has multiple roots')", "\"\"\" return set(list(self.parents) + list(self.children)) def direction(self, direction): \"\"\" Returns this node's parents", "a flat tree structure from a list of nodes. It is assumed that", "return set(list(self.parents) + list(self.children)) def direction(self, direction): \"\"\" Returns this node's parents if", "added, that node's `parent` NodeSet will automatically be populated with the owner of", "node's parents if direction is BACKWARD, else, returns children nodes. :int direction: int", "tree. Nodes can be restricted by specifying a direction. :type direction: int :rtype:", ":rtype: Node :raises: ValueError \"\"\" roots = self.roots() if len(roots) > 1: raise", ":rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None): \"\"\" Returns a list", "nodes with no parents) of this node. :rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self) def", "for node in nodes: self.add(node) def discard_many(self, nodes): for node in nodes: self.discard(node)", "nodes with no children) of this node. :rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self) def", "Nodes, with the return value being the root node. :param tree_dict: dict :type", "in the tree. Nodes can be restricted by specifying a direction. :type direction:", "set[Node] \"\"\" return helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\" Removes this node from the", "forms a new root. :rtype: Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition,", "on set with multiple values') return next(iter(self.items), None) def __contains__(self, x): return self.items.__contains__(x)", ":type data_converter: (Any) -> (Any) | None :rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter,", "helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a breadth-first", "StopIteration will terminate the traversal. :type callback: (Node, Node, object) -> () :type", "and children associated with this Node. :rtype: set[Node] \"\"\" return set(list(self.parents) + list(self.children))", "BACKWARD = -1 # used to look at Node parents class NodeSet(MutableSet): \"\"\"", "return helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None): \"\"\" Returns a list of node lists", "cls=type(self)) def find_all(self, condition, direction=None): \"\"\" Returns all nodes which match the given", "= ('parents', 'children', 'data') def __init__(self, data=None, parents=None, children=None): self.parents = NodeSet(self, []", "data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls, nodes): \"\"\" Creates a flat tree structure from", "node has multiple roots') return next(iter(roots)) def gather_nodes(self, direction=None): \"\"\" Returns all nodes", ":rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls, nodes): \"\"\" Creates", "new root. :rtype: Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition, direction=None): \"\"\"", "obj=None): \"\"\" Walks the each link for this node. Raising a StopIteration will", "\"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self, condition, direction=None, raise_on_empty=False): \"\"\" Returns a", "automatically populates parent/child node sets. For example, if this NodeSet contains `children` nodes", "\"\"\" Returns a single node which matches the given condition. :type condition: (Node)", "= 1 # used to look at Node children BACKWARD = -1 #", "terminate the traversal. :type callback: (Node, object) -> () :type direction: int :type", "\"\"\" Returns all nodes which match the given condition. :type condition: (Node) ->", "NodeSet.one on empty set') elif len(self.items) > 1: raise ValueError('Called NodeSet.one on set", "the root node of this node if it only has one root node.", "return self.items.discard(value) def update(self, nodes): for node in nodes: self.add(node) def discard_many(self, nodes):", ":type direction: int :rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None): \"\"\"", "Returns a list of node lists representing a path on the tree. :type", "delete(self, direction=None): \"\"\" Removes this node from the NodeSets of connected nodes. If", "self.items.add(value) def discard(self, value): \"\"\" Removes the node from this NodeSet and removes", "root node. :rtype: Node :raises: ValueError \"\"\" roots = self.roots() if len(roots) >", "def breadth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a breadth-first traversal from this node", "its child nodes and forms a new root. :rtype: Node \"\"\" return helpers.clone_subtree(node=self,", ":rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts", "+ list(self.children)) def direction(self, direction): \"\"\" Returns this node's parents if direction is", "class Node(object): __slots__ = ('parents', 'children', 'data') def __init__(self, data=None, parents=None, children=None): self.parents", "Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def root(self): \"\"\" Returns the root", "Returns an item from this NodeSet if there is only one item. :type", "structure from a list of nodes. It is assumed that the first Node", "only one item. :type raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\"", "value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value) def update(self, nodes): for node in nodes: self.add(node)", "data def __repr__(self): return '<{} {}>'.format(type(self).__name__, self.data) @property def connections(self): \"\"\" Returns all", "('owner', 'items', 'direction') def __init__(self, owner, items, direction): \"\"\" :type owner: Node :type", "direction. Raising a StopIteration will terminate the traversal. :type callback: (Node, object) ->", "# used to look at Node children BACKWARD = -1 # used to", "bool :type direction: int :type raise_on_empty: bool :rtype: Node | None :raises: ValueError", "Removes the node from this NodeSet and removes this NodeSet's owner from the", "\"\"\" if value in self: value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value) def update(self, nodes):", "nodes and a new node was added, that node's `parent` NodeSet will automatically", "discard(self, value): \"\"\" Removes the node from this NodeSet and removes this NodeSet's", "parent/child node sets. For example, if this NodeSet contains `children` nodes and a", "nodes in the tree. Nodes can be restricted by specifying a direction. :type", "-> () :type direction: int :type obj: Any :return: Returns `obj` (or None", "import helpers FORWARD = 1 # used to look at Node children BACKWARD", "and populates the node's NodeSet with the owner of this NodeSet. :type value:", "NodeSet and populates the node's NodeSet with the owner of this NodeSet. :type", "supplied). :rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self, callback, direction,", ":type raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\" return helpers.find_node(node=self, condition=condition,", "from collections import MutableSet from . import helpers FORWARD = 1 # used", ":rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\" Removes this node from", "connected nodes in the given direction. :type direction: int :rtype: Node \"\"\" return", "if not self.items and raise_on_empty: raise ValueError('Called NodeSet.one on empty set') elif len(self.items)", "self.parents = NodeSet(self, [] if parents is None else parents, BACKWARD) self.children =", "@classmethod def from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts a dict into a tree of", "node to this NodeSet and populates the node's NodeSet with the owner of", "__slots__ = ('parents', 'children', 'data') def __init__(self, data=None, parents=None, children=None): self.parents = NodeSet(self,", "a dictionary. :type data_converter: (Any) -> (Any) | None :rtype: list[dict] \"\"\" return", "= NodeSet(self, [] if parents is None else parents, BACKWARD) self.children = NodeSet(self,", "was added, that node's `parent` NodeSet will automatically be populated with the owner", "node's `parent` NodeSet will automatically be populated with the owner of this NodeSet.", "the each link for this node. Raising a StopIteration will terminate the traversal.", "def leaves(self): \"\"\" Returns all leaves (any child nodes with no children) of", "self.parents if direction == BACKWARD else self.children def depth_first_traversal(self, callback, direction, obj=None): \"\"\"", "assumed that the first Node in the list is the root and each", "in nodes: self.discard(node) def one(self, raise_on_empty=False): \"\"\" Returns an item from this NodeSet", "(any parent nodes with no parents) of this node. :rtype: set[Node] \"\"\" return", "one root node. :rtype: Node :raises: ValueError \"\"\" roots = self.roots() if len(roots)", ":type data_converter: (Any) -> (Any) | None :rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter)", "direction): \"\"\" Returns this node's parents if direction is BACKWARD, else, returns children", "\"\"\" Returns all nodes in the tree. Nodes can be restricted by specifying", "tree. :type direction: int | None :rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction) def", "Adds the node to this NodeSet and populates the node's NodeSet with the", "'children', 'data') def __init__(self, data=None, parents=None, children=None): self.parents = NodeSet(self, [] if parents", "* -1).items.discard(self.owner) return self.items.discard(value) def update(self, nodes): for node in nodes: self.add(node) def", "child. Any existing parents or children will be disregarded. :type nodes: collections.Sequence[Node] :rtype:", "len(roots) > 1: raise ValueError('Node.root is not applicable when the node has multiple", "return helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\" Returns all roots (any parent nodes with", "of this NodeSet. \"\"\" __slots__ = ('owner', 'items', 'direction') def __init__(self, owner, items,", "parents, BACKWARD) self.children = NodeSet(self, [] if children is None else children, FORWARD)", "1 # used to look at Node children BACKWARD = -1 # used", "Returns this node's parents if direction is BACKWARD, else, returns children nodes. :int", "in the given direction. :type direction: int :rtype: Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction)", "direction: int :rtype: NodeSet \"\"\" return self.parents if direction == BACKWARD else self.children", "callback: (Node, object) -> () :type direction: int :type obj: Any :return: Returns", "of this node. :rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns all", "Node | None :raises: ValueError \"\"\" if not self.items and raise_on_empty: raise ValueError('Called", "a path on the tree. :type direction: int | None :rtype: list[list[treestruct.Node]] \"\"\"", "NodeSet contains `children` nodes and a new node was added, that node's `parent`", "data_converter=None): \"\"\" Converts a dict into a tree of Nodes, with the return", ". import helpers FORWARD = 1 # used to look at Node children", "self.data = data def __repr__(self): return '<{} {}>'.format(type(self).__name__, self.data) @property def connections(self): \"\"\"", "data_converter: (Any) -> (Any) | None :rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls)", "lists representing a path on the tree. :type direction: int | None :rtype:", "structure into a dictionary. :type data_converter: (Any) -> (Any) | None :rtype: list[dict]", "returns children nodes. :int direction: int :rtype: NodeSet \"\"\" return self.parents if direction", "data=None, parents=None, children=None): self.parents = NodeSet(self, [] if parents is None else parents,", "an item from this NodeSet if there is only one item. :type raise_on_empty:", "ValueError('Called NodeSet.one on empty set') elif len(self.items) > 1: raise ValueError('Called NodeSet.one on", "Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls, nodes): \"\"\" Creates a", "Any existing parents or children will be disregarded. :type nodes: collections.Sequence[Node] :rtype: Node", "obj=None): \"\"\" Executes a breadth-first traversal from this node in a given direction.", "nodes. It is assumed that the first Node in the list is the", "def to_dict(self, data_converter=None): \"\"\" Converts this node's complete structure into a dictionary. :type", "is BACKWARD, else, returns children nodes. :int direction: int :rtype: NodeSet \"\"\" return", "subsequent Node is a child. Any existing parents or children will be disregarded.", "helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\" Removes this node from the NodeSets of connected", "the node from the connected nodes in the given direction. :type direction: int", "roots(self): \"\"\" Returns all roots (any parent nodes with no parents) of this", ":type direction: int :type obj: Any :return: Returns `obj` (or None if no", "\"\"\" Walks the each link for this node. Raising a StopIteration will terminate", "parents and children associated with this Node. :rtype: set[Node] \"\"\" return set(list(self.parents) +", "node of this node if it only has one root node. :rtype: Node", ":raises: ValueError \"\"\" return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\" Converts", "owner of this NodeSet. :type value: Node \"\"\" if value not in self:", "for node in nodes: self.discard(node) def one(self, raise_on_empty=False): \"\"\" Returns an item from", "dictionary. :type data_converter: (Any) -> (Any) | None :rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self,", "root node of this node if it only has one root node. :rtype:", "nodes in the given direction. :type direction: int :rtype: Node \"\"\" return helpers.delete_node_relationships(node=self,", "a StopIteration will terminate the traversal. :type callback: (Node, Node, object) -> ()", "direction): \"\"\" :type owner: Node :type items: set[Node] :type direction: int \"\"\" self.owner", "set[Node] \"\"\" return set(list(self.parents) + list(self.children)) def direction(self, direction): \"\"\" Returns this node's", "return value being the root node. :param tree_dict: dict :type data_converter: (Any) ->", "and forms a new root. :rtype: Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self,", "helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns all leaves (any child nodes with no children)", "nodes and forms a new root. :rtype: Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def", ":type value: Node \"\"\" if value not in self: value.direction(self.direction * -1).items.add(self.owner) return", ":rtype: Node | None :raises: ValueError \"\"\" if not self.items and raise_on_empty: raise", "callback: (Node, Node, object) -> () :type direction: int :type obj: Any :return:", "= owner self.items = set() self.direction = direction self.update(items) def __iter__(self): return iter(self.items)", "is None else parents, BACKWARD) self.children = NodeSet(self, [] if children is None", "children, FORWARD) self.data = data def __repr__(self): return '<{} {}>'.format(type(self).__name__, self.data) @property def", "= self.roots() if len(roots) > 1: raise ValueError('Node.root is not applicable when the", "set(list(self.parents) + list(self.children)) def direction(self, direction): \"\"\" Returns this node's parents if direction", "Removes this node from the NodeSets of connected nodes. If direction is given,", "existing parents or children will be disregarded. :type nodes: collections.Sequence[Node] :rtype: Node \"\"\"", "def depth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a depth-first traversal from this node", "value not in self: value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value) def discard(self, value): \"\"\"", "NodeSets. :type value: Node \"\"\" if value in self: value.direction(self.direction * -1).items.discard(self.owner) return", "\"\"\" return helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\" Returns all roots (any parent nodes", "int :rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None): \"\"\" Returns a", "ValueError \"\"\" return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\" Converts this", "Returns all parents and children associated with this Node. :rtype: set[Node] \"\"\" return", "direction: int :type raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\" return", "object) -> () :type direction: int :type obj: Any :return: Returns `obj` (or", "Returns all roots (any parent nodes with no parents) of this node. :rtype:", "supplied). :rtype: Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def root(self): \"\"\" Returns", "nodes which match the given condition. :type condition: (Node) -> bool :type direction:", "direction(self, direction): \"\"\" Returns this node's parents if direction is BACKWARD, else, returns", "\"\"\" Executes a breadth-first traversal from this node in a given direction. Raising", ":type callback: (Node, Node, object) -> () :type direction: int :type obj: Any", "condition=condition, direction=direction) def find(self, condition, direction=None, raise_on_empty=False): \"\"\" Returns a single node which", "Walks the each link for this node. Raising a StopIteration will terminate the", "Executes a depth-first traversal from this node in a given direction. Raising a", "\"\"\" Returns the root node of this node if it only has one", "Node | None :raises: ValueError \"\"\" return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self,", "node lists representing a path on the tree. :type direction: int | None", "raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\" Converts this node's complete structure into a dictionary.", "direction == BACKWARD else self.children def depth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a", "set') elif len(self.items) > 1: raise ValueError('Called NodeSet.one on set with multiple values')", "Node :type items: set[Node] :type direction: int \"\"\" self.owner = owner self.items =", "data_converter=None): \"\"\" Converts this node's complete structure into a dictionary. :type data_converter: (Any)", "(Node, object) -> () :type direction: int :type obj: Any :return: Returns `obj`", "NodeSet(self, [] if parents is None else parents, BACKWARD) self.children = NodeSet(self, []", "each subsequent Node is a child. Any existing parents or children will be", "node sets. For example, if this NodeSet contains `children` nodes and a new", "None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction,", "def add(self, value): \"\"\" Adds the node to this NodeSet and populates the", "NodeSet. :type value: Node \"\"\" if value not in self: value.direction(self.direction * -1).items.add(self.owner)", "direction: int :rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None): \"\"\" Returns", "matches the given condition. :type condition: (Node) -> bool :type direction: int :type", "into a tree of Nodes, with the return value being the root node.", ":param tree_dict: dict :type data_converter: (Any) -> (Any) | None :rtype: Node \"\"\"", "raise ValueError('Called NodeSet.one on set with multiple values') return next(iter(self.items), None) def __contains__(self,", "raise_on_empty: raise ValueError('Called NodeSet.one on empty set') elif len(self.items) > 1: raise ValueError('Called", "the tree. :type direction: int | None :rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction)", "this node's parents if direction is BACKWARD, else, returns children nodes. :int direction:", "removes this NodeSet's owner from the node's NodeSets. :type value: Node \"\"\" if", "(Node, Node, object) -> () :type direction: int :type obj: Any :return: Returns", "direction, obj=None): \"\"\" Walks the each link for this node. Raising a StopIteration", "value): \"\"\" Removes the node from this NodeSet and removes this NodeSet's owner", "if it only has one root node. :rtype: Node :raises: ValueError \"\"\" roots", "direction. :type direction: int :rtype: Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\"", "the given condition. :type condition: (Node) -> bool :type direction: int :rtype: set[Node]", "NodeSet(MutableSet): \"\"\" A mutable set which automatically populates parent/child node sets. For example,", "the list is the root and each subsequent Node is a child. Any", "not in self: value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value) def discard(self, value): \"\"\" Removes", "BACKWARD) self.children = NodeSet(self, [] if children is None else children, FORWARD) self.data", "restricted by specifying a direction. :type direction: int :rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self,", "node. :rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns all leaves (any", "helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def walk_links(self, callback, direction, obj=None): \"\"\" Walks the each", "return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a", "Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\" Clones the node and all", "Returns all nodes which match the given condition. :type condition: (Node) -> bool", "NodeSets of connected nodes. If direction is given, only remove the node from", "\"\"\" Clones the node and all its child nodes and forms a new", "flat tree structure from a list of nodes. It is assumed that the", "\"\"\" Adds the node to this NodeSet and populates the node's NodeSet with", "elif len(self.items) > 1: raise ValueError('Called NodeSet.one on set with multiple values') return", "NodeSet \"\"\" return self.parents if direction == BACKWARD else self.children def depth_first_traversal(self, callback,", "Raising a StopIteration will terminate the traversal. :type callback: (Node, Node, object) ->", "or children will be disregarded. :type nodes: collections.Sequence[Node] :rtype: Node \"\"\" return helpers.node_from_node_sequence(nodes=nodes,", "clone(self): \"\"\" Clones the node and all its child nodes and forms a", "is None else children, FORWARD) self.data = data def __repr__(self): return '<{} {}>'.format(type(self).__name__,", "def update(self, nodes): for node in nodes: self.add(node) def discard_many(self, nodes): for node", "set with multiple values') return next(iter(self.items), None) def __contains__(self, x): return self.items.__contains__(x) def", "self.items and raise_on_empty: raise ValueError('Called NodeSet.one on empty set') elif len(self.items) > 1:", "from the NodeSets of connected nodes. If direction is given, only remove the", "if children is None else children, FORWARD) self.data = data def __repr__(self): return", "NodeSet. \"\"\" __slots__ = ('owner', 'items', 'direction') def __init__(self, owner, items, direction): \"\"\"", "None :rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\" Returns all roots", "nodes: self.discard(node) def one(self, raise_on_empty=False): \"\"\" Returns an item from this NodeSet if", "__slots__ = ('owner', 'items', 'direction') def __init__(self, owner, items, direction): \"\"\" :type owner:", "values') return next(iter(self.items), None) def __contains__(self, x): return self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items))", "children nodes. :int direction: int :rtype: NodeSet \"\"\" return self.parents if direction ==", "list(self.children)) def direction(self, direction): \"\"\" Returns this node's parents if direction is BACKWARD,", "the given direction. :type direction: int :rtype: Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def", "link for this node. Raising a StopIteration will terminate the traversal. :type callback:", "breadth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a breadth-first traversal from this node in", "direction=direction, obj=obj) def walk_links(self, callback, direction, obj=None): \"\"\" Walks the each link for", "of connected nodes. If direction is given, only remove the node from the", "traversal. :type callback: (Node, Node, object) -> () :type direction: int :type obj:", "direction=direction) def clone(self): \"\"\" Clones the node and all its child nodes and", "= direction self.update(items) def __iter__(self): return iter(self.items) def __len__(self): return len(self.items) def add(self,", "parents class NodeSet(MutableSet): \"\"\" A mutable set which automatically populates parent/child node sets.", "traversal. :type callback: (Node, object) -> () :type direction: int :type obj: Any", "children associated with this Node. :rtype: set[Node] \"\"\" return set(list(self.parents) + list(self.children)) def", "return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ = ('parents', 'children', 'data') def __init__(self, data=None, parents=None,", "data_converter: (Any) -> (Any) | None :rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod", "def walk_links(self, callback, direction, obj=None): \"\"\" Walks the each link for this node.", "def root(self): \"\"\" Returns the root node of this node if it only", "int | None :rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\" Returns", "at Node parents class NodeSet(MutableSet): \"\"\" A mutable set which automatically populates parent/child", "iter(self.items) def __len__(self): return len(self.items) def add(self, value): \"\"\" Adds the node to", "Node \"\"\" if value in self: value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value) def update(self,", "self.data) @property def connections(self): \"\"\" Returns all parents and children associated with this", "from this node in a given direction. Raising a StopIteration will terminate the", "Any :return: Returns `obj` (or None if no `obj` is supplied). :rtype: Any", "value being the root node. :param tree_dict: dict :type data_converter: (Any) -> (Any)", "def __repr__(self): return '<{} {}>'.format(type(self).__name__, self.data) @property def connections(self): \"\"\" Returns all parents", "NodeSet with the owner of this NodeSet. :type value: Node \"\"\" if value", "the connected nodes in the given direction. :type direction: int :rtype: Node \"\"\"", "gather_nodes(self, direction=None): \"\"\" Returns all nodes in the tree. Nodes can be restricted", "that node's `parent` NodeSet will automatically be populated with the owner of this", "self.roots() if len(roots) > 1: raise ValueError('Node.root is not applicable when the node", "obj: Any :return: Returns `obj` (or None if no `obj` is supplied). :rtype:", "helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None): \"\"\" Returns a list of node lists representing", "this NodeSet's owner from the node's NodeSets. :type value: Node \"\"\" if value", "nodes): \"\"\" Creates a flat tree structure from a list of nodes. It", "`obj` (or None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self,", "for this node. Raising a StopIteration will terminate the traversal. :type callback: (Node,", "callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a breadth-first traversal", "node from the connected nodes in the given direction. :type direction: int :rtype:", "(any child nodes with no children) of this node. :rtype: set[Node] \"\"\" return", "def __len__(self): return len(self.items) def add(self, value): \"\"\" Adds the node to this", "\"\"\" Returns a list of node lists representing a path on the tree.", "all its child nodes and forms a new root. :rtype: Node \"\"\" return", "\"\"\" Converts this node's complete structure into a dictionary. :type data_converter: (Any) ->", "raise_on_empty=False): \"\"\" Returns a single node which matches the given condition. :type condition:", "BACKWARD, else, returns children nodes. :int direction: int :rtype: NodeSet \"\"\" return self.parents", ":raises: ValueError \"\"\" if not self.items and raise_on_empty: raise ValueError('Called NodeSet.one on empty", "`obj` (or None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.walk_links_for_node(node=self,", "def roots(self): \"\"\" Returns all roots (any parent nodes with no parents) of", "\"\"\" Removes the node from this NodeSet and removes this NodeSet's owner from", "raise_on_empty=False): \"\"\" Returns an item from this NodeSet if there is only one", "FORWARD) self.data = data def __repr__(self): return '<{} {}>'.format(type(self).__name__, self.data) @property def connections(self):", "return len(self.items) def add(self, value): \"\"\" Adds the node to this NodeSet and", "Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self, callback, direction, obj=None): \"\"\"", "node which matches the given condition. :type condition: (Node) -> bool :type direction:", "leaves(self): \"\"\" Returns all leaves (any child nodes with no children) of this", "\"\"\" self.owner = owner self.items = set() self.direction = direction self.update(items) def __iter__(self):", "\"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes", "direction=None): \"\"\" Returns a list of node lists representing a path on the", "update(self, nodes): for node in nodes: self.add(node) def discard_many(self, nodes): for node in", "NodeSet(self, [] if children is None else children, FORWARD) self.data = data def", "of node lists representing a path on the tree. :type direction: int |", "condition. :type condition: (Node) -> bool :type direction: int :type raise_on_empty: bool :rtype:", "if this NodeSet contains `children` nodes and a new node was added, that", "return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls, nodes): \"\"\" Creates a flat tree", "parents=None, children=None): self.parents = NodeSet(self, [] if parents is None else parents, BACKWARD)", "of nodes. It is assumed that the first Node in the list is", "self.items = set() self.direction = direction self.update(items) def __iter__(self): return iter(self.items) def __len__(self):", "there is only one item. :type raise_on_empty: bool :rtype: Node | None :raises:", "\"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def root(self): \"\"\" Returns the root node", "all parents and children associated with this Node. :rtype: set[Node] \"\"\" return set(list(self.parents)", "return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def root(self): \"\"\" Returns the root node of", "self.owner = owner self.items = set() self.direction = direction self.update(items) def __iter__(self): return", "None else children, FORWARD) self.data = data def __repr__(self): return '<{} {}>'.format(type(self).__name__, self.data)", "a breadth-first traversal from this node in a given direction. Raising a StopIteration", "# used to look at Node parents class NodeSet(MutableSet): \"\"\" A mutable set", "has one root node. :rtype: Node :raises: ValueError \"\"\" roots = self.roots() if", "ValueError('Node.root is not applicable when the node has multiple roots') return next(iter(roots)) def", "discard_many(self, nodes): for node in nodes: self.discard(node) def one(self, raise_on_empty=False): \"\"\" Returns an", "look at Node children BACKWARD = -1 # used to look at Node", "be populated with the owner of this NodeSet. \"\"\" __slots__ = ('owner', 'items',", "with the owner of this NodeSet. \"\"\" __slots__ = ('owner', 'items', 'direction') def", "is the root and each subsequent Node is a child. Any existing parents", "not self.items and raise_on_empty: raise ValueError('Called NodeSet.one on empty set') elif len(self.items) >", "direction=None): \"\"\" Returns all nodes in the tree. Nodes can be restricted by", "a StopIteration will terminate the traversal. :type callback: (Node, object) -> () :type", "\"\"\" Returns all roots (any parent nodes with no parents) of this node.", "| None :raises: ValueError \"\"\" return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None):", "this NodeSet. \"\"\" __slots__ = ('owner', 'items', 'direction') def __init__(self, owner, items, direction):", "def __contains__(self, x): return self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ =", "next(iter(roots)) def gather_nodes(self, direction=None): \"\"\" Returns all nodes in the tree. Nodes can", "is a child. Any existing parents or children will be disregarded. :type nodes:", "return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\" Converts this node's complete", "condition, direction=None, raise_on_empty=False): \"\"\" Returns a single node which matches the given condition.", "child nodes and forms a new root. :rtype: Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self))", "self.add(node) def discard_many(self, nodes): for node in nodes: self.discard(node) def one(self, raise_on_empty=False): \"\"\"", "len(self.items) > 1: raise ValueError('Called NodeSet.one on set with multiple values') return next(iter(self.items),", "walk_links(self, callback, direction, obj=None): \"\"\" Walks the each link for this node. Raising", "\"\"\" return helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\" Removes this node from the NodeSets", "def __iter__(self): return iter(self.items) def __len__(self): return len(self.items) def add(self, value): \"\"\" Adds", "`obj` is supplied). :rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self,", "direction is given, only remove the node from the connected nodes in the", "bool :type direction: int :rtype: set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self,", "> 1: raise ValueError('Called NodeSet.one on set with multiple values') return next(iter(self.items), None)", "if value in self: value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value) def update(self, nodes): for", "[] if parents is None else parents, BACKWARD) self.children = NodeSet(self, [] if", "Converts this node's complete structure into a dictionary. :type data_converter: (Any) -> (Any)", ":int direction: int :rtype: NodeSet \"\"\" return self.parents if direction == BACKWARD else", "self.children = NodeSet(self, [] if children is None else children, FORWARD) self.data =", ":type items: set[Node] :type direction: int \"\"\" self.owner = owner self.items = set()", "\"\"\" Returns an item from this NodeSet if there is only one item.", "else, returns children nodes. :int direction: int :rtype: NodeSet \"\"\" return self.parents if", "| None :raises: ValueError \"\"\" if not self.items and raise_on_empty: raise ValueError('Called NodeSet.one", "@classmethod def from_nodes(cls, nodes): \"\"\" Creates a flat tree structure from a list", "in self: value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value) def update(self, nodes): for node in", "no parents) of this node. :rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self) def leaves(self): \"\"\"", "\"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts a dict", "contains `children` nodes and a new node was added, that node's `parent` NodeSet", "self.discard(node) def one(self, raise_on_empty=False): \"\"\" Returns an item from this NodeSet if there", ":rtype: Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition, direction=None): \"\"\" Returns all", "children will be disregarded. :type nodes: collections.Sequence[Node] :rtype: Node \"\"\" return helpers.node_from_node_sequence(nodes=nodes, cls=cls)", "__len__(self): return len(self.items) def add(self, value): \"\"\" Adds the node to this NodeSet", "(Node) -> bool :type direction: int :rtype: set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction)", "\"\"\" roots = self.roots() if len(roots) > 1: raise ValueError('Node.root is not applicable", "to this NodeSet and populates the node's NodeSet with the owner of this", "parents if direction is BACKWARD, else, returns children nodes. :int direction: int :rtype:", "ValueError('Called NodeSet.one on set with multiple values') return next(iter(self.items), None) def __contains__(self, x):", "children=None): self.parents = NodeSet(self, [] if parents is None else parents, BACKWARD) self.children", "\"\"\" return helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns all leaves (any child nodes with", "def discard_many(self, nodes): for node in nodes: self.discard(node) def one(self, raise_on_empty=False): \"\"\" Returns", "helpers FORWARD = 1 # used to look at Node children BACKWARD =", "if parents is None else parents, BACKWARD) self.children = NodeSet(self, [] if children", "this NodeSet and populates the node's NodeSet with the owner of this NodeSet.", "used to look at Node parents class NodeSet(MutableSet): \"\"\" A mutable set which", "direction: int :type obj: Any :return: Returns `obj` (or None if no `obj`", "a single node which matches the given condition. :type condition: (Node) -> bool", "\"\"\" return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\" Converts this node's", "-1).items.add(self.owner) return self.items.add(value) def discard(self, value): \"\"\" Removes the node from this NodeSet", "condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\" Converts this node's complete structure into", "example, if this NodeSet contains `children` nodes and a new node was added,", "condition. :type condition: (Node) -> bool :type direction: int :rtype: set[Node] \"\"\" return", "in the list is the root and each subsequent Node is a child.", "add(self, value): \"\"\" Adds the node to this NodeSet and populates the node's", "find(self, condition, direction=None, raise_on_empty=False): \"\"\" Returns a single node which matches the given", "def delete(self, direction=None): \"\"\" Removes this node from the NodeSets of connected nodes.", "the traversal. :type callback: (Node, object) -> () :type direction: int :type obj:", "= data def __repr__(self): return '<{} {}>'.format(type(self).__name__, self.data) @property def connections(self): \"\"\" Returns", "def find_all(self, condition, direction=None): \"\"\" Returns all nodes which match the given condition.", "def find(self, condition, direction=None, raise_on_empty=False): \"\"\" Returns a single node which matches the", "one item. :type raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\" if", "\"\"\" if not self.items and raise_on_empty: raise ValueError('Called NodeSet.one on empty set') elif", "with multiple values') return next(iter(self.items), None) def __contains__(self, x): return self.items.__contains__(x) def __repr__(self):", "a list of nodes. It is assumed that the first Node in the", "can be restricted by specifying a direction. :type direction: int :rtype: set[Node] \"\"\"", "will terminate the traversal. :type callback: (Node, Node, object) -> () :type direction:", "(Any) | None :rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls,", "if value not in self: value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value) def discard(self, value):", "from . import helpers FORWARD = 1 # used to look at Node", "tree of Nodes, with the return value being the root node. :param tree_dict:", "\"\"\" Creates a flat tree structure from a list of nodes. It is", "None :raises: ValueError \"\"\" return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\"", "tree_dict, data_converter=None): \"\"\" Converts a dict into a tree of Nodes, with the", "is assumed that the first Node in the list is the root and", "first Node in the list is the root and each subsequent Node is", "this node's complete structure into a dictionary. :type data_converter: (Any) -> (Any) |", "\"\"\" Returns all leaves (any child nodes with no children) of this node.", "callback, direction, obj=None): \"\"\" Walks the each link for this node. Raising a", "list of nodes. It is assumed that the first Node in the list", "else self.children def depth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a depth-first traversal from", "all nodes in the tree. Nodes can be restricted by specifying a direction.", "this node. :rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\" Removes this", "from a list of nodes. It is assumed that the first Node in", "def gather_nodes(self, direction=None): \"\"\" Returns all nodes in the tree. Nodes can be", "owner self.items = set() self.direction = direction self.update(items) def __iter__(self): return iter(self.items) def", "direction is BACKWARD, else, returns children nodes. :int direction: int :rtype: NodeSet \"\"\"", "value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value) def discard(self, value): \"\"\" Removes the node from", "the owner of this NodeSet. \"\"\" __slots__ = ('owner', 'items', 'direction') def __init__(self,", "single node which matches the given condition. :type condition: (Node) -> bool :type", "def flatten(self, direction=None): \"\"\" Returns a list of node lists representing a path", "the owner of this NodeSet. :type value: Node \"\"\" if value not in", "(Any) -> (Any) | None :rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod", "from the node's NodeSets. :type value: Node \"\"\" if value in self: value.direction(self.direction", ":rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def breadth_first_traversal(self, callback, direction, obj=None):", "-> bool :type direction: int :type raise_on_empty: bool :rtype: Node | None :raises:", "('parents', 'children', 'data') def __init__(self, data=None, parents=None, children=None): self.parents = NodeSet(self, [] if", "look at Node parents class NodeSet(MutableSet): \"\"\" A mutable set which automatically populates", "return next(iter(self.items), None) def __contains__(self, x): return self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class", "value): \"\"\" Adds the node to this NodeSet and populates the node's NodeSet", "import MutableSet from . import helpers FORWARD = 1 # used to look", "this NodeSet if there is only one item. :type raise_on_empty: bool :rtype: Node", "__repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ = ('parents', 'children', 'data') def __init__(self, data=None,", "root(self): \"\"\" Returns the root node of this node if it only has", "set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self, condition, direction=None, raise_on_empty=False): \"\"\" Returns", "leaves (any child nodes with no children) of this node. :rtype: set[Node] \"\"\"", "helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\" Clones the node and all its child nodes", "cls=cls) @classmethod def from_nodes(cls, nodes): \"\"\" Creates a flat tree structure from a", "this node from the NodeSets of connected nodes. If direction is given, only", "def direction(self, direction): \"\"\" Returns this node's parents if direction is BACKWARD, else,", "root node. :param tree_dict: dict :type data_converter: (Any) -> (Any) | None :rtype:", "on the tree. :type direction: int | None :rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self,", "bool :rtype: Node | None :raises: ValueError \"\"\" if not self.items and raise_on_empty:", "\"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition, direction=None): \"\"\" Returns all nodes which", "None :raises: ValueError \"\"\" if not self.items and raise_on_empty: raise ValueError('Called NodeSet.one on", "and a new node was added, that node's `parent` NodeSet will automatically be", "__repr__(self): return '<{} {}>'.format(type(self).__name__, self.data) @property def connections(self): \"\"\" Returns all parents and", "int :rtype: Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\" Clones the node", "in a given direction. Raising a StopIteration will terminate the traversal. :type callback:", ":type direction: int :rtype: Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\" Clones", "node in nodes: self.discard(node) def one(self, raise_on_empty=False): \"\"\" Returns an item from this", "nodes: self.add(node) def discard_many(self, nodes): for node in nodes: self.discard(node) def one(self, raise_on_empty=False):", "Returns all leaves (any child nodes with no children) of this node. :rtype:", "a new root. :rtype: Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition, direction=None):", "tree_dict: dict :type data_converter: (Any) -> (Any) | None :rtype: Node \"\"\" return", "Node \"\"\" return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition, direction=None): \"\"\" Returns all nodes", "direction, obj=None): \"\"\" Executes a breadth-first traversal from this node in a given", ":raises: ValueError \"\"\" roots = self.roots() if len(roots) > 1: raise ValueError('Node.root is", "with the return value being the root node. :param tree_dict: dict :type data_converter:", "list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts a", "1: raise ValueError('Called NodeSet.one on set with multiple values') return next(iter(self.items), None) def", "depth-first traversal from this node in a given direction. Raising a StopIteration will", "representing a path on the tree. :type direction: int | None :rtype: list[list[treestruct.Node]]", "item. :type raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\" if not", "of this NodeSet. :type value: Node \"\"\" if value not in self: value.direction(self.direction", "the traversal. :type callback: (Node, Node, object) -> () :type direction: int :type", "obj=None): \"\"\" Executes a depth-first traversal from this node in a given direction.", "helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def root(self): \"\"\" Returns the root node of this", "is given, only remove the node from the connected nodes in the given", "helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self, condition, direction=None, raise_on_empty=False): \"\"\" Returns a single node", "It is assumed that the first Node in the list is the root", "will terminate the traversal. :type callback: (Node, object) -> () :type direction: int", "populates parent/child node sets. For example, if this NodeSet contains `children` nodes and", "Nodes can be restricted by specifying a direction. :type direction: int :rtype: set[Node]", ":rtype: NodeSet \"\"\" return self.parents if direction == BACKWARD else self.children def depth_first_traversal(self,", "new node was added, that node's `parent` NodeSet will automatically be populated with", ":rtype: Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def root(self): \"\"\" Returns the", "populated with the owner of this NodeSet. \"\"\" __slots__ = ('owner', 'items', 'direction')", "return self.parents if direction == BACKWARD else self.children def depth_first_traversal(self, callback, direction, obj=None):", "value: Node \"\"\" if value in self: value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value) def", "path on the tree. :type direction: int | None :rtype: list[list[treestruct.Node]] \"\"\" return", "raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\" if not self.items and", "node if it only has one root node. :rtype: Node :raises: ValueError \"\"\"", "with no parents) of this node. :rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self) def leaves(self):", "def __init__(self, data=None, parents=None, children=None): self.parents = NodeSet(self, [] if parents is None", "None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction,", "at Node children BACKWARD = -1 # used to look at Node parents", "def discard(self, value): \"\"\" Removes the node from this NodeSet and removes this", "not applicable when the node has multiple roots') return next(iter(roots)) def gather_nodes(self, direction=None):", "the node to this NodeSet and populates the node's NodeSet with the owner", "multiple values') return next(iter(self.items), None) def __contains__(self, x): return self.items.__contains__(x) def __repr__(self): return", ":type value: Node \"\"\" if value in self: value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value)", "bool :rtype: Node | None :raises: ValueError \"\"\" return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty)", "return helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns all leaves (any child nodes with no", "int :rtype: NodeSet \"\"\" return self.parents if direction == BACKWARD else self.children def", "Raising a StopIteration will terminate the traversal. :type callback: (Node, object) -> ()", "the given condition. :type condition: (Node) -> bool :type direction: int :type raise_on_empty:", "direction=direction, raise_on_empty=raise_on_empty) def to_dict(self, data_converter=None): \"\"\" Converts this node's complete structure into a", "a depth-first traversal from this node in a given direction. Raising a StopIteration", "direction: int :rtype: set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self, condition, direction=None,", ":rtype: set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self, condition, direction=None, raise_on_empty=False): \"\"\"", "return '<{} {}>'.format(type(self).__name__, self.data) @property def connections(self): \"\"\" Returns all parents and children", "raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\" return helpers.find_node(node=self, condition=condition, direction=direction,", "| None :rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls, nodes):", "a new node was added, that node's `parent` NodeSet will automatically be populated", "`obj` is supplied). :rtype: Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def root(self):", "\"\"\" if value not in self: value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value) def discard(self,", "of this node. :rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\" Removes", "node from this NodeSet and removes this NodeSet's owner from the node's NodeSets.", ":type direction: int :rtype: set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self, condition,", "only remove the node from the connected nodes in the given direction. :type", "\"\"\" Converts a dict into a tree of Nodes, with the return value", "and removes this NodeSet's owner from the node's NodeSets. :type value: Node \"\"\"", "the node's NodeSets. :type value: Node \"\"\" if value in self: value.direction(self.direction *", "BACKWARD else self.children def depth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a depth-first traversal", "multiple roots') return next(iter(roots)) def gather_nodes(self, direction=None): \"\"\" Returns all nodes in the", "None :rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls, tree_dict, data_converter=None): \"\"\"", "empty set') elif len(self.items) > 1: raise ValueError('Called NodeSet.one on set with multiple", "list of node lists representing a path on the tree. :type direction: int", "sets. For example, if this NodeSet contains `children` nodes and a new node", "one(self, raise_on_empty=False): \"\"\" Returns an item from this NodeSet if there is only", "nodes): for node in nodes: self.discard(node) def one(self, raise_on_empty=False): \"\"\" Returns an item", "Returns the root node of this node if it only has one root", "node and all its child nodes and forms a new root. :rtype: Node", "this node. Raising a StopIteration will terminate the traversal. :type callback: (Node, Node,", "def connections(self): \"\"\" Returns all parents and children associated with this Node. :rtype:", "condition: (Node) -> bool :type direction: int :type raise_on_empty: bool :rtype: Node |", "roots') return next(iter(roots)) def gather_nodes(self, direction=None): \"\"\" Returns all nodes in the tree.", "node in nodes: self.add(node) def discard_many(self, nodes): for node in nodes: self.discard(node) def", "NodeSet.one on set with multiple values') return next(iter(self.items), None) def __contains__(self, x): return", "= -1 # used to look at Node parents class NodeSet(MutableSet): \"\"\" A", "callback=callback, direction=direction, obj=obj) def walk_links(self, callback, direction, obj=None): \"\"\" Walks the each link", "node. :rtype: Node :raises: ValueError \"\"\" roots = self.roots() if len(roots) > 1:", "this node. :rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns all leaves", "given, only remove the node from the connected nodes in the given direction.", ":type condition: (Node) -> bool :type direction: int :type raise_on_empty: bool :rtype: Node", "Node in the list is the root and each subsequent Node is a", "node was added, that node's `parent` NodeSet will automatically be populated with the", "if no `obj` is supplied). :rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj)", ":type direction: int :type raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\"", "ValueError \"\"\" if not self.items and raise_on_empty: raise ValueError('Called NodeSet.one on empty set')", "given condition. :type condition: (Node) -> bool :type direction: int :rtype: set[Node] \"\"\"", "callback, direction, obj=None): \"\"\" Executes a breadth-first traversal from this node in a", "Creates a flat tree structure from a list of nodes. It is assumed", "== BACKWARD else self.children def depth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a depth-first", "ValueError \"\"\" roots = self.roots() if len(roots) > 1: raise ValueError('Node.root is not", "* -1).items.add(self.owner) return self.items.add(value) def discard(self, value): \"\"\" Removes the node from this", "which match the given condition. :type condition: (Node) -> bool :type direction: int", "(Node) -> bool :type direction: int :type raise_on_empty: bool :rtype: Node | None", "children) of this node. :rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\"", "-1 # used to look at Node parents class NodeSet(MutableSet): \"\"\" A mutable", "item from this NodeSet if there is only one item. :type raise_on_empty: bool", "set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction) def flatten(self, direction=None): \"\"\" Returns a list of", "roots (any parent nodes with no parents) of this node. :rtype: set[Node] \"\"\"", "= set() self.direction = direction self.update(items) def __iter__(self): return iter(self.items) def __len__(self): return", "given direction. Raising a StopIteration will terminate the traversal. :type callback: (Node, object)", "only has one root node. :rtype: Node :raises: ValueError \"\"\" roots = self.roots()", "Node. :rtype: set[Node] \"\"\" return set(list(self.parents) + list(self.children)) def direction(self, direction): \"\"\" Returns", "self.direction = direction self.update(items) def __iter__(self): return iter(self.items) def __len__(self): return len(self.items) def", "if there is only one item. :type raise_on_empty: bool :rtype: Node | None", "nodes. :int direction: int :rtype: NodeSet \"\"\" return self.parents if direction == BACKWARD", "automatically be populated with the owner of this NodeSet. \"\"\" __slots__ = ('owner',", "if direction is BACKWARD, else, returns children nodes. :int direction: int :rtype: NodeSet", "else children, FORWARD) self.data = data def __repr__(self): return '<{} {}>'.format(type(self).__name__, self.data) @property", "Returns all nodes in the tree. Nodes can be restricted by specifying a", "(or None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback,", "parents) of this node. :rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns", "this node if it only has one root node. :rtype: Node :raises: ValueError", "return self.items.add(value) def discard(self, value): \"\"\" Removes the node from this NodeSet and", "self.items.discard(value) def update(self, nodes): for node in nodes: self.add(node) def discard_many(self, nodes): for", "all nodes which match the given condition. :type condition: (Node) -> bool :type", "Node is a child. Any existing parents or children will be disregarded. :type", "remove the node from the connected nodes in the given direction. :type direction:", "() :type direction: int :type obj: Any :return: Returns `obj` (or None if", "self: value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value) def update(self, nodes): for node in nodes:", "FORWARD = 1 # used to look at Node children BACKWARD = -1", "items, direction): \"\"\" :type owner: Node :type items: set[Node] :type direction: int \"\"\"", "connections(self): \"\"\" Returns all parents and children associated with this Node. :rtype: set[Node]", "match the given condition. :type condition: (Node) -> bool :type direction: int :rtype:", "each link for this node. Raising a StopIteration will terminate the traversal. :type", "which matches the given condition. :type condition: (Node) -> bool :type direction: int", "in self: value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value) def discard(self, value): \"\"\" Removes the", "helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\" Returns all roots (any parent nodes with no", "which automatically populates parent/child node sets. For example, if this NodeSet contains `children`", "a dict into a tree of Nodes, with the return value being the", "on empty set') elif len(self.items) > 1: raise ValueError('Called NodeSet.one on set with", "this NodeSet and removes this NodeSet's owner from the node's NodeSets. :type value:", "dict into a tree of Nodes, with the return value being the root", "from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts a dict into a tree of Nodes, with", "this Node. :rtype: set[Node] \"\"\" return set(list(self.parents) + list(self.children)) def direction(self, direction): \"\"\"", "obj=obj) def breadth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a breadth-first traversal from this", "value in self: value.direction(self.direction * -1).items.discard(self.owner) return self.items.discard(value) def update(self, nodes): for node", "-> (Any) | None :rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls,", "self.update(items) def __iter__(self): return iter(self.items) def __len__(self): return len(self.items) def add(self, value): \"\"\"", "Executes a breadth-first traversal from this node in a given direction. Raising a", "direction: int :rtype: Node \"\"\" return helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\" Clones the", "helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition, direction=None): \"\"\" Returns all nodes which match the", "this NodeSet contains `children` nodes and a new node was added, that node's", "items: set[Node] :type direction: int \"\"\" self.owner = owner self.items = set() self.direction", "def __init__(self, owner, items, direction): \"\"\" :type owner: Node :type items: set[Node] :type", "is only one item. :type raise_on_empty: bool :rtype: Node | None :raises: ValueError", "complete structure into a dictionary. :type data_converter: (Any) -> (Any) | None :rtype:", "direction: int \"\"\" self.owner = owner self.items = set() self.direction = direction self.update(items)", "children is None else children, FORWARD) self.data = data def __repr__(self): return '<{}", "return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def walk_links(self, callback, direction, obj=None): \"\"\" Walks the", "raise ValueError('Called NodeSet.one on empty set') elif len(self.items) > 1: raise ValueError('Called NodeSet.one", "and all its child nodes and forms a new root. :rtype: Node \"\"\"", "with this Node. :rtype: set[Node] \"\"\" return set(list(self.parents) + list(self.children)) def direction(self, direction):", "direction=direction, obj=obj) def breadth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a breadth-first traversal from", "= ('owner', 'items', 'direction') def __init__(self, owner, items, direction): \"\"\" :type owner: Node", "len(self.items) def add(self, value): \"\"\" Adds the node to this NodeSet and populates", "Node children BACKWARD = -1 # used to look at Node parents class", "the first Node in the list is the root and each subsequent Node", "return self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ = ('parents', 'children', 'data')", "\"\"\" Removes this node from the NodeSets of connected nodes. If direction is", ":rtype: set[Node] \"\"\" return helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns all leaves (any child", ":type raise_on_empty: bool :rtype: Node | None :raises: ValueError \"\"\" if not self.items", "x): return self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ = ('parents', 'children',", "\"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def walk_links(self, callback, direction, obj=None): \"\"\" Walks", "(Any) -> (Any) | None :rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def", "the return value being the root node. :param tree_dict: dict :type data_converter: (Any)", "and raise_on_empty: raise ValueError('Called NodeSet.one on empty set') elif len(self.items) > 1: raise", "set[Node] \"\"\" return helpers.roots_for_node(node=self) def leaves(self): \"\"\" Returns all leaves (any child nodes", "condition: (Node) -> bool :type direction: int :rtype: set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition,", "__init__(self, owner, items, direction): \"\"\" :type owner: Node :type items: set[Node] :type direction:", "has multiple roots') return next(iter(roots)) def gather_nodes(self, direction=None): \"\"\" Returns all nodes in", "data_converter=data_converter) @classmethod def from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts a dict into a tree", "return helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\" Removes this node from the NodeSets of", "'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ = ('parents', 'children', 'data') def __init__(self, data=None, parents=None, children=None):", "direction self.update(items) def __iter__(self): return iter(self.items) def __len__(self): return len(self.items) def add(self, value):", "child nodes with no children) of this node. :rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self)", "owner: Node :type items: set[Node] :type direction: int \"\"\" self.owner = owner self.items", "@property def connections(self): \"\"\" Returns all parents and children associated with this Node.", "from this NodeSet and removes this NodeSet's owner from the node's NodeSets. :type", "collections import MutableSet from . import helpers FORWARD = 1 # used to", "owner from the node's NodeSets. :type value: Node \"\"\" if value in self:", ":type direction: int \"\"\" self.owner = owner self.items = set() self.direction = direction", "a direction. :type direction: int :rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction) def flatten(self,", ":type direction: int | None :rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction) def roots(self):", ":rtype: Node | None :raises: ValueError \"\"\" return helpers.find_node(node=self, condition=condition, direction=direction, raise_on_empty=raise_on_empty) def", "For example, if this NodeSet contains `children` nodes and a new node was", "this node in a given direction. Raising a StopIteration will terminate the traversal.", "Node parents class NodeSet(MutableSet): \"\"\" A mutable set which automatically populates parent/child node", "set[Node] :type direction: int \"\"\" self.owner = owner self.items = set() self.direction =", "node. Raising a StopIteration will terminate the traversal. :type callback: (Node, Node, object)", "the node and all its child nodes and forms a new root. :rtype:", "next(iter(self.items), None) def __contains__(self, x): return self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object):", "Returns `obj` (or None if no `obj` is supplied). :rtype: Any \"\"\" return", "no `obj` is supplied). :rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def", "be restricted by specifying a direction. :type direction: int :rtype: set[Node] \"\"\" return", "NodeSet's owner from the node's NodeSets. :type value: Node \"\"\" if value in", "None) def __contains__(self, x): return self.items.__contains__(x) def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__", "the NodeSets of connected nodes. If direction is given, only remove the node", "raise ValueError('Node.root is not applicable when the node has multiple roots') return next(iter(roots))", "roots = self.roots() if len(roots) > 1: raise ValueError('Node.root is not applicable when", "= NodeSet(self, [] if children is None else children, FORWARD) self.data = data", "traversal from this node in a given direction. Raising a StopIteration will terminate", "nodes. If direction is given, only remove the node from the connected nodes", "node from the NodeSets of connected nodes. If direction is given, only remove", "int :rtype: set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self, condition, direction=None, raise_on_empty=False):", "def from_nodes(cls, nodes): \"\"\" Creates a flat tree structure from a list of", "the tree. Nodes can be restricted by specifying a direction. :type direction: int", "node's complete structure into a dictionary. :type data_converter: (Any) -> (Any) | None", "(Any) | None :rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls, tree_dict,", "return helpers.clone_subtree(node=self, cls=type(self)) def find_all(self, condition, direction=None): \"\"\" Returns all nodes which match", "direction=direction) def flatten(self, direction=None): \"\"\" Returns a list of node lists representing a", "\"\"\" :type owner: Node :type items: set[Node] :type direction: int \"\"\" self.owner =", "mutable set which automatically populates parent/child node sets. For example, if this NodeSet", ":rtype: set[Node] \"\"\" return set(list(self.parents) + list(self.children)) def direction(self, direction): \"\"\" Returns this", "callback, direction, obj=None): \"\"\" Executes a depth-first traversal from this node in a", "def one(self, raise_on_empty=False): \"\"\" Returns an item from this NodeSet if there is", "given condition. :type condition: (Node) -> bool :type direction: int :type raise_on_empty: bool", "`obj` (or None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self,", "is not applicable when the node has multiple roots') return next(iter(roots)) def gather_nodes(self,", ":type condition: (Node) -> bool :type direction: int :rtype: set[Node] \"\"\" return helpers.find_nodes(node=self,", "to_dict(self, data_converter=None): \"\"\" Converts this node's complete structure into a dictionary. :type data_converter:", ":type obj: Any :return: Returns `obj` (or None if no `obj` is supplied).", "None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback, direction=direction,", "Node \"\"\" if value not in self: value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value) def", ":return: Returns `obj` (or None if no `obj` is supplied). :rtype: Any \"\"\"", "return helpers.find_nodes(node=self, condition=condition, direction=direction) def find(self, condition, direction=None, raise_on_empty=False): \"\"\" Returns a single", "direction: int | None :rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\"", "set() self.direction = direction self.update(items) def __iter__(self): return iter(self.items) def __len__(self): return len(self.items)", "value: Node \"\"\" if value not in self: value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value)", "__init__(self, data=None, parents=None, children=None): self.parents = NodeSet(self, [] if parents is None else", "nodes): for node in nodes: self.add(node) def discard_many(self, nodes): for node in nodes:", "| None :rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\" Returns all", "'data') def __init__(self, data=None, parents=None, children=None): self.parents = NodeSet(self, [] if parents is", "-1).items.discard(self.owner) return self.items.discard(value) def update(self, nodes): for node in nodes: self.add(node) def discard_many(self,", "NodeSet will automatically be populated with the owner of this NodeSet. \"\"\" __slots__", "self: value.direction(self.direction * -1).items.add(self.owner) return self.items.add(value) def discard(self, value): \"\"\" Removes the node", "def __repr__(self): return 'NodeSet{}'.format(tuple(self.items)) class Node(object): __slots__ = ('parents', 'children', 'data') def __init__(self,", "helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls, nodes): \"\"\" Creates a flat tree structure", "`obj` is supplied). :rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def walk_links(self,", "node in a given direction. Raising a StopIteration will terminate the traversal. :type", "by specifying a direction. :type direction: int :rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction)", ":type owner: Node :type items: set[Node] :type direction: int \"\"\" self.owner = owner", "all leaves (any child nodes with no children) of this node. :rtype: set[Node]", "None else parents, BACKWARD) self.children = NodeSet(self, [] if children is None else", ":rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def walk_links(self, callback, direction, obj=None):", "the root and each subsequent Node is a child. Any existing parents or", "None :rtype: Node \"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls, nodes): \"\"\"", "terminate the traversal. :type callback: (Node, Node, object) -> () :type direction: int", "to look at Node parents class NodeSet(MutableSet): \"\"\" A mutable set which automatically", "find_all(self, condition, direction=None): \"\"\" Returns all nodes which match the given condition. :type", "'items', 'direction') def __init__(self, owner, items, direction): \"\"\" :type owner: Node :type items:", "if direction == BACKWARD else self.children def depth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes", "no `obj` is supplied). :rtype: Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj) def", "from this NodeSet if there is only one item. :type raise_on_empty: bool :rtype:", "if no `obj` is supplied). :rtype: Any \"\"\" return helpers.walk_links_for_node(node=self, callback=callback, direction=direction, obj=obj)", "all roots (any parent nodes with no parents) of this node. :rtype: set[Node]", "int \"\"\" self.owner = owner self.items = set() self.direction = direction self.update(items) def", "StopIteration will terminate the traversal. :type callback: (Node, object) -> () :type direction:", "supplied). :rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def walk_links(self, callback, direction,", "direction=None): \"\"\" Removes this node from the NodeSets of connected nodes. If direction", "\"\"\" return helpers.from_dict(tree_dict=tree_dict, data_converter=data_converter, cls=cls) @classmethod def from_nodes(cls, nodes): \"\"\" Creates a flat", "breadth-first traversal from this node in a given direction. Raising a StopIteration will", "MutableSet from . import helpers FORWARD = 1 # used to look at", "owner of this NodeSet. \"\"\" __slots__ = ('owner', 'items', 'direction') def __init__(self, owner,", "\"\"\" __slots__ = ('owner', 'items', 'direction') def __init__(self, owner, items, direction): \"\"\" :type", "Returns a single node which matches the given condition. :type condition: (Node) ->", "tree structure from a list of nodes. It is assumed that the first", "[] if children is None else children, FORWARD) self.data = data def __repr__(self):", ":rtype: list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\" Returns all roots (any", "else parents, BACKWARD) self.children = NodeSet(self, [] if children is None else children,", "callback=callback, direction=direction, obj=obj) def root(self): \"\"\" Returns the root node of this node", "Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def walk_links(self, callback, direction, obj=None): \"\"\"", "return next(iter(roots)) def gather_nodes(self, direction=None): \"\"\" Returns all nodes in the tree. Nodes", "-> bool :type direction: int :rtype: set[Node] \"\"\" return helpers.find_nodes(node=self, condition=condition, direction=direction) def", "helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts a dict into a", "return iter(self.items) def __len__(self): return len(self.items) def add(self, value): \"\"\" Adds the node", "when the node has multiple roots') return next(iter(roots)) def gather_nodes(self, direction=None): \"\"\" Returns", "that the first Node in the list is the root and each subsequent", "`children` nodes and a new node was added, that node's `parent` NodeSet will", "NodeSet if there is only one item. :type raise_on_empty: bool :rtype: Node |", "direction=None, raise_on_empty=False): \"\"\" Returns a single node which matches the given condition. :type", "class NodeSet(MutableSet): \"\"\" A mutable set which automatically populates parent/child node sets. For", "node. :rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self) def delete(self, direction=None): \"\"\" Removes this node", "a list of node lists representing a path on the tree. :type direction:", "\"\"\" Executes a depth-first traversal from this node in a given direction. Raising", "specifying a direction. :type direction: int :rtype: set[Node] \"\"\" return helpers.gather_nodes(node=self, direction=direction) def", "the node's NodeSet with the owner of this NodeSet. :type value: Node \"\"\"", "(or None if no `obj` is supplied). :rtype: Any \"\"\" return helpers.depth_first_traversal_for_node(node=self, callback=callback,", "connected nodes. If direction is given, only remove the node from the connected", "A mutable set which automatically populates parent/child node sets. For example, if this", "set which automatically populates parent/child node sets. For example, if this NodeSet contains", "associated with this Node. :rtype: set[Node] \"\"\" return set(list(self.parents) + list(self.children)) def direction(self,", "| None :rtype: list[dict] \"\"\" return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls, tree_dict, data_converter=None):", "the node from this NodeSet and removes this NodeSet's owner from the node's", "depth_first_traversal(self, callback, direction, obj=None): \"\"\" Executes a depth-first traversal from this node in", "\"\"\" Returns this node's parents if direction is BACKWARD, else, returns children nodes.", "a given direction. Raising a StopIteration will terminate the traversal. :type callback: (Node,", "return helpers.delete_node_relationships(node=self, direction=direction) def clone(self): \"\"\" Clones the node and all its child", "parents or children will be disregarded. :type nodes: collections.Sequence[Node] :rtype: Node \"\"\" return", "used to look at Node children BACKWARD = -1 # used to look", "list[list[treestruct.Node]] \"\"\" return helpers.flatten_from_node(node=self, direction=direction) def roots(self): \"\"\" Returns all roots (any parent", "condition, direction=None): \"\"\" Returns all nodes which match the given condition. :type condition:", "of this node if it only has one root node. :rtype: Node :raises:", "to look at Node children BACKWARD = -1 # used to look at", "node. :param tree_dict: dict :type data_converter: (Any) -> (Any) | None :rtype: Node", "if len(roots) > 1: raise ValueError('Node.root is not applicable when the node has", "def clone(self): \"\"\" Clones the node and all its child nodes and forms", "into a dictionary. :type data_converter: (Any) -> (Any) | None :rtype: list[dict] \"\"\"", "from the connected nodes in the given direction. :type direction: int :rtype: Node", "the root node. :param tree_dict: dict :type data_converter: (Any) -> (Any) | None", "no `obj` is supplied). :rtype: Any \"\"\" return helpers.breadth_first_traversal_for_node(node=self, callback=callback, direction=direction, obj=obj) def", "no children) of this node. :rtype: set[Node] \"\"\" return helpers.leaves_for_node(node=self) def delete(self, direction=None):", "return helpers.to_dict_from_node(node=self, data_converter=data_converter) @classmethod def from_dict(cls, tree_dict, data_converter=None): \"\"\" Converts a dict into", "1: raise ValueError('Node.root is not applicable when the node has multiple roots') return", "with the owner of this NodeSet. :type value: Node \"\"\" if value not", "children BACKWARD = -1 # used to look at Node parents class NodeSet(MutableSet):", "being the root node. :param tree_dict: dict :type data_converter: (Any) -> (Any) |", "obj=obj) def root(self): \"\"\" Returns the root node of this node if it", "'direction') def __init__(self, owner, items, direction): \"\"\" :type owner: Node :type items: set[Node]", ":type callback: (Node, object) -> () :type direction: int :type obj: Any :return:", "direction=None): \"\"\" Returns all nodes which match the given condition. :type condition: (Node)", "a child. Any existing parents or children will be disregarded. :type nodes: collections.Sequence[Node]" ]
[]
[ "'apikey' headers = usajobs.connect(email=email, apikey=apikey) assert headers == {'Host': 'data.usajobs.gov', 'User-Agent': 'email', 'Authorization-Key':", "headers = usajobs.connect(email=email, apikey=apikey) assert headers == {'Host': 'data.usajobs.gov', 'User-Agent': 'email', 'Authorization-Key': 'apikey'}", "<gh_stars>1-10 import usajobs import pytest def test_connect(): email, apikey = 'email', 'apikey' headers", "import pytest def test_connect(): email, apikey = 'email', 'apikey' headers = usajobs.connect(email=email, apikey=apikey)", "'email', 'apikey' headers = usajobs.connect(email=email, apikey=apikey) assert headers == {'Host': 'data.usajobs.gov', 'User-Agent': 'email',", "usajobs import pytest def test_connect(): email, apikey = 'email', 'apikey' headers = usajobs.connect(email=email,", "= 'email', 'apikey' headers = usajobs.connect(email=email, apikey=apikey) assert headers == {'Host': 'data.usajobs.gov', 'User-Agent':", "pytest def test_connect(): email, apikey = 'email', 'apikey' headers = usajobs.connect(email=email, apikey=apikey) assert", "import usajobs import pytest def test_connect(): email, apikey = 'email', 'apikey' headers =", "apikey = 'email', 'apikey' headers = usajobs.connect(email=email, apikey=apikey) assert headers == {'Host': 'data.usajobs.gov',", "def test_connect(): email, apikey = 'email', 'apikey' headers = usajobs.connect(email=email, apikey=apikey) assert headers", "email, apikey = 'email', 'apikey' headers = usajobs.connect(email=email, apikey=apikey) assert headers == {'Host':", "test_connect(): email, apikey = 'email', 'apikey' headers = usajobs.connect(email=email, apikey=apikey) assert headers ==" ]
[ "for processing. nproc : The number of workers to use for parallelization. output_pkl", ": The list of file paths to the reader outputs to be processed.", "mode to use for processing. nproc : The number of workers to use", "grounding_mode : The type of grounding mode to use for processing. nproc :", "chunk_size = 10 process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = []", "from indra.statements import Statement from indra_world.sources import eidos, hume, sofia logger = logging.getLogger(__name__)", "output_pkl : The path to an output pickle file in which to dump", "Mapping, Optional from multiprocessing import Pool from indra.statements import Statement from indra_world.sources import", "reader: str, dart_ids: Mapping[str, str] = None, extract_filter: List[str] = None, grounding_mode: str", "logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool closed and joined.') if output_pkl: logger.info(f'Writing", "of statements to extract. grounding_mode : The type of grounding mode to use", "str = None) -> List[Statement]: \"\"\"Process a set of reader outputs in parallel.", "dart_ids=None, **kwargs): if reader == 'eidos': pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree = None", "reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = [] for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size),", "Statement from indra_world.sources import eidos, hume, sofia logger = logging.getLogger(__name__) def _reader_wrapper(fname, reader,", "fname in the fnames list to a DART document ID. These are then", "path to an output pickle file in which to dump the statements extracted", "The type of grounding mode to use for processing. nproc : The number", "Mapping[str, str] = None, extract_filter: List[str] = None, grounding_mode: str = 'compositional', nproc:", ": The name of the reader which produced the outputs. dart_ids : A", "output_pkl: logger.info(f'Writing into {output_pkl}') with open(output_pkl, 'wb') as fh: pickle.dump(stmts, fh) return stmts", "= hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id = dart_ids.get(fname) for stmt in pr.statements: for", "and joined.') if output_pkl: logger.info(f'Writing into {output_pkl}') with open(output_pkl, 'wb') as fh: pickle.dump(stmts,", "res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts += res logger.debug('Closing pool...') pool.close() logger.debug('Joining", "for ev in stmt.evidence: ev.text_refs['DART'] = dart_id return pr.statements def process_reader_outputs(fnames: List[str], reader:", "= None) -> List[Statement]: \"\"\"Process a set of reader outputs in parallel. Parameters", "reader which produced the outputs. dart_ids : A dict which maps each fname", "= None elif reader == 'sofia': pr = sofia.process_json_file(fname, **kwargs) elif reader ==", "use for processing. nproc : The number of workers to use for parallelization.", "Returns ------- : The list of statements extracted from the outputs. \"\"\" if", "+= res logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool closed and joined.') if", "pool...') pool.join() logger.info('Pool closed and joined.') if output_pkl: logger.info(f'Writing into {output_pkl}') with open(output_pkl,", "'compositional', nproc: int = 8, output_pkl: str = None) -> List[Statement]: \"\"\"Process a", "ev.text_refs['DART'] = dart_id return pr.statements def process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str, str]", "import logging import functools from typing import List, Mapping, Optional from multiprocessing import", "pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool closed and joined.') if output_pkl: logger.info(f'Writing into {output_pkl}')", "extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = [] for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts", "The list of file paths to the reader outputs to be processed. reader", "str, dart_ids: Mapping[str, str] = None, extract_filter: List[str] = None, grounding_mode: str =", "**kwargs): if reader == 'eidos': pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree = None elif", "to use for processing. nproc : The number of workers to use for", "['influence'] pool = Pool(nproc) chunk_size = 10 process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter,", "list of statements extracted from the outputs. \"\"\" if extract_filter is None: extract_filter", "_reader_wrapper(fname, reader, dart_ids=None, **kwargs): if reader == 'eidos': pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree", "= dart_id return pr.statements def process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str, str] =", "= eidos.process_json_file(fname, **kwargs) pr.doc.tree = None elif reader == 'sofia': pr = sofia.process_json_file(fname,", "= sofia.process_json_file(fname, **kwargs) elif reader == 'hume': pr = hume.process_jsonld_file(fname, **kwargs) if dart_ids:", "stmt in pr.statements: for ev in stmt.evidence: ev.text_refs['DART'] = dart_id return pr.statements def", "the fnames list to a DART document ID. These are then set in", "logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None, **kwargs): if reader == 'eidos': pr = eidos.process_json_file(fname,", "total=len(fnames)): stmts += res logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool closed and", "indra_world.sources import eidos, hume, sofia logger = logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None, **kwargs):", "reader == 'eidos': pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree = None elif reader ==", "to the reader outputs to be processed. reader : The name of the", "def process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str, str] = None, extract_filter: List[str] =", "elif reader == 'sofia': pr = sofia.process_json_file(fname, **kwargs) elif reader == 'hume': pr", "dart_ids : A dict which maps each fname in the fnames list to", "---------- fnames : The list of file paths to the reader outputs to", "extracted from the outputs. \"\"\" if extract_filter is None: extract_filter = ['influence'] pool", "is None: extract_filter = ['influence'] pool = Pool(nproc) chunk_size = 10 process_fun =", "import List, Mapping, Optional from multiprocessing import Pool from indra.statements import Statement from", "process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = [] for res in", "functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = [] for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames,", "def _reader_wrapper(fname, reader, dart_ids=None, **kwargs): if reader == 'eidos': pr = eidos.process_json_file(fname, **kwargs)", "the reader outputs to be processed. reader : The name of the reader", "-> List[Statement]: \"\"\"Process a set of reader outputs in parallel. Parameters ---------- fnames", "import Statement from indra_world.sources import eidos, hume, sofia logger = logging.getLogger(__name__) def _reader_wrapper(fname,", "= None, extract_filter: List[str] = None, grounding_mode: str = 'compositional', nproc: int =", "which produced the outputs. dart_ids : A dict which maps each fname in", "pickle import logging import functools from typing import List, Mapping, Optional from multiprocessing", "stmts = [] for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts += res", "in which to dump the statements extracted from the outputs. Returns ------- :", "sofia.process_json_file(fname, **kwargs) elif reader == 'hume': pr = hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id", "hume, sofia logger = logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None, **kwargs): if reader ==", "to an output pickle file in which to dump the statements extracted from", "= None, grounding_mode: str = 'compositional', nproc: int = 8, output_pkl: str =", "paths to the reader outputs to be processed. reader : The name of", "document ID. These are then set in the evidences of statements exxtracted from", "Parameters ---------- fnames : The list of file paths to the reader outputs", "stmt.evidence: ev.text_refs['DART'] = dart_id return pr.statements def process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str,", "for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts += res logger.debug('Closing pool...') pool.close()", "pool...') pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool closed and joined.') if output_pkl: logger.info(f'Writing into", "of the reader which produced the outputs. dart_ids : A dict which maps", "exxtracted from the output. extract_filter : What types of statements to extract. grounding_mode", "= ['influence'] pool = Pool(nproc) chunk_size = 10 process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids,", "of reader outputs in parallel. Parameters ---------- fnames : The list of file", "in the fnames list to a DART document ID. These are then set", "= [] for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts += res logger.debug('Closing", "dart_ids.get(fname) for stmt in pr.statements: for ev in stmt.evidence: ev.text_refs['DART'] = dart_id return", "pool = Pool(nproc) chunk_size = 10 process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode)", "dart_id = dart_ids.get(fname) for stmt in pr.statements: for ev in stmt.evidence: ev.text_refs['DART'] =", "fnames : The list of file paths to the reader outputs to be", "logger.info('Pool closed and joined.') if output_pkl: logger.info(f'Writing into {output_pkl}') with open(output_pkl, 'wb') as", "dict which maps each fname in the fnames list to a DART document", "of grounding mode to use for processing. nproc : The number of workers", "str = 'compositional', nproc: int = 8, output_pkl: str = None) -> List[Statement]:", "\"\"\"Process a set of reader outputs in parallel. Parameters ---------- fnames : The", "stmts += res logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool closed and joined.')", "= Pool(nproc) chunk_size = 10 process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts", "return pr.statements def process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str, str] = None, extract_filter:", "nproc : The number of workers to use for parallelization. output_pkl : The", "outputs. \"\"\" if extract_filter is None: extract_filter = ['influence'] pool = Pool(nproc) chunk_size", "== 'hume': pr = hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id = dart_ids.get(fname) for stmt", "DART document ID. These are then set in the evidences of statements exxtracted", "None, extract_filter: List[str] = None, grounding_mode: str = 'compositional', nproc: int = 8,", "'eidos': pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree = None elif reader == 'sofia': pr", "statements extracted from the outputs. Returns ------- : The list of statements extracted", "eidos.process_json_file(fname, **kwargs) pr.doc.tree = None elif reader == 'sofia': pr = sofia.process_json_file(fname, **kwargs)", "set in the evidences of statements exxtracted from the output. extract_filter : What", "to a DART document ID. These are then set in the evidences of", "reader outputs in parallel. Parameters ---------- fnames : The list of file paths", "for parallelization. output_pkl : The path to an output pickle file in which", "extract_filter = ['influence'] pool = Pool(nproc) chunk_size = 10 process_fun = functools.partial(_reader_wrapper, reader=reader,", "logging import functools from typing import List, Mapping, Optional from multiprocessing import Pool", "reader == 'sofia': pr = sofia.process_json_file(fname, **kwargs) elif reader == 'hume': pr =", "8, output_pkl: str = None) -> List[Statement]: \"\"\"Process a set of reader outputs", "file paths to the reader outputs to be processed. reader : The name", ": A dict which maps each fname in the fnames list to a", "of statements exxtracted from the output. extract_filter : What types of statements to", "multiprocessing import Pool from indra.statements import Statement from indra_world.sources import eidos, hume, sofia", "= dart_ids.get(fname) for stmt in pr.statements: for ev in stmt.evidence: ev.text_refs['DART'] = dart_id", "from the output. extract_filter : What types of statements to extract. grounding_mode :", "the output. extract_filter : What types of statements to extract. grounding_mode : The", "logger.debug('Joining pool...') pool.join() logger.info('Pool closed and joined.') if output_pkl: logger.info(f'Writing into {output_pkl}') with", "outputs. dart_ids : A dict which maps each fname in the fnames list", "which maps each fname in the fnames list to a DART document ID.", "dart_ids: dart_id = dart_ids.get(fname) for stmt in pr.statements: for ev in stmt.evidence: ev.text_refs['DART']", "which to dump the statements extracted from the outputs. Returns ------- : The", "tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts += res logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...') pool.join()", "output pickle file in which to dump the statements extracted from the outputs.", "in stmt.evidence: ev.text_refs['DART'] = dart_id return pr.statements def process_reader_outputs(fnames: List[str], reader: str, dart_ids:", "None) -> List[Statement]: \"\"\"Process a set of reader outputs in parallel. Parameters ----------", "= logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None, **kwargs): if reader == 'eidos': pr =", "logger = logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None, **kwargs): if reader == 'eidos': pr", "10 process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = [] for res", "= 'compositional', nproc: int = 8, output_pkl: str = None) -> List[Statement]: \"\"\"Process", "of statements extracted from the outputs. \"\"\" if extract_filter is None: extract_filter =", "outputs to be processed. reader : The name of the reader which produced", "**kwargs) elif reader == 'hume': pr = hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id =", "A dict which maps each fname in the fnames list to a DART", "workers to use for parallelization. output_pkl : The path to an output pickle", "functools from typing import List, Mapping, Optional from multiprocessing import Pool from indra.statements", "**kwargs) if dart_ids: dart_id = dart_ids.get(fname) for stmt in pr.statements: for ev in", "None elif reader == 'sofia': pr = sofia.process_json_file(fname, **kwargs) elif reader == 'hume':", "pr.statements: for ev in stmt.evidence: ev.text_refs['DART'] = dart_id return pr.statements def process_reader_outputs(fnames: List[str],", "reader, dart_ids=None, **kwargs): if reader == 'eidos': pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree =", "extract_filter: List[str] = None, grounding_mode: str = 'compositional', nproc: int = 8, output_pkl:", "processing. nproc : The number of workers to use for parallelization. output_pkl :", "import tqdm import pickle import logging import functools from typing import List, Mapping,", "number of workers to use for parallelization. output_pkl : The path to an", "the outputs. Returns ------- : The list of statements extracted from the outputs.", "ID. These are then set in the evidences of statements exxtracted from the", "hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id = dart_ids.get(fname) for stmt in pr.statements: for ev", "== 'sofia': pr = sofia.process_json_file(fname, **kwargs) elif reader == 'hume': pr = hume.process_jsonld_file(fname,", "output_pkl: str = None) -> List[Statement]: \"\"\"Process a set of reader outputs in", "'hume': pr = hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id = dart_ids.get(fname) for stmt in", "from indra_world.sources import eidos, hume, sofia logger = logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None,", "str] = None, extract_filter: List[str] = None, grounding_mode: str = 'compositional', nproc: int", "each fname in the fnames list to a DART document ID. These are", "file in which to dump the statements extracted from the outputs. Returns -------", "dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = [] for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)):", "if output_pkl: logger.info(f'Writing into {output_pkl}') with open(output_pkl, 'wb') as fh: pickle.dump(stmts, fh) return", "in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts += res logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...')", ": The type of grounding mode to use for processing. nproc : The", "------- : The list of statements extracted from the outputs. \"\"\" if extract_filter", "produced the outputs. dart_ids : A dict which maps each fname in the", "The list of statements extracted from the outputs. \"\"\" if extract_filter is None:", "in parallel. Parameters ---------- fnames : The list of file paths to the", "extracted from the outputs. Returns ------- : The list of statements extracted from", "of workers to use for parallelization. output_pkl : The path to an output", "type of grounding mode to use for processing. nproc : The number of", "List[str], reader: str, dart_ids: Mapping[str, str] = None, extract_filter: List[str] = None, grounding_mode:", "reader : The name of the reader which produced the outputs. dart_ids :", "Pool(nproc) chunk_size = 10 process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts =", "List[Statement]: \"\"\"Process a set of reader outputs in parallel. Parameters ---------- fnames :", "= 10 process_fun = functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = [] for", "What types of statements to extract. grounding_mode : The type of grounding mode", ": The path to an output pickle file in which to dump the", "if extract_filter is None: extract_filter = ['influence'] pool = Pool(nproc) chunk_size = 10", "chunksize=chunk_size), total=len(fnames)): stmts += res logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool closed", "from the outputs. \"\"\" if extract_filter is None: extract_filter = ['influence'] pool =", "extract. grounding_mode : The type of grounding mode to use for processing. nproc", "import eidos, hume, sofia logger = logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None, **kwargs): if", "pool.join() logger.info('Pool closed and joined.') if output_pkl: logger.info(f'Writing into {output_pkl}') with open(output_pkl, 'wb')", "in the evidences of statements exxtracted from the output. extract_filter : What types", "**kwargs) pr.doc.tree = None elif reader == 'sofia': pr = sofia.process_json_file(fname, **kwargs) elif", "= functools.partial(_reader_wrapper, reader=reader, dart_ids=dart_ids, extract_filter=extract_filter, grounding_mode=grounding_mode) stmts = [] for res in tqdm.tqdm(pool.imap_unordered(process_fun,", "None: extract_filter = ['influence'] pool = Pool(nproc) chunk_size = 10 process_fun = functools.partial(_reader_wrapper,", "joined.') if output_pkl: logger.info(f'Writing into {output_pkl}') with open(output_pkl, 'wb') as fh: pickle.dump(stmts, fh)", "for stmt in pr.statements: for ev in stmt.evidence: ev.text_refs['DART'] = dart_id return pr.statements", "parallel. Parameters ---------- fnames : The list of file paths to the reader", "The path to an output pickle file in which to dump the statements", "import Pool from indra.statements import Statement from indra_world.sources import eidos, hume, sofia logger", "outputs in parallel. Parameters ---------- fnames : The list of file paths to", "pickle file in which to dump the statements extracted from the outputs. Returns", "dart_id return pr.statements def process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str, str] = None,", "fnames, chunksize=chunk_size), total=len(fnames)): stmts += res logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool", "output. extract_filter : What types of statements to extract. grounding_mode : The type", "\"\"\" if extract_filter is None: extract_filter = ['influence'] pool = Pool(nproc) chunk_size =", "closed and joined.') if output_pkl: logger.info(f'Writing into {output_pkl}') with open(output_pkl, 'wb') as fh:", ": What types of statements to extract. grounding_mode : The type of grounding", "reader outputs to be processed. reader : The name of the reader which", "pr.statements def process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str, str] = None, extract_filter: List[str]", "pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree = None elif reader == 'sofia': pr =", "name of the reader which produced the outputs. dart_ids : A dict which", "a DART document ID. These are then set in the evidences of statements", "reader == 'hume': pr = hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id = dart_ids.get(fname) for", "These are then set in the evidences of statements exxtracted from the output.", "grounding_mode=grounding_mode) stmts = [] for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts +=", "to use for parallelization. output_pkl : The path to an output pickle file", "to dump the statements extracted from the outputs. Returns ------- : The list", "fnames list to a DART document ID. These are then set in the", "the evidences of statements exxtracted from the output. extract_filter : What types of", ": The number of workers to use for parallelization. output_pkl : The path", "extract_filter is None: extract_filter = ['influence'] pool = Pool(nproc) chunk_size = 10 process_fun", "if dart_ids: dart_id = dart_ids.get(fname) for stmt in pr.statements: for ev in stmt.evidence:", "pr = sofia.process_json_file(fname, **kwargs) elif reader == 'hume': pr = hume.process_jsonld_file(fname, **kwargs) if", "res logger.debug('Closing pool...') pool.close() logger.debug('Joining pool...') pool.join() logger.info('Pool closed and joined.') if output_pkl:", "parallelization. output_pkl : The path to an output pickle file in which to", "eidos, hume, sofia logger = logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None, **kwargs): if reader", "list of file paths to the reader outputs to be processed. reader :", "of file paths to the reader outputs to be processed. reader : The", "to extract. grounding_mode : The type of grounding mode to use for processing.", "use for parallelization. output_pkl : The path to an output pickle file in", "import pickle import logging import functools from typing import List, Mapping, Optional from", "from typing import List, Mapping, Optional from multiprocessing import Pool from indra.statements import", "sofia logger = logging.getLogger(__name__) def _reader_wrapper(fname, reader, dart_ids=None, **kwargs): if reader == 'eidos':", "List[str] = None, grounding_mode: str = 'compositional', nproc: int = 8, output_pkl: str", "grounding_mode: str = 'compositional', nproc: int = 8, output_pkl: str = None) ->", "indra.statements import Statement from indra_world.sources import eidos, hume, sofia logger = logging.getLogger(__name__) def", "int = 8, output_pkl: str = None) -> List[Statement]: \"\"\"Process a set of", "Pool from indra.statements import Statement from indra_world.sources import eidos, hume, sofia logger =", "the reader which produced the outputs. dart_ids : A dict which maps each", "if reader == 'eidos': pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree = None elif reader", "statements extracted from the outputs. \"\"\" if extract_filter is None: extract_filter = ['influence']", "pr.doc.tree = None elif reader == 'sofia': pr = sofia.process_json_file(fname, **kwargs) elif reader", "pr = hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id = dart_ids.get(fname) for stmt in pr.statements:", "import functools from typing import List, Mapping, Optional from multiprocessing import Pool from", "then set in the evidences of statements exxtracted from the output. extract_filter :", "the outputs. \"\"\" if extract_filter is None: extract_filter = ['influence'] pool = Pool(nproc)", "be processed. reader : The name of the reader which produced the outputs.", "extract_filter : What types of statements to extract. grounding_mode : The type of", "outputs. Returns ------- : The list of statements extracted from the outputs. \"\"\"", "dart_ids: Mapping[str, str] = None, extract_filter: List[str] = None, grounding_mode: str = 'compositional',", "maps each fname in the fnames list to a DART document ID. These", "statements exxtracted from the output. extract_filter : What types of statements to extract.", "types of statements to extract. grounding_mode : The type of grounding mode to", "[] for res in tqdm.tqdm(pool.imap_unordered(process_fun, fnames, chunksize=chunk_size), total=len(fnames)): stmts += res logger.debug('Closing pool...')", "= 8, output_pkl: str = None) -> List[Statement]: \"\"\"Process a set of reader", "to be processed. reader : The name of the reader which produced the", "typing import List, Mapping, Optional from multiprocessing import Pool from indra.statements import Statement", "== 'eidos': pr = eidos.process_json_file(fname, **kwargs) pr.doc.tree = None elif reader == 'sofia':", ": The list of statements extracted from the outputs. \"\"\" if extract_filter is", "dump the statements extracted from the outputs. Returns ------- : The list of", "set of reader outputs in parallel. Parameters ---------- fnames : The list of", "List, Mapping, Optional from multiprocessing import Pool from indra.statements import Statement from indra_world.sources", "process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str, str] = None, extract_filter: List[str] = None,", "elif reader == 'hume': pr = hume.process_jsonld_file(fname, **kwargs) if dart_ids: dart_id = dart_ids.get(fname)", "The number of workers to use for parallelization. output_pkl : The path to", "Optional from multiprocessing import Pool from indra.statements import Statement from indra_world.sources import eidos,", "from multiprocessing import Pool from indra.statements import Statement from indra_world.sources import eidos, hume,", "the statements extracted from the outputs. Returns ------- : The list of statements", "ev in stmt.evidence: ev.text_refs['DART'] = dart_id return pr.statements def process_reader_outputs(fnames: List[str], reader: str,", "a set of reader outputs in parallel. Parameters ---------- fnames : The list", "grounding mode to use for processing. nproc : The number of workers to", "nproc: int = 8, output_pkl: str = None) -> List[Statement]: \"\"\"Process a set", "the outputs. dart_ids : A dict which maps each fname in the fnames", "None, grounding_mode: str = 'compositional', nproc: int = 8, output_pkl: str = None)", "in pr.statements: for ev in stmt.evidence: ev.text_refs['DART'] = dart_id return pr.statements def process_reader_outputs(fnames:", "from the outputs. Returns ------- : The list of statements extracted from the", "The name of the reader which produced the outputs. dart_ids : A dict", "an output pickle file in which to dump the statements extracted from the", "'sofia': pr = sofia.process_json_file(fname, **kwargs) elif reader == 'hume': pr = hume.process_jsonld_file(fname, **kwargs)", "statements to extract. grounding_mode : The type of grounding mode to use for", "evidences of statements exxtracted from the output. extract_filter : What types of statements", "tqdm import pickle import logging import functools from typing import List, Mapping, Optional", "processed. reader : The name of the reader which produced the outputs. dart_ids", "list to a DART document ID. These are then set in the evidences", "are then set in the evidences of statements exxtracted from the output. extract_filter" ]
[ "ok to continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__ == \"__main__\": root", "__on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok = False self.destroy() def __on_click_confirm(self): self.__ok", "you really want to continue ?\\nPress ok to continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\",", "self.__header @property def message(self): return self.__message @property def on_close(self): return self.__on_close @property def", "import Confirmation def my_handler(result): print(result) root = tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\",", "black and the BODY's background to red: options = { BODY: {\"background\": \"red\"},", "that you want to set the LABEL_MESSAGE's background to black and the BODY's", "This callback should accept a boolean positional argument. True means Ok, confirmed. -", "None def _build(self): self._body = tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def", "if user confirmed, else get False \"\"\" return self.__ok @property def parts(self): \"\"\"", "if self.__geometry: self.geometry(self.__geometry) # if self.__header: label_header = tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER,", "Confirmation(tk.Toplevel): \"\"\" Confirmation is a dialog box to ask the user to confirm", "action. Example: import tkinter as tk from megawidget import Confirmation def my_handler(result): print(result)", "frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) # button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM]", "self.__header: label_header = tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X,", "return self.message class _ConfirmTest(Viewable): def __init__(self, root): super().__init__() self._root = root self._body =", "widget parent. Example: an instance of tk.Frame - title: title of dialog box", "if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok = False self.destroy() def __on_click_confirm(self): self.__ok =", "==================================== # PROPERTIES # ==================================== @property def header(self): return self.__header @property def message(self):", "tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you", "PARAMETERS: - master: widget parent. Example: an instance of tk.Frame - title: title", "button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel", "master=None, title=None, header=None, message=None, on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS: - master: widget parent.", "to show as header - message: the text to show as message -", "you really want to continue ?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\" def __init__(self, master=None,", "merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header = header self.__message = message", "return self.__on_close @property def ok(self): \"\"\" Returns True if user confirmed, else get", "are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the presence of key", "= True self.destroy() class Error(Exception): def __init__(self, *args, **kwargs): self.message = args[0] if", "to build this dialog. This property returns a dict. The keys are: BODY,", "anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10)) # frame_footer", "padx=2) # button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT)", "= \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation is a dialog box to ask the", "- handler: a callback to be executed immediately after closing the dialog box.", "handler=my_handler) confirmation.build() root.mainloop() \"\"\" def __init__(self, master=None, title=None, header=None, message=None, on_close=None, geometry=None, megaconfig=None):", "\"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header = header", "the dialog box is a toplevel (BODY), you can edit its geometry. Example:", "_ConfirmTest(Viewable): def __init__(self, root): super().__init__() self._root = root self._body = None def _build(self):", "LABEL_HEADER = \"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM", "the presence of key before usage \"\"\" return self.__parts # ==================================== # INTERNAL", "text to show as header - message: the text to show as message", "message=None, on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS: - master: widget parent. Example: an instance", "__setup(self): custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def __build(self): self.title(self.__title) self.resizable(0,", "geometry self.__parts = {} self.__ok = False # build self.__setup() # ==================================== #", "returns a dict. The keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning:", "self.__on_close = on_close self.__geometry = geometry self.__parts = {} self.__ok = False #", "LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title =", "label_header = tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1,", "tk import tkutil from viewable import Viewable, CustomView from tkutil import merge_megaconfig #", "header: the text to show as header - message: the text to show", "# PROPERTIES # ==================================== @property def header(self): return self.__header @property def message(self): return", "should accept a boolean positional argument. True means Ok, confirmed. - geometry: str,", "self.__ok @property def parts(self): \"\"\" Get the parts (widgets instances) used to build", "to show as message - handler: a callback to be executed immediately after", "LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the presence of key before usage \"\"\"", "- title: title of dialog box - header: the text to show as", "presence of key before usage \"\"\" return self.__parts # ==================================== # INTERNAL #", "after closing the dialog box. This callback should accept a boolean positional argument.", "on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def __build(self): self.title(self.__title) self.resizable(0, 0) # # if self.__geometry:", "handler: a callback to be executed immediately after closing the dialog box. This", "\"\"\" Confirmation is a dialog box to ask the user to confirm an", "if self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message", "class Confirmation(tk.Toplevel): \"\"\" Confirmation is a dialog box to ask the user to", "self.title(self.__title) self.resizable(0, 0) # # if self.__geometry: self.geometry(self.__geometry) # if self.__header: label_header =", "user to confirm an action. Example: import tkinter as tk from megawidget import", "argument. True means Ok, confirmed. - geometry: str, as the dialog box is", "The widgets keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that", "text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5)", "self._body = tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation =", "the text to show as message - handler: a callback to be executed", "tkinter as tk from megawidget import Confirmation def my_handler(result): print(result) root = tk.Tk()", "def ok(self): \"\"\" Returns True if user confirmed, else get False \"\"\" return", "to confirm an action. Example: import tkinter as tk from megawidget import Confirmation", "parts(self): \"\"\" Get the parts (widgets instances) used to build this dialog. This", "import Viewable, CustomView from tkutil import merge_megaconfig # parts BODY = \"body\" LABEL_HEADER", "executed immediately after closing the dialog box. This callback should accept a boolean", "self.__geometry: self.geometry(self.__geometry) # if self.__header: label_header = tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER))", "text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really", "on_close(self): return self.__on_close @property def ok(self): \"\"\" Returns True if user confirmed, else", "_on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\\nPress", "= tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) # button_confirm =", "cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) # button_confirm = tk.Button(frame_footer, text=\"Confirmation\",", "to ask the user to confirm an action. Example: import tkinter as tk", "toplevel (BODY), you can edit its geometry. Example: \"500x300\" - options: dictionary of", "btn_launch.pack() def _on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to", "label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5) # if self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE,", "edit its geometry. Example: \"500x300\" - options: dictionary of widgets options The widgets", "\"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation is a", "pady=(0, 2), padx=2) # button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] =", "\"\"\" def __init__(self, master=None, title=None, header=None, message=None, on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS: -", "megawidget import Confirmation def my_handler(result): print(result) root = tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\",", "= message self.__on_close = on_close self.__geometry = geometry self.__parts = {} self.__ok =", "BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation is a dialog box to ask", "= None def _build(self): self._body = tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack()", "super().__init__(self.message) def __str__(self): return self.message class _ConfirmTest(Viewable): def __init__(self, root): super().__init__() self._root =", "pady=5, padx=5) # if self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE))", "= { BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig)", "dialog. This property returns a dict. The keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER,", "Warning: check the presence of key before usage \"\"\" return self.__parts # ====================================", "= \"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL =", "= merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header = header self.__message =", "self.__message = message self.__on_close = on_close self.__geometry = geometry self.__parts = {} self.__ok", "header(self): return self.__header @property def message(self): return self.__message @property def on_close(self): return self.__on_close", "box - header: the text to show as header - message: the text", "are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that you want to", "label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5) # if self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message,", "PROPERTIES # ==================================== @property def header(self): return self.__header @property def message(self): return self.__message", "\"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL = \"button_cancel\"", "confirmation.build() root.mainloop() \"\"\" def __init__(self, master=None, title=None, header=None, message=None, on_close=None, geometry=None, megaconfig=None): \"\"\"", "want to set the LABEL_MESSAGE's background to black and the BODY's background to", "dictionary of widgets options The widgets keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL,", "LABEL_MESSAGE's background to black and the BODY's background to red: options = {", "frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) # button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM))", "continue ?\\nPress ok to continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__ ==", "return self.__header @property def message(self): return self.__message @property def on_close(self): return self.__on_close @property", "\"\"\" Returns True if user confirmed, else get False \"\"\" return self.__ok @property", "= tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5,", "= button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close:", "confirmed, else get False \"\"\" return self.__ok @property def parts(self): \"\"\" Get the", "really want to continue ?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\" def __init__(self, master=None, title=None,", "button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok)", "self.__title = title self.__header = header self.__message = message self.__on_close = on_close self.__geometry", "a dialog box to ask the user to confirm an action. Example: import", "to black and the BODY's background to red: options = { BODY: {\"background\":", "= label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5) # if self.__message: label_message = tk.Label(self,", "self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5) # if self.__message: label_message =", "def __on_click_confirm(self): self.__ok = True self.destroy() class Error(Exception): def __init__(self, *args, **kwargs): self.message", "as message - handler: a callback to be executed immediately after closing the", "red: options = { BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\" self.__megaconfig", "?\\nPress ok to continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__ == \"__main__\":", "command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want", "# button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) #", "def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok =", "BUTTON_CONFIRM Warning: check the presence of key before usage \"\"\" return self.__parts #", "title=None, header=None, message=None, on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS: - master: widget parent. Example:", "text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self,", "tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\",", "\"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title", "= Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\", handler=my_handler) confirmation.build()", "an action. Example: import tkinter as tk from megawidget import Confirmation def my_handler(result):", "INTERNAL # ==================================== def __setup(self): custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build()", "expand=1, anchor=\"w\", pady=5, padx=5) # if self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\",", "my_handler(result): print(result) root = tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really", "def parts(self): \"\"\" Get the parts (widgets instances) used to build this dialog.", "build self.__setup() # ==================================== # PROPERTIES # ==================================== @property def header(self): return self.__header", "= title self.__header = header self.__message = message self.__on_close = on_close self.__geometry =", "geometry: str, as the dialog box is a toplevel (BODY), you can edit", "\"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\"", "\"\"\" Get the parts (widgets instances) used to build this dialog. This property", "{\"background\": \"black\"} } \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title", "command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def", "message=\"Do you really want to continue ?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\" def __init__(self,", "else \"\" super().__init__(self.message) def __str__(self): return self.message class _ConfirmTest(Viewable): def __init__(self, root): super().__init__()", "as tk from megawidget import Confirmation def my_handler(result): print(result) root = tk.Tk() confirmation", "the user to confirm an action. Example: import tkinter as tk from megawidget", "tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5,", "BODY's background to red: options = { BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"}", "The keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the presence", "within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok = False self.destroy() def", "dialog box - header: the text to show as header - message: the", "get False \"\"\" return self.__ok @property def parts(self): \"\"\" Get the parts (widgets", "{} self.__ok = False # build self.__setup() # ==================================== # PROPERTIES # ====================================", "= \"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel):", "property returns a dict. The keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM", "title of dialog box - header: the text to show as header -", "\"\"\" return self.__parts # ==================================== # INTERNAL # ==================================== def __setup(self): custom_view =", "accept a boolean positional argument. True means Ok, confirmed. - geometry: str, as", "to continue ?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\" def __init__(self, master=None, title=None, header=None, message=None,", "def __str__(self): return self.message class _ConfirmTest(Viewable): def __init__(self, root): super().__init__() self._root = root", "# button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0,", "FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the presence of key before usage \"\"\" return", "and the BODY's background to red: options = { BODY: {\"background\": \"red\"}, LABEL_MESSAGE:", "\"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\"", "= button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] =", "tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer,", "label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10)) # frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer", "custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def __build(self): self.title(self.__title) self.resizable(0, 0)", "widgets keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that you", "return self.__message @property def on_close(self): return self.__on_close @property def ok(self): \"\"\" Returns True", "CustomView from tkutil import merge_megaconfig # parts BODY = \"body\" LABEL_HEADER = \"label_header\"", "dialog box to ask the user to confirm an action. Example: import tkinter", "ask the user to confirm an action. Example: import tkinter as tk from", "= tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel =", "= tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def", "LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that you want to set the", "tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\",", "__on_click_cancel(self): self.__ok = False self.destroy() def __on_click_confirm(self): self.__ok = True self.destroy() class Error(Exception):", "widgets options The widgets keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example:", "the parts (widgets instances) used to build this dialog. This property returns a", "__init__(self, root): super().__init__() self._root = root self._body = None def _build(self): self._body =", "\"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation is a dialog box to ask the user", "2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok", "self.__ok = False self.destroy() def __on_click_confirm(self): self.__ok = True self.destroy() class Error(Exception): def", "tkutil from viewable import Viewable, CustomView from tkutil import merge_megaconfig # parts BODY", "label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10)) # frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] =", "tkutil import merge_megaconfig # parts BODY = \"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE =", "cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10)) # frame_footer = tk.Frame(self,", "from megawidget import Confirmation def my_handler(result): print(result) root = tk.Tk() confirmation = Confirmation(root,", "FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation", "*args, **kwargs): self.message = args[0] if args else \"\" super().__init__(self.message) def __str__(self): return", "= \"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation is", "= root self._body = None def _build(self): self._body = tk.Frame(self._root) btn_launch = tk.Button(self._body,", "def __init__(self, *args, **kwargs): self.message = args[0] if args else \"\" super().__init__(self.message) def", "\"black\"} } \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header", "{\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY))", "# build self.__setup() # ==================================== # PROPERTIES # ==================================== @property def header(self): return", "button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel", "of tk.Frame - title: title of dialog box - header: the text to", "class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header = header self.__message = message self.__on_close =", "\"\"\" return self.__ok @property def parts(self): \"\"\" Get the parts (widgets instances) used", "= \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation is a dialog box", "self.message = args[0] if args else \"\" super().__init__(self.message) def __str__(self): return self.message class", "custom_view.build() def __build(self): self.title(self.__title) self.resizable(0, 0) # # if self.__geometry: self.geometry(self.__geometry) # if", "= label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10)) # frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER]", "# INTERNAL # ==================================== def __setup(self): custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return", "text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10)) #", "root.mainloop() \"\"\" def __init__(self, master=None, title=None, header=None, message=None, on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS:", "return self.__ok @property def parts(self): \"\"\" Get the parts (widgets instances) used to", "on_destroy=self.__on_destroy) return custom_view.build() def __build(self): self.title(self.__title) self.resizable(0, 0) # # if self.__geometry: self.geometry(self.__geometry)", "def my_handler(result): print(result) root = tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you", "padx=5, pady=(5, 10)) # frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0,", "True means Ok, confirmed. - geometry: str, as the dialog box is a", "dialog box is a toplevel (BODY), you can edit its geometry. Example: \"500x300\"", "from viewable import Viewable, CustomView from tkutil import merge_megaconfig # parts BODY =", "parent. Example: an instance of tk.Frame - title: title of dialog box -", "Example: \"500x300\" - options: dictionary of widgets options The widgets keys are: BODY,", "self._body = None def _build(self): self._body = tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch)", "the BODY's background to red: options = { BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\":", "0) # # if self.__geometry: self.geometry(self.__geometry) # if self.__header: label_header = tk.Label(self, text=self.__header,", "box. This callback should accept a boolean positional argument. True means Ok, confirmed.", "as the dialog box is a toplevel (BODY), you can edit its geometry.", "(widgets instances) used to build this dialog. This property returns a dict. The", "= False # build self.__setup() # ==================================== # PROPERTIES # ==================================== @property def", "frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) # button_confirm", "Assume that you want to set the LABEL_MESSAGE's background to black and the", "message - handler: a callback to be executed immediately after closing the dialog", "options = { BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\" self.__megaconfig =", "button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def", "def __on_click_cancel(self): self.__ok = False self.destroy() def __on_click_confirm(self): self.__ok = True self.destroy() class", "self.__ok = False # build self.__setup() # ==================================== # PROPERTIES # ==================================== @property", "self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok = False self.destroy() def __on_click_confirm(self): self.__ok = True", "pady=(5, 10)) # frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2),", "the LABEL_MESSAGE's background to black and the BODY's background to red: options =", "megaconfig=None): \"\"\" PARAMETERS: - master: widget parent. Example: an instance of tk.Frame -", "Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\\nPress ok to continue\\nOr", "really want to continue ?\\nPress ok to continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok)", "message=\"Do you really want to continue ?\\nPress ok to continue\\nOr die !\") confirmation.wait_window()", "anchor=\"w\", pady=5, padx=5) # if self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT,", "if __name__ == \"__main__\": root = tk.Tk() root.geometry(\"500x300+0+0\") confirm_test = _ConfirmTest(root) confirm_test.build_pack() root.mainloop()", "Returns True if user confirmed, else get False \"\"\" return self.__ok @property def", "- geometry: str, as the dialog box is a toplevel (BODY), you can", "= header self.__message = message self.__on_close = on_close self.__geometry = geometry self.__parts =", "keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the presence of", "tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5,", "else get False \"\"\" return self.__ok @property def parts(self): \"\"\" Get the parts", "you can edit its geometry. Example: \"500x300\" - options: dictionary of widgets options", "padx=5) # if self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE]", "an instance of tk.Frame - title: title of dialog box - header: the", "= False self.destroy() def __on_click_confirm(self): self.__ok = True self.destroy() class Error(Exception): def __init__(self,", "title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\"", "\"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation is a dialog box to", "= frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) # button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm,", "message self.__on_close = on_close self.__geometry = geometry self.__parts = {} self.__ok = False", "self._root = root self._body = None def _build(self): self._body = tk.Frame(self._root) btn_launch =", "tkinter as tk import tkutil from viewable import Viewable, CustomView from tkutil import", "continue ?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\" def __init__(self, master=None, title=None, header=None, message=None, on_close=None,", "self.__geometry = geometry self.__parts = {} self.__ok = False # build self.__setup() #", "# frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) #", "@property def ok(self): \"\"\" Returns True if user confirmed, else get False \"\"\"", "Error(Exception): def __init__(self, *args, **kwargs): self.message = args[0] if args else \"\" super().__init__(self.message)", "a dict. The keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check", "class _ConfirmTest(Viewable): def __init__(self, root): super().__init__() self._root = root self._body = None def", "Example: Assume that you want to set the LABEL_MESSAGE's background to black and", "@property def header(self): return self.__header @property def message(self): return self.__message @property def on_close(self):", "text to show as message - handler: a callback to be executed immediately", "= tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\",", "as tk import tkutil from viewable import Viewable, CustomView from tkutil import merge_megaconfig", "want to continue ?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\" def __init__(self, master=None, title=None, header=None,", "self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) # button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM,", "merge_megaconfig # parts BODY = \"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER", "# parts BODY = \"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER =", "BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class Confirmation(tk.Toplevel): \"\"\" Confirmation is a dialog", "class Error(Exception): def __init__(self, *args, **kwargs): self.message = args[0] if args else \"\"", "header=\"Confirmation\", message=\"Do you really want to continue ?\\nPress ok to continue\\nOr die !\")", "import merge_megaconfig # parts BODY = \"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE = \"label_message\"", "on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS: - master: widget parent. Example: an instance of", "= Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\\nPress ok to", "master: widget parent. Example: an instance of tk.Frame - title: title of dialog", "user confirmed, else get False \"\"\" return self.__ok @property def parts(self): \"\"\" Get", "tk.Frame - title: title of dialog box - header: the text to show", "btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\",", "= tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation = Confirmation(self._body,", "text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer, text=\"Cancel\",", "= {} self.__ok = False # build self.__setup() # ==================================== # PROPERTIES #", "Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\", handler=my_handler) confirmation.build() root.mainloop()", "self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header = header self.__message", "import tkinter as tk from megawidget import Confirmation def my_handler(result): print(result) root =", "= on_close self.__geometry = geometry self.__parts = {} self.__ok = False # build", "root = tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to", "positional argument. True means Ok, confirmed. - geometry: str, as the dialog box", "self.__message @property def on_close(self): return self.__on_close @property def ok(self): \"\"\" Returns True if", "__init__(self, master=None, title=None, header=None, message=None, on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS: - master: widget", "header=None, message=None, on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS: - master: widget parent. Example: an", "of key before usage \"\"\" return self.__parts # ==================================== # INTERNAL # ====================================", "name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10))", "= geometry self.__parts = {} self.__ok = False # build self.__setup() # ====================================", "anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5) #", "# if self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] =", "check the presence of key before usage \"\"\" return self.__parts # ==================================== #", "# if self.__header: label_header = tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] =", "the text to show as header - message: the text to show as", "Viewable, CustomView from tkutil import merge_megaconfig # parts BODY = \"body\" LABEL_HEADER =", "as header - message: the text to show as message - handler: a", "- options: dictionary of widgets options The widgets keys are: BODY, LABEL_HEADER, LABEL_MESSAGE,", "@property def parts(self): \"\"\" Get the parts (widgets instances) used to build this", "LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the presence of key before usage", "BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the presence of key before usage \"\"\" return self.__parts", "(BODY), you can edit its geometry. Example: \"500x300\" - options: dictionary of widgets", "def _on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue", "BODY = \"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL", "to continue ?\\nPress ok to continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__", "@property def message(self): return self.__message @property def on_close(self): return self.__on_close @property def ok(self):", "key before usage \"\"\" return self.__parts # ==================================== # INTERNAL # ==================================== def", "to red: options = { BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\"", "def on_close(self): return self.__on_close @property def ok(self): \"\"\" Returns True if user confirmed,", "show as message - handler: a callback to be executed immediately after closing", "def header(self): return self.__header @property def message(self): return self.__message @property def on_close(self): return", "instance of tk.Frame - title: title of dialog box - header: the text", "command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel,", "die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__ == \"__main__\": root = tk.Tk() root.geometry(\"500x300+0+0\")", "} \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header =", "is a toplevel (BODY), you can edit its geometry. Example: \"500x300\" - options:", "header=\"Confirmation\", message=\"Do you really want to continue ?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\" def", "dialog box. This callback should accept a boolean positional argument. True means Ok,", "self.__message: label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH,", "parts BODY = \"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER = \"frame_footer\"", "to be executed immediately after closing the dialog box. This callback should accept", "this dialog. This property returns a dict. The keys are: BODY, LABEL_HEADER, LABEL_MESSAGE,", "keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that you want", "str, as the dialog box is a toplevel (BODY), you can edit its", "# # if self.__geometry: self.geometry(self.__geometry) # if self.__header: label_header = tk.Label(self, text=self.__header, anchor=\"w\",", "title: title of dialog box - header: the text to show as header", "BUTTON_CONFIRM. Example: Assume that you want to set the LABEL_MESSAGE's background to black", "- header: the text to show as header - message: the text to", "= tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do", "# if self.__geometry: self.geometry(self.__geometry) # if self.__header: label_header = tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT,", "title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\\nPress ok to continue\\nOr die", "you want to set the LABEL_MESSAGE's background to black and the BODY's background", "?\", handler=my_handler) confirmation.build() root.mainloop() \"\"\" def __init__(self, master=None, title=None, header=None, message=None, on_close=None, geometry=None,", "means Ok, confirmed. - geometry: str, as the dialog box is a toplevel", "of dialog box - header: the text to show as header - message:", "self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL]", "justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10)) # frame_footer =", "confirmation = Confirmation(self._body, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\\nPress ok", "viewable import Viewable, CustomView from tkutil import merge_megaconfig # parts BODY = \"body\"", "__build(self): self.title(self.__title) self.resizable(0, 0) # # if self.__geometry: self.geometry(self.__geometry) # if self.__header: label_header", "message(self): return self.__message @property def on_close(self): return self.__on_close @property def ok(self): \"\"\" Returns", "self.__parts # ==================================== # INTERNAL # ==================================== def __setup(self): custom_view = CustomView(body=self, builder=self.__build,", "\"500x300\" - options: dictionary of widgets options The widgets keys are: BODY, LABEL_HEADER,", "usage \"\"\" return self.__parts # ==================================== # INTERNAL # ==================================== def __setup(self): custom_view", "True if user confirmed, else get False \"\"\" return self.__ok @property def parts(self):", "if self.__header: label_header = tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header", "builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def __build(self): self.title(self.__title) self.resizable(0, 0) # # if", "@property def on_close(self): return self.__on_close @property def ok(self): \"\"\" Returns True if user", "a callback to be executed immediately after closing the dialog box. This callback", "import tkutil from viewable import Viewable, CustomView from tkutil import merge_megaconfig # parts", "\"\"\" PARAMETERS: - master: widget parent. Example: an instance of tk.Frame - title:", "self.destroy() def __on_click_confirm(self): self.__ok = True self.destroy() class Error(Exception): def __init__(self, *args, **kwargs):", "header - message: the text to show as message - handler: a callback", "= tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue", "super().__init__() self._root = root self._body = None def _build(self): self._body = tk.Frame(self._root) btn_launch", "# ==================================== @property def header(self): return self.__header @property def message(self): return self.__message @property", "name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5) # if self.__message:", "title self.__header = header self.__message = message self.__on_close = on_close self.__geometry = geometry", "_build(self): self._body = tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self): confirmation", "- message: the text to show as message - handler: a callback to", "confirmed. - geometry: str, as the dialog box is a toplevel (BODY), you", "background to red: options = { BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} }", "tk from megawidget import Confirmation def my_handler(result): print(result) root = tk.Tk() confirmation =", "Get the parts (widgets instances) used to build this dialog. This property returns", "geometry. Example: \"500x300\" - options: dictionary of widgets options The widgets keys are:", "def message(self): return self.__message @property def on_close(self): return self.__on_close @property def ok(self): \"\"\"", "instances) used to build this dialog. This property returns a dict. The keys", "False # build self.__setup() # ==================================== # PROPERTIES # ==================================== @property def header(self):", "\"\" super().__init__(self.message) def __str__(self): return self.message class _ConfirmTest(Viewable): def __init__(self, root): super().__init__() self._root", "header self.__message = message self.__on_close = on_close self.__geometry = geometry self.__parts = {}", "want to continue ?\\nPress ok to continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if", "Example: import tkinter as tk from megawidget import Confirmation def my_handler(result): print(result) root", "ok(self): \"\"\" Returns True if user confirmed, else get False \"\"\" return self.__ok", "tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self):", "of widgets options The widgets keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM.", "cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header = header self.__message = message self.__on_close = on_close", "to continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__ == \"__main__\": root =", "print(\"Confirmation:\", confirmation.ok) if __name__ == \"__main__\": root = tk.Tk() root.geometry(\"500x300+0+0\") confirm_test = _ConfirmTest(root)", "Example: an instance of tk.Frame - title: title of dialog box - header:", "the dialog box. This callback should accept a boolean positional argument. True means", "closing the dialog box. This callback should accept a boolean positional argument. True", "can edit its geometry. Example: \"500x300\" - options: dictionary of widgets options The", "# ==================================== # PROPERTIES # ==================================== @property def header(self): return self.__header @property def", "Confirmation is a dialog box to ask the user to confirm an action.", "options The widgets keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume", "self.geometry(self.__geometry) # if self.__header: label_header = tk.Label(self, text=self.__header, anchor=\"w\", justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER]", "parts (widgets instances) used to build this dialog. This property returns a dict.", "self.resizable(0, 0) # # if self.__geometry: self.geometry(self.__geometry) # if self.__header: label_header = tk.Label(self,", "args else \"\" super().__init__(self.message) def __str__(self): return self.message class _ConfirmTest(Viewable): def __init__(self, root):", "def __build(self): self.title(self.__title) self.resizable(0, 0) # # if self.__geometry: self.geometry(self.__geometry) # if self.__header:", "build this dialog. This property returns a dict. The keys are: BODY, LABEL_HEADER,", "self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if", "10)) # frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2)", "self.__setup() # ==================================== # PROPERTIES # ==================================== @property def header(self): return self.__header @property", "self.__header = header self.__message = message self.__on_close = on_close self.__geometry = geometry self.__parts", "root self._body = None def _build(self): self._body = tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\",", "2), padx=2) # button_confirm = tk.Button(frame_footer, text=\"Confirmation\", name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm", "def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok = False self.destroy() def __on_click_confirm(self):", "- master: widget parent. Example: an instance of tk.Frame - title: title of", "# ==================================== # INTERNAL # ==================================== def __setup(self): custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map,", "= \"label_header\" LABEL_MESSAGE = \"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM =", "True self.destroy() class Error(Exception): def __init__(self, *args, **kwargs): self.message = args[0] if args", "= args[0] if args else \"\" super().__init__(self.message) def __str__(self): return self.message class _ConfirmTest(Viewable):", "name=BUTTON_CONFIRM, command=self.__on_click_confirm, cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL,", "padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self):", "__init__(self, *args, **kwargs): self.message = args[0] if args else \"\" super().__init__(self.message) def __str__(self):", "self.__parts = {} self.__ok = False # build self.__setup() # ==================================== # PROPERTIES", "if args else \"\" super().__init__(self.message) def __str__(self): return self.message class _ConfirmTest(Viewable): def __init__(self,", "self.__ok = True self.destroy() class Error(Exception): def __init__(self, *args, **kwargs): self.message = args[0]", "background to black and the BODY's background to red: options = { BODY:", "button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT,", "BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the presence of key before", "This property returns a dict. The keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL,", "= CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def __build(self): self.title(self.__title) self.resizable(0, 0) #", "expand=1, padx=5, pady=(5, 10)) # frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\",", "before usage \"\"\" return self.__parts # ==================================== # INTERNAL # ==================================== def __setup(self):", "import tkinter as tk import tkutil from viewable import Viewable, CustomView from tkutil", "its geometry. Example: \"500x300\" - options: dictionary of widgets options The widgets keys", "set the LABEL_MESSAGE's background to black and the BODY's background to red: options", "FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that you want to set the LABEL_MESSAGE's background", "False self.destroy() def __on_click_confirm(self): self.__ok = True self.destroy() class Error(Exception): def __init__(self, *args,", "self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok = False self.destroy() def __on_click_confirm(self): self.__ok = True self.destroy()", "Ok, confirmed. - geometry: str, as the dialog box is a toplevel (BODY),", "==================================== # INTERNAL # ==================================== def __setup(self): custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy)", "immediately after closing the dialog box. This callback should accept a boolean positional", "is a dialog box to ask the user to confirm an action. Example:", "Confirmation def my_handler(result): print(result) root = tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do", "show as header - message: the text to show as message - handler:", "to set the LABEL_MESSAGE's background to black and the BODY's background to red:", "CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def __build(self): self.title(self.__title) self.resizable(0, 0) # #", "==================================== def __setup(self): custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def __build(self):", "__str__(self): return self.message class _ConfirmTest(Viewable): def __init__(self, root): super().__init__() self._root = root self._body", "be executed immediately after closing the dialog box. This callback should accept a", "used to build this dialog. This property returns a dict. The keys are:", "def _build(self): self._body = tk.Frame(self._root) btn_launch = tk.Button(self._body, text=\"Launch\", command=self._on_click_launch) btn_launch.pack() def _on_click_launch(self):", "args[0] if args else \"\" super().__init__(self.message) def __str__(self): return self.message class _ConfirmTest(Viewable): def", "BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that you want to set", "dict. The keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM Warning: check the", "<reponame>pyrustic/megawidget<gh_stars>0 import tkinter as tk import tkutil from viewable import Viewable, CustomView from", "name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel())", "**kwargs): self.message = args[0] if args else \"\" super().__init__(self.message) def __str__(self): return self.message", "on_close self.__geometry = geometry self.__parts = {} self.__ok = False # build self.__setup()", "box to ask the user to confirm an action. Example: import tkinter as", "print(result) root = tk.Tk() confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want", "options: dictionary of widgets options The widgets keys are: BODY, LABEL_HEADER, LABEL_MESSAGE, FRAME_FOOTER,", "confirm an action. Example: import tkinter as tk from megawidget import Confirmation def", "callback to be executed immediately after closing the dialog box. This callback should", "label_message = tk.Label(self, name=LABEL_MESSAGE, text=self.__message, anchor=\"w\", justify=tk.LEFT, cnf=self.__megaconfig.get(LABEL_MESSAGE)) self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1,", "a toplevel (BODY), you can edit its geometry. Example: \"500x300\" - options: dictionary", "cnf=self.__megaconfig.get(BUTTON_CONFIRM)) self.__parts[BUTTON_CONFIRM] = button_confirm button_confirm.pack(side=tk.RIGHT) # button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL))", "__on_click_confirm(self): self.__ok = True self.destroy() class Error(Exception): def __init__(self, *args, **kwargs): self.message =", "LABEL_MESSAGE, FRAME_FOOTER, BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that you want to set the LABEL_MESSAGE's", "==================================== @property def header(self): return self.__header @property def message(self): return self.__message @property def", "confirmation.ok) if __name__ == \"__main__\": root = tk.Tk() root.geometry(\"500x300+0+0\") confirm_test = _ConfirmTest(root) confirm_test.build_pack()", "boolean positional argument. True means Ok, confirmed. - geometry: str, as the dialog", "cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2)) def __on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self):", "self.__on_close @property def ok(self): \"\"\" Returns True if user confirmed, else get False", "return custom_view.build() def __build(self): self.title(self.__title) self.resizable(0, 0) # # if self.__geometry: self.geometry(self.__geometry) #", "self.destroy() class Error(Exception): def __init__(self, *args, **kwargs): self.message = args[0] if args else", "tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok = False self.destroy()", "def __init__(self, master=None, title=None, header=None, message=None, on_close=None, geometry=None, megaconfig=None): \"\"\" PARAMETERS: - master:", "super().__init__(master=master, class_=\"Confirmation\", cnf=self.__megaconfig.get(BODY)) self.__title = title self.__header = header self.__message = message self.__on_close", "justify=tk.LEFT, name=LABEL_HEADER, cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5) # if", "geometry=None, megaconfig=None): \"\"\" PARAMETERS: - master: widget parent. Example: an instance of tk.Frame", "LABEL_MESSAGE = \"label_message\" FRAME_FOOTER = \"frame_footer\" BUTTON_CANCEL = \"button_cancel\" BUTTON_CONFIRM = \"button_confirm\" class", "root): super().__init__() self._root = root self._body = None def _build(self): self._body = tk.Frame(self._root)", "return self.__parts # ==================================== # INTERNAL # ==================================== def __setup(self): custom_view = CustomView(body=self,", "def __setup(self): custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def __build(self): self.title(self.__title)", "BUTTON_CANCEL, BUTTON_CONFIRM. Example: Assume that you want to set the LABEL_MESSAGE's background to", "button_cancel = tk.Button(frame_footer, text=\"Cancel\", name=BUTTON_CANCEL, command=self.__on_click_cancel, cnf=self.__megaconfig.get(BUTTON_CANCEL)) self.__parts[BUTTON_CANCEL] = button_cancel button_cancel.pack(side=tk.RIGHT, padx=(0, 2))", "callback should accept a boolean positional argument. True means Ok, confirmed. - geometry:", "BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master, class_=\"Confirmation\",", "{ BODY: {\"background\": \"red\"}, LABEL_MESSAGE: {\"background\": \"black\"} } \"\"\" self.__megaconfig = merge_megaconfig(secondary=megaconfig) super().__init__(master=master,", "continue\\nOr die !\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__ == \"__main__\": root = tk.Tk()", "from tkutil import merge_megaconfig # parts BODY = \"body\" LABEL_HEADER = \"label_header\" LABEL_MESSAGE", "cnf=self.__megaconfig.get(LABEL_HEADER)) self.__parts[LABEL_HEADER] = label_header label_header.pack(fill=tk.X, expand=1, anchor=\"w\", pady=5, padx=5) # if self.__message: label_message", "box is a toplevel (BODY), you can edit its geometry. Example: \"500x300\" -", "self.__parts[LABEL_MESSAGE] = label_message label_message.pack(fill=tk.BOTH, expand=1, padx=5, pady=(5, 10)) # frame_footer = tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER))", "message: the text to show as message - handler: a callback to be", "False \"\"\" return self.__ok @property def parts(self): \"\"\" Get the parts (widgets instances)", "# ==================================== def __setup(self): custom_view = CustomView(body=self, builder=self.__build, on_map=self.__on_map, on_destroy=self.__on_destroy) return custom_view.build() def", "__on_map(self): tkutil.center_dialog_effect(self, within=self.master.winfo_toplevel()) def __on_destroy(self): if self.__on_close: self.__on_close(self.__ok) def __on_click_cancel(self): self.__ok = False", "a boolean positional argument. True means Ok, confirmed. - geometry: str, as the", "def __init__(self, root): super().__init__() self._root = root self._body = None def _build(self): self._body", "self.message class _ConfirmTest(Viewable): def __init__(self, root): super().__init__() self._root = root self._body = None", "confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__ == \"__main__\": root = tk.Tk() root.geometry(\"500x300+0+0\") confirm_test =", "tk.Frame(self, cnf=self.__megaconfig.get(FRAME_FOOTER)) self.__parts[FRAME_FOOTER] = frame_footer frame_footer.pack(anchor=\"e\", pady=(0, 2), padx=2) # button_confirm = tk.Button(frame_footer,", "!\") confirmation.wait_window() print(\"Confirmation:\", confirmation.ok) if __name__ == \"__main__\": root = tk.Tk() root.geometry(\"500x300+0+0\") confirm_test", "confirmation = Confirmation(root, title=\"Confirmation\", header=\"Confirmation\", message=\"Do you really want to continue ?\", handler=my_handler)" ]
[ "= im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws): _, h, w, _ =", "def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize here # h, w - input size", "ws): _, h, w, _ = imgs.shape with tf.variable_scope(\"resize_area\"): out = inter_area_batch(imgs, int(h),", "h, w, _ = imgs.shape with tf.variable_scope(\"resize_area\"): out = inter_area_batch(imgs, int(h), int(w), hs,", "- scaled size whole = im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws): _,", "import division, print_function, absolute_import import tensorflow as tf import numpy as np def", "resize_area_batch(imgs, hs, ws): _, h, w, _ = imgs.shape with tf.variable_scope(\"resize_area\"): out =", "def resize_area_batch(imgs, hs, ws): _, h, w, _ = imgs.shape with tf.variable_scope(\"resize_area\"): out", "- input size # hs, ws - scaled size whole = im_inp return", "absolute_import import tensorflow as tf import numpy as np def inter_area_batch(im_inp,h,w,hs,ws): # Do", "here # h, w - input size # hs, ws - scaled size", "np def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize here # h, w - input", "resize here # h, w - input size # hs, ws - scaled", "print_function, absolute_import import tensorflow as tf import numpy as np def inter_area_batch(im_inp,h,w,hs,ws): #", "import numpy as np def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize here # h,", "__future__ import division, print_function, absolute_import import tensorflow as tf import numpy as np", "# h, w - input size # hs, ws - scaled size whole", "h, w - input size # hs, ws - scaled size whole =", "w, _ = imgs.shape with tf.variable_scope(\"resize_area\"): out = inter_area_batch(imgs, int(h), int(w), hs, ws)", "<gh_stars>10-100 from __future__ import division, print_function, absolute_import import tensorflow as tf import numpy", "input size # hs, ws - scaled size whole = im_inp return tf.clip_by_value(whole,0.,1.)", "INTER_AREA resize here # h, w - input size # hs, ws -", "numpy as np def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize here # h, w", "inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize here # h, w - input size #", "hs, ws): _, h, w, _ = imgs.shape with tf.variable_scope(\"resize_area\"): out = inter_area_batch(imgs,", "= imgs.shape with tf.variable_scope(\"resize_area\"): out = inter_area_batch(imgs, int(h), int(w), hs, ws) return out", "# Do INTER_AREA resize here # h, w - input size # hs,", "tensorflow as tf import numpy as np def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize", "Do INTER_AREA resize here # h, w - input size # hs, ws", "# hs, ws - scaled size whole = im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs,", "_ = imgs.shape with tf.variable_scope(\"resize_area\"): out = inter_area_batch(imgs, int(h), int(w), hs, ws) return", "from __future__ import division, print_function, absolute_import import tensorflow as tf import numpy as", "division, print_function, absolute_import import tensorflow as tf import numpy as np def inter_area_batch(im_inp,h,w,hs,ws):", "as tf import numpy as np def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize here", "size # hs, ws - scaled size whole = im_inp return tf.clip_by_value(whole,0.,1.) def", "w - input size # hs, ws - scaled size whole = im_inp", "im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws): _, h, w, _ = imgs.shape", "tf import numpy as np def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize here #", "size whole = im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws): _, h, w,", "as np def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA resize here # h, w -", "tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws): _, h, w, _ = imgs.shape with tf.variable_scope(\"resize_area\"):", "ws - scaled size whole = im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws):", "whole = im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws): _, h, w, _", "hs, ws - scaled size whole = im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs,", "return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws): _, h, w, _ = imgs.shape with", "_, h, w, _ = imgs.shape with tf.variable_scope(\"resize_area\"): out = inter_area_batch(imgs, int(h), int(w),", "scaled size whole = im_inp return tf.clip_by_value(whole,0.,1.) def resize_area_batch(imgs, hs, ws): _, h,", "import tensorflow as tf import numpy as np def inter_area_batch(im_inp,h,w,hs,ws): # Do INTER_AREA" ]
[ "from output.models.ms_data.regex.re_c43_xsd.re_c43 import ( Regex, Doc, ) __all__ = [ \"Regex\", \"Doc\", ]", "<filename>output/models/ms_data/regex/re_c43_xsd/__init__.py from output.models.ms_data.regex.re_c43_xsd.re_c43 import ( Regex, Doc, ) __all__ = [ \"Regex\", \"Doc\"," ]
[ "ExpMatrix, num_components: int = 50, transform_name: str = 'freeman-tukey', pca_model: PCAModel = None,", "# This file is part of Monet. from typing import Tuple import pandas", "go from ..core import ExpMatrix from ..latent import PCAModel from .cells import plot_cells", "import PCAModel from .cells import plot_cells def force_plot( matrix: ExpMatrix, num_components: int =", "tl import scanpy.pp as pp import plotly.graph_objs as go from ..core import ExpMatrix", "PCAModel = None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]: if pca_model is None: pca_model =", "force_plot( matrix: ExpMatrix, num_components: int = 50, transform_name: str = 'freeman-tukey', pca_model: PCAModel", "adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values # determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y", "None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix) adata", "50, transform_name: str = 'freeman-tukey', pca_model: PCAModel = None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]:", "-> Tuple[go.Figure, pd.DataFrame]: if pca_model is None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores =", "This file is part of Monet. from typing import Tuple import pandas as", "import ExpMatrix from ..latent import PCAModel from .cells import plot_cells def force_plot( matrix:", "..latent import PCAModel from .cells import plot_cells def force_plot( matrix: ExpMatrix, num_components: int", "Copyright (c) 2021 <NAME> # # This file is part of Monet. from", "scanpy.pp as pp import plotly.graph_objs as go from ..core import ExpMatrix from ..latent", "typing import Tuple import pandas as pd import scanpy.tl as tl import scanpy.pp", "= None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]: if pca_model is None: pca_model = PCAModel(num_components=num_components,", "(c) 2021 <NAME> # # This file is part of Monet. from typing", "pc_scores.values # determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame(", "scanpy.tl as tl import scanpy.pp as pp import plotly.graph_objs as go from ..core", "matrix: ExpMatrix, num_components: int = 50, transform_name: str = 'freeman-tukey', pca_model: PCAModel =", "file is part of Monet. from typing import Tuple import pandas as pd", "determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names, columns=['Dim.", "from ..core import ExpMatrix from ..latent import PCAModel from .cells import plot_cells def", "pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'], data=Y) fig = plot_cells(scores, **kwargs) return fig,", "import scanpy.tl as tl import scanpy.pp as pp import plotly.graph_objs as go from", "= ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values # determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y =", "nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names, columns=['Dim. 1',", "pca_model is None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else: pc_scores =", "pd import scanpy.tl as tl import scanpy.pp as pp import plotly.graph_objs as go", "pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values # determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata)", "index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'], data=Y) fig = plot_cells(scores, **kwargs) return fig, scores", "# # This file is part of Monet. from typing import Tuple import", "tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'], data=Y)", "= 'freeman-tukey', pca_model: PCAModel = None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]: if pca_model is", "use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'],", "import scanpy.pp as pp import plotly.graph_objs as go from ..core import ExpMatrix from", "adata.obsm['pc_scores'] = pc_scores.values # determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores", "PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores']", "None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]: if pca_model is None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name)", "is None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix)", "of Monet. from typing import Tuple import pandas as pd import scanpy.tl as", "Tuple[go.Figure, pd.DataFrame]: if pca_model is None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix)", "Monet. from typing import Tuple import pandas as pd import scanpy.tl as tl", "pd.DataFrame]: if pca_model is None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else:", "'freeman-tukey', pca_model: PCAModel = None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]: if pca_model is None:", "= adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'], data=Y) fig =", "= pc_scores.values # determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores =", "import plot_cells def force_plot( matrix: ExpMatrix, num_components: int = 50, transform_name: str =", "from ..latent import PCAModel from .cells import plot_cells def force_plot( matrix: ExpMatrix, num_components:", ".cells import plot_cells def force_plot( matrix: ExpMatrix, num_components: int = 50, transform_name: str", "import pandas as pd import scanpy.tl as tl import scanpy.pp as pp import", "pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim.", "is part of Monet. from typing import Tuple import pandas as pd import", "pc_scores = pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values", "else: pc_scores = pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values # determine nearest-neighbors", "<NAME> # # This file is part of Monet. from typing import Tuple", "pp import plotly.graph_objs as go from ..core import ExpMatrix from ..latent import PCAModel", "scores = pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'], data=Y) fig = plot_cells(scores, **kwargs)", "import plotly.graph_objs as go from ..core import ExpMatrix from ..latent import PCAModel from", "<gh_stars>10-100 # Author: <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> # # This", "if pca_model is None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else: pc_scores", "**kwargs) -> Tuple[go.Figure, pd.DataFrame]: if pca_model is None: pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores", "from typing import Tuple import pandas as pd import scanpy.tl as tl import", "plot_cells def force_plot( matrix: ExpMatrix, num_components: int = 50, transform_name: str = 'freeman-tukey',", "transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] =", "adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'], data=Y) fig = plot_cells(scores,", "as pp import plotly.graph_objs as go from ..core import ExpMatrix from ..latent import", "pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values # determine", "= pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values # determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores')", "pandas as pd import scanpy.tl as tl import scanpy.pp as pp import plotly.graph_objs", "# determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names,", "as go from ..core import ExpMatrix from ..latent import PCAModel from .cells import", "ExpMatrix from ..latent import PCAModel from .cells import plot_cells def force_plot( matrix: ExpMatrix,", "= PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata()", "pc_scores = pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values # determine nearest-neighbors pp.neighbors(adata,", "pca_model: PCAModel = None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]: if pca_model is None: pca_model", "int = 50, transform_name: str = 'freeman-tukey', pca_model: PCAModel = None, **kwargs) ->", "PCAModel from .cells import plot_cells def force_plot( matrix: ExpMatrix, num_components: int = 50,", "Author: <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> # # This file is", "pca_model = PCAModel(num_components=num_components, transform_name=transform_name) pc_scores = pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix) adata =", "= pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'], data=Y) fig = plot_cells(scores, **kwargs) return", "Tuple import pandas as pd import scanpy.tl as tl import scanpy.pp as pp", "# Author: <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> # # This file", "<NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> # # This file is part", "ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values # determine nearest-neighbors pp.neighbors(adata, use_rep='pc_scores') tl.draw_graph(adata) Y = adata.obsm['X_draw_graph_fa']", "num_components: int = 50, transform_name: str = 'freeman-tukey', pca_model: PCAModel = None, **kwargs)", "# Copyright (c) 2021 <NAME> # # This file is part of Monet.", "def force_plot( matrix: ExpMatrix, num_components: int = 50, transform_name: str = 'freeman-tukey', pca_model:", "part of Monet. from typing import Tuple import pandas as pd import scanpy.tl", "= pca_model.fit_transform(matrix) else: pc_scores = pca_model.transform(matrix) adata = ExpMatrix(pc_scores.T).to_anndata() adata.obsm['pc_scores'] = pc_scores.values #", "<<EMAIL>> # Copyright (c) 2021 <NAME> # # This file is part of", "as tl import scanpy.pp as pp import plotly.graph_objs as go from ..core import", "from .cells import plot_cells def force_plot( matrix: ExpMatrix, num_components: int = 50, transform_name:", "transform_name: str = 'freeman-tukey', pca_model: PCAModel = None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]: if", "Y = adata.obsm['X_draw_graph_fa'] scores = pd.DataFrame( index=adata.obs_names, columns=['Dim. 1', 'Dim. 2'], data=Y) fig", "import Tuple import pandas as pd import scanpy.tl as tl import scanpy.pp as", "..core import ExpMatrix from ..latent import PCAModel from .cells import plot_cells def force_plot(", "= 50, transform_name: str = 'freeman-tukey', pca_model: PCAModel = None, **kwargs) -> Tuple[go.Figure,", "2021 <NAME> # # This file is part of Monet. from typing import", "str = 'freeman-tukey', pca_model: PCAModel = None, **kwargs) -> Tuple[go.Figure, pd.DataFrame]: if pca_model", "as pd import scanpy.tl as tl import scanpy.pp as pp import plotly.graph_objs as", "plotly.graph_objs as go from ..core import ExpMatrix from ..latent import PCAModel from .cells" ]
[ "'__main__': # parsing arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to", "# init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as main()'.format(__file__)) # make all paths", "in the reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the location to", "log.banner('Start execute {} as main()'.format(__file__)) # make all paths from user to absolute", "df_exp_descr.keys(): dict_line[answ_col] = input('{} : '.format(answ_col)) else: log.warning('{} not in columns!'.format(answ_col)) log.info('Columns are", "# create dataframe cols_exp_descr_f = ['Experiment name', 'Platform', 'OS', 'Compiler (with version)', 'Optimisation", "shutil.copy(pdf_file,place_for_reference) # root is important to not fail during git commands os.chdir(paths.rootdir) #", "'Exps_description.csv' with additional # information via user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not", "utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what is the filename in the reference pool filename_in_ref_dir", "if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf with bar-plots from Welch's-test if", "line for exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the content of the", "user to absolute paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages,", "not fail during git commands os.chdir(paths.rootdir) # checkout new branch if not ltestsuite:", "steps:') log.info('1. Push the new branch into the official repo:') log.info(' git push", "Add a new line to the experiment description file with all information about", "to git for file in files_to_commit: git_cmd = 'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd,", "main: asks user for additional information about experiment, commits data of new experiment", "-B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified files prior in the function to", "name', 'Platform', 'OS', 'Compiler (with version)', 'Optimisation level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)',", "experiment {}'.format(exp)) return() if __name__ == '__main__': # parsing arguments parser = argparse.ArgumentParser(", "elif answ_chg.upper() == 'N': answ_col = input('Which column field you want to change", "Web interface (GitHub) , open a Pull Request.') log.banner('End add_exp_to_ref for experiment {}'.format(exp))", "absolute path of the csv \\ files of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files,", "git-repository Help: python add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021 (C2SM) ''' def", "# commit all modified files prior in the function to git for file", "save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of the loop return False elif", "is important to not fail during git commands os.chdir(paths.rootdir) # checkout new branch", "'test_postproc_{}_{}.csv' .format(test,exp)) # what is the filename in the reference pool filename_in_ref_dir =", "= os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference)", "parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of testsuite') args =", "logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as main()'.format(__file__)) # make all paths from user to", "from lib.logger_config import log from lib.test_config import get_config_of_current_test from lib.color import Style '''", "file 'Exps_description.csv' with additional # information via user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if", "(y/n)', 'fldcor (y/n)', 'rmse (y/n)', 'emi (y/n)', 'Date of experiment (month yyyy)'] df_exp_descr", "paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages, p_ref_csv_files=args.p_ref_csv_files, ltestsuite=args.ltestsuite, lverbose=args.lverbose)", "cols_exp_descr_f = ['Experiment name', 'Platform', 'OS', 'Compiler (with version)', 'Optimisation level (-OX)', '-fast-transcendentals", "exp: new expirement name :param f_exp_descr: file in which the new line has", "is the filename in the reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is", "in the reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what is the location to", "''' Module providing the functionality to add an experiment to the reference pool.", "\\ files of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the pool of", "p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit = [] # fill", "copy pdf with bar-plots from Welch's-test if test == 'welch': pdf_file = utils.clean_path(p_stages,", "parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages,", "the experiment description file with all information about an experiment - main: asks", "__name__ == '__main__': # parsing arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True,", "= input('Please type your commit message :') git_cmd = 'git commit -m \"{}\"'.format(commit_message)", "the reference pool. It contains: - add_line_descr_f: Add a new line to the", "new_branch_name = 'test_add_{}'.format(exp) files_to_commit = [] # fill up file 'Exps_description.csv' with additional", "file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of the loop return False elif answ_chg.upper() ==", "column field you want to change ?') if answ_col in df_exp_descr.keys(): dict_line[answ_col] =", "the functionality to add an experiment to the reference pool. It contains: -", "which the new line has to be added return: None ''' log.info('Adding line", "dataframe if not os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f = ['Experiment name', 'Platform', 'OS',", "if not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is important to not fail during git", "# information via user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr)", "checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified files prior in the function", "modules import pandas as pd # modules of sanity checker import lib.paths as", "Style ''' Module providing the functionality to add an experiment to the reference", "experiment description file with all information about an experiment - main: asks user", "log.debug('Commit files {}'.format(files_to_commit)) commit_message = input('Please type your commit message :') git_cmd =", "branch: ' '{} in your local git repository.' .format(new_branch_name))) log.info('To add the file", "modified files prior in the function to git for file in files_to_commit: git_cmd", "dict_line[col_name] = input('{} : '.format(col_name)) # amend the information if needed while True:", "''' def add_line_descr_f(exp,f_exp_descr): ''' Add line for exp exp in file f_exp_descr :param", "'Compiler (with version)', 'Optimisation level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch", "= {'Experiment name': exp} for col_name in df_exp_descr.keys(): if col_name != 'Experiment name':", "test in tests: test_cfg = get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what", "files_to_commit.append(place_for_reference) # copy pdf with bar-plots from Welch's-test if test == 'welch': pdf_file", "exp} for col_name in df_exp_descr.keys(): if col_name != 'Experiment name': # ask the", "'{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is the name of the pdf in the reference", "additional information about experiment, commits data of new experiment to git-repository Help: python", "= pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';') # collect information from user log.banner('Please", "(y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch (y/n)', 'fldcor (y/n)', 'rmse (y/n)', 'emi (y/n)',", "user for additional information about experiment, commits data of new experiment to git-repository", "for additional information about experiment, commits data of new experiment to git-repository Help:", "exp)) # what is the name of the pdf in the reference pool", "exp in file f_exp_descr :param exp: new expirement name :param f_exp_descr: file in", "return() if __name__ == '__main__': # parsing arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e',", "{}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT': exit() return() def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False,", "dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of testsuite') args = parser.parse_args()", "you type n, you will be able to change ' 'column values\\n' 'If", "parsing arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to add') parser.add_argument('--p_stages',", "right ? (y/n/abort).\\n' 'If you type n, you will be able to change", "commands os.chdir(paths.rootdir) # checkout new branch if not ltestsuite: log.info('Create and checkout new", "pool of csv files, \\ one per reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+',", "filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is", "informations ' 'about your experiment') dict_line = {'Experiment name': exp} for col_name in", "'about your experiment') dict_line = {'Experiment name': exp} for col_name in df_exp_descr.keys(): if", "# standard modules import os import shutil import argparse # aliased standard modules", "the information if needed while True: # new dataframe containing new line for", "git_cmd = 'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files are added", "# modules of sanity checker import lib.paths as paths import lib.utils as utils", "during git commands os.chdir(paths.rootdir) # checkout new branch if not ltestsuite: log.info('Create and", "parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the pool of csv files, \\ one per", "to add to reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true',", "== '__main__': # parsing arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp", "{}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message = input('Please type your commit", "'test_add_{}'.format(exp) files_to_commit = [] # fill up file 'Exps_description.csv' with additional # information", "log.banner('Here is the content of the description ' 'file including your new experiment.')", "prior in the function to git for file in files_to_commit: git_cmd = 'git", "help='relative or absolute path of the csv \\ files of the testresults') parser.add_argument('--p_ref_csv_files',", "to absolute paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages, p_ref_csv_files=args.p_ref_csv_files,", "''' Add line for exp exp in file f_exp_descr :param exp: new expirement", "== 'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is the name of", "parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as main()'.format(__file__)) # make all", "' 'column values\\n' 'If you type abort, the process of adding ' 'the", "input('{} : '.format(col_name)) # amend the information if needed while True: # new", "'If you type n, you will be able to change ' 'column values\\n'", "lib.logger_config import log from lib.test_config import get_config_of_current_test from lib.color import Style ''' Module", "return: None ''' log.info('Adding line {} in the file {}:'.format(exp,f_exp_descr)) # open file", "location to store that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to", "exit() return() def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation new_branch_name =", "store that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if", "'-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch (y/n)', 'fldcor (y/n)', 'rmse (y/n)', 'emi", "file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not", "add to reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run", "f_exp_descr :param exp: new expirement name :param f_exp_descr: file in which the new", "info dict_line[col_name] = input('{} : '.format(col_name)) # amend the information if needed while", "pandas as pd # modules of sanity checker import lib.paths as paths import", "(GitHub) , open a Pull Request.') log.banner('End add_exp_to_ref for experiment {}'.format(exp)) return() if", "\\ one per reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add to", "absolute paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages, p_ref_csv_files=args.p_ref_csv_files, ltestsuite=args.ltestsuite,", "for experiment {}'.format(exp)) return() if __name__ == '__main__': # parsing arguments parser =", "'(y/n/abort) : ' ''.format(exp)) if answ_chg.upper() == 'Y': # save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False)", "help='path to the pool of csv files, \\ one per reference experiment') parser.add_argument('--tests','-t',", "of the loop return False elif answ_chg.upper() == 'N': answ_col = input('Which column", "the following informations ' 'about your experiment') dict_line = {'Experiment name': exp} for", "the csv \\ files of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the", "def add_line_descr_f(exp,f_exp_descr): ''' Add line for exp exp in file f_exp_descr :param exp:", "values\\n' 'If you type abort, the process of adding ' 'the experiment {}", "if test == 'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is the", "log.banner('Please give the following informations ' 'about your experiment') dict_line = {'Experiment name':", "answ_chg = input('Is the new file right ? (y/n/abort).\\n' 'If you type n,", "dest='exp', required=True, help='exp to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or absolute path of", "ltestsuite=False, lverbose=False): # initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit = [] # fill up", "of testsuite') args = parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as", "Welch's-test if test == 'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is", "add_exp_to_ref for experiment {}'.format(exp)) return() if __name__ == '__main__': # parsing arguments parser", "the reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the location to store", "default=paths.p_ref_csv_files, help='path to the pool of csv files, \\ one per reference experiment')", "import pandas as pd # modules of sanity checker import lib.paths as paths", "(C2SM) J.Jucker 01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr): ''' Add line for exp exp", "all paths from user to absolute paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files)", "df_exp_descr.keys(): if col_name != 'Experiment name': # ask the user for info dict_line[col_name]", "csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what is the filename in the reference", "providing the functionality to add an experiment to the reference pool. It contains:", "answ_chg.upper() == 'N': answ_col = input('Which column field you want to change ?')", "{}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is important to not fail", "pool. It contains: - add_line_descr_f: Add a new line to the experiment description", "os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference) #", "file {}:'.format(exp,f_exp_descr)) # open file in dataframe if not os.path.isfile(f_exp_descr): # create dataframe", "path of the csv \\ files of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path", "needed while True: # new dataframe containing new line for exp df_exp_descr_new =", "the loop return False elif answ_chg.upper() == 'N': answ_col = input('Which column field", "be added return: None ''' log.info('Adding line {} in the file {}:'.format(exp,f_exp_descr)) #", "'{}_plots.pdf'.format(test_cfg.ref_name) # what is the location to store that file place_for_reference = os.path.join(p_ref_csv_files,", "what is the name of the pdf in the reference pool filename_in_ref_dir =", "'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message = input('Please type", "{}'.format(files_to_commit)) commit_message = input('Please type your commit message :') git_cmd = 'git commit", "' '{} in your local git repository.' .format(new_branch_name))) log.info('To add the file to", "main()'.format(__file__)) # make all paths from user to absolute paths args.p_stages = utils.abs_path(args.p_stages)", "if col_name != 'Experiment name': # ask the user for info dict_line[col_name] =", "'rmse (y/n)', 'emi (y/n)', 'Date of experiment (month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else:", "'file including your new experiment.') log.info(df_exp_descr_new) answ_chg = input('Is the new file right", "log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is important", "import get_config_of_current_test from lib.color import Style ''' Module providing the functionality to add", "= pd.read_csv(f_exp_descr, sep=';') # collect information from user log.banner('Please give the following informations", "action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of testsuite') args = parser.parse_args() #", "be able to change ' 'column values\\n' 'If you type abort, the process", "return False elif answ_chg.upper() == 'N': answ_col = input('Which column field you want", "for exp exp in file f_exp_descr :param exp: new expirement name :param f_exp_descr:", "# ask the user for info dict_line[col_name] = input('{} : '.format(col_name)) # amend", "Pull Request.') log.banner('End add_exp_to_ref for experiment {}'.format(exp)) return() if __name__ == '__main__': #", "containing new line for exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the content", "# get out of the loop return False elif answ_chg.upper() == 'N': answ_col", "you want to change ?') if answ_col in df_exp_descr.keys(): dict_line[answ_col] = input('{} :", "dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the pool of csv files, \\ one per reference", "as paths import lib.utils as utils import lib.logger_config as logger_config # standalone imports", "repository, ' 'please perform the following steps:') log.info('1. Push the new branch into", "args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages, p_ref_csv_files=args.p_ref_csv_files, ltestsuite=args.ltestsuite, lverbose=args.lverbose) log.banner('End", "= input('{} : '.format(col_name)) # amend the information if needed while True: #", "amend the information if needed while True: # new dataframe containing new line", "the new branch into the official repo:') log.info(' git push --set-upstream origin {}'.format(new_branch_name))", "lverbose=False): # initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit = [] # fill up file", "to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or absolute path of the csv \\", "test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root", "new experiment.') log.info(df_exp_descr_new) answ_chg = input('Is the new file right ? (y/n/abort).\\n' 'If", "with additional # information via user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite:", "to reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of", ": '.format(answ_col)) else: log.warning('{} not in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() ==", "log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf with", "dest='p_stages', default=paths.p_stages, help='relative or absolute path of the csv \\ files of the", "imports from lib.logger_config import log from lib.test_config import get_config_of_current_test from lib.color import Style", "parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or absolute path of the csv \\ files of", "experiment to git-repository Help: python add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021 (C2SM)", "if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in tests: test_cfg = get_config_of_current_test(test) csv_file", "type your commit message :') git_cmd = 'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__)", "= 'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message = input('Please", "df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the content of the description ' 'file including your", "file to the official repository, ' 'please perform the following steps:') log.info('1. Push", "process of adding ' 'the experiment {} to the reference is stoped.\\n' '(y/n/abort)", "shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf with bar-plots from Welch's-test if test == 'welch':", "that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if not", "col_name != 'Experiment name': # ask the user for info dict_line[col_name] = input('{}", "default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add to reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output')", "not in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT': exit() return() def", "import log from lib.test_config import get_config_of_current_test from lib.color import Style ''' Module providing", "new line to the experiment description file with all information about an experiment", "name :param f_exp_descr: file in which the new line has to be added", "tests: test_cfg = get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what is the", "add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or absolute path of the csv \\ files", "import lib.paths as paths import lib.utils as utils import lib.logger_config as logger_config #", "the description ' 'file including your new experiment.') log.info(df_exp_descr_new) answ_chg = input('Is the", "make all paths from user to absolute paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files =", "of adding ' 'the experiment {} to the reference is stoped.\\n' '(y/n/abort) :", "else: log.warning('{} not in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT': exit()", "' 'file including your new experiment.') log.info(df_exp_descr_new) answ_chg = input('Is the new file", "to the reference is stoped.\\n' '(y/n/abort) : ' ''.format(exp)) if answ_chg.upper() == 'Y':", ": '.format(col_name)) # amend the information if needed while True: # new dataframe", "add the file to the official repository, ' 'please perform the following steps:')", "test == 'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is the name", "= os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in tests: test_cfg =", "for file in files_to_commit: git_cmd = 'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit", "to the reference pool. It contains: - add_line_descr_f: Add a new line to", "'column values\\n' 'If you type abort, the process of adding ' 'the experiment", "in files_to_commit: git_cmd = 'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit))", "the following steps:') log.info('1. Push the new branch into the official repo:') log.info('", "origin {}'.format(new_branch_name)) log.info('2. On the Open Web interface (GitHub) , open a Pull", "# root is important to not fail during git commands os.chdir(paths.rootdir) # checkout", "file f_exp_descr :param exp: new expirement name :param f_exp_descr: file in which the", "interface (GitHub) , open a Pull Request.') log.banner('End add_exp_to_ref for experiment {}'.format(exp)) return()", "output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of testsuite') args = parser.parse_args() # init logger", "log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message = input('Please type your commit message", "utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified files prior in the function to git for", "log from lib.test_config import get_config_of_current_test from lib.color import Style ''' Module providing the", "pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the location to store that file", "file in which the new line has to be added return: None '''", "(y/n)', 'welch (y/n)', 'fldcor (y/n)', 'rmse (y/n)', 'emi (y/n)', 'Date of experiment (month", "one per reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add to reference", "reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add to reference pool') parser.add_argument('--verbose','-v',", "from Welch's-test if test == 'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what", "add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message = input('Please type your", "to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is important to not", "'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files are added in the", "test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy", "in df_exp_descr.keys(): if col_name != 'Experiment name': # ask the user for info", "f_exp_descr: file in which the new line has to be added return: None", "official repository, ' 'please perform the following steps:') log.info('1. Push the new branch", "os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f = ['Experiment name', 'Platform', 'OS', 'Compiler (with version)',", "lib.logger_config as logger_config # standalone imports from lib.logger_config import log from lib.test_config import", "import Style ''' Module providing the functionality to add an experiment to the", "the pool of csv files, \\ one per reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'],", "csv files, \\ one per reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to", "if answ_chg.upper() == 'Y': # save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of", ": ' ''.format(exp)) if answ_chg.upper() == 'Y': # save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) #", "if needed while True: # new dataframe containing new line for exp df_exp_descr_new", "== 'ABORT': exit() return() def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation", "what is the location to store that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir)", "not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in tests: test_cfg = get_config_of_current_test(test) csv_file =", "of experiment (month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';') #", "!= 'Experiment name': # ask the user for info dict_line[col_name] = input('{} :", "from user log.banner('Please give the following informations ' 'about your experiment') dict_line =", "= input('Which column field you want to change ?') if answ_col in df_exp_descr.keys():", "user log.banner('Please give the following informations ' 'about your experiment') dict_line = {'Experiment", "import lib.utils as utils import lib.logger_config as logger_config # standalone imports from lib.logger_config", "- add_line_descr_f: Add a new line to the experiment description file with all", "standard modules import os import shutil import argparse # aliased standard modules import", "import os import shutil import argparse # aliased standard modules import pandas as", "for test in tests: test_cfg = get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) #", "log.info('To add the file to the official repository, ' 'please perform the following", "aliased standard modules import pandas as pd # modules of sanity checker import", "the reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what is the location to store", "'If you type abort, the process of adding ' 'the experiment {} to", "if not os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f = ['Experiment name', 'Platform', 'OS', 'Compiler", "On the Open Web interface (GitHub) , open a Pull Request.') log.banner('End add_exp_to_ref", "name': # ask the user for info dict_line[col_name] = input('{} : '.format(col_name)) #", "type abort, the process of adding ' 'the experiment {} to the reference", "' ''.format(exp)) if answ_chg.upper() == 'Y': # save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get", "if __name__ == '__main__': # parsing arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp',", "the user for info dict_line[col_name] = input('{} : '.format(col_name)) # amend the information", "# parsing arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to add')", "answ_col in df_exp_descr.keys(): dict_line[answ_col] = input('{} : '.format(answ_col)) else: log.warning('{} not in columns!'.format(answ_col))", "initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit = [] # fill up file 'Exps_description.csv' with", ".format(test,exp)) # what is the filename in the reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp)", "ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in tests: test_cfg = get_config_of_current_test(test) csv_file = utils.clean_path(p_stages,", "init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as main()'.format(__file__)) # make all paths from", "or absolute path of the csv \\ files of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files',", "args = parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as main()'.format(__file__)) #", "file right ? (y/n/abort).\\n' 'If you type n, you will be able to", "'ABORT': exit() return() def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation new_branch_name", "user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in", "dataframe containing new line for exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the", "'{} in your local git repository.' .format(new_branch_name))) log.info('To add the file to the", "log.info(df_exp_descr_new) answ_chg = input('Is the new file right ? (y/n/abort).\\n' 'If you type", "for exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the content of the description", "add an experiment to the reference pool. It contains: - add_line_descr_f: Add a", "# what is the name of the pdf in the reference pool filename_in_ref_dir", "to git-repository Help: python add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021 (C2SM) '''", "'please perform the following steps:') log.info('1. Push the new branch into the official", "line {} in the file {}:'.format(exp,f_exp_descr)) # open file in dataframe if not", "= [] # fill up file 'Exps_description.csv' with additional # information via user", "the official repository, ' 'please perform the following steps:') log.info('1. Push the new", "your experiment') dict_line = {'Experiment name': exp} for col_name in df_exp_descr.keys(): if col_name", "'.format(answ_col)) else: log.warning('{} not in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT':", "file in files_to_commit: git_cmd = 'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files", "fail during git commands os.chdir(paths.rootdir) # checkout new branch if not ltestsuite: log.info('Create", "files_to_commit = [] # fill up file 'Exps_description.csv' with additional # information via", "in your local git repository.' .format(new_branch_name))) log.info('To add the file to the official", "will be able to change ' 'column values\\n' 'If you type abort, the", "reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the location to store that", "utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files are added in the new branch: ' '{}", "in dataframe if not os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f = ['Experiment name', 'Platform',", "perform the following steps:') log.info('1. Push the new branch into the official repo:')", "{} to the reference is stoped.\\n' '(y/n/abort) : ' ''.format(exp)) if answ_chg.upper() ==", "df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';') # collect information from user", "the file to the official repository, ' 'please perform the following steps:') log.info('1.", "not os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f = ['Experiment name', 'Platform', 'OS', 'Compiler (with", "your new experiment.') log.info(df_exp_descr_new) answ_chg = input('Is the new file right ? (y/n/abort).\\n'", "argparse # aliased standard modules import pandas as pd # modules of sanity", "as pd # modules of sanity checker import lib.paths as paths import lib.utils", "file in dataframe if not os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f = ['Experiment name',", "{}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified files prior in the function to git", "new branch into the official repo:') log.info(' git push --set-upstream origin {}'.format(new_branch_name)) log.info('2.", "utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages, p_ref_csv_files=args.p_ref_csv_files, ltestsuite=args.ltestsuite, lverbose=args.lverbose) log.banner('End execute {}", "stoped.\\n' '(y/n/abort) : ' ''.format(exp)) if answ_chg.upper() == 'Y': # save new file", "= 'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified files prior in", "arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to add') parser.add_argument('--p_stages', dest='p_stages',", "parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of testsuite') args = parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__)", "Module providing the functionality to add an experiment to the reference pool. It", "to change ?') if answ_col in df_exp_descr.keys(): dict_line[answ_col] = input('{} : '.format(answ_col)) else:", "modules import os import shutil import argparse # aliased standard modules import pandas", "to {}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf with bar-plots from", "(y/n)', '-no-prec-div (y/n)', 'welch (y/n)', 'fldcor (y/n)', 'rmse (y/n)', 'emi (y/n)', 'Date of", "add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in tests: test_cfg = get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv'", "ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf with bar-plots from Welch's-test if test ==", "user for info dict_line[col_name] = input('{} : '.format(col_name)) # amend the information if", "out of the loop return False elif answ_chg.upper() == 'N': answ_col = input('Which", "of new experiment to git-repository Help: python add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM) J.Jucker", "log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT': exit() return() def main(exp, tests, p_stages=paths.p_stages,", "if not ltestsuite: log.info('Create and checkout new branch {}'.format(new_branch_name)) git_cmd = 'git checkout", "into the official repo:') log.info(' git push --set-upstream origin {}'.format(new_branch_name)) log.info('2. On the", "'-no-prec-div (y/n)', 'welch (y/n)', 'fldcor (y/n)', 'rmse (y/n)', 'emi (y/n)', 'Date of experiment", "commits data of new experiment to git-repository Help: python add_exp_tp_ref.py --help C.Siegenthaler 07.2020", "# new dataframe containing new line for exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here", "p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit = [] #", "a new line to the experiment description file with all information about an", "'-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch (y/n)', 'fldcor (y/n)', 'rmse (y/n)', 'emi (y/n)', 'Date", "files {}'.format(files_to_commit)) commit_message = input('Please type your commit message :') git_cmd = 'git", "input('Please type your commit message :') git_cmd = 'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd,", "information about an experiment - main: asks user for additional information about experiment,", "not ltestsuite: log.info('Create and checkout new branch {}'.format(new_branch_name)) git_cmd = 'git checkout -B", "log.info(Style.GREEN('Files are added in the new branch: ' '{} in your local git", "execute {} as main()'.format(__file__)) # make all paths from user to absolute paths", "store that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference)", "os import shutil import argparse # aliased standard modules import pandas as pd", "(y/n)', 'Date of experiment (month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr,", "os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in tests: test_cfg = get_config_of_current_test(test)", "sep=';') # collect information from user log.banner('Please give the following informations ' 'about", "to add an experiment to the reference pool. It contains: - add_line_descr_f: Add", "filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the location to store that file place_for_reference", "ltestsuite: log.info('Create and checkout new branch {}'.format(new_branch_name)) git_cmd = 'git checkout -B {}'.format(new_branch_name)", "in which the new line has to be added return: None ''' log.info('Adding", "the name of the pdf in the reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) #", "git push --set-upstream origin {}'.format(new_branch_name)) log.info('2. On the Open Web interface (GitHub) ,", "Open Web interface (GitHub) , open a Pull Request.') log.banner('End add_exp_to_ref for experiment", "pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';') # collect information from user log.banner('Please give", "# make all paths from user to absolute paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files", "in tests: test_cfg = get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what is", "return() def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation new_branch_name = 'test_add_{}'.format(exp)", "shutil import argparse # aliased standard modules import pandas as pd # modules", "with bar-plots from Welch's-test if test == 'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp))", "lib.test_config import get_config_of_current_test from lib.color import Style ''' Module providing the functionality to", "for col_name in df_exp_descr.keys(): if col_name != 'Experiment name': # ask the user", "open a Pull Request.') log.banner('End add_exp_to_ref for experiment {}'.format(exp)) return() if __name__ ==", "os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) #", "pdf in the reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what is the location", "pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is the name of the pdf", "{} to {}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf with bar-plots", "the reference is stoped.\\n' '(y/n/abort) : ' ''.format(exp)) if answ_chg.upper() == 'Y': #", "including your new experiment.') log.info(df_exp_descr_new) answ_chg = input('Is the new file right ?", "you will be able to change ' 'column values\\n' 'If you type abort,", "git for file in files_to_commit: git_cmd = 'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__)", "# Finish log.info(Style.GREEN('Files are added in the new branch: ' '{} in your", "dest='ltestsuite', action='store_true', help='Run of testsuite') args = parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start", "answ_col = input('Which column field you want to change ?') if answ_col in", "nargs='+', help='Tests to add to reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts',", "elif answ_chg.upper() == 'ABORT': exit() return() def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False):", "message :') git_cmd = 'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files", "contains: - add_line_descr_f: Add a new line to the experiment description file with", "'Experiment name': # ask the user for info dict_line[col_name] = input('{} : '.format(col_name))", "(month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';') # collect information", "log.info(' git push --set-upstream origin {}'.format(new_branch_name)) log.info('2. On the Open Web interface (GitHub)", "'.format(col_name)) # amend the information if needed while True: # new dataframe containing", "files of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the pool of csv", "{} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is important to", "test_cfg = get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what is the filename", "to the experiment description file with all information about an experiment - main:", "== 'Y': # save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of the loop", "= 'test_add_{}'.format(exp) files_to_commit = [] # fill up file 'Exps_description.csv' with additional #", "the filename in the reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the", "{}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf with bar-plots from Welch's-test", "experiment') dict_line = {'Experiment name': exp} for col_name in df_exp_descr.keys(): if col_name !=", "and checkout new branch {}'.format(new_branch_name)) git_cmd = 'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') #", "place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference)", "logger_config # standalone imports from lib.logger_config import log from lib.test_config import get_config_of_current_test from", "pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of testsuite') args", "col_name in df_exp_descr.keys(): if col_name != 'Experiment name': # ask the user for", "new experiment to git-repository Help: python add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021", "field you want to change ?') if answ_col in df_exp_descr.keys(): dict_line[answ_col] = input('{}", "dict_line = {'Experiment name': exp} for col_name in df_exp_descr.keys(): if col_name != 'Experiment", "open file in dataframe if not os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f = ['Experiment", "name': exp} for col_name in df_exp_descr.keys(): if col_name != 'Experiment name': # ask", "files, \\ one per reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add", "an experiment to the reference pool. It contains: - add_line_descr_f: Add a new", "n, you will be able to change ' 'column values\\n' 'If you type", "add_line_descr_f: Add a new line to the experiment description file with all information", "= '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the location to store that file place_for_reference =", "'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified files prior in the", "get_config_of_current_test from lib.color import Style ''' Module providing the functionality to add an", "filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf", "create dataframe cols_exp_descr_f = ['Experiment name', 'Platform', 'OS', 'Compiler (with version)', 'Optimisation level", "formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or absolute", "exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the content of the description '", "expirement name :param f_exp_descr: file in which the new line has to be", "collect information from user log.banner('Please give the following informations ' 'about your experiment')", "files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is important to not fail during", "to change ' 'column values\\n' 'If you type abort, the process of adding", "['Experiment name', 'Platform', 'OS', 'Compiler (with version)', 'Optimisation level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt", "in the function to git for file in files_to_commit: git_cmd = 'git add", "asks user for additional information about experiment, commits data of new experiment to", "help='exp to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or absolute path of the csv", "parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or absolute path", "git_cmd = 'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified files prior", "repository.' .format(new_branch_name))) log.info('To add the file to the official repository, ' 'please perform", "of sanity checker import lib.paths as paths import lib.utils as utils import lib.logger_config", "paths import lib.utils as utils import lib.logger_config as logger_config # standalone imports from", "type n, you will be able to change ' 'column values\\n' 'If you", "bar-plots from Welch's-test if test == 'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) #", "are added in the new branch: ' '{} in your local git repository.'", "adding ' 'the experiment {} to the reference is stoped.\\n' '(y/n/abort) : '", "df_exp_descr = pd.read_csv(f_exp_descr, sep=';') # collect information from user log.banner('Please give the following", "version)', 'Optimisation level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch (y/n)', 'fldcor", "tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit = []", "about experiment, commits data of new experiment to git-repository Help: python add_exp_tp_ref.py --help", "= utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is the name of the pdf in", "{}'.format(new_branch_name)) git_cmd = 'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified files", "of the csv \\ files of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to", "(y/n/abort).\\n' 'If you type n, you will be able to change ' 'column", "ignore_index=True) log.banner('Here is the content of the description ' 'file including your new", "the new line has to be added return: None ''' log.info('Adding line {}", "files_to_commit.append(f_exp_descr) for test in tests: test_cfg = get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp))", "= utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages, p_ref_csv_files=args.p_ref_csv_files, ltestsuite=args.ltestsuite, lverbose=args.lverbose) log.banner('End execute", "'{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the location to store that file place_for_reference = os.path.join(p_ref_csv_files,", "are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT': exit() return() def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files,", "file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) if not ltestsuite:", "the pdf in the reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what is the", "line has to be added return: None ''' log.info('Adding line {} in the", "dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add to reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug", "= get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what is the filename in", "csv \\ files of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the pool", "f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in tests: test_cfg", "information via user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for", "log.banner('End add_exp_to_ref for experiment {}'.format(exp)) return() if __name__ == '__main__': # parsing arguments", "fill up file 'Exps_description.csv' with additional # information via user input f_exp_descr =", "experiment, commits data of new experiment to git-repository Help: python add_exp_tp_ref.py --help C.Siegenthaler", "ask the user for info dict_line[col_name] = input('{} : '.format(col_name)) # amend the", "py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message = input('Please type your commit message :') git_cmd", "log.info('Create and checkout new branch {}'.format(new_branch_name)) git_cmd = 'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py')", "commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files are added in the new", "paths from user to absolute paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp,", "input('{} : '.format(answ_col)) else: log.warning('{} not in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper()", "all modified files prior in the function to git for file in files_to_commit:", "# collect information from user log.banner('Please give the following informations ' 'about your", "give the following informations ' 'about your experiment') dict_line = {'Experiment name': exp}", "that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if", "'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is the name of the", "(-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch (y/n)', 'fldcor (y/n)', 'rmse (y/n)',", "branch into the official repo:') log.info(' git push --set-upstream origin {}'.format(new_branch_name)) log.info('2. On", "experiment (month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';') # collect", "of the description ' 'file including your new experiment.') log.info(df_exp_descr_new) answ_chg = input('Is", "name of the pdf in the reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what", "utils import lib.logger_config as logger_config # standalone imports from lib.logger_config import log from", "is stoped.\\n' '(y/n/abort) : ' ''.format(exp)) if answ_chg.upper() == 'Y': # save new", "information about experiment, commits data of new experiment to git-repository Help: python add_exp_tp_ref.py", "experiment.') log.info(df_exp_descr_new) answ_chg = input('Is the new file right ? (y/n/abort).\\n' 'If you", "# fill up file 'Exps_description.csv' with additional # information via user input f_exp_descr", "(C2SM) ''' def add_line_descr_f(exp,f_exp_descr): ''' Add line for exp exp in file f_exp_descr", "is the name of the pdf in the reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name)", "' 'about your experiment') dict_line = {'Experiment name': exp} for col_name in df_exp_descr.keys():", "your commit message :') git_cmd = 'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) #", "what is the filename in the reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what", "line for exp exp in file f_exp_descr :param exp: new expirement name :param", "a Pull Request.') log.banner('End add_exp_to_ref for experiment {}'.format(exp)) return() if __name__ == '__main__':", "files_to_commit: git_cmd = 'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message", "Finish log.info(Style.GREEN('Files are added in the new branch: ' '{} in your local", "the new branch: ' '{} in your local git repository.' .format(new_branch_name))) log.info('To add", "= 'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files are added in", "help='Run of testsuite') args = parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {}", "args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages, p_ref_csv_files=args.p_ref_csv_files, ltestsuite=args.ltestsuite, lverbose=args.lverbose) log.banner('End execute {} as", "default=paths.p_stages, help='relative or absolute path of the csv \\ files of the testresults')", "import argparse # aliased standard modules import pandas as pd # modules of", "new line has to be added return: None ''' log.info('Adding line {} in", "branch if not ltestsuite: log.info('Create and checkout new branch {}'.format(new_branch_name)) git_cmd = 'git", "data of new experiment to git-repository Help: python add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM)", "testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the pool of csv files, \\ one", "as logger_config # standalone imports from lib.logger_config import log from lib.test_config import get_config_of_current_test", "= utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests, p_stages=args.p_stages, p_ref_csv_files=args.p_ref_csv_files, ltestsuite=args.ltestsuite, lverbose=args.lverbose) log.banner('End execute {} as main()'.format(__file__))", "pd.read_csv(f_exp_descr, sep=';') # collect information from user log.banner('Please give the following informations '", "? (y/n/abort).\\n' 'If you type n, you will be able to change '", "following informations ' 'about your experiment') dict_line = {'Experiment name': exp} for col_name", "'the experiment {} to the reference is stoped.\\n' '(y/n/abort) : ' ''.format(exp)) if", "the location to store that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {}", "Push the new branch into the official repo:') log.info(' git push --set-upstream origin", ", open a Pull Request.') log.banner('End add_exp_to_ref for experiment {}'.format(exp)) return() if __name__", "import shutil import argparse # aliased standard modules import pandas as pd #", "answ_chg.upper() == 'ABORT': exit() return() def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): #", ":param exp: new expirement name :param f_exp_descr: file in which the new line", "the process of adding ' 'the experiment {} to the reference is stoped.\\n'", "lib.utils as utils import lib.logger_config as logger_config # standalone imports from lib.logger_config import", "description ' 'file including your new experiment.') log.info(df_exp_descr_new) answ_chg = input('Is the new", "ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is important to not fail during git commands os.chdir(paths.rootdir)", "exp exp in file f_exp_descr :param exp: new expirement name :param f_exp_descr: file", "os.chdir(paths.rootdir) # checkout new branch if not ltestsuite: log.info('Create and checkout new branch", "07.2020 (C2SM) J.Jucker 01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr): ''' Add line for exp", "False elif answ_chg.upper() == 'N': answ_col = input('Which column field you want to", "answ_chg.upper() == 'Y': # save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of the", "information if needed while True: # new dataframe containing new line for exp", "input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test in tests:", "columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT': exit() return() def main(exp, tests,", "to be added return: None ''' log.info('Adding line {} in the file {}:'.format(exp,f_exp_descr))", "up file 'Exps_description.csv' with additional # information via user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv')", "able to change ' 'column values\\n' 'If you type abort, the process of", "new file right ? (y/n/abort).\\n' 'If you type n, you will be able", "log.info('2. On the Open Web interface (GitHub) , open a Pull Request.') log.banner('End", "added return: None ''' log.info('Adding line {} in the file {}:'.format(exp,f_exp_descr)) # open", "main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit =", "new line for exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the content of", "file with all information about an experiment - main: asks user for additional", "from lib.color import Style ''' Module providing the functionality to add an experiment", "checkout new branch if not ltestsuite: log.info('Create and checkout new branch {}'.format(new_branch_name)) git_cmd", "= argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative", "Help: python add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr):", "get_config_of_current_test(test) csv_file = utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what is the filename in the", "not ltestsuite: shutil.copy(csv_file,place_for_reference) files_to_commit.append(place_for_reference) # copy pdf with bar-plots from Welch's-test if test", "help='Tests to add to reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite',", "Request.') log.banner('End add_exp_to_ref for experiment {}'.format(exp)) return() if __name__ == '__main__': # parsing", "to the official repository, ' 'please perform the following steps:') log.info('1. Push the", "in the new branch: ' '{} in your local git repository.' .format(new_branch_name))) log.info('To", "new expirement name :param f_exp_descr: file in which the new line has to", "pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what is the location to store that file", "important to not fail during git commands os.chdir(paths.rootdir) # checkout new branch if", "''' log.info('Adding line {} in the file {}:'.format(exp,f_exp_descr)) # open file in dataframe", "action='store_true', help='Run of testsuite') args = parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute", "git commands os.chdir(paths.rootdir) # checkout new branch if not ltestsuite: log.info('Create and checkout", "as utils import lib.logger_config as logger_config # standalone imports from lib.logger_config import log", "from lib.test_config import get_config_of_current_test from lib.color import Style ''' Module providing the functionality", "yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';') # collect information from", "' 'please perform the following steps:') log.info('1. Push the new branch into the", "as main()'.format(__file__)) # make all paths from user to absolute paths args.p_stages =", "is the location to store that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy", "= ['Experiment name', 'Platform', 'OS', 'Compiler (with version)', 'Optimisation level (-OX)', '-fast-transcendentals (y/n)',", "(with version)', 'Optimisation level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch (y/n)',", "add_line_descr_f(exp,f_exp_descr): ''' Add line for exp exp in file f_exp_descr :param exp: new", "content of the description ' 'file including your new experiment.') log.info(df_exp_descr_new) answ_chg =", "the file {}:'.format(exp,f_exp_descr)) # open file in dataframe if not os.path.isfile(f_exp_descr): # create", "files prior in the function to git for file in files_to_commit: git_cmd =", "git repository.' .format(new_branch_name))) log.info('To add the file to the official repository, ' 'please", "input('Is the new file right ? (y/n/abort).\\n' 'If you type n, you will", "in df_exp_descr.keys(): dict_line[answ_col] = input('{} : '.format(answ_col)) else: log.warning('{} not in columns!'.format(answ_col)) log.info('Columns", "'welch (y/n)', 'fldcor (y/n)', 'rmse (y/n)', 'emi (y/n)', 'Date of experiment (month yyyy)']", "to not fail during git commands os.chdir(paths.rootdir) # checkout new branch if not", "--set-upstream origin {}'.format(new_branch_name)) log.info('2. On the Open Web interface (GitHub) , open a", "--help C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr): ''' Add line", "def main(exp, tests, p_stages=paths.p_stages, p_ref_csv_files=paths.p_ref_csv_files, ltestsuite=False, lverbose=False): # initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit", "additional # information via user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr)", "''.format(exp)) if answ_chg.upper() == 'Y': # save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out", "description file with all information about an experiment - main: asks user for", "' 'the experiment {} to the reference is stoped.\\n' '(y/n/abort) : ' ''.format(exp))", "= df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the content of the description ' 'file including", "'OS', 'Compiler (with version)', 'Optimisation level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)',", "{}:'.format(exp,f_exp_descr)) # open file in dataframe if not os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f", "the Open Web interface (GitHub) , open a Pull Request.') log.banner('End add_exp_to_ref for", "pdf with bar-plots from Welch's-test if test == 'welch': pdf_file = utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name,", "J.Jucker 01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr): ''' Add line for exp exp in", "dataframe cols_exp_descr_f = ['Experiment name', 'Platform', 'OS', 'Compiler (with version)', 'Optimisation level (-OX)',", "\"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files are added in the new branch: '", "help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of testsuite') args = parser.parse_args() # init", "experiment to the reference pool. It contains: - add_line_descr_f: Add a new line", "[] # fill up file 'Exps_description.csv' with additional # information via user input", "sanity checker import lib.paths as paths import lib.utils as utils import lib.logger_config as", "standard modules import pandas as pd # modules of sanity checker import lib.paths", "# what is the location to store that file place_for_reference = os.path.join(p_ref_csv_files, test,", "01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr): ''' Add line for exp exp in file", "level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch (y/n)', 'fldcor (y/n)', 'rmse", ":') git_cmd = 'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files are", "the content of the description ' 'file including your new experiment.') log.info(df_exp_descr_new) answ_chg", "= '{}_plots.pdf'.format(test_cfg.ref_name) # what is the location to store that file place_for_reference =", "# open file in dataframe if not os.path.isfile(f_exp_descr): # create dataframe cols_exp_descr_f =", "# initialisation new_branch_name = 'test_add_{}'.format(exp) files_to_commit = [] # fill up file 'Exps_description.csv'", "lib.paths as paths import lib.utils as utils import lib.logger_config as logger_config # standalone", ".format(new_branch_name))) log.info('To add the file to the official repository, ' 'please perform the", "git_cmd = 'git add {}'.format(file) log.debug(git_cmd) utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message =", "{} as main()'.format(__file__)) # make all paths from user to absolute paths args.p_stages", "- main: asks user for additional information about experiment, commits data of new", "reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true', help='Debug output') parser.add_argument('--testsuite','-ts', dest='ltestsuite', action='store_true', help='Run of testsuite')", "change ' 'column values\\n' 'If you type abort, the process of adding '", "line to the experiment description file with all information about an experiment -", "experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add to reference pool') parser.add_argument('--verbose','-v', dest='lverbose',", "new branch: ' '{} in your local git repository.' .format(new_branch_name))) log.info('To add the", "new dataframe containing new line for exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is", "you type abort, the process of adding ' 'the experiment {} to the", "not ltestsuite: shutil.copy(pdf_file,place_for_reference) # root is important to not fail during git commands", "about an experiment - main: asks user for additional information about experiment, commits", "experiment {} to the reference is stoped.\\n' '(y/n/abort) : ' ''.format(exp)) if answ_chg.upper()", "# checkout new branch if not ltestsuite: log.info('Create and checkout new branch {}'.format(new_branch_name))", "for info dict_line[col_name] = input('{} : '.format(col_name)) # amend the information if needed", "per reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add to reference pool')", "pd # modules of sanity checker import lib.paths as paths import lib.utils as", "= input('Is the new file right ? (y/n/abort).\\n' 'If you type n, you", "-m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish log.info(Style.GREEN('Files are added in the new branch:", "experiment - main: asks user for additional information about experiment, commits data of", "has to be added return: None ''' log.info('Adding line {} in the file", "reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what is the location to store that", "lib.color import Style ''' Module providing the functionality to add an experiment to", "abort, the process of adding ' 'the experiment {} to the reference is", "df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of the loop return False elif answ_chg.upper() == 'N':", "official repo:') log.info(' git push --set-upstream origin {}'.format(new_branch_name)) log.info('2. On the Open Web", "# what is the filename in the reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) #", "{}'.format(exp)) return() if __name__ == '__main__': # parsing arguments parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter)", "change ?') if answ_col in df_exp_descr.keys(): dict_line[answ_col] = input('{} : '.format(answ_col)) else: log.warning('{}", "new branch if not ltestsuite: log.info('Create and checkout new branch {}'.format(new_branch_name)) git_cmd =", "# amend the information if needed while True: # new dataframe containing new", "{} in the file {}:'.format(exp,f_exp_descr)) # open file in dataframe if not os.path.isfile(f_exp_descr):", "(y/n)', 'rmse (y/n)', 'emi (y/n)', 'Date of experiment (month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f)", "checkout new branch {}'.format(new_branch_name)) git_cmd = 'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit", "input('Which column field you want to change ?') if answ_col in df_exp_descr.keys(): dict_line[answ_col]", "(y/n)', 'emi (y/n)', 'Date of experiment (month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr", "None ''' log.info('Adding line {} in the file {}:'.format(exp,f_exp_descr)) # open file in", "?') if answ_col in df_exp_descr.keys(): dict_line[answ_col] = input('{} : '.format(answ_col)) else: log.warning('{} not", "the function to git for file in files_to_commit: git_cmd = 'git add {}'.format(file)", ":param f_exp_descr: file in which the new line has to be added return:", "{}'.format(new_branch_name)) log.info('2. On the Open Web interface (GitHub) , open a Pull Request.')", "== 'N': answ_col = input('Which column field you want to change ?') if", "reference pool. It contains: - add_line_descr_f: Add a new line to the experiment", "from user to absolute paths args.p_stages = utils.abs_path(args.p_stages) args.p_ref_csv_files = utils.abs_path(args.p_ref_csv_files) main(exp=args.exp, tests=args.tests,", "branch {}'.format(new_branch_name)) git_cmd = 'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all modified", "function to git for file in files_to_commit: git_cmd = 'git add {}'.format(file) log.debug(git_cmd)", "python add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr): '''", "log.info('Adding line {} in the file {}:'.format(exp,f_exp_descr)) # open file in dataframe if", "reference is stoped.\\n' '(y/n/abort) : ' ''.format(exp)) if answ_chg.upper() == 'Y': # save", "in file f_exp_descr :param exp: new expirement name :param f_exp_descr: file in which", "dict_line[answ_col] = input('{} : '.format(answ_col)) else: log.warning('{} not in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns)))", "py_routine=__name__) # Finish log.info(Style.GREEN('Files are added in the new branch: ' '{} in", "log.info('1. Push the new branch into the official repo:') log.info(' git push --set-upstream", "argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--exp','-e', dest='exp', required=True, help='exp to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or", "to the pool of csv files, \\ one per reference experiment') parser.add_argument('--tests','-t', dest='tests',", "= parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as main()'.format(__file__)) # make", "{'Experiment name': exp} for col_name in df_exp_descr.keys(): if col_name != 'Experiment name': #", "of the pdf in the reference pool filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what is", "filename_in_ref_dir = '{}_plots.pdf'.format(test_cfg.ref_name) # what is the location to store that file place_for_reference", "import lib.logger_config as logger_config # standalone imports from lib.logger_config import log from lib.test_config", "utils.shell_cmd(git_cmd, py_routine=__name__) log.debug('Commit files {}'.format(files_to_commit)) commit_message = input('Please type your commit message :')", "get out of the loop return False elif answ_chg.upper() == 'N': answ_col =", "Add line for exp exp in file f_exp_descr :param exp: new expirement name", "True: # new dataframe containing new line for exp df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True)", "new branch {}'.format(new_branch_name)) git_cmd = 'git checkout -B {}'.format(new_branch_name) utils.shell_cmd(git_cmd,py_routine='add_exp_to_ref.py') # commit all", "= utils.clean_path(p_stages, 'test_postproc_{}_{}.csv' .format(test,exp)) # what is the filename in the reference pool", "all information about an experiment - main: asks user for additional information about", "your local git repository.' .format(new_branch_name))) log.info('To add the file to the official repository,", "an experiment - main: asks user for additional information about experiment, commits data", "the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the pool of csv files, \\", "'Date of experiment (month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';')", "root is important to not fail during git commands os.chdir(paths.rootdir) # checkout new", "testsuite') args = parser.parse_args() # init logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as main()'.format(__file__))", "if answ_col in df_exp_descr.keys(): dict_line[answ_col] = input('{} : '.format(answ_col)) else: log.warning('{} not in", "# copy pdf with bar-plots from Welch's-test if test == 'welch': pdf_file =", "'Optimisation level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div (y/n)', 'welch (y/n)', 'fldcor (y/n)',", "of csv files, \\ one per reference experiment') parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests", "following steps:') log.info('1. Push the new branch into the official repo:') log.info(' git", "'fldcor (y/n)', 'rmse (y/n)', 'emi (y/n)', 'Date of experiment (month yyyy)'] df_exp_descr =", "with all information about an experiment - main: asks user for additional information", "# standalone imports from lib.logger_config import log from lib.test_config import get_config_of_current_test from lib.color", "C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr): ''' Add line for", "in the file {}:'.format(exp,f_exp_descr)) # open file in dataframe if not os.path.isfile(f_exp_descr): #", "while True: # new dataframe containing new line for exp df_exp_descr_new = df_exp_descr.append(dict_line,", "want to change ?') if answ_col in df_exp_descr.keys(): dict_line[answ_col] = input('{} : '.format(answ_col))", "required=True, help='exp to add') parser.add_argument('--p_stages', dest='p_stages', default=paths.p_stages, help='relative or absolute path of the", "the new file right ? (y/n/abort).\\n' 'If you type n, you will be", "filename in the reference pool filename_in_ref_dir = '{}_{}.csv'.format(test_cfg.ref_name,exp) # what is the location", "place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite:", "df_exp_descr_new = df_exp_descr.append(dict_line, ignore_index=True) log.banner('Here is the content of the description ' 'file", "the official repo:') log.info(' git push --set-upstream origin {}'.format(new_branch_name)) log.info('2. On the Open", "= os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference)) files_to_commit.append(place_for_reference) if not ltestsuite: shutil.copy(pdf_file,place_for_reference)", "add_exp_tp_ref.py --help C.Siegenthaler 07.2020 (C2SM) J.Jucker 01.2021 (C2SM) ''' def add_line_descr_f(exp,f_exp_descr): ''' Add", "utils.clean_path(p_stages, '{}_{}.pdf'.format(test_cfg.ref_name, exp)) # what is the name of the pdf in the", "of the testresults') parser.add_argument('--p_ref_csv_files', dest='p_ref_csv_files', default=paths.p_ref_csv_files, help='path to the pool of csv files,", "else: df_exp_descr = pd.read_csv(f_exp_descr, sep=';') # collect information from user log.banner('Please give the", "commit all modified files prior in the function to git for file in", "logger logger_config.init_logger(args.lverbose,__file__) log.banner('Start execute {} as main()'.format(__file__)) # make all paths from user", "new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of the loop return False elif answ_chg.upper()", "# save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of the loop return False", "added in the new branch: ' '{} in your local git repository.' .format(new_branch_name)))", "repo:') log.info(' git push --set-upstream origin {}'.format(new_branch_name)) log.info('2. On the Open Web interface", "modules of sanity checker import lib.paths as paths import lib.utils as utils import", "'emi (y/n)', 'Date of experiment (month yyyy)'] df_exp_descr = pd.DataFrame(columns=cols_exp_descr_f) else: df_exp_descr =", "loop return False elif answ_chg.upper() == 'N': answ_col = input('Which column field you", "= input('{} : '.format(answ_col)) else: log.warning('{} not in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif", "in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT': exit() return() def main(exp,", "is the content of the description ' 'file including your new experiment.') log.info(df_exp_descr_new)", "'N': answ_col = input('Which column field you want to change ?') if answ_col", "log.warning('{} not in columns!'.format(answ_col)) log.info('Columns are {}\\n'.format(list(df_exp_descr.columns))) elif answ_chg.upper() == 'ABORT': exit() return()", "local git repository.' .format(new_branch_name))) log.info('To add the file to the official repository, '", "'Platform', 'OS', 'Compiler (with version)', 'Optimisation level (-OX)', '-fast-transcendentals (y/n)', '-no-prec-sqrt (y/n)', '-no-prec-div", "functionality to add an experiment to the reference pool. It contains: - add_line_descr_f:", "# aliased standard modules import pandas as pd # modules of sanity checker", "information from user log.banner('Please give the following informations ' 'about your experiment') dict_line", "via user input f_exp_descr = os.path.join(p_ref_csv_files,'Exps_description.csv') if not ltestsuite: add_line_descr_f(exp=exp,f_exp_descr=f_exp_descr) files_to_commit.append(f_exp_descr) for test", "commit_message = input('Please type your commit message :') git_cmd = 'git commit -m", "to store that file place_for_reference = os.path.join(p_ref_csv_files, test, filename_in_ref_dir) log.debug('Copy {} to {}'.format(csv_file,place_for_reference))", "standalone imports from lib.logger_config import log from lib.test_config import get_config_of_current_test from lib.color import", "parser.add_argument('--tests','-t', dest='tests', default=['welch','fldcor','rmse','emi'], nargs='+', help='Tests to add to reference pool') parser.add_argument('--verbose','-v', dest='lverbose', action='store_true',", "commit message :') git_cmd = 'git commit -m \"{}\"'.format(commit_message) utils.shell_cmd(git_cmd, py_routine=__name__) # Finish", "checker import lib.paths as paths import lib.utils as utils import lib.logger_config as logger_config", "push --set-upstream origin {}'.format(new_branch_name)) log.info('2. On the Open Web interface (GitHub) , open", "It contains: - add_line_descr_f: Add a new line to the experiment description file", "'Y': # save new file df_exp_descr_new.to_csv(f_exp_descr,sep=';',index=False) # get out of the loop return" ]
[ "flask_restx import Resource from ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the", "the HealthLiveness class.\"\"\" from flask_restx import Resource from ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\")", "from ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the /liveness GET method.\"\"\"", "\"Success\", } ) def get() -> FlaskApiReturnType: \"\"\" Returns liveness status. \"\"\" return", ") def get() -> FlaskApiReturnType: \"\"\" Returns liveness status. \"\"\" return {\"Alive\": True},", "HealthLiveness(Resource): \"\"\"Implements the /liveness GET method.\"\"\" @staticmethod @api.doc( responses={ 200: \"Success\", } )", "<gh_stars>10-100 \"\"\"This module implements the HealthLiveness class.\"\"\" from flask_restx import Resource from ml_rest_api.api.restx", "class.\"\"\" from flask_restx import Resource from ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource):", "GET method.\"\"\" @staticmethod @api.doc( responses={ 200: \"Success\", } ) def get() -> FlaskApiReturnType:", "ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the /liveness GET method.\"\"\" @staticmethod", "def get() -> FlaskApiReturnType: \"\"\" Returns liveness status. \"\"\" return {\"Alive\": True}, 200", "/liveness GET method.\"\"\" @staticmethod @api.doc( responses={ 200: \"Success\", } ) def get() ->", "@api.doc( responses={ 200: \"Success\", } ) def get() -> FlaskApiReturnType: \"\"\" Returns liveness", "method.\"\"\" @staticmethod @api.doc( responses={ 200: \"Success\", } ) def get() -> FlaskApiReturnType: \"\"\"", "module implements the HealthLiveness class.\"\"\" from flask_restx import Resource from ml_rest_api.api.restx import api,", "from flask_restx import Resource from ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements", "Resource from ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the /liveness GET", "@api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the /liveness GET method.\"\"\" @staticmethod @api.doc( responses={ 200: \"Success\",", "\"\"\"Implements the /liveness GET method.\"\"\" @staticmethod @api.doc( responses={ 200: \"Success\", } ) def", "import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the /liveness GET method.\"\"\" @staticmethod @api.doc(", "FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the /liveness GET method.\"\"\" @staticmethod @api.doc( responses={ 200:", "\"\"\"This module implements the HealthLiveness class.\"\"\" from flask_restx import Resource from ml_rest_api.api.restx import", "@staticmethod @api.doc( responses={ 200: \"Success\", } ) def get() -> FlaskApiReturnType: \"\"\" Returns", "api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the /liveness GET method.\"\"\" @staticmethod @api.doc( responses={", "responses={ 200: \"Success\", } ) def get() -> FlaskApiReturnType: \"\"\" Returns liveness status.", "implements the HealthLiveness class.\"\"\" from flask_restx import Resource from ml_rest_api.api.restx import api, FlaskApiReturnType", "HealthLiveness class.\"\"\" from flask_restx import Resource from ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class", "the /liveness GET method.\"\"\" @staticmethod @api.doc( responses={ 200: \"Success\", } ) def get()", "class HealthLiveness(Resource): \"\"\"Implements the /liveness GET method.\"\"\" @staticmethod @api.doc( responses={ 200: \"Success\", }", "} ) def get() -> FlaskApiReturnType: \"\"\" Returns liveness status. \"\"\" return {\"Alive\":", "import Resource from ml_rest_api.api.restx import api, FlaskApiReturnType @api.default_namespace.route(\"/liveness\") class HealthLiveness(Resource): \"\"\"Implements the /liveness", "200: \"Success\", } ) def get() -> FlaskApiReturnType: \"\"\" Returns liveness status. \"\"\"" ]
[ "of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model): logger.error('`layer` can only", "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "layer wrapper for a keras layer. Args: layer: The keras layer to be", "= tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as", "the License. # ============================================================================== \"\"\"Wrapper which is custom layer over underlying layer. `CustomOpWrapper`", "this file except in compliance with the License. # You may obtain a", "def get_config(self): base_config = super(CustomOpWrapper, self).get_config() config = {} return dict(list(base_config.items()) + list(config.items()))", "placed in the graph. \"\"\" from __future__ import absolute_import from __future__ import division", "is None: logger.error('`layer` cannot be None.') # Check against keras.Model since it is", "in kwargs: kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def build(self, input_shape):", "for modifying the construction of the underlying layer to ensure proper attributes are", "{input}.'.format( input=layer.__class__.__name__)) if 'name' not in kwargs: kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs)", "ANY KIND, either express or implied. # See the License for the specific", "outputs def get_config(self): base_config = super(CustomOpWrapper, self).get_config() config = {} return dict(list(base_config.items()) +", "absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "custom layer wrapper for a keras layer. Args: layer: The keras layer to", "trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): return self.layer.updates", "build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None):", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model): logger.error('`layer` can only be a `tf.keras.layers.Layer` instance.", "since it is an instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance(", "an instance of type: {input}.'.format( input=layer.__class__.__name__)) if 'name' not in kwargs: kwargs['name'] =", "attributes are placed in the graph. \"\"\" from __future__ import absolute_import from __future__", "OF ANY KIND, either express or implied. # See the License for the", "layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self,", "import copy from tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable", "@classmethod def from_config(cls, config): config = config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config)", "def call(self, inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args if 'training' in args: outputs =", "logger.error('`layer` cannot be None.') # Check against keras.Model since it is an instance", "layer over underlying layer. `CustomOpWrapper` is responsible for modifying the construction of the", "config): config = config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property def trainable_weights(self):", "tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "self).build(input_shape) def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args", "outputs = self.layer.call(inputs) return outputs def get_config(self): base_config = super(CustomOpWrapper, self).get_config() config =", "the graph. \"\"\" from __future__ import absolute_import from __future__ import division from __future__", "specific language governing permissions and # limitations under the License. # ============================================================================== \"\"\"Wrapper", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "it is an instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer,", "division from __future__ import print_function import tensorflow as tf import copy from tensorflow.python.util", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "limitations under the License. # ============================================================================== \"\"\"Wrapper which is custom layer over underlying", "class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as a custom layer and set some attributes\"\"\"", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "and # limitations under the License. # ============================================================================== \"\"\"Wrapper which is custom layer", "# ============================================================================== \"\"\"Wrapper which is custom layer over underlying layer. `CustomOpWrapper` is responsible", "required by applicable law or agreed to in writing, software # distributed under", "from tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object =", "applicable law or agreed to in writing, software # distributed under the License", "layer. `CustomOpWrapper` is responsible for modifying the construction of the underlying layer to", "instance of type: {input}.'.format( input=layer.__class__.__name__)) if 'name' not in kwargs: kwargs['name'] = layer.name", "or agreed to in writing, software # distributed under the License is distributed", "return cls(layer=layer, **config) @property def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights", "import print_function import tensorflow as tf import copy from tensorflow.python.util import tf_inspect from", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "cls(layer=layer, **config) @property def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property", "tf.keras.Model): logger.error('`layer` can only be a `tf.keras.layers.Layer` instance. ' 'You passed an instance", "passed to the keras layer. \"\"\" if layer is None: logger.error('`layer` cannot be", "wrapper for a keras layer. Args: layer: The keras layer to be quantized.", "def __init__(self, layer, **kwargs): \"\"\"Create a custom layer wrapper for a keras layer.", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "writing, software # distributed under the License is distributed on an \"AS IS\"", "import tensorflow as tf import copy from tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import", "be a `tf.keras.layers.Layer` instance. ' 'You passed an instance of type: {input}.'.format( input=layer.__class__.__name__))", "**config) @property def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def", "tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "= super(CustomOpWrapper, self).get_config() config = {} return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls,", "License. # You may obtain a copy of the License at # #", "layer, tf.keras.Model): logger.error('`layer` can only be a `tf.keras.layers.Layer` instance. ' 'You passed an", "as a custom layer and set some attributes\"\"\" def __init__(self, layer, **kwargs): \"\"\"Create", "list(config.items())) @classmethod def from_config(cls, config): config = config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer,", "compliance with the License. # You may obtain a copy of the License", "keras layer. \"\"\" if layer is None: logger.error('`layer` cannot be None.') # Check", "import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger =", "not in kwargs: kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def build(self,", "underlying layer to ensure proper attributes are placed in the graph. \"\"\" from", "keras layer. Args: layer: The keras layer to be quantized. **kwargs: Additional keyword", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as a custom layer and set some attributes\"\"\" def", "can only be a `tf.keras.layers.Layer` instance. ' 'You passed an instance of type:", "keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model): logger.error('`layer` can only be", "============================================================================== \"\"\"Wrapper which is custom layer over underlying layer. `CustomOpWrapper` is responsible for", "not use this file except in compliance with the License. # You may", "to the keras layer. \"\"\" if layer is None: logger.error('`layer` cannot be None.')", "call(self, inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args if 'training' in args: outputs = self.layer.call(inputs,", "cannot be None.') # Check against keras.Model since it is an instance of", "License, Version 2.0 (the \"License\"); # you may not use this file except", "instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model): logger.error('`layer` can", "2019 Xilinx Inc. # # Licensed under the Apache License, Version 2.0 (the", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "set some attributes\"\"\" def __init__(self, layer, **kwargs): \"\"\"Create a custom layer wrapper for", "a `tf.keras.layers.Layer` instance. ' 'You passed an instance of type: {input}.'.format( input=layer.__class__.__name__)) if", "self._track_trackable(layer, name='layer') def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def", "config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property def trainable_weights(self): return self.layer.trainable_weights @property", "deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper):", "common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger", "# you may not use this file except in compliance with the License.", "Check against keras.Model since it is an instance of keras.layers.Layer. if not isinstance(layer,", "agreed to in writing, software # distributed under the License is distributed on", "= self.layer.call(inputs, training=training) else: outputs = self.layer.call(inputs) return outputs def get_config(self): base_config =", "' 'You passed an instance of type: {input}.'.format( input=layer.__class__.__name__)) if 'name' not in", "only be a `tf.keras.layers.Layer` instance. ' 'You passed an instance of type: {input}.'.format(", "**kwargs) self._track_trackable(layer, name='layer') def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape)", "(the \"License\"); # you may not use this file except in compliance with", "in the graph. \"\"\" from __future__ import absolute_import from __future__ import division from", "tf import copy from tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable =", "self.layer.call(inputs) return outputs def get_config(self): base_config = super(CustomOpWrapper, self).get_config() config = {} return", "= config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property def trainable_weights(self): return self.layer.trainable_weights", "# Unless required by applicable law or agreed to in writing, software #", "return self.layer.non_trainable_weights @property def updates(self): return self.layer.updates + self._updates @property def losses(self): return", "by applicable law or agreed to in writing, software # distributed under the", "not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model): logger.error('`layer` can only be a `tf.keras.layers.Layer`", "tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "some attributes\"\"\" def __init__(self, layer, **kwargs): \"\"\"Create a custom layer wrapper for a", "Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "**kwargs): \"\"\"Create a custom layer wrapper for a keras layer. Args: layer: The", "type: {input}.'.format( input=layer.__class__.__name__)) if 'name' not in kwargs: kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer,", "is an instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model):", "ensure proper attributes are placed in the graph. \"\"\" from __future__ import absolute_import", "keras layer to be quantized. **kwargs: Additional keyword arguments to be passed to", "file except in compliance with the License. # You may obtain a copy", "quantized. **kwargs: Additional keyword arguments to be passed to the keras layer. \"\"\"", "attributes\"\"\" def __init__(self, layer, **kwargs): \"\"\"Create a custom layer wrapper for a keras", "License for the specific language governing permissions and # limitations under the License.", "**kwargs: Additional keyword arguments to be passed to the keras layer. \"\"\" if", "and set some attributes\"\"\" def __init__(self, layer, **kwargs): \"\"\"Create a custom layer wrapper", "to in writing, software # distributed under the License is distributed on an", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "layer. Args: layer: The keras layer to be quantized. **kwargs: Additional keyword arguments", "None: logger.error('`layer` cannot be None.') # Check against keras.Model since it is an", "input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None): args", "get_config(self): base_config = super(CustomOpWrapper, self).get_config() config = {} return dict(list(base_config.items()) + list(config.items())) @classmethod", "__init__(self, layer, **kwargs): \"\"\"Create a custom layer wrapper for a keras layer. Args:", "\"\"\"Mark this layer as a custom layer and set some attributes\"\"\" def __init__(self,", "base_config = super(CustomOpWrapper, self).get_config() config = {} return dict(list(base_config.items()) + list(config.items())) @classmethod def", "`CustomOpWrapper` is responsible for modifying the construction of the underlying layer to ensure", "permissions and # limitations under the License. # ============================================================================== \"\"\"Wrapper which is custom", "tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object =", "or implied. # See the License for the specific language governing permissions and", "import division from __future__ import print_function import tensorflow as tf import copy from", "layer: The keras layer to be quantized. **kwargs: Additional keyword arguments to be", "self).get_config() config = {} return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): config", "def updates(self): return self.layer.updates + self._updates @property def losses(self): return self.layer.losses + self._losses", "return self.layer.updates + self._updates @property def losses(self): return self.layer.losses + self._losses _types_dict =", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "modifying the construction of the underlying layer to ensure proper attributes are placed", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "def from_config(cls, config): config = config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "responsible for modifying the construction of the underlying layer to ensure proper attributes", "__future__ import print_function import tensorflow as tf import copy from tensorflow.python.util import tf_inspect", "super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None): args =", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "Args: layer: The keras layer to be quantized. **kwargs: Additional keyword arguments to", "a keras layer. Args: layer: The keras layer to be quantized. **kwargs: Additional", "tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return", "kwargs: kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def build(self, input_shape): super(CustomOpWrapper,", "if layer is None: logger.error('`layer` cannot be None.') # Check against keras.Model since", "proper attributes are placed in the graph. \"\"\" from __future__ import absolute_import from", "= tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper')", "Copyright 2019 Xilinx Inc. # # Licensed under the Apache License, Version 2.0", "@property def updates(self): return self.layer.updates + self._updates @property def losses(self): return self.layer.losses +", "'name' not in kwargs: kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def", "{} return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): config = config.copy() layer", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "is responsible for modifying the construction of the underlying layer to ensure proper", "you may not use this file except in compliance with the License. #", "under the License. # ============================================================================== \"\"\"Wrapper which is custom layer over underlying layer.", "the underlying layer to ensure proper attributes are placed in the graph. \"\"\"", "instance. ' 'You passed an instance of type: {input}.'.format( input=layer.__class__.__name__)) if 'name' not", "self.layer.updates + self._updates @property def losses(self): return self.layer.losses + self._losses _types_dict = {\"CustomOpWrapper\",", "def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): return self.layer.updates + self._updates @property def", "'training' in args: outputs = self.layer.call(inputs, training=training) else: outputs = self.layer.call(inputs) return outputs", "compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args if 'training'", "tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model): logger.error('`layer` can only be a `tf.keras.layers.Layer` instance. '", "from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object", "be quantized. **kwargs: Additional keyword arguments to be passed to the keras layer.", "use this file except in compliance with the License. # You may obtain", "input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args if 'training' in", "non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): return self.layer.updates + self._updates @property def losses(self):", "tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger", "__future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow", "copy from tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object", "Xilinx Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as a custom layer and", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "args: outputs = self.layer.call(inputs, training=training) else: outputs = self.layer.call(inputs) return outputs def get_config(self):", "if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model): logger.error('`layer` can only be a", "2.0 (the \"License\"); # you may not use this file except in compliance", "print_function import tensorflow as tf import copy from tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils", "outputs = self.layer.call(inputs, training=training) else: outputs = self.layer.call(inputs) return outputs def get_config(self): base_config", "the construction of the underlying layer to ensure proper attributes are placed in", "for the specific language governing permissions and # limitations under the License. #", "register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis',", "@property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): return self.layer.updates + self._updates @property", "if 'training' in args: outputs = self.layer.call(inputs, training=training) else: outputs = self.layer.call(inputs) return", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "<reponame>hito0512/Vitis-AI # Copyright 2019 Xilinx Inc. # # Licensed under the Apache License,", "else: outputs = self.layer.call(inputs) return outputs def get_config(self): base_config = super(CustomOpWrapper, self).get_config() config", "# # Unless required by applicable law or agreed to in writing, software", "of the underlying layer to ensure proper attributes are placed in the graph.", "express or implied. # See the License for the specific language governing permissions", "input=layer.__class__.__name__)) if 'name' not in kwargs: kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer,", "return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): return self.layer.updates +", "either express or implied. # See the License for the specific language governing", "= tf.keras.utils.deserialize_keras_object serialize_keras_object = tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark", "\"\"\"Create a custom layer wrapper for a keras layer. Args: layer: The keras", "which is custom layer over underlying layer. `CustomOpWrapper` is responsible for modifying the", "The keras layer to be quantized. **kwargs: Additional keyword arguments to be passed", "training=training) else: outputs = self.layer.call(inputs) return outputs def get_config(self): base_config = super(CustomOpWrapper, self).get_config()", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): config = config.copy() layer =", "to ensure proper attributes are placed in the graph. \"\"\" from __future__ import", "def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): return", "'You passed an instance of type: {input}.'.format( input=layer.__class__.__name__)) if 'name' not in kwargs:", "name='layer') def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self,", "training=None): args = tf_inspect.getfullargspec(self.layer.call).args if 'training' in args: outputs = self.layer.call(inputs, training=training) else:", "layer, **kwargs): \"\"\"Create a custom layer wrapper for a keras layer. Args: layer:", "to be passed to the keras layer. \"\"\" if layer is None: logger.error('`layer`", "name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as a custom layer and set some", "passed an instance of type: {input}.'.format( input=layer.__class__.__name__)) if 'name' not in kwargs: kwargs['name']", "tf_inspect.getfullargspec(self.layer.call).args if 'training' in args: outputs = self.layer.call(inputs, training=training) else: outputs = self.layer.call(inputs)", "= tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self):", "the License. # You may obtain a copy of the License at #", "logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as a custom", "# Check against keras.Model since it is an instance of keras.layers.Layer. if not", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "`tf.keras.layers.Layer` instance. ' 'You passed an instance of type: {input}.'.format( input=layer.__class__.__name__)) if 'name'", "= self.layer.call(inputs) return outputs def get_config(self): base_config = super(CustomOpWrapper, self).get_config() config = {}", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "isinstance( layer, tf.keras.Model): logger.error('`layer` can only be a `tf.keras.layers.Layer` instance. ' 'You passed", "\"\"\"Wrapper which is custom layer over underlying layer. `CustomOpWrapper` is responsible for modifying", "in args: outputs = self.layer.call(inputs, training=training) else: outputs = self.layer.call(inputs) return outputs def", "= tf_inspect.getfullargspec(self.layer.call).args if 'training' in args: outputs = self.layer.call(inputs, training=training) else: outputs =", "from __future__ import absolute_import from __future__ import division from __future__ import print_function import", "self.layer.call(inputs, training=training) else: outputs = self.layer.call(inputs) return outputs def get_config(self): base_config = super(CustomOpWrapper,", "self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape): return", "tensorflow as tf import copy from tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils", "with the License. # You may obtain a copy of the License at", "= layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def", "if 'name' not in kwargs: kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer')", "config = config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property def trainable_weights(self): return", "over underlying layer. `CustomOpWrapper` is responsible for modifying the construction of the underlying", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "layer to be quantized. **kwargs: Additional keyword arguments to be passed to the", "kwargs['name'] = layer.name super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape)", "are placed in the graph. \"\"\" from __future__ import absolute_import from __future__ import", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args if", "config = {} return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): config =", "import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable = tf.keras.utils.register_keras_serializable deserialize_keras_object = tf.keras.utils.deserialize_keras_object serialize_keras_object", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "= {} return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): config = config.copy()", "from_config(cls, config): config = config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property def", "serialize_keras_object = tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer", "+ list(config.items())) @classmethod def from_config(cls, config): config = config.copy() layer = tf.keras.layers.deserialize(config.pop('layer')) return", "is custom layer over underlying layer. `CustomOpWrapper` is responsible for modifying the construction", "# limitations under the License. # ============================================================================== \"\"\"Wrapper which is custom layer over", "# Copyright 2019 Xilinx Inc. # # Licensed under the Apache License, Version", "this layer as a custom layer and set some attributes\"\"\" def __init__(self, layer,", "to be quantized. **kwargs: Additional keyword arguments to be passed to the keras", "layer as a custom layer and set some attributes\"\"\" def __init__(self, layer, **kwargs):", "updates(self): return self.layer.updates + self._updates @property def losses(self): return self.layer.losses + self._losses _types_dict", "layer to ensure proper attributes are placed in the graph. \"\"\" from __future__", "in compliance with the License. # You may obtain a copy of the", "keras.Model since it is an instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "tf.keras.utils.serialize_keras_object logger = common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as a", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "an instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model): logger.error('`layer`", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "License. # ============================================================================== \"\"\"Wrapper which is custom layer over underlying layer. `CustomOpWrapper` is", "super(CustomOpWrapper, self).get_config() config = {} return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config):", "language governing permissions and # limitations under the License. # ============================================================================== \"\"\"Wrapper which", "for a keras layer. Args: layer: The keras layer to be quantized. **kwargs:", "self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self): return self.layer.updates + self._updates", "See the License for the specific language governing permissions and # limitations under", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "import absolute_import from __future__ import division from __future__ import print_function import tensorflow as", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "@register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as a custom layer and set", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "custom layer and set some attributes\"\"\" def __init__(self, layer, **kwargs): \"\"\"Create a custom", "construction of the underlying layer to ensure proper attributes are placed in the", "None.') # Check against keras.Model since it is an instance of keras.layers.Layer. if", "\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function", "def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape): return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs,", "be None.') # Check against keras.Model since it is an instance of keras.layers.Layer.", "a custom layer wrapper for a keras layer. Args: layer: The keras layer", "self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args if 'training' in args: outputs", "\"\"\" if layer is None: logger.error('`layer` cannot be None.') # Check against keras.Model", "layer is None: logger.error('`layer` cannot be None.') # Check against keras.Model since it", "the keras layer. \"\"\" if layer is None: logger.error('`layer` cannot be None.') #", "keyword arguments to be passed to the keras layer. \"\"\" if layer is", "Version 2.0 (the \"License\"); # you may not use this file except in", "except in compliance with the License. # You may obtain a copy of", "the specific language governing permissions and # limitations under the License. # ==============================================================================", "be passed to the keras layer. \"\"\" if layer is None: logger.error('`layer` cannot", "graph. \"\"\" from __future__ import absolute_import from __future__ import division from __future__ import", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "+ self._updates @property def losses(self): return self.layer.losses + self._losses _types_dict = {\"CustomOpWrapper\", CustomOpWrapper}", "arguments to be passed to the keras layer. \"\"\" if layer is None:", "layer = tf.keras.layers.deserialize(config.pop('layer')) return cls(layer=layer, **config) @property def trainable_weights(self): return self.layer.trainable_weights @property def", "self.layer.non_trainable_weights @property def updates(self): return self.layer.updates + self._updates @property def losses(self): return self.layer.losses", "underlying layer. `CustomOpWrapper` is responsible for modifying the construction of the underlying layer", "__future__ import division from __future__ import print_function import tensorflow as tf import copy", "args = tf_inspect.getfullargspec(self.layer.call).args if 'training' in args: outputs = self.layer.call(inputs, training=training) else: outputs", "against keras.Model since it is an instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer)", "layer. \"\"\" if layer is None: logger.error('`layer` cannot be None.') # Check against", "custom layer over underlying layer. `CustomOpWrapper` is responsible for modifying the construction of", "@property def trainable_weights(self): return self.layer.trainable_weights @property def non_trainable_weights(self): return self.layer.non_trainable_weights @property def updates(self):", "from __future__ import print_function import tensorflow as tf import copy from tensorflow.python.util import", "or isinstance( layer, tf.keras.Model): logger.error('`layer` can only be a `tf.keras.layers.Layer` instance. ' 'You", "of type: {input}.'.format( input=layer.__class__.__name__)) if 'name' not in kwargs: kwargs['name'] = layer.name super(CustomOpWrapper,", "as tf import copy from tensorflow.python.util import tf_inspect from tensorflow_model_optimization.python.core.quantization.keras.vitis.utils import common_utils register_keras_serializable", "logger.error('`layer` can only be a `tf.keras.layers.Layer` instance. ' 'You passed an instance of", "return outputs def get_config(self): base_config = super(CustomOpWrapper, self).get_config() config = {} return dict(list(base_config.items())", "= common_utils.VAILogger @register_keras_serializable(package='Vitis', name='CustomOpWrapper') class CustomOpWrapper(tf.keras.layers.Wrapper): \"\"\"Mark this layer as a custom layer", "governing permissions and # limitations under the License. # ============================================================================== \"\"\"Wrapper which is", "from __future__ import division from __future__ import print_function import tensorflow as tf import", "Additional keyword arguments to be passed to the keras layer. \"\"\" if layer", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "super(CustomOpWrapper, self).__init__(layer, **kwargs) self._track_trackable(layer, name='layer') def build(self, input_shape): super(CustomOpWrapper, self).build(input_shape) def compute_output_shape(self, input_shape):", "dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): config = config.copy() layer = tf.keras.layers.deserialize(config.pop('layer'))", "inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args if 'training' in args: outputs = self.layer.call(inputs, training=training)", "a custom layer and set some attributes\"\"\" def __init__(self, layer, **kwargs): \"\"\"Create a", "return self.layer.compute_output_shape(self.layer.input_shape) def call(self, inputs, training=None): args = tf_inspect.getfullargspec(self.layer.call).args if 'training' in args:", "layer and set some attributes\"\"\" def __init__(self, layer, **kwargs): \"\"\"Create a custom layer" ]
[ "response.status_code != 200: raise BadResponse( \"The service responded with a {}: {}\".format( response.status_code,", "urljoin import requests from crosswalk_client.exceptions import BadResponse from crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain", "validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain, update_attrs): response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"),", "def update_domain(self, domain, update_attrs): response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if", "BadResponse from crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def", "UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain, update_attrs): response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs,", "service responded with a {}: {}\".format( response.status_code, response.content ) ) return DomainObject(response.json(), client=self)", "from crosswalk_client.exceptions import BadResponse from crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg class", ") if response.status_code != 200: raise BadResponse( \"The service responded with a {}:", "\"The service responded with a {}: {}\".format( response.status_code, response.content ) ) return DomainObject(response.json(),", "from urllib.parse import urljoin import requests from crosswalk_client.exceptions import BadResponse from crosswalk_client.objects.domain import", "update_domain(self, domain, update_attrs): response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if response.status_code", "200: raise BadResponse( \"The service responded with a {}: {}\".format( response.status_code, response.content )", "urllib.parse import urljoin import requests from crosswalk_client.exceptions import BadResponse from crosswalk_client.objects.domain import DomainObject", "raise BadResponse( \"The service responded with a {}: {}\".format( response.status_code, response.content ) )", "requests from crosswalk_client.exceptions import BadResponse from crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg", "import DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain, update_attrs):", "BadResponse( \"The service responded with a {}: {}\".format( response.status_code, response.content ) ) return", "headers=self.headers, json=update_attrs, ) if response.status_code != 200: raise BadResponse( \"The service responded with", "response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if response.status_code != 200: raise", "import requests from crosswalk_client.exceptions import BadResponse from crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain import", "crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain, update_attrs): response = requests.patch(", "import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain, update_attrs): response = requests.patch( urljoin(self.service_address,", "requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if response.status_code != 200: raise BadResponse( \"The", "DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain, update_attrs): response", "urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if response.status_code != 200: raise BadResponse( \"The service", "from crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain, update_attrs): response =", "json=update_attrs, ) if response.status_code != 200: raise BadResponse( \"The service responded with a", "crosswalk_client.exceptions import BadResponse from crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object):", "class UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain, update_attrs): response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers,", "!= 200: raise BadResponse( \"The service responded with a {}: {}\".format( response.status_code, response.content", "@validate_required_domain_arg def update_domain(self, domain, update_attrs): response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, )", "import BadResponse from crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg", "import urljoin import requests from crosswalk_client.exceptions import BadResponse from crosswalk_client.objects.domain import DomainObject from", "f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if response.status_code != 200: raise BadResponse( \"The service responded", "if response.status_code != 200: raise BadResponse( \"The service responded with a {}: {}\".format(", "update_attrs): response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if response.status_code != 200:", "crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def update_domain(self, domain,", "from crosswalk_client.objects.domain import DomainObject from crosswalk_client.validators.domain import validate_required_domain_arg class UpdateDomain(object): @validate_required_domain_arg def update_domain(self,", "= requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if response.status_code != 200: raise BadResponse(", "domain, update_attrs): response = requests.patch( urljoin(self.service_address, f\"domains/{domain}/\"), headers=self.headers, json=update_attrs, ) if response.status_code !=" ]
[]
[]
[ "from mozdns.sshfp.forms import SSHFPForm class SSHFPView(object): model = SSHFP form_class = SSHFPForm queryset", "from mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms import SSHFPForm class SSHFPView(object): model = SSHFP", "form_class = SSHFPForm queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView,", "SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView, MozdnsUpdateView): \"\"\" \"\"\" class SSHFPListView(SSHFPView, MozdnsListView): \"\"\"", "= SSHFPForm queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView):", "from mozdns.views import MozdnsListView from mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms import SSHFPForm class", "import MozdnsCreateView from mozdns.views import MozdnsDetailView from mozdns.views import MozdnsUpdateView from mozdns.views import", "MozdnsUpdateView from mozdns.views import MozdnsListView from mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms import SSHFPForm", "model = SSHFP form_class = SSHFPForm queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\"", "MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView, MozdnsUpdateView): \"\"\" \"\"\" class SSHFPListView(SSHFPView, MozdnsListView): \"\"\" \"\"\"", "queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\"", "SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class", "mozdns.views import MozdnsUpdateView from mozdns.views import MozdnsListView from mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms", "SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html' class", "\"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\"", "MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView,", "template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView, MozdnsUpdateView): \"\"\" \"\"\"", "mozdns.views import MozdnsListView from mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms import SSHFPForm class SSHFPView(object):", "\"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView):", "'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView, MozdnsUpdateView): \"\"\" \"\"\" class SSHFPListView(SSHFPView,", "import MozdnsDetailView from mozdns.views import MozdnsUpdateView from mozdns.views import MozdnsListView from mozdns.sshfp.models import", "# Create your views here. from mozdns.views import MozdnsDeleteView from mozdns.views import MozdnsCreateView", "from mozdns.views import MozdnsUpdateView from mozdns.views import MozdnsListView from mozdns.sshfp.models import SSHFP from", "class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html'", "\"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView, MozdnsUpdateView):", "views here. from mozdns.views import MozdnsDeleteView from mozdns.views import MozdnsCreateView from mozdns.views import", "MozdnsCreateView from mozdns.views import MozdnsDetailView from mozdns.views import MozdnsUpdateView from mozdns.views import MozdnsListView", "here. from mozdns.views import MozdnsDeleteView from mozdns.views import MozdnsCreateView from mozdns.views import MozdnsDetailView", "Create your views here. from mozdns.views import MozdnsDeleteView from mozdns.views import MozdnsCreateView from", "import MozdnsUpdateView from mozdns.views import MozdnsListView from mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms import", "import SSHFP from mozdns.sshfp.forms import SSHFPForm class SSHFPView(object): model = SSHFP form_class =", "SSHFPForm class SSHFPView(object): model = SSHFP form_class = SSHFPForm queryset = SSHFP.objects.all() class", "SSHFPForm queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\"", "from mozdns.views import MozdnsDetailView from mozdns.views import MozdnsUpdateView from mozdns.views import MozdnsListView from", "SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name =", "MozdnsDetailView from mozdns.views import MozdnsUpdateView from mozdns.views import MozdnsListView from mozdns.sshfp.models import SSHFP", "mozdns.sshfp.forms import SSHFPForm class SSHFPView(object): model = SSHFP form_class = SSHFPForm queryset =", "your views here. from mozdns.views import MozdnsDeleteView from mozdns.views import MozdnsCreateView from mozdns.views", "= SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name", "mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms import SSHFPForm class SSHFPView(object): model = SSHFP form_class", "MozdnsListView from mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms import SSHFPForm class SSHFPView(object): model =", "mozdns.views import MozdnsDeleteView from mozdns.views import MozdnsCreateView from mozdns.views import MozdnsDetailView from mozdns.views", "SSHFP form_class = SSHFPForm queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\" class", "class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView, MozdnsUpdateView): \"\"\" \"\"\" class SSHFPListView(SSHFPView, MozdnsListView):", "import MozdnsListView from mozdns.sshfp.models import SSHFP from mozdns.sshfp.forms import SSHFPForm class SSHFPView(object): model", "import SSHFPForm class SSHFPView(object): model = SSHFP form_class = SSHFPForm queryset = SSHFP.objects.all()", "class SSHFPDetailView(SSHFPView, MozdnsDetailView): \"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\"", "from mozdns.views import MozdnsDeleteView from mozdns.views import MozdnsCreateView from mozdns.views import MozdnsDetailView from", "MozdnsDetailView): \"\"\" \"\"\" template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView,", "from mozdns.views import MozdnsCreateView from mozdns.views import MozdnsDetailView from mozdns.views import MozdnsUpdateView from", "= 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView, MozdnsUpdateView): \"\"\" \"\"\" class", "mozdns.views import MozdnsDetailView from mozdns.views import MozdnsUpdateView from mozdns.views import MozdnsListView from mozdns.sshfp.models", "SSHFP from mozdns.sshfp.forms import SSHFPForm class SSHFPView(object): model = SSHFP form_class = SSHFPForm", "class SSHFPView(object): model = SSHFP form_class = SSHFPForm queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView,", "\"\"\" template_name = 'sshfp/sshfp_detail.html' class SSHFPCreateView(SSHFPView, MozdnsCreateView): \"\"\" \"\"\" class SSHFPUpdateView(SSHFPView, MozdnsUpdateView): \"\"\"", "= SSHFP form_class = SSHFPForm queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView): \"\"\" \"\"\"", "import MozdnsDeleteView from mozdns.views import MozdnsCreateView from mozdns.views import MozdnsDetailView from mozdns.views import", "MozdnsDeleteView from mozdns.views import MozdnsCreateView from mozdns.views import MozdnsDetailView from mozdns.views import MozdnsUpdateView", "mozdns.views import MozdnsCreateView from mozdns.views import MozdnsDetailView from mozdns.views import MozdnsUpdateView from mozdns.views", "SSHFPView(object): model = SSHFP form_class = SSHFPForm queryset = SSHFP.objects.all() class SSHFPDeleteView(SSHFPView, MozdnsDeleteView):" ]
[ "chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs) await sourceurl(page,", "chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs) await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page,", "**kwargs) await chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs) await sourceurl(page, **kwargs)", "from .chrome_runtime import chrome_runtime from .iframe_content_window import iframe_content_window from .media_codecs import media_codecs from", "import navigator_permissions from .navigator_plugins import navigator_plugins from .navigator_vendor import navigator_vendor from .navigator_webdriver import", ".navigator_languages import navigator_languages from .navigator_permissions import navigator_permissions from .navigator_plugins import navigator_plugins from .navigator_vendor", "navigator_permissions from .navigator_plugins import navigator_plugins from .navigator_vendor import navigator_vendor from .navigator_webdriver import navigator_webdriver", "import navigator_languages from .navigator_permissions import navigator_permissions from .navigator_plugins import navigator_plugins from .navigator_vendor import", "navigator_webdriver from .user_agent_override import user_agent_override from .utils import with_utils from .webgl_vendor import webgl_vendor", ".navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages import navigator_languages from .navigator_permissions import navigator_permissions from .navigator_plugins", "from .chrome_app import chrome_app from .chrome_runtime import chrome_runtime from .iframe_content_window import iframe_content_window from", "import Page from .chrome_app import chrome_app from .chrome_runtime import chrome_runtime from .iframe_content_window import", "from .sourceurl import sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages import navigator_languages from", "chrome_runtime from .iframe_content_window import iframe_content_window from .media_codecs import media_codecs from .sourceurl import sourceurl", "navigator_hardware_concurrency from .navigator_languages import navigator_languages from .navigator_permissions import navigator_permissions from .navigator_plugins import navigator_plugins", ".navigator_plugins import navigator_plugins from .navigator_vendor import navigator_vendor from .navigator_webdriver import navigator_webdriver from .user_agent_override", "await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs) await", "Page): raise ValueError(\"page must be pyppeteer.page.Page\") await with_utils(page, **kwargs) await chrome_app(page, **kwargs) await", "Page from .chrome_app import chrome_app from .chrome_runtime import chrome_runtime from .iframe_content_window import iframe_content_window", "not isinstance(page, Page): raise ValueError(\"page must be pyppeteer.page.Page\") await with_utils(page, **kwargs) await chrome_app(page,", "navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs) await user_agent_override(page, **kwargs) await webgl_vendor(page,", "**kwargs) await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs)", "if not isinstance(page, Page): raise ValueError(\"page must be pyppeteer.page.Page\") await with_utils(page, **kwargs) await", "await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs) await", "pyppeteer.page import Page from .chrome_app import chrome_app from .chrome_runtime import chrome_runtime from .iframe_content_window", "import user_agent_override from .utils import with_utils from .webgl_vendor import webgl_vendor from .window_outerdimensions import", ".chrome_app import chrome_app from .chrome_runtime import chrome_runtime from .iframe_content_window import iframe_content_window from .media_codecs", "None: if not isinstance(page, Page): raise ValueError(\"page must be pyppeteer.page.Page\") await with_utils(page, **kwargs)", "import with_utils from .webgl_vendor import webgl_vendor from .window_outerdimensions import window_outerdimensions async def stealth(page:", "from .user_agent_override import user_agent_override from .utils import with_utils from .webgl_vendor import webgl_vendor from", "navigator_plugins from .navigator_vendor import navigator_vendor from .navigator_webdriver import navigator_webdriver from .user_agent_override import user_agent_override", "from pyppeteer.page import Page from .chrome_app import chrome_app from .chrome_runtime import chrome_runtime from", "from .webgl_vendor import webgl_vendor from .window_outerdimensions import window_outerdimensions async def stealth(page: Page, **kwargs)", "await iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs) await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs) await", "navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs) await user_agent_override(page,", "ValueError(\"page must be pyppeteer.page.Page\") await with_utils(page, **kwargs) await chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs)", ".navigator_vendor import navigator_vendor from .navigator_webdriver import navigator_webdriver from .user_agent_override import user_agent_override from .utils", "from .navigator_webdriver import navigator_webdriver from .user_agent_override import user_agent_override from .utils import with_utils from", ".window_outerdimensions import window_outerdimensions async def stealth(page: Page, **kwargs) -> None: if not isinstance(page,", ".media_codecs import media_codecs from .sourceurl import sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages", "import navigator_hardware_concurrency from .navigator_languages import navigator_languages from .navigator_permissions import navigator_permissions from .navigator_plugins import", "await navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs) await", ".webgl_vendor import webgl_vendor from .window_outerdimensions import window_outerdimensions async def stealth(page: Page, **kwargs) ->", "navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs) await navigator_vendor(page,", "**kwargs) await iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs) await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs)", "from .navigator_permissions import navigator_permissions from .navigator_plugins import navigator_plugins from .navigator_vendor import navigator_vendor from", "raise ValueError(\"page must be pyppeteer.page.Page\") await with_utils(page, **kwargs) await chrome_app(page, **kwargs) await chrome_runtime(page,", "from .iframe_content_window import iframe_content_window from .media_codecs import media_codecs from .sourceurl import sourceurl from", "stealth(page: Page, **kwargs) -> None: if not isinstance(page, Page): raise ValueError(\"page must be", "import chrome_app from .chrome_runtime import chrome_runtime from .iframe_content_window import iframe_content_window from .media_codecs import", "**kwargs) await navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs) await user_agent_override(page, **kwargs)", "await chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs) await", "**kwargs) -> None: if not isinstance(page, Page): raise ValueError(\"page must be pyppeteer.page.Page\") await", "from .media_codecs import media_codecs from .sourceurl import sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency from", ".chrome_runtime import chrome_runtime from .iframe_content_window import iframe_content_window from .media_codecs import media_codecs from .sourceurl", "with_utils from .webgl_vendor import webgl_vendor from .window_outerdimensions import window_outerdimensions async def stealth(page: Page,", "Page, **kwargs) -> None: if not isinstance(page, Page): raise ValueError(\"page must be pyppeteer.page.Page\")", "isinstance(page, Page): raise ValueError(\"page must be pyppeteer.page.Page\") await with_utils(page, **kwargs) await chrome_app(page, **kwargs)", "user_agent_override from .utils import with_utils from .webgl_vendor import webgl_vendor from .window_outerdimensions import window_outerdimensions", ".iframe_content_window import iframe_content_window from .media_codecs import media_codecs from .sourceurl import sourceurl from .navigator_hardware_concurrency", "with_utils(page, **kwargs) await chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs) await media_codecs(page,", "import navigator_plugins from .navigator_vendor import navigator_vendor from .navigator_webdriver import navigator_webdriver from .user_agent_override import", "**kwargs) await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs)", "await navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs) await user_agent_override(page, **kwargs) await", "**kwargs) await navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs)", "webgl_vendor from .window_outerdimensions import window_outerdimensions async def stealth(page: Page, **kwargs) -> None: if", "def stealth(page: Page, **kwargs) -> None: if not isinstance(page, Page): raise ValueError(\"page must", "iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs) await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page,", "navigator_vendor from .navigator_webdriver import navigator_webdriver from .user_agent_override import user_agent_override from .utils import with_utils", "await chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs) await sourceurl(page, **kwargs) await", "**kwargs) await navigator_webdriver(page, **kwargs) await user_agent_override(page, **kwargs) await webgl_vendor(page, **kwargs) await window_outerdimensions(page, **kwargs)", "from .utils import with_utils from .webgl_vendor import webgl_vendor from .window_outerdimensions import window_outerdimensions async", "iframe_content_window from .media_codecs import media_codecs from .sourceurl import sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency", "await navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs) await user_agent_override(page, **kwargs) await webgl_vendor(page, **kwargs) await", "navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs) await navigator_webdriver(page,", ".utils import with_utils from .webgl_vendor import webgl_vendor from .window_outerdimensions import window_outerdimensions async def", "await with_utils(page, **kwargs) await chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs) await", ".navigator_webdriver import navigator_webdriver from .user_agent_override import user_agent_override from .utils import with_utils from .webgl_vendor", "be pyppeteer.page.Page\") await with_utils(page, **kwargs) await chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs) await iframe_content_window(page,", "import chrome_runtime from .iframe_content_window import iframe_content_window from .media_codecs import media_codecs from .sourceurl import", "from .navigator_languages import navigator_languages from .navigator_permissions import navigator_permissions from .navigator_plugins import navigator_plugins from", "import navigator_vendor from .navigator_webdriver import navigator_webdriver from .user_agent_override import user_agent_override from .utils import", "**kwargs) await navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs) await user_agent_override(page, **kwargs) await webgl_vendor(page, **kwargs)", "from .navigator_plugins import navigator_plugins from .navigator_vendor import navigator_vendor from .navigator_webdriver import navigator_webdriver from", "**kwargs) await navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs)", "pyppeteer.page.Page\") await with_utils(page, **kwargs) await chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs)", "sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs) await navigator_plugins(page,", "**kwargs) await chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs) await iframe_content_window(page, **kwargs) await media_codecs(page, **kwargs)", "navigator_vendor(page, **kwargs) await navigator_webdriver(page, **kwargs) await user_agent_override(page, **kwargs) await webgl_vendor(page, **kwargs) await window_outerdimensions(page,", "must be pyppeteer.page.Page\") await with_utils(page, **kwargs) await chrome_app(page, **kwargs) await chrome_runtime(page, **kwargs) await", "media_codecs(page, **kwargs) await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs) await navigator_permissions(page,", ".user_agent_override import user_agent_override from .utils import with_utils from .webgl_vendor import webgl_vendor from .window_outerdimensions", "sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages import navigator_languages from .navigator_permissions import navigator_permissions", "navigator_languages from .navigator_permissions import navigator_permissions from .navigator_plugins import navigator_plugins from .navigator_vendor import navigator_vendor", "<reponame>ramiezer2/pyppeteer_stealth from pyppeteer.page import Page from .chrome_app import chrome_app from .chrome_runtime import chrome_runtime", "**kwargs) await media_codecs(page, **kwargs) await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs)", "chrome_app from .chrome_runtime import chrome_runtime from .iframe_content_window import iframe_content_window from .media_codecs import media_codecs", ".sourceurl import sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages import navigator_languages from .navigator_permissions", ".navigator_permissions import navigator_permissions from .navigator_plugins import navigator_plugins from .navigator_vendor import navigator_vendor from .navigator_webdriver", "from .window_outerdimensions import window_outerdimensions async def stealth(page: Page, **kwargs) -> None: if not", "import navigator_webdriver from .user_agent_override import user_agent_override from .utils import with_utils from .webgl_vendor import", "from .navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages import navigator_languages from .navigator_permissions import navigator_permissions from", "import iframe_content_window from .media_codecs import media_codecs from .sourceurl import sourceurl from .navigator_hardware_concurrency import", "await navigator_languages(page, **kwargs) await navigator_permissions(page, **kwargs) await navigator_plugins(page, **kwargs) await navigator_vendor(page, **kwargs) await", "import window_outerdimensions async def stealth(page: Page, **kwargs) -> None: if not isinstance(page, Page):", "await media_codecs(page, **kwargs) await sourceurl(page, **kwargs) await navigator_hardware_concurrency(page, **kwargs) await navigator_languages(page, **kwargs) await", "from .navigator_vendor import navigator_vendor from .navigator_webdriver import navigator_webdriver from .user_agent_override import user_agent_override from", "media_codecs from .sourceurl import sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages import navigator_languages", "window_outerdimensions async def stealth(page: Page, **kwargs) -> None: if not isinstance(page, Page): raise", "import sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages import navigator_languages from .navigator_permissions import", "-> None: if not isinstance(page, Page): raise ValueError(\"page must be pyppeteer.page.Page\") await with_utils(page,", "import webgl_vendor from .window_outerdimensions import window_outerdimensions async def stealth(page: Page, **kwargs) -> None:", "async def stealth(page: Page, **kwargs) -> None: if not isinstance(page, Page): raise ValueError(\"page", "import media_codecs from .sourceurl import sourceurl from .navigator_hardware_concurrency import navigator_hardware_concurrency from .navigator_languages import" ]
[ "remaining, discard any * sets. The regex is a match if at the", "string and pattern are equal. \"\"\" import functools @functools.lru_cache() def is_match(s, p): if", "is True assert is_match('bbbba', '.*a*a') is True assert is_match('a', '.*..a*') is False assert", "True # examine if skipping the pattern leads to a match return is_match(s,", "false \"\"\" \"\"\" We go backwards through the string and pattern. If there", "any character (.)\". Example 4: Input: s = \"aab\", p = \"c*a*b\", Output:", "characters from the pattern (the * matching 0 characters). If we get to", "p[:-2]) else: # no match, no * after return False assert is_match('a', 'ab*')", "Output: false \"\"\" \"\"\" We go backwards through the string and pattern. If", "the end of the string and there is still a pattern remaining, discard", "*. Example 1: Input: s = \"aa\", p = \"a\", Output: false Explanation:", "return False elif not s: return is_match(s, p[:-2]) if len(p) >= 2 and", "is_match(s, p[:-2]) if len(p) >= 2 and p[-1] == '*' else False if", "'*' means zero or more of the preceding element, 'a'. Therefore, by repeating", "input string (not partial). Note: s could be empty and contains only lowercase", "'a*a') is True assert is_match('bbbba', '.*a*a') is True assert is_match('a', '.*..a*') is False", "\"a\" does not match the entire string \"aa\". Example 2: Input: s =", "s == p: return True elif s and not p: return False elif", "is True assert is_match('aa', 'a*') is True assert is_match('ab', '.*') is True assert", "whether combinations of consuming more characters from the string (repeating characters) or more", "True assert is_match('a', '.*..a*') is False assert is_match('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c') is False assert is_match('aa',", "else: # no match, no * after return False assert is_match('a', 'ab*') is", "'ab*') is True assert is_match('abc', 'abc') is True assert is_match('aa', 'a') is False", "(repeating characters) or more characters from the pattern (the * matching 0 characters).", "'.*c') is False assert is_match('aab', 'c*a*b') is True assert is_match('mississippi', 'mis*is*p*.') is False", "if s[-1] == p[-1] or p[-1] == '.': # simple match return is_match(s[:-1],", "examine if skipping the pattern leads to a match return is_match(s, p[:-2]) else:", "# examine if skipping the pattern leads to a match return is_match(s, p[:-2])", "len(s)+1): # examine if consuming more string characters leads to a match if", "repeated 1 time. Therefore, it matches \"aab\". Example 5: Input: s = \"mississippi\",", "a *, examine whether combinations of consuming more characters from the string (repeating", "does not match the entire string \"aa\". Example 2: Input: s = \"aa\",", "we get to the end of the string and there is still a", "no match, but * after return is_match(s, p[:-2]) else: # match, with *", "means zero or more of the preceding element, 'a'. Therefore, by repeating 'a'", "Explanation: \"a\" does not match the entire string \"aa\". Example 2: Input: s", "the end the string and pattern are equal. \"\"\" import functools @functools.lru_cache() def", "= \"aa\", p = \"a*\", Output: true Explanation: '*' means zero or more", "at the end the string and pattern are equal. \"\"\" import functools @functools.lru_cache()", "'*' Matches zero or more of the preceding element. The matching should cover", "3: Input: s = \"ab\", p = \".*\", Output: true Explanation: \".*\" means", "and contains only lowercase letters a-z, and characters like . or *. Example", "p: return True elif s and not p: return False elif not s:", "after for idx in range(1, len(s)+1): # examine if consuming more string characters", "True assert is_match('ab', '.*c') is False assert is_match('aab', 'c*a*b') is True assert is_match('mississippi',", "through the string and pattern. If there is a character match and there", "match return is_match(s[:-1], p[:-1]) elif p[-1] == '*': if p[-2] != s[-1] and", "0 times, a can be repeated 1 time. Therefore, it matches \"aab\". Example", "repeated 0 times, a can be repeated 1 time. Therefore, it matches \"aab\".", "True assert is_match('ab', '.*') is True assert is_match('ab', '.*c') is False assert is_match('aab',", "zero or more of the preceding element. The matching should cover the entire", "is a match if at the end the string and pattern are equal.", "else: # match, with * after for idx in range(1, len(s)+1): # examine", "is_match('a', 'a*a') is True assert is_match('bbbba', '.*a*a') is True assert is_match('a', '.*..a*') is", "(s) and a pattern (p), implement regular expression matching with support for '.'", "and pattern by one. If there is a *, examine whether combinations of", "for idx in range(1, len(s)+1): # examine if consuming more string characters leads", "Input: s = \"mississippi\", p = \"mis*is*p*.\", Output: false \"\"\" \"\"\" We go", "there is a character match and there is no *, advance through the", ">= 2 and p[-1] == '*' else False if s[-1] == p[-1] or", "'.*a*a') is True assert is_match('a', '.*..a*') is False assert is_match('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c') is False", "and pattern are equal. \"\"\" import functools @functools.lru_cache() def is_match(s, p): if s", "and p[-1] == '*' else False if s[-1] == p[-1] or p[-1] ==", "assert is_match('aab', 'c*aab') is True assert is_match('aa', 'a*') is True assert is_match('ab', '.*')", "s = \"aa\", p = \"a\", Output: false Explanation: \"a\" does not match", "still a pattern remaining, discard any * sets. The regex is a match", "pattern (p), implement regular expression matching with support for '.' and '*'. '.'", "examine if consuming more string characters leads to a match if s[-idx] !=", "expression matching with support for '.' and '*'. '.' Matches any single character.", "matching 0 characters). If we get to the end of the string and", "characters leads to a match if s[-idx] != s[-1] and p[-2] != '.':", "s: return is_match(s, p[:-2]) if len(p) >= 2 and p[-1] == '*' else", "If we get to the end of the string and there is still", "elif not s: return is_match(s, p[:-2]) if len(p) >= 2 and p[-1] ==", "is_match('aab', 'c*aab') is True assert is_match('aa', 'a*') is True assert is_match('ab', '.*') is", "Input: s = \"aa\", p = \"a*\", Output: true Explanation: '*' means zero", "False if s[-1] == p[-1] or p[-1] == '.': # simple match return", "is True assert is_match('a', '.*..a*') is False assert is_match('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c') is False assert", "or more (*) of any character (.)\". Example 4: Input: s = \"aab\",", "\"aa\". Example 3: Input: s = \"ab\", p = \".*\", Output: true Explanation:", "If there is a *, examine whether combinations of consuming more characters from", "of consuming more characters from the string (repeating characters) or more characters from", "# no match, but * after return is_match(s, p[:-2]) else: # match, with", "False assert is_match('aab', 'c*a*b') is True assert is_match('mississippi', 'mis*is*p*.') is False assert is_match('a',", "not s: return is_match(s, p[:-2]) if len(p) >= 2 and p[-1] == '*'", "single character. '*' Matches zero or more of the preceding element. The matching", "<filename>1-99/10-19/10.py \"\"\" Given an input string (s) and a pattern (p), implement regular", "and p[-2] != '.': break if is_match(s[:-idx], p): return True # examine if", "p[-2] != '.': # no match, but * after return is_match(s, p[:-2]) else:", "character (.)\". Example 4: Input: s = \"aab\", p = \"c*a*b\", Output: true", "or more characters from the pattern (the * matching 0 characters). If we", "leads to a match if s[-idx] != s[-1] and p[-2] != '.': break", "of the preceding element. The matching should cover the entire input string (not", "p[-1] == '*' else False if s[-1] == p[-1] or p[-1] == '.':", "\"c*a*b\", Output: true Explanation: c can be repeated 0 times, a can be", "p = \"c*a*b\", Output: true Explanation: c can be repeated 0 times, a", "regex is a match if at the end the string and pattern are", "no * after return False assert is_match('a', 'ab*') is True assert is_match('abc', 'abc')", "return is_match(s, p[:-2]) if len(p) >= 2 and p[-1] == '*' else False", "match and there is no *, advance through the string and pattern by", "is_match('ab', '.*c') is False assert is_match('aab', 'c*a*b') is True assert is_match('mississippi', 'mis*is*p*.') is", "Therefore, it matches \"aab\". Example 5: Input: s = \"mississippi\", p = \"mis*is*p*.\",", "more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes", "= \"aa\", p = \"a\", Output: false Explanation: \"a\" does not match the", "string characters leads to a match if s[-idx] != s[-1] and p[-2] !=", "\"ab\", p = \".*\", Output: true Explanation: \".*\" means \"zero or more (*)", "and there is no *, advance through the string and pattern by one.", "end of the string and there is still a pattern remaining, discard any", "'.': # no match, but * after return is_match(s, p[:-2]) else: # match,", "c can be repeated 0 times, a can be repeated 1 time. Therefore,", "characters from the string (repeating characters) or more characters from the pattern (the", "it matches \"aab\". Example 5: Input: s = \"mississippi\", p = \"mis*is*p*.\", Output:", "s and not p: return False elif not s: return is_match(s, p[:-2]) if", "return True # examine if skipping the pattern leads to a match return", "of any character (.)\". Example 4: Input: s = \"aab\", p = \"c*a*b\",", "== p: return True elif s and not p: return False elif not", "Example 3: Input: s = \"ab\", p = \".*\", Output: true Explanation: \".*\"", "true Explanation: c can be repeated 0 times, a can be repeated 1", "of the string and there is still a pattern remaining, discard any *", "not match the entire string \"aa\". Example 2: Input: s = \"aa\", p", "return is_match(s, p[:-2]) else: # match, with * after for idx in range(1,", "*, advance through the string and pattern by one. If there is a", "p[-1] == '.': # simple match return is_match(s[:-1], p[:-1]) elif p[-1] == '*':", "assert is_match('aab', 'c*a*b') is True assert is_match('mississippi', 'mis*is*p*.') is False assert is_match('a', 'a*a')", "contains only lowercase letters a-z, and characters like . or *. Example 1:", "and '*'. '.' Matches any single character. '*' Matches zero or more of", "\"zero or more (*) of any character (.)\". Example 4: Input: s =", "input string (s) and a pattern (p), implement regular expression matching with support", "Matches zero or more of the preceding element. The matching should cover the", "Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by", "is_match('abc', 'abc') is True assert is_match('aa', 'a') is False assert is_match('aab', 'c*aab') is", "assert is_match('aa', 'a*') is True assert is_match('ab', '.*') is True assert is_match('ab', '.*c')", "the string and pattern by one. If there is a *, examine whether", "or *. Example 1: Input: s = \"aa\", p = \"a\", Output: false", "repeating 'a' once, it becomes \"aa\". Example 3: Input: s = \"ab\", p", "backwards through the string and pattern. If there is a character match and", "\"aa\", p = \"a*\", Output: true Explanation: '*' means zero or more of", "characters like . or *. Example 1: Input: s = \"aa\", p =", "p): return True # examine if skipping the pattern leads to a match", "s = \"aa\", p = \"a*\", Output: true Explanation: '*' means zero or", "\"\"\" Given an input string (s) and a pattern (p), implement regular expression", "sets. The regex is a match if at the end the string and", "is False assert is_match('aab', 'c*a*b') is True assert is_match('mississippi', 'mis*is*p*.') is False assert", "*, examine whether combinations of consuming more characters from the string (repeating characters)", "entire string \"aa\". Example 2: Input: s = \"aa\", p = \"a*\", Output:", "string and pattern by one. If there is a *, examine whether combinations", "return is_match(s[:-1], p[:-1]) elif p[-1] == '*': if p[-2] != s[-1] and p[-2]", "== p[-1] or p[-1] == '.': # simple match return is_match(s[:-1], p[:-1]) elif", "and a pattern (p), implement regular expression matching with support for '.' and", "True assert is_match('aa', 'a') is False assert is_match('aab', 'c*aab') is True assert is_match('aa',", "string and pattern. If there is a character match and there is no", "p[:-2]) else: # match, with * after for idx in range(1, len(s)+1): #", "the entire input string (not partial). Note: s could be empty and contains", "= \"mississippi\", p = \"mis*is*p*.\", Output: false \"\"\" \"\"\" We go backwards through", "\"aab\", p = \"c*a*b\", Output: true Explanation: c can be repeated 0 times,", "We go backwards through the string and pattern. If there is a character", "if p[-2] != s[-1] and p[-2] != '.': # no match, but *", "\"\"\" We go backwards through the string and pattern. If there is a", "from the string (repeating characters) or more characters from the pattern (the *", "equal. \"\"\" import functools @functools.lru_cache() def is_match(s, p): if s == p: return", "not p: return False elif not s: return is_match(s, p[:-2]) if len(p) >=", "assert is_match('abc', 'abc') is True assert is_match('aa', 'a') is False assert is_match('aab', 'c*aab')", "once, it becomes \"aa\". Example 3: Input: s = \"ab\", p = \".*\",", "\"\"\" import functools @functools.lru_cache() def is_match(s, p): if s == p: return True", "partial). Note: s could be empty and contains only lowercase letters a-z. p", "True assert is_match('bbbba', '.*a*a') is True assert is_match('a', '.*..a*') is False assert is_match('aaaaaaaaaaaaab',", "= \"aab\", p = \"c*a*b\", Output: true Explanation: c can be repeated 0", "is False assert is_match('a', 'a*a') is True assert is_match('bbbba', '.*a*a') is True assert", "the string and pattern are equal. \"\"\" import functools @functools.lru_cache() def is_match(s, p):", "if consuming more string characters leads to a match if s[-idx] != s[-1]", "more characters from the pattern (the * matching 0 characters). If we get", "any * sets. The regex is a match if at the end the", "a-z, and characters like . or *. Example 1: Input: s = \"aa\",", "if skipping the pattern leads to a match return is_match(s, p[:-2]) else: #", "# no match, no * after return False assert is_match('a', 'ab*') is True", "matches \"aab\". Example 5: Input: s = \"mississippi\", p = \"mis*is*p*.\", Output: false", "there is still a pattern remaining, discard any * sets. The regex is", "string (s) and a pattern (p), implement regular expression matching with support for", "is_match(s, p): if s == p: return True elif s and not p:", "is_match('a', 'ab*') is True assert is_match('abc', 'abc') is True assert is_match('aa', 'a') is", "lowercase letters a-z. p could be empty and contains only lowercase letters a-z,", "(*) of any character (.)\". Example 4: Input: s = \"aab\", p =", "p could be empty and contains only lowercase letters a-z, and characters like", "false Explanation: \"a\" does not match the entire string \"aa\". Example 2: Input:", "to a match return is_match(s, p[:-2]) else: # no match, no * after", "= \"ab\", p = \".*\", Output: true Explanation: \".*\" means \"zero or more", "and not p: return False elif not s: return is_match(s, p[:-2]) if len(p)", "a character match and there is no *, advance through the string and", "can be repeated 0 times, a can be repeated 1 time. Therefore, it", "by one. If there is a *, examine whether combinations of consuming more", "'*'. '.' Matches any single character. '*' Matches zero or more of the", "p = \".*\", Output: true Explanation: \".*\" means \"zero or more (*) of", "\"a*\", Output: true Explanation: '*' means zero or more of the preceding element,", "True assert is_match('mississippi', 'mis*is*p*.') is False assert is_match('a', 'a*a') is True assert is_match('bbbba',", "\"mississippi\", p = \"mis*is*p*.\", Output: false \"\"\" \"\"\" We go backwards through the", "leads to a match return is_match(s, p[:-2]) else: # no match, no *", "zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once,", "preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\". Example 3:", "cover the entire input string (not partial). Note: s could be empty and", "with * after for idx in range(1, len(s)+1): # examine if consuming more", "assert is_match('a', 'ab*') is True assert is_match('abc', 'abc') is True assert is_match('aa', 'a')", "one. If there is a *, examine whether combinations of consuming more characters", "p[:-1]) elif p[-1] == '*': if p[-2] != s[-1] and p[-2] != '.':", "assert is_match('aa', 'a') is False assert is_match('aab', 'c*aab') is True assert is_match('aa', 'a*')", "Output: false Explanation: \"a\" does not match the entire string \"aa\". Example 2:", "pattern remaining, discard any * sets. The regex is a match if at", "a-z. p could be empty and contains only lowercase letters a-z, and characters", "there is no *, advance through the string and pattern by one. If", "match, but * after return is_match(s, p[:-2]) else: # match, with * after", "1 time. Therefore, it matches \"aab\". Example 5: Input: s = \"mississippi\", p", "Example 4: Input: s = \"aab\", p = \"c*a*b\", Output: true Explanation: c", "match the entire string \"aa\". Example 2: Input: s = \"aa\", p =", "like . or *. Example 1: Input: s = \"aa\", p = \"a\",", "is a *, examine whether combinations of consuming more characters from the string", "more (*) of any character (.)\". Example 4: Input: s = \"aab\", p", "be repeated 0 times, a can be repeated 1 time. Therefore, it matches", "p): if s == p: return True elif s and not p: return", "== '*': if p[-2] != s[-1] and p[-2] != '.': # no match,", "'.': # simple match return is_match(s[:-1], p[:-1]) elif p[-1] == '*': if p[-2]", "s = \"aab\", p = \"c*a*b\", Output: true Explanation: c can be repeated", "a pattern remaining, discard any * sets. The regex is a match if", "pattern are equal. \"\"\" import functools @functools.lru_cache() def is_match(s, p): if s ==", "match return is_match(s, p[:-2]) else: # no match, no * after return False", "p[-2] != s[-1] and p[-2] != '.': # no match, but * after", "advance through the string and pattern by one. If there is a *,", "is True assert is_match('abc', 'abc') is True assert is_match('aa', 'a') is False assert", "\"\"\" \"\"\" We go backwards through the string and pattern. If there is", "through the string and pattern by one. If there is a *, examine", "is_match('a', '.*..a*') is False assert is_match('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c') is False assert is_match('aa', 'ab*a*') is", "Input: s = \"aab\", p = \"c*a*b\", Output: true Explanation: c can be", "true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore,", "True assert is_match('aa', 'a*') is True assert is_match('ab', '.*') is True assert is_match('ab',", "Example 5: Input: s = \"mississippi\", p = \"mis*is*p*.\", Output: false \"\"\" \"\"\"", "s[-1] and p[-2] != '.': # no match, but * after return is_match(s,", "Therefore, by repeating 'a' once, it becomes \"aa\". Example 3: Input: s =", "'*' else False if s[-1] == p[-1] or p[-1] == '.': # simple", "string and there is still a pattern remaining, discard any * sets. The", "examine whether combinations of consuming more characters from the string (repeating characters) or", "= \"mis*is*p*.\", Output: false \"\"\" \"\"\" We go backwards through the string and", "p[-1] == '*': if p[-2] != s[-1] and p[-2] != '.': # no", "4: Input: s = \"aab\", p = \"c*a*b\", Output: true Explanation: c can", "pattern. If there is a character match and there is no *, advance", "# simple match return is_match(s[:-1], p[:-1]) elif p[-1] == '*': if p[-2] !=", "is True assert is_match('mississippi', 'mis*is*p*.') is False assert is_match('a', 'a*a') is True assert", "element. The matching should cover the entire input string (not partial). Note: s", "the string and pattern. If there is a character match and there is", "s could be empty and contains only lowercase letters a-z. p could be", "\"aa\". Example 2: Input: s = \"aa\", p = \"a*\", Output: true Explanation:", "False elif not s: return is_match(s, p[:-2]) if len(p) >= 2 and p[-1]", ". or *. Example 1: Input: s = \"aa\", p = \"a\", Output:", "time. Therefore, it matches \"aab\". Example 5: Input: s = \"mississippi\", p =", "'.' Matches any single character. '*' Matches zero or more of the preceding", "end the string and pattern are equal. \"\"\" import functools @functools.lru_cache() def is_match(s,", "2: Input: s = \"aa\", p = \"a*\", Output: true Explanation: '*' means", "from the pattern (the * matching 0 characters). If we get to the", "assert is_match('bbbba', '.*a*a') is True assert is_match('a', '.*..a*') is False assert is_match('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c')", "contains only lowercase letters a-z. p could be empty and contains only lowercase", "more characters from the string (repeating characters) or more characters from the pattern", "\"aa\", p = \"a\", Output: false Explanation: \"a\" does not match the entire", "is_match('ab', '.*') is True assert is_match('ab', '.*c') is False assert is_match('aab', 'c*a*b') is", "'a*') is True assert is_match('ab', '.*') is True assert is_match('ab', '.*c') is False", "\"aab\". Example 5: Input: s = \"mississippi\", p = \"mis*is*p*.\", Output: false \"\"\"", "is_match('bbbba', '.*a*a') is True assert is_match('a', '.*..a*') is False assert is_match('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c') is", "assert is_match('ab', '.*') is True assert is_match('ab', '.*c') is False assert is_match('aab', 'c*a*b')", "'a'. Therefore, by repeating 'a' once, it becomes \"aa\". Example 3: Input: s", "== '*' else False if s[-1] == p[-1] or p[-1] == '.': #", "idx in range(1, len(s)+1): # examine if consuming more string characters leads to", "is_match(s[:-idx], p): return True # examine if skipping the pattern leads to a", "string \"aa\". Example 2: Input: s = \"aa\", p = \"a*\", Output: true", "character. '*' Matches zero or more of the preceding element. The matching should", "!= '.': break if is_match(s[:-idx], p): return True # examine if skipping the", "@functools.lru_cache() def is_match(s, p): if s == p: return True elif s and", "a pattern (p), implement regular expression matching with support for '.' and '*'.", "'mis*is*p*.') is False assert is_match('a', 'a*a') is True assert is_match('bbbba', '.*a*a') is True", "'c*a*b') is True assert is_match('mississippi', 'mis*is*p*.') is False assert is_match('a', 'a*a') is True", "'abc') is True assert is_match('aa', 'a') is False assert is_match('aab', 'c*aab') is True", "s[-1] == p[-1] or p[-1] == '.': # simple match return is_match(s[:-1], p[:-1])", "be empty and contains only lowercase letters a-z. p could be empty and", "or more of the preceding element. The matching should cover the entire input", "a match if s[-idx] != s[-1] and p[-2] != '.': break if is_match(s[:-idx],", "pattern leads to a match return is_match(s, p[:-2]) else: # no match, no", "\".*\", Output: true Explanation: \".*\" means \"zero or more (*) of any character", "return False assert is_match('a', 'ab*') is True assert is_match('abc', 'abc') is True assert", "Input: s = \"aa\", p = \"a\", Output: false Explanation: \"a\" does not", "* after return is_match(s, p[:-2]) else: # match, with * after for idx", "and contains only lowercase letters a-z. p could be empty and contains only", "is_match(s[:-1], p[:-1]) elif p[-1] == '*': if p[-2] != s[-1] and p[-2] !=", "is a character match and there is no *, advance through the string", "True elif s and not p: return False elif not s: return is_match(s,", "is still a pattern remaining, discard any * sets. The regex is a", "len(p) >= 2 and p[-1] == '*' else False if s[-1] == p[-1]", "'a') is False assert is_match('aab', 'c*aab') is True assert is_match('aa', 'a*') is True", "False assert is_match('a', 'a*a') is True assert is_match('bbbba', '.*a*a') is True assert is_match('a',", "for '.' and '*'. '.' Matches any single character. '*' Matches zero or", "could be empty and contains only lowercase letters a-z, and characters like .", "is True assert is_match('aa', 'a') is False assert is_match('aab', 'c*aab') is True assert", "!= '.': # no match, but * after return is_match(s, p[:-2]) else: #", "empty and contains only lowercase letters a-z. p could be empty and contains", "consuming more characters from the string (repeating characters) or more characters from the", "regular expression matching with support for '.' and '*'. '.' Matches any single", "be empty and contains only lowercase letters a-z, and characters like . or", "a can be repeated 1 time. Therefore, it matches \"aab\". Example 5: Input:", "Example 1: Input: s = \"aa\", p = \"a\", Output: false Explanation: \"a\"", "characters). If we get to the end of the string and there is", "no *, advance through the string and pattern by one. If there is", "string (not partial). Note: s could be empty and contains only lowercase letters", "it becomes \"aa\". Example 3: Input: s = \"ab\", p = \".*\", Output:", "'a' once, it becomes \"aa\". Example 3: Input: s = \"ab\", p =", "(.)\". Example 4: Input: s = \"aab\", p = \"c*a*b\", Output: true Explanation:", "letters a-z. p could be empty and contains only lowercase letters a-z, and", "assert is_match('mississippi', 'mis*is*p*.') is False assert is_match('a', 'a*a') is True assert is_match('bbbba', '.*a*a')", "match if at the end the string and pattern are equal. \"\"\" import", "element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\". Example 3: Input:", "p = \"mis*is*p*.\", Output: false \"\"\" \"\"\" We go backwards through the string", "the string (repeating characters) or more characters from the pattern (the * matching", "simple match return is_match(s[:-1], p[:-1]) elif p[-1] == '*': if p[-2] != s[-1]", "Given an input string (s) and a pattern (p), implement regular expression matching", "'c*aab') is True assert is_match('aa', 'a*') is True assert is_match('ab', '.*') is True", "match, no * after return False assert is_match('a', 'ab*') is True assert is_match('abc',", "and pattern. If there is a character match and there is no *,", "and p[-2] != '.': # no match, but * after return is_match(s, p[:-2])", "is_match(s, p[:-2]) else: # match, with * after for idx in range(1, len(s)+1):", "support for '.' and '*'. '.' Matches any single character. '*' Matches zero", "times, a can be repeated 1 time. Therefore, it matches \"aab\". Example 5:", "p = \"a\", Output: false Explanation: \"a\" does not match the entire string", "Explanation: \".*\" means \"zero or more (*) of any character (.)\". Example 4:", "0 characters). If we get to the end of the string and there", "is_match('aa', 'a') is False assert is_match('aab', 'c*aab') is True assert is_match('aa', 'a*') is", "letters a-z, and characters like . or *. Example 1: Input: s =", "if len(p) >= 2 and p[-1] == '*' else False if s[-1] ==", "the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\". Example", "combinations of consuming more characters from the string (repeating characters) or more characters", "p[-2] != '.': break if is_match(s[:-idx], p): return True # examine if skipping", "False assert is_match('a', 'ab*') is True assert is_match('abc', 'abc') is True assert is_match('aa',", "= \"c*a*b\", Output: true Explanation: c can be repeated 0 times, a can", "s = \"mississippi\", p = \"mis*is*p*.\", Output: false \"\"\" \"\"\" We go backwards", "s = \"ab\", p = \".*\", Output: true Explanation: \".*\" means \"zero or", "assert is_match('ab', '.*c') is False assert is_match('aab', 'c*a*b') is True assert is_match('mississippi', 'mis*is*p*.')", "range(1, len(s)+1): # examine if consuming more string characters leads to a match", "an input string (s) and a pattern (p), implement regular expression matching with", "= \"a\", Output: false Explanation: \"a\" does not match the entire string \"aa\".", "of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\".", "any single character. '*' Matches zero or more of the preceding element. The", "or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it", "be repeated 1 time. Therefore, it matches \"aab\". Example 5: Input: s =", "is False assert is_match('aab', 'c*aab') is True assert is_match('aa', 'a*') is True assert", "can be repeated 1 time. Therefore, it matches \"aab\". Example 5: Input: s", "'*': if p[-2] != s[-1] and p[-2] != '.': # no match, but", "string (repeating characters) or more characters from the pattern (the * matching 0", "If there is a character match and there is no *, advance through", "match if s[-idx] != s[-1] and p[-2] != '.': break if is_match(s[:-idx], p):", "# examine if consuming more string characters leads to a match if s[-idx]", "Input: s = \"ab\", p = \".*\", Output: true Explanation: \".*\" means \"zero", "Example 2: Input: s = \"aa\", p = \"a*\", Output: true Explanation: '*'", "the preceding element. The matching should cover the entire input string (not partial).", "p: return False elif not s: return is_match(s, p[:-2]) if len(p) >= 2", "after return is_match(s, p[:-2]) else: # match, with * after for idx in", "could be empty and contains only lowercase letters a-z. p could be empty", "Explanation: c can be repeated 0 times, a can be repeated 1 time.", "Output: true Explanation: \".*\" means \"zero or more (*) of any character (.)\".", "assert is_match('a', 'a*a') is True assert is_match('bbbba', '.*a*a') is True assert is_match('a', '.*..a*')", "else False if s[-1] == p[-1] or p[-1] == '.': # simple match", "is_match('aab', 'c*a*b') is True assert is_match('mississippi', 'mis*is*p*.') is False assert is_match('a', 'a*a') is", "matching should cover the entire input string (not partial). Note: s could be", "entire input string (not partial). Note: s could be empty and contains only", "if s[-idx] != s[-1] and p[-2] != '.': break if is_match(s[:-idx], p): return", "the entire string \"aa\". Example 2: Input: s = \"aa\", p = \"a*\",", "and there is still a pattern remaining, discard any * sets. The regex", "return is_match(s, p[:-2]) else: # no match, no * after return False assert", "a match return is_match(s, p[:-2]) else: # no match, no * after return", "if s == p: return True elif s and not p: return False", "the pattern leads to a match return is_match(s, p[:-2]) else: # no match,", "empty and contains only lowercase letters a-z, and characters like . or *.", "match, with * after for idx in range(1, len(s)+1): # examine if consuming", "= \".*\", Output: true Explanation: \".*\" means \"zero or more (*) of any", "means \"zero or more (*) of any character (.)\". Example 4: Input: s", "there is a *, examine whether combinations of consuming more characters from the", "False assert is_match('aab', 'c*aab') is True assert is_match('aa', 'a*') is True assert is_match('ab',", "True assert is_match('abc', 'abc') is True assert is_match('aa', 'a') is False assert is_match('aab',", "more string characters leads to a match if s[-idx] != s[-1] and p[-2]", "elif s and not p: return False elif not s: return is_match(s, p[:-2])", "pattern by one. If there is a *, examine whether combinations of consuming", "'.*..a*') is False assert is_match('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c') is False assert is_match('aa', 'ab*a*') is True", "preceding element. The matching should cover the entire input string (not partial). Note:", "1: Input: s = \"aa\", p = \"a\", Output: false Explanation: \"a\" does", "skipping the pattern leads to a match return is_match(s, p[:-2]) else: # no", "to a match if s[-idx] != s[-1] and p[-2] != '.': break if", "matching with support for '.' and '*'. '.' Matches any single character. '*'", "lowercase letters a-z, and characters like . or *. Example 1: Input: s", "true Explanation: \".*\" means \"zero or more (*) of any character (.)\". Example", "\".*\" means \"zero or more (*) of any character (.)\". Example 4: Input:", "becomes \"aa\". Example 3: Input: s = \"ab\", p = \".*\", Output: true", "pattern (the * matching 0 characters). If we get to the end of", "is_match('mississippi', 'mis*is*p*.') is False assert is_match('a', 'a*a') is True assert is_match('bbbba', '.*a*a') is", "is True assert is_match('ab', '.*') is True assert is_match('ab', '.*c') is False assert", "Output: true Explanation: '*' means zero or more of the preceding element, 'a'.", "p[:-2]) if len(p) >= 2 and p[-1] == '*' else False if s[-1]", "if is_match(s[:-idx], p): return True # examine if skipping the pattern leads to", "(not partial). Note: s could be empty and contains only lowercase letters a-z.", "(p), implement regular expression matching with support for '.' and '*'. '.' Matches", "2 and p[-1] == '*' else False if s[-1] == p[-1] or p[-1]", "by repeating 'a' once, it becomes \"aa\". Example 3: Input: s = \"ab\",", "# match, with * after for idx in range(1, len(s)+1): # examine if", "Matches any single character. '*' Matches zero or more of the preceding element.", "(the * matching 0 characters). If we get to the end of the", "return True elif s and not p: return False elif not s: return", "go backwards through the string and pattern. If there is a character match", "with support for '.' and '*'. '.' Matches any single character. '*' Matches", "\"mis*is*p*.\", Output: false \"\"\" \"\"\" We go backwards through the string and pattern.", "implement regular expression matching with support for '.' and '*'. '.' Matches any", "only lowercase letters a-z, and characters like . or *. Example 1: Input:", "'.': break if is_match(s[:-idx], p): return True # examine if skipping the pattern", "== '.': # simple match return is_match(s[:-1], p[:-1]) elif p[-1] == '*': if", "assert is_match('a', '.*..a*') is False assert is_match('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c') is False assert is_match('aa', 'ab*a*')", "p = \"a*\", Output: true Explanation: '*' means zero or more of the", "5: Input: s = \"mississippi\", p = \"mis*is*p*.\", Output: false \"\"\" \"\"\" We", "is no *, advance through the string and pattern by one. If there", "to the end of the string and there is still a pattern remaining,", "import functools @functools.lru_cache() def is_match(s, p): if s == p: return True elif", "Note: s could be empty and contains only lowercase letters a-z. p could", "The regex is a match if at the end the string and pattern", "'.*') is True assert is_match('ab', '.*c') is False assert is_match('aab', 'c*a*b') is True", "* matching 0 characters). If we get to the end of the string", "or p[-1] == '.': # simple match return is_match(s[:-1], p[:-1]) elif p[-1] ==", "no match, no * after return False assert is_match('a', 'ab*') is True assert", "functools @functools.lru_cache() def is_match(s, p): if s == p: return True elif s", "!= s[-1] and p[-2] != '.': # no match, but * after return", "a match if at the end the string and pattern are equal. \"\"\"", "s[-1] and p[-2] != '.': break if is_match(s[:-idx], p): return True # examine", "* sets. The regex is a match if at the end the string", "is True assert is_match('ab', '.*c') is False assert is_match('aab', 'c*a*b') is True assert", "if at the end the string and pattern are equal. \"\"\" import functools", "only lowercase letters a-z. p could be empty and contains only lowercase letters", "is_match('aa', 'a*') is True assert is_match('ab', '.*') is True assert is_match('ab', '.*c') is", "characters) or more characters from the pattern (the * matching 0 characters). If", "get to the end of the string and there is still a pattern", "in range(1, len(s)+1): # examine if consuming more string characters leads to a", "are equal. \"\"\" import functools @functools.lru_cache() def is_match(s, p): if s == p:", "Output: true Explanation: c can be repeated 0 times, a can be repeated", "elif p[-1] == '*': if p[-2] != s[-1] and p[-2] != '.': #", "!= s[-1] and p[-2] != '.': break if is_match(s[:-idx], p): return True #", "The matching should cover the entire input string (not partial). Note: s could", "def is_match(s, p): if s == p: return True elif s and not", "but * after return is_match(s, p[:-2]) else: # match, with * after for", "s[-idx] != s[-1] and p[-2] != '.': break if is_match(s[:-idx], p): return True", "is_match(s, p[:-2]) else: # no match, no * after return False assert is_match('a',", "consuming more string characters leads to a match if s[-idx] != s[-1] and", "discard any * sets. The regex is a match if at the end", "should cover the entire input string (not partial). Note: s could be empty", "more of the preceding element. The matching should cover the entire input string", "the pattern (the * matching 0 characters). If we get to the end", "the string and there is still a pattern remaining, discard any * sets.", "\"a\", Output: false Explanation: \"a\" does not match the entire string \"aa\". Example", "'.' and '*'. '.' Matches any single character. '*' Matches zero or more", "p[-1] or p[-1] == '.': # simple match return is_match(s[:-1], p[:-1]) elif p[-1]", "* after return False assert is_match('a', 'ab*') is True assert is_match('abc', 'abc') is", "and characters like . or *. Example 1: Input: s = \"aa\", p", "after return False assert is_match('a', 'ab*') is True assert is_match('abc', 'abc') is True", "break if is_match(s[:-idx], p): return True # examine if skipping the pattern leads", "= \"a*\", Output: true Explanation: '*' means zero or more of the preceding", "character match and there is no *, advance through the string and pattern", "* after for idx in range(1, len(s)+1): # examine if consuming more string" ]
[ "f\"{self.flight} (Details N/A)\" self.altitude = line[15:21].replace(\" \", \"\") self.speed = line[26:29] lat =", "ValueError: lat = 0 lon = 0 self.coordinates = Point(lat, lon) self.track =", "= 0 self.coordinates = Point(lat, lon) self.track = line[54:57] self.msg = line[60:63] self.last", "(Details N/A)\" self.altitude = line[15:21].replace(\" \", \"\") self.speed = line[26:29] lat = line[34:41].replace(\"", "= \"N/A\" self.destination = \"N/A\" self.destination_name = \"N/A\" self.type = \"N/A\" self.dist_to_home =", "from datetime import datetime, timedelta from shapely.geometry import Point class Aircraft: def __init__(self,", "line[60:63] self.last = line[69:73] self.in_geofence = False self.origin = \"N/A\" self.origin_name = \"N/A\"", "line[34:41].replace(\" \", \"\") lon = line[44:52].replace(\" \", \"\") try: lat = float(lat) lon", "self.altitude = line[15:21].replace(\" \", \"\") self.speed = line[26:29] lat = line[34:41].replace(\" \", \"\")", "\"N/A\" self.destination = \"N/A\" self.destination_name = \"N/A\" self.type = \"N/A\" self.dist_to_home = 1001", "def __init__(self, line): ts = datetime.now() self.hexcode = line[0:6] self.flight = line[7:14].replace(\" \",", "N/A)\" self.altitude = line[15:21].replace(\" \", \"\") self.speed = line[26:29] lat = line[34:41].replace(\" \",", "self.in_geofence = False self.origin = \"N/A\" self.origin_name = \"N/A\" self.destination = \"N/A\" self.destination_name", "= \"N/A\" self.destination_name = \"N/A\" self.type = \"N/A\" self.dist_to_home = 1001 self.ts =", "datetime.now() self.hexcode = line[0:6] self.flight = line[7:14].replace(\" \", \"\") self.description = f\"{self.flight} (Details", "ts = datetime.now() self.hexcode = line[0:6] self.flight = line[7:14].replace(\" \", \"\") self.description =", "import Point class Aircraft: def __init__(self, line): ts = datetime.now() self.hexcode = line[0:6]", "= 0 lon = 0 self.coordinates = Point(lat, lon) self.track = line[54:57] self.msg", "lon = 0 self.coordinates = Point(lat, lon) self.track = line[54:57] self.msg = line[60:63]", "\"\") self.speed = line[26:29] lat = line[34:41].replace(\" \", \"\") lon = line[44:52].replace(\" \",", "False self.origin = \"N/A\" self.origin_name = \"N/A\" self.destination = \"N/A\" self.destination_name = \"N/A\"", "\"N/A\" self.origin_name = \"N/A\" self.destination = \"N/A\" self.destination_name = \"N/A\" self.type = \"N/A\"", "self.speed = line[26:29] lat = line[34:41].replace(\" \", \"\") lon = line[44:52].replace(\" \", \"\")", "__init__(self, line): ts = datetime.now() self.hexcode = line[0:6] self.flight = line[7:14].replace(\" \", \"\")", "self.origin_name = \"N/A\" self.destination = \"N/A\" self.destination_name = \"N/A\" self.type = \"N/A\" self.dist_to_home", "\", \"\") lon = line[44:52].replace(\" \", \"\") try: lat = float(lat) lon =", "self.hexcode = line[0:6] self.flight = line[7:14].replace(\" \", \"\") self.description = f\"{self.flight} (Details N/A)\"", "lon = line[44:52].replace(\" \", \"\") try: lat = float(lat) lon = float(lon) except", "= float(lat) lon = float(lon) except ValueError: lat = 0 lon = 0", "self.track = line[54:57] self.msg = line[60:63] self.last = line[69:73] self.in_geofence = False self.origin", "datetime, timedelta from shapely.geometry import Point class Aircraft: def __init__(self, line): ts =", "= f\"{self.flight} (Details N/A)\" self.altitude = line[15:21].replace(\" \", \"\") self.speed = line[26:29] lat", "\"\") try: lat = float(lat) lon = float(lon) except ValueError: lat = 0", "lon = float(lon) except ValueError: lat = 0 lon = 0 self.coordinates =", "= datetime.now() self.hexcode = line[0:6] self.flight = line[7:14].replace(\" \", \"\") self.description = f\"{self.flight}", "\", \"\") self.description = f\"{self.flight} (Details N/A)\" self.altitude = line[15:21].replace(\" \", \"\") self.speed", "import datetime, timedelta from shapely.geometry import Point class Aircraft: def __init__(self, line): ts", "= line[54:57] self.msg = line[60:63] self.last = line[69:73] self.in_geofence = False self.origin =", "= line[44:52].replace(\" \", \"\") try: lat = float(lat) lon = float(lon) except ValueError:", "= line[34:41].replace(\" \", \"\") lon = line[44:52].replace(\" \", \"\") try: lat = float(lat)", "lon) self.track = line[54:57] self.msg = line[60:63] self.last = line[69:73] self.in_geofence = False", "line[69:73] self.in_geofence = False self.origin = \"N/A\" self.origin_name = \"N/A\" self.destination = \"N/A\"", "self.destination = \"N/A\" self.destination_name = \"N/A\" self.type = \"N/A\" self.dist_to_home = 1001 self.ts", "class Aircraft: def __init__(self, line): ts = datetime.now() self.hexcode = line[0:6] self.flight =", "\", \"\") self.speed = line[26:29] lat = line[34:41].replace(\" \", \"\") lon = line[44:52].replace(\"", "self.flight = line[7:14].replace(\" \", \"\") self.description = f\"{self.flight} (Details N/A)\" self.altitude = line[15:21].replace(\"", "= float(lon) except ValueError: lat = 0 lon = 0 self.coordinates = Point(lat,", "line[26:29] lat = line[34:41].replace(\" \", \"\") lon = line[44:52].replace(\" \", \"\") try: lat", "self.coordinates = Point(lat, lon) self.track = line[54:57] self.msg = line[60:63] self.last = line[69:73]", "\"\") lon = line[44:52].replace(\" \", \"\") try: lat = float(lat) lon = float(lon)", "= line[69:73] self.in_geofence = False self.origin = \"N/A\" self.origin_name = \"N/A\" self.destination =", "from shapely.geometry import Point class Aircraft: def __init__(self, line): ts = datetime.now() self.hexcode", "line[15:21].replace(\" \", \"\") self.speed = line[26:29] lat = line[34:41].replace(\" \", \"\") lon =", "= line[60:63] self.last = line[69:73] self.in_geofence = False self.origin = \"N/A\" self.origin_name =", "float(lon) except ValueError: lat = 0 lon = 0 self.coordinates = Point(lat, lon)", "= line[0:6] self.flight = line[7:14].replace(\" \", \"\") self.description = f\"{self.flight} (Details N/A)\" self.altitude", "= line[7:14].replace(\" \", \"\") self.description = f\"{self.flight} (Details N/A)\" self.altitude = line[15:21].replace(\" \",", "Point class Aircraft: def __init__(self, line): ts = datetime.now() self.hexcode = line[0:6] self.flight", "0 self.coordinates = Point(lat, lon) self.track = line[54:57] self.msg = line[60:63] self.last =", "lat = float(lat) lon = float(lon) except ValueError: lat = 0 lon =", "shapely.geometry import Point class Aircraft: def __init__(self, line): ts = datetime.now() self.hexcode =", "datetime import datetime, timedelta from shapely.geometry import Point class Aircraft: def __init__(self, line):", "except ValueError: lat = 0 lon = 0 self.coordinates = Point(lat, lon) self.track", "lat = 0 lon = 0 self.coordinates = Point(lat, lon) self.track = line[54:57]", "Point(lat, lon) self.track = line[54:57] self.msg = line[60:63] self.last = line[69:73] self.in_geofence =", "float(lat) lon = float(lon) except ValueError: lat = 0 lon = 0 self.coordinates", "= Point(lat, lon) self.track = line[54:57] self.msg = line[60:63] self.last = line[69:73] self.in_geofence", "line[0:6] self.flight = line[7:14].replace(\" \", \"\") self.description = f\"{self.flight} (Details N/A)\" self.altitude =", "self.description = f\"{self.flight} (Details N/A)\" self.altitude = line[15:21].replace(\" \", \"\") self.speed = line[26:29]", "line[44:52].replace(\" \", \"\") try: lat = float(lat) lon = float(lon) except ValueError: lat", "= line[15:21].replace(\" \", \"\") self.speed = line[26:29] lat = line[34:41].replace(\" \", \"\") lon", "\", \"\") try: lat = float(lat) lon = float(lon) except ValueError: lat =", "= False self.origin = \"N/A\" self.origin_name = \"N/A\" self.destination = \"N/A\" self.destination_name =", "self.origin = \"N/A\" self.origin_name = \"N/A\" self.destination = \"N/A\" self.destination_name = \"N/A\" self.type", "= \"N/A\" self.origin_name = \"N/A\" self.destination = \"N/A\" self.destination_name = \"N/A\" self.type =", "line[7:14].replace(\" \", \"\") self.description = f\"{self.flight} (Details N/A)\" self.altitude = line[15:21].replace(\" \", \"\")", "0 lon = 0 self.coordinates = Point(lat, lon) self.track = line[54:57] self.msg =", "self.msg = line[60:63] self.last = line[69:73] self.in_geofence = False self.origin = \"N/A\" self.origin_name", "Aircraft: def __init__(self, line): ts = datetime.now() self.hexcode = line[0:6] self.flight = line[7:14].replace(\"", "self.last = line[69:73] self.in_geofence = False self.origin = \"N/A\" self.origin_name = \"N/A\" self.destination", "\"\") self.description = f\"{self.flight} (Details N/A)\" self.altitude = line[15:21].replace(\" \", \"\") self.speed =", "line): ts = datetime.now() self.hexcode = line[0:6] self.flight = line[7:14].replace(\" \", \"\") self.description", "<reponame>jacob-zeiger/skyspy from datetime import datetime, timedelta from shapely.geometry import Point class Aircraft: def", "try: lat = float(lat) lon = float(lon) except ValueError: lat = 0 lon", "line[54:57] self.msg = line[60:63] self.last = line[69:73] self.in_geofence = False self.origin = \"N/A\"", "\"N/A\" self.destination_name = \"N/A\" self.type = \"N/A\" self.dist_to_home = 1001 self.ts = ts", "lat = line[34:41].replace(\" \", \"\") lon = line[44:52].replace(\" \", \"\") try: lat =", "= line[26:29] lat = line[34:41].replace(\" \", \"\") lon = line[44:52].replace(\" \", \"\") try:", "timedelta from shapely.geometry import Point class Aircraft: def __init__(self, line): ts = datetime.now()" ]
[ "= [ \"Programming Language :: Python :: 3\", \"License :: OSI Approved ::", "with open(\"environment.yml\", \"r\") as fh: env = yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip() for", "for a in env['dependencies'] ] setuptools.setup( name = \"mortie\", version = \"0.1.0\", author", "\"<NAME>\", author_email = \"<EMAIL>\", description = \"Morton numbering for healpix grids\", long_description =", "grids\", long_description = long_description, long_description_content_type = \"text/markdown\", packages = setuptools.find_packages(), classifiers = [", "= \"0.1.0\", author = \"<NAME>\", author_email = \"<EMAIL>\", description = \"Morton numbering for", ":: BSD License\", \"Operating System :: OS Independent\", ], python_requires = '>= 3.5',", "a Python project installable. import setuptools import yaml with open(\"README.md\", \"r\") as fh:", "for healpix grids\", long_description = long_description, long_description_content_type = \"text/markdown\", packages = setuptools.find_packages(), classifiers", "yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip() for a in env['dependencies'] ] setuptools.setup( name =", "import yaml with open(\"README.md\", \"r\") as fh: long_description = fh.read() with open(\"environment.yml\", \"r\")", "\"mortie\", version = \"0.1.0\", author = \"<NAME>\", author_email = \"<EMAIL>\", description = \"Morton", "fh: long_description = fh.read() with open(\"environment.yml\", \"r\") as fh: env = yaml.safe_load(fh) requirements", ":: Python :: 3\", \"License :: OSI Approved :: BSD License\", \"Operating System", "Approved :: BSD License\", \"Operating System :: OS Independent\", ], python_requires = '>=", "= \"<NAME>\", author_email = \"<EMAIL>\", description = \"Morton numbering for healpix grids\", long_description", "System :: OS Independent\", ], python_requires = '>= 3.5', install_requires = requirements, )", "env['dependencies'] ] setuptools.setup( name = \"mortie\", version = \"0.1.0\", author = \"<NAME>\", author_email", "= [a.split('=', 1)[0].strip() for a in env['dependencies'] ] setuptools.setup( name = \"mortie\", version", "\"<EMAIL>\", description = \"Morton numbering for healpix grids\", long_description = long_description, long_description_content_type =", "= \"<EMAIL>\", description = \"Morton numbering for healpix grids\", long_description = long_description, long_description_content_type", "long_description_content_type = \"text/markdown\", packages = setuptools.find_packages(), classifiers = [ \"Programming Language :: Python", "3\", \"License :: OSI Approved :: BSD License\", \"Operating System :: OS Independent\",", "Python :: 3\", \"License :: OSI Approved :: BSD License\", \"Operating System ::", "1)[0].strip() for a in env['dependencies'] ] setuptools.setup( name = \"mortie\", version = \"0.1.0\",", "\"Programming Language :: Python :: 3\", \"License :: OSI Approved :: BSD License\",", "author_email = \"<EMAIL>\", description = \"Morton numbering for healpix grids\", long_description = long_description,", "\"Operating System :: OS Independent\", ], python_requires = '>= 3.5', install_requires = requirements,", "version = \"0.1.0\", author = \"<NAME>\", author_email = \"<EMAIL>\", description = \"Morton numbering", "healpix grids\", long_description = long_description, long_description_content_type = \"text/markdown\", packages = setuptools.find_packages(), classifiers =", "author = \"<NAME>\", author_email = \"<EMAIL>\", description = \"Morton numbering for healpix grids\",", "= \"Morton numbering for healpix grids\", long_description = long_description, long_description_content_type = \"text/markdown\", packages", "yaml with open(\"README.md\", \"r\") as fh: long_description = fh.read() with open(\"environment.yml\", \"r\") as", "A minimal setup.py file to make a Python project installable. import setuptools import", "] setuptools.setup( name = \"mortie\", version = \"0.1.0\", author = \"<NAME>\", author_email =", "env = yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip() for a in env['dependencies'] ] setuptools.setup(", "\"r\") as fh: env = yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip() for a in", "with open(\"README.md\", \"r\") as fh: long_description = fh.read() with open(\"environment.yml\", \"r\") as fh:", "\"0.1.0\", author = \"<NAME>\", author_email = \"<EMAIL>\", description = \"Morton numbering for healpix", "numbering for healpix grids\", long_description = long_description, long_description_content_type = \"text/markdown\", packages = setuptools.find_packages(),", "= yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip() for a in env['dependencies'] ] setuptools.setup( name", "minimal setup.py file to make a Python project installable. import setuptools import yaml", "name = \"mortie\", version = \"0.1.0\", author = \"<NAME>\", author_email = \"<EMAIL>\", description", "packages = setuptools.find_packages(), classifiers = [ \"Programming Language :: Python :: 3\", \"License", "long_description, long_description_content_type = \"text/markdown\", packages = setuptools.find_packages(), classifiers = [ \"Programming Language ::", "import setuptools import yaml with open(\"README.md\", \"r\") as fh: long_description = fh.read() with", "setup.py file to make a Python project installable. import setuptools import yaml with", "as fh: env = yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip() for a in env['dependencies']", "\"text/markdown\", packages = setuptools.find_packages(), classifiers = [ \"Programming Language :: Python :: 3\",", ":: OSI Approved :: BSD License\", \"Operating System :: OS Independent\", ], python_requires", "as fh: long_description = fh.read() with open(\"environment.yml\", \"r\") as fh: env = yaml.safe_load(fh)", "[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved :: BSD", "setuptools.find_packages(), classifiers = [ \"Programming Language :: Python :: 3\", \"License :: OSI", "project installable. import setuptools import yaml with open(\"README.md\", \"r\") as fh: long_description =", "= setuptools.find_packages(), classifiers = [ \"Programming Language :: Python :: 3\", \"License ::", "file to make a Python project installable. import setuptools import yaml with open(\"README.md\",", "= \"mortie\", version = \"0.1.0\", author = \"<NAME>\", author_email = \"<EMAIL>\", description =", "License\", \"Operating System :: OS Independent\", ], python_requires = '>= 3.5', install_requires =", "make a Python project installable. import setuptools import yaml with open(\"README.md\", \"r\") as", "[a.split('=', 1)[0].strip() for a in env['dependencies'] ] setuptools.setup( name = \"mortie\", version =", "long_description = long_description, long_description_content_type = \"text/markdown\", packages = setuptools.find_packages(), classifiers = [ \"Programming", "Language :: Python :: 3\", \"License :: OSI Approved :: BSD License\", \"Operating", "fh: env = yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip() for a in env['dependencies'] ]", "description = \"Morton numbering for healpix grids\", long_description = long_description, long_description_content_type = \"text/markdown\",", "installable. import setuptools import yaml with open(\"README.md\", \"r\") as fh: long_description = fh.read()", "\"r\") as fh: long_description = fh.read() with open(\"environment.yml\", \"r\") as fh: env =", "= \"text/markdown\", packages = setuptools.find_packages(), classifiers = [ \"Programming Language :: Python ::", "fh.read() with open(\"environment.yml\", \"r\") as fh: env = yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip()", "open(\"README.md\", \"r\") as fh: long_description = fh.read() with open(\"environment.yml\", \"r\") as fh: env", "open(\"environment.yml\", \"r\") as fh: env = yaml.safe_load(fh) requirements = [a.split('=', 1)[0].strip() for a", "OSI Approved :: BSD License\", \"Operating System :: OS Independent\", ], python_requires =", "= fh.read() with open(\"environment.yml\", \"r\") as fh: env = yaml.safe_load(fh) requirements = [a.split('=',", "setuptools.setup( name = \"mortie\", version = \"0.1.0\", author = \"<NAME>\", author_email = \"<EMAIL>\",", "setuptools import yaml with open(\"README.md\", \"r\") as fh: long_description = fh.read() with open(\"environment.yml\",", "to make a Python project installable. import setuptools import yaml with open(\"README.md\", \"r\")", "\"Morton numbering for healpix grids\", long_description = long_description, long_description_content_type = \"text/markdown\", packages =", ":: 3\", \"License :: OSI Approved :: BSD License\", \"Operating System :: OS", "\"License :: OSI Approved :: BSD License\", \"Operating System :: OS Independent\", ],", "long_description = fh.read() with open(\"environment.yml\", \"r\") as fh: env = yaml.safe_load(fh) requirements =", "a in env['dependencies'] ] setuptools.setup( name = \"mortie\", version = \"0.1.0\", author =", "requirements = [a.split('=', 1)[0].strip() for a in env['dependencies'] ] setuptools.setup( name = \"mortie\",", "classifiers = [ \"Programming Language :: Python :: 3\", \"License :: OSI Approved", "in env['dependencies'] ] setuptools.setup( name = \"mortie\", version = \"0.1.0\", author = \"<NAME>\",", "Python project installable. import setuptools import yaml with open(\"README.md\", \"r\") as fh: long_description", "BSD License\", \"Operating System :: OS Independent\", ], python_requires = '>= 3.5', install_requires", "= long_description, long_description_content_type = \"text/markdown\", packages = setuptools.find_packages(), classifiers = [ \"Programming Language", "# A minimal setup.py file to make a Python project installable. import setuptools" ]
[ "*y = tmp; return x; } int* main(){ swap(&a, &b); return &a ;", "swap(&a, &b); return &a ; } ''', llvmdump=True) # ret_value = ret.contents print(\"The", "type is {} content \".format(ret, type(ret))) # so the global var assert ret.contents.value", "tmp; tmp = *x; *x = *y; *y = tmp; return x; }", "ret.contents print(\"The answer is {} ret type is {} content \".format(ret, type(ret))) #", "= 50; int b = 4; int* swap(int *x, int *y){ int tmp;", "*x = *y; *y = tmp; return x; } int* main(){ swap(&a, &b);", "*y; *y = tmp; return x; } int* main(){ swap(&a, &b); return &a", "= os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase): def", "= tmp; return x; } int* main(){ swap(&a, &b); return &a ; }", "test_simple(self): pcc = CEvaluator() ret = pcc.evaluate(''' int a = 50; int b", "*x, int *y){ int tmp; tmp = *x; *x = *y; *y =", "b = 4; int* swap(int *x, int *y){ int tmp; tmp = *x;", "# ret_value = ret.contents print(\"The answer is {} ret type is {} content", "return &a ; } ''', llvmdump=True) # ret_value = ret.contents print(\"The answer is", "os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self):", "= os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import CEvaluator import unittest", "int a = 50; int b = 4; int* swap(int *x, int *y){", "pcc.evaluate(''' int a = 50; int b = 4; int* swap(int *x, int", "pcc.evaluater.c_evaluator import CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc = CEvaluator() ret", "answer is {} ret type is {} content \".format(ret, type(ret))) # so the", "is {} ret type is {} content \".format(ret, type(ret))) # so the global", "} ''', llvmdump=True) # ret_value = ret.contents print(\"The answer is {} ret type", "CEvaluator() ret = pcc.evaluate(''' int a = 50; int b = 4; int*", "tmp = *x; *x = *y; *y = tmp; return x; } int*", "&a ; } ''', llvmdump=True) # ret_value = ret.contents print(\"The answer is {}", "} int* main(){ swap(&a, &b); return &a ; } ''', llvmdump=True) # ret_value", "&b); return &a ; } ''', llvmdump=True) # ret_value = ret.contents print(\"The answer", "sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc", "pcc = CEvaluator() ret = pcc.evaluate(''' int a = 50; int b =", "{} ret type is {} content \".format(ret, type(ret))) # so the global var", "ret = pcc.evaluate(''' int a = 50; int b = 4; int* swap(int", "*x; *x = *y; *y = tmp; return x; } int* main(){ swap(&a,", "= *x; *x = *y; *y = tmp; return x; } int* main(){", "# so the global var assert ret.contents.value == 4 if __name__ == \"__main__\":", "TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc = CEvaluator() ret = pcc.evaluate(''' int a = 50;", "; } ''', llvmdump=True) # ret_value = ret.contents print(\"The answer is {} ret", "swap(int *x, int *y){ int tmp; tmp = *x; *x = *y; *y", "import sys import ctypes this_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from", "x; } int* main(){ swap(&a, &b); return &a ; } ''', llvmdump=True) #", "\".format(ret, type(ret))) # so the global var assert ret.contents.value == 4 if __name__", "so the global var assert ret.contents.value == 4 if __name__ == \"__main__\": unittest.main()", "tmp; return x; } int* main(){ swap(&a, &b); return &a ; } ''',", "''', llvmdump=True) # ret_value = ret.contents print(\"The answer is {} ret type is", "int tmp; tmp = *x; *x = *y; *y = tmp; return x;", "= pcc.evaluate(''' int a = 50; int b = 4; int* swap(int *x,", "a = 50; int b = 4; int* swap(int *x, int *y){ int", "os import sys import ctypes this_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir)", "ctypes this_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import CEvaluator", "= *y; *y = tmp; return x; } int* main(){ swap(&a, &b); return", "import unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc = CEvaluator() ret = pcc.evaluate(''' int", "import CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc = CEvaluator() ret =", "int* swap(int *x, int *y){ int tmp; tmp = *x; *x = *y;", "50; int b = 4; int* swap(int *x, int *y){ int tmp; tmp", "4; int* swap(int *x, int *y){ int tmp; tmp = *x; *x =", "from pcc.evaluater.c_evaluator import CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc = CEvaluator()", "def test_simple(self): pcc = CEvaluator() ret = pcc.evaluate(''' int a = 50; int", "parent_dir) from pcc.evaluater.c_evaluator import CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc =", "content \".format(ret, type(ret))) # so the global var assert ret.contents.value == 4 if", "os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import CEvaluator import unittest class", "llvmdump=True) # ret_value = ret.contents print(\"The answer is {} ret type is {}", "CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc = CEvaluator() ret = pcc.evaluate('''", "= ret.contents print(\"The answer is {} ret type is {} content \".format(ret, type(ret)))", "ret_value = ret.contents print(\"The answer is {} ret type is {} content \".format(ret,", "parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import CEvaluator import unittest class TestMainReturnPtr(unittest.TestCase):", "unittest class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc = CEvaluator() ret = pcc.evaluate(''' int a", "return x; } int* main(){ swap(&a, &b); return &a ; } ''', llvmdump=True)", "type(ret))) # so the global var assert ret.contents.value == 4 if __name__ ==", "is {} content \".format(ret, type(ret))) # so the global var assert ret.contents.value ==", "main(){ swap(&a, &b); return &a ; } ''', llvmdump=True) # ret_value = ret.contents", "import os import sys import ctypes this_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0,", "= 4; int* swap(int *x, int *y){ int tmp; tmp = *x; *x", "ret type is {} content \".format(ret, type(ret))) # so the global var assert", "print(\"The answer is {} ret type is {} content \".format(ret, type(ret))) # so", "sys import ctypes this_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator", "int b = 4; int* swap(int *x, int *y){ int tmp; tmp =", "class TestMainReturnPtr(unittest.TestCase): def test_simple(self): pcc = CEvaluator() ret = pcc.evaluate(''' int a =", "int *y){ int tmp; tmp = *x; *x = *y; *y = tmp;", "*y){ int tmp; tmp = *x; *x = *y; *y = tmp; return", "int* main(){ swap(&a, &b); return &a ; } ''', llvmdump=True) # ret_value =", "{} content \".format(ret, type(ret))) # so the global var assert ret.contents.value == 4", "= CEvaluator() ret = pcc.evaluate(''' int a = 50; int b = 4;", "import ctypes this_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import", "this_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) sys.path.insert(0, parent_dir) from pcc.evaluater.c_evaluator import CEvaluator import" ]
[ "content(self) -> str: extras = self.extras if not extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\",", "enable. extras: list = [] @oneshot def content(self) -> str: extras = self.extras", "load_md(path: Path) -> LoaderResult: data = path.read_text(encoding=\"utf-8\") return data, {\"content_type\": \"MarkdownPage\"} Site.register_loader(\"md\", load_md)", "in ``config.yml`` via: content_type:MarkdownPage or using the ``extras`` attribute. \"\"\" # List of", "markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path: Path) -> LoaderResult: data = path.read_text(encoding=\"utf-8\") return data,", "List of Markdown extensions to enable. extras: list = [] @oneshot def content(self)", "import markdown from gilbert import Site from gilbert.content import Page from gilbert.types import", "be configured in ``config.yml`` via: content_type:MarkdownPage or using the ``extras`` attribute. \"\"\" #", "from gilbert.types import LoaderResult from gilbert.utils import oneshot class MarkdownPage(Page): \"\"\" Page type", "self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path: Path) -> LoaderResult: data", "extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path: Path)", "import oneshot class MarkdownPage(Page): \"\"\" Page type that renders its content as Markdown.", "if not extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\", extensions=extras) def", "attribute. \"\"\" # List of Markdown extensions to enable. extras: list = []", "list = [] @oneshot def content(self) -> str: extras = self.extras if not", "[] @oneshot def content(self) -> str: extras = self.extras if not extras: extras", "str: extras = self.extras if not extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return", "import Site from gilbert.content import Page from gilbert.types import LoaderResult from gilbert.utils import", "Markdown. Extensions can be configured in ``config.yml`` via: content_type:MarkdownPage or using the ``extras``", "pathlib import Path from markdown import markdown from gilbert import Site from gilbert.content", "MarkdownPage(Page): \"\"\" Page type that renders its content as Markdown. Extensions can be", "{}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path: Path) -> LoaderResult: data =", "-> str: extras = self.extras if not extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", [])", "output_format=\"html5\", extensions=extras) def load_md(path: Path) -> LoaderResult: data = path.read_text(encoding=\"utf-8\") return data, {\"content_type\":", "markdown from gilbert import Site from gilbert.content import Page from gilbert.types import LoaderResult", "import Page from gilbert.types import LoaderResult from gilbert.utils import oneshot class MarkdownPage(Page): \"\"\"", "of Markdown extensions to enable. extras: list = [] @oneshot def content(self) ->", "extras = self.extras if not extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data,", "self.extras if not extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\", extensions=extras)", "from pathlib import Path from markdown import markdown from gilbert import Site from", "\"\"\" # List of Markdown extensions to enable. extras: list = [] @oneshot", "its content as Markdown. Extensions can be configured in ``config.yml`` via: content_type:MarkdownPage or", "def load_md(path: Path) -> LoaderResult: data = path.read_text(encoding=\"utf-8\") return data, {\"content_type\": \"MarkdownPage\"} Site.register_loader(\"md\",", "# List of Markdown extensions to enable. extras: list = [] @oneshot def", "or using the ``extras`` attribute. \"\"\" # List of Markdown extensions to enable.", "gilbert import Site from gilbert.content import Page from gilbert.types import LoaderResult from gilbert.utils", "``extras`` attribute. \"\"\" # List of Markdown extensions to enable. extras: list =", "extras: list = [] @oneshot def content(self) -> str: extras = self.extras if", "@oneshot def content(self) -> str: extras = self.extras if not extras: extras =", "from gilbert.utils import oneshot class MarkdownPage(Page): \"\"\" Page type that renders its content", "\"\"\" Page type that renders its content as Markdown. Extensions can be configured", "to enable. extras: list = [] @oneshot def content(self) -> str: extras =", "extensions=extras) def load_md(path: Path) -> LoaderResult: data = path.read_text(encoding=\"utf-8\") return data, {\"content_type\": \"MarkdownPage\"}", "Page from gilbert.types import LoaderResult from gilbert.utils import oneshot class MarkdownPage(Page): \"\"\" Page", "content_type:MarkdownPage or using the ``extras`` attribute. \"\"\" # List of Markdown extensions to", "can be configured in ``config.yml`` via: content_type:MarkdownPage or using the ``extras`` attribute. \"\"\"", "not extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path:", "Site from gilbert.content import Page from gilbert.types import LoaderResult from gilbert.utils import oneshot", "def content(self) -> str: extras = self.extras if not extras: extras = self.site.config.get(\"content_type\",", "[]) return markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path: Path) -> LoaderResult: data = path.read_text(encoding=\"utf-8\")", "Extensions can be configured in ``config.yml`` via: content_type:MarkdownPage or using the ``extras`` attribute.", "``config.yml`` via: content_type:MarkdownPage or using the ``extras`` attribute. \"\"\" # List of Markdown", "oneshot class MarkdownPage(Page): \"\"\" Page type that renders its content as Markdown. Extensions", "content as Markdown. Extensions can be configured in ``config.yml`` via: content_type:MarkdownPage or using", "Path from markdown import markdown from gilbert import Site from gilbert.content import Page", "from markdown import markdown from gilbert import Site from gilbert.content import Page from", "extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path: Path) ->", "as Markdown. Extensions can be configured in ``config.yml`` via: content_type:MarkdownPage or using the", "from gilbert import Site from gilbert.content import Page from gilbert.types import LoaderResult from", "LoaderResult from gilbert.utils import oneshot class MarkdownPage(Page): \"\"\" Page type that renders its", "using the ``extras`` attribute. \"\"\" # List of Markdown extensions to enable. extras:", "= self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path: Path) -> LoaderResult:", "markdown import markdown from gilbert import Site from gilbert.content import Page from gilbert.types", "gilbert.content import Page from gilbert.types import LoaderResult from gilbert.utils import oneshot class MarkdownPage(Page):", "class MarkdownPage(Page): \"\"\" Page type that renders its content as Markdown. Extensions can", "gilbert.types import LoaderResult from gilbert.utils import oneshot class MarkdownPage(Page): \"\"\" Page type that", "configured in ``config.yml`` via: content_type:MarkdownPage or using the ``extras`` attribute. \"\"\" # List", "the ``extras`` attribute. \"\"\" # List of Markdown extensions to enable. extras: list", "that renders its content as Markdown. Extensions can be configured in ``config.yml`` via:", "gilbert.utils import oneshot class MarkdownPage(Page): \"\"\" Page type that renders its content as", "via: content_type:MarkdownPage or using the ``extras`` attribute. \"\"\" # List of Markdown extensions", "return markdown(self.data, output_format=\"html5\", extensions=extras) def load_md(path: Path) -> LoaderResult: data = path.read_text(encoding=\"utf-8\") return", "type that renders its content as Markdown. Extensions can be configured in ``config.yml``", "renders its content as Markdown. Extensions can be configured in ``config.yml`` via: content_type:MarkdownPage", "= self.extras if not extras: extras = self.site.config.get(\"content_type\", {}).get(\"MarkdownPage\", []) return markdown(self.data, output_format=\"html5\",", "= [] @oneshot def content(self) -> str: extras = self.extras if not extras:", "Page type that renders its content as Markdown. Extensions can be configured in", "from gilbert.content import Page from gilbert.types import LoaderResult from gilbert.utils import oneshot class", "import LoaderResult from gilbert.utils import oneshot class MarkdownPage(Page): \"\"\" Page type that renders", "Markdown extensions to enable. extras: list = [] @oneshot def content(self) -> str:", "extensions to enable. extras: list = [] @oneshot def content(self) -> str: extras", "import Path from markdown import markdown from gilbert import Site from gilbert.content import" ]
[ "os.path.abspath(os.path.expanduser(__file__)) sys.path.insert(0, os.path.dirname(EXGDBFILE) + \"/lib/\") import utils from enert import * def clearscreen():", "import * def clearscreen(): \"\"\" Customized clearscreen from https://github.com/longld/peda \"\"\" print(\"\\x1b[2J\\x1b[H\") utils.clearscreen =", "os.path.dirname(EXGDBFILE) + \"/lib/\") import utils from enert import * def clearscreen(): \"\"\" Customized", "enert import * def clearscreen(): \"\"\" Customized clearscreen from https://github.com/longld/peda \"\"\" print(\"\\x1b[2J\\x1b[H\") utils.clearscreen", "os import sys EXGDBFILE = os.path.abspath(os.path.expanduser(__file__)) sys.path.insert(0, os.path.dirname(EXGDBFILE) + \"/lib/\") import utils from", "* def clearscreen(): \"\"\" Customized clearscreen from https://github.com/longld/peda \"\"\" print(\"\\x1b[2J\\x1b[H\") utils.clearscreen = clearscreen", "sys EXGDBFILE = os.path.abspath(os.path.expanduser(__file__)) sys.path.insert(0, os.path.dirname(EXGDBFILE) + \"/lib/\") import utils from enert import", "sys.path.insert(0, os.path.dirname(EXGDBFILE) + \"/lib/\") import utils from enert import * def clearscreen(): \"\"\"", "import utils from enert import * def clearscreen(): \"\"\" Customized clearscreen from https://github.com/longld/peda", "import sys EXGDBFILE = os.path.abspath(os.path.expanduser(__file__)) sys.path.insert(0, os.path.dirname(EXGDBFILE) + \"/lib/\") import utils from enert", "utils from enert import * def clearscreen(): \"\"\" Customized clearscreen from https://github.com/longld/peda \"\"\"", "import os import sys EXGDBFILE = os.path.abspath(os.path.expanduser(__file__)) sys.path.insert(0, os.path.dirname(EXGDBFILE) + \"/lib/\") import utils", "from enert import * def clearscreen(): \"\"\" Customized clearscreen from https://github.com/longld/peda \"\"\" print(\"\\x1b[2J\\x1b[H\")", "\"/lib/\") import utils from enert import * def clearscreen(): \"\"\" Customized clearscreen from", "EXGDBFILE = os.path.abspath(os.path.expanduser(__file__)) sys.path.insert(0, os.path.dirname(EXGDBFILE) + \"/lib/\") import utils from enert import *", "= os.path.abspath(os.path.expanduser(__file__)) sys.path.insert(0, os.path.dirname(EXGDBFILE) + \"/lib/\") import utils from enert import * def", "+ \"/lib/\") import utils from enert import * def clearscreen(): \"\"\" Customized clearscreen" ]
[ "row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text", "key_start) def get_espn_batter_stats(self, row, key_start): self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp']", "+ '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] =", "key_start + \"_\" + site if site == 'ESPN': self.get_espn_stats(row, key) elif site", "{ 'name': self.name, 'position': self.position, 'mlb_team': self.mlb_team, 'throws': self.throws, 'bats': self.bats, 'espn_id': self.espn_id,", "+ \"_\" + site if site == 'ESPN': self.get_espn_stats(row, key) elif site ==", "except Exception: self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start", "mine, 'team_number': self.team } for key, value in self.stats.items(): player_dict[key] = value return", "self.mlb_team = player['mlb_team'] self.throws = player['throws'] self.bats = player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id", "self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops']", "self.position = player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws = player['throws'] self.bats = player['bats'] self.espn_id", "= str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id = '' self.mine = False self.batter =", "= player['espn_name'] self.position = player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws = player['throws'] self.bats =", "def get_espn_stats(self, row, key_start): if self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self,", "= row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start", "'team_number': self.team } for key, value in self.stats.items(): player_dict[key] = value return player_dict", "self.team } for key, value in self.stats.items(): player_dict[key] = value return player_dict def", "== 'BR': self.get_br_stats(row, key) def get_br_stats(self, row, key_start): try: self.stats[key_start + '_ba'] =", "row, key_start, site): key = key_start + \"_\" + site if site ==", "row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip']", "self.mine = False self.batter = self.position != 'RP' and self.position != 'SP' self.stats", "self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row, key_start): self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start +", "self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine': mine, 'team_number': self.team } for key, value", "'x' player_dict = { 'name': self.name, 'position': self.position, 'mlb_team': self.mlb_team, 'throws': self.throws, 'bats':", "row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start +", "self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start): if self.batter: self.get_espn_batter_stats(row, key_start)", "player['bref_id'] self.fg_id = '' self.mine = False self.batter = self.position != 'RP' and", "get_stats(self, row, key_start, site): key = key_start + \"_\" + site if site", "row, key_start): self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start", "= row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start): if self.batter:", "= row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start", "= row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] =", "self.fg_id = '' self.mine = False self.batter = self.position != 'RP' and self.position", "self.bref_id = player['bref_id'] self.fg_id = '' self.mine = False self.batter = self.position !=", "player_dict def get_stats(self, row, key_start, site): key = key_start + \"_\" + site", "def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] =", "self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start + '_era'] =", "self.stats = {} self.team = player['team_id'] def to_dict(self): mine = '' if self.mine:", "player_dict[key] = value return player_dict def get_stats(self, row, key_start, site): key = key_start", "= row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start +", "if self.mine: mine = 'x' player_dict = { 'name': self.name, 'position': self.position, 'mlb_team':", "'mine': mine, 'team_number': self.team } for key, value in self.stats.items(): player_dict[key] = value", "self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start + '_so']", "key_start) else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row, key_start): self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text", "self.position, 'mlb_team': self.mlb_team, 'throws': self.throws, 'bats': self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id,", "player['throws'] self.bats = player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id = ''", "self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start", "'_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip']", "+ '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] =", "= self.position != 'RP' and self.position != 'SP' self.stats = {} self.team =", "elif site == 'BR': self.get_br_stats(row, key) def get_br_stats(self, row, key_start): try: self.stats[key_start +", "!= 'RP' and self.position != 'SP' self.stats = {} self.team = player['team_id'] def", "+ '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start + '_so'] =", "+ '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start +", "self.team = player['team_id'] def to_dict(self): mine = '' if self.mine: mine = 'x'", "'fg_id': self.fg_id, 'mine': mine, 'team_number': self.team } for key, value in self.stats.items(): player_dict[key]", "row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start +", "self.mlb_team, 'throws': self.throws, 'bats': self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine': mine,", "self.get_br_stats(row, key) def get_br_stats(self, row, key_start): try: self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start", "get_br_stats(self, row, key_start): try: self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] =", "} for key, value in self.stats.items(): player_dict[key] = value return player_dict def get_stats(self,", "'_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[15]').text", "+ '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] =", "= row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except", "self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so']", "player): self.name = player['espn_name'] self.position = player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws = player['throws']", "= row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start", "'RP' and self.position != 'SP' self.stats = {} self.team = player['team_id'] def to_dict(self):", "try: self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start +", "'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine': mine, 'team_number': self.team } for key,", "'_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text", "self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row,", "player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id = '' self.mine = False", "False self.batter = self.position != 'RP' and self.position != 'SP' self.stats = {}", "= value return player_dict def get_stats(self, row, key_start, site): key = key_start +", "self.name, 'position': self.position, 'mlb_team': self.mlb_team, 'throws': self.throws, 'bats': self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id,", "'position': self.position, 'mlb_team': self.mlb_team, 'throws': self.throws, 'bats': self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id':", "'_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start): if", "self.stats.items(): player_dict[key] = value return player_dict def get_stats(self, row, key_start, site): key =", "value in self.stats.items(): player_dict[key] = value return player_dict def get_stats(self, row, key_start, site):", "= player['team_id'] def to_dict(self): mine = '' if self.mine: mine = 'x' player_dict", "row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start): if self.batter: self.get_espn_batter_stats(row,", "= '' if self.mine: mine = 'x' player_dict = { 'name': self.name, 'position':", "'name': self.name, 'position': self.position, 'mlb_team': self.mlb_team, 'throws': self.throws, 'bats': self.bats, 'espn_id': self.espn_id, 'bref_id':", "self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row,", "row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start +", "self.bref_id, 'fg_id': self.fg_id, 'mine': mine, 'team_number': self.team } for key, value in self.stats.items():", "return player_dict def get_stats(self, row, key_start, site): key = key_start + \"_\" +", "def get_br_stats(self, row, key_start): try: self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp']", "self.mine: mine = 'x' player_dict = { 'name': self.name, 'position': self.position, 'mlb_team': self.mlb_team,", "self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row, key_start): self.stats[key_start + '_ba'] =", "mine = 'x' player_dict = { 'name': self.name, 'position': self.position, 'mlb_team': self.mlb_team, 'throws':", "get_espn_batter_stats(self, row, key_start): self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text", "in self.stats.items(): player_dict[key] = value return player_dict def get_stats(self, row, key_start, site): key", "self.name = player['espn_name'] self.position = player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws = player['throws'] self.bats", "= '' self.mine = False self.batter = self.position != 'RP' and self.position !=", "{} self.team = player['team_id'] def to_dict(self): mine = '' if self.mine: mine =", "'bats': self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine': mine, 'team_number': self.team }", "= 'x' player_dict = { 'name': self.name, 'position': self.position, 'mlb_team': self.mlb_team, 'throws': self.throws,", "'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine': mine, 'team_number': self.team } for key, value in", "+ '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_bb'] =", "key_start): try: self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start", "row, key_start): if self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row, key_start):", "get_espn_stats(self, row, key_start): if self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row,", "+ '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start):", "if self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row, key_start): self.stats[key_start +", "'_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text", "key) elif site == 'BR': self.get_br_stats(row, key) def get_br_stats(self, row, key_start): try: self.stats[key_start", "'' self.mine = False self.batter = self.position != 'RP' and self.position != 'SP'", "= key_start + \"_\" + site if site == 'ESPN': self.get_espn_stats(row, key) elif", "row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self,", "\"_\" + site if site == 'ESPN': self.get_espn_stats(row, key) elif site == 'BR':", "= row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start + '_era'] =", "'_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text", "player_dict = { 'name': self.name, 'position': self.position, 'mlb_team': self.mlb_team, 'throws': self.throws, 'bats': self.bats,", "'throws': self.throws, 'bats': self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine': mine, 'team_number':", "row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self,", "= row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text def", "= row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start +", "for key, value in self.stats.items(): player_dict[key] = value return player_dict def get_stats(self, row,", "'' if self.mine: mine = 'x' player_dict = { 'name': self.name, 'position': self.position,", "= row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start): if self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start)", "+ site if site == 'ESPN': self.get_espn_stats(row, key) elif site == 'BR': self.get_br_stats(row,", "= player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws = player['throws'] self.bats = player['bats'] self.espn_id =", "key_start): self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start +", "player['espn_name'] self.position = player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws = player['throws'] self.bats = player['bats']", "key_start): if self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row, key_start): self.stats[key_start", "class Player(): def __init__(self, player): self.name = player['espn_name'] self.position = player['espn_pos'] self.mlb_team =", "key, value in self.stats.items(): player_dict[key] = value return player_dict def get_stats(self, row, key_start,", "'_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start + '_era']", "get_espn_pitcher_stats(self, row, key_start): self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text", "Player(): def __init__(self, player): self.name = player['espn_name'] self.position = player['espn_pos'] self.mlb_team = player['mlb_team']", "self.espn_id = str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id = '' self.mine = False self.batter", "'BR': self.get_br_stats(row, key) def get_br_stats(self, row, key_start): try: self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text", "self.position != 'SP' self.stats = {} self.team = player['team_id'] def to_dict(self): mine =", "str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id = '' self.mine = False self.batter = self.position", "self.batter = self.position != 'RP' and self.position != 'SP' self.stats = {} self.team", "if site == 'ESPN': self.get_espn_stats(row, key) elif site == 'BR': self.get_br_stats(row, key) def", "row, key_start): self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start", "'ESPN': self.get_espn_stats(row, key) elif site == 'BR': self.get_br_stats(row, key) def get_br_stats(self, row, key_start):", "self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops']", "+ '_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text", "row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start + '_era']", "self.fg_id, 'mine': mine, 'team_number': self.team } for key, value in self.stats.items(): player_dict[key] =", "site if site == 'ESPN': self.get_espn_stats(row, key) elif site == 'BR': self.get_br_stats(row, key)", "'_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start", "site): key = key_start + \"_\" + site if site == 'ESPN': self.get_espn_stats(row,", "+ '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] =", "+ '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start +", "'_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start): self.stats[key_start", "row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text", "key_start): self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start +", "row, key_start): try: self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text", "= player['mlb_team'] self.throws = player['throws'] self.bats = player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id =", "'_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text", "'_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start): if self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row,", "= row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def", "player['team_id'] def to_dict(self): mine = '' if self.mine: mine = 'x' player_dict =", "player['mlb_team'] self.throws = player['throws'] self.bats = player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id = player['bref_id']", "to_dict(self): mine = '' if self.mine: mine = 'x' player_dict = { 'name':", "key) def get_br_stats(self, row, key_start): try: self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start +", "row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[@data-stat=\"slugging_perc\"]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception:", "self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_plus_slugging\"]').text except Exception: self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start", "__init__(self, player): self.name = player['espn_name'] self.position = player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws =", "= player['throws'] self.bats = player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id =", "Exception: self.stats[key_start + '_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start +", "'_era'] = row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[16]').text", "'_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text", "key = key_start + \"_\" + site if site == 'ESPN': self.get_espn_stats(row, key)", "def to_dict(self): mine = '' if self.mine: mine = 'x' player_dict = {", "self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb']", "== 'ESPN': self.get_espn_stats(row, key) elif site == 'BR': self.get_br_stats(row, key) def get_br_stats(self, row,", "= player['bref_id'] self.fg_id = '' self.mine = False self.batter = self.position != 'RP'", "+ '_bb'] = row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start): if self.batter: self.get_espn_batter_stats(row, key_start) else:", "key_start, site): key = key_start + \"_\" + site if site == 'ESPN':", "site == 'ESPN': self.get_espn_stats(row, key) elif site == 'BR': self.get_br_stats(row, key) def get_br_stats(self,", "self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row, key_start): self.stats[key_start + '_ba']", "else: self.get_espn_pitcher_stats(row, key_start) def get_espn_batter_stats(self, row, key_start): self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start", "self.throws = player['throws'] self.bats = player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id", "row.find_element_by_xpath('.//td[@data-stat=\"BB\"]').text def get_espn_stats(self, row, key_start): if self.batter: self.get_espn_batter_stats(row, key_start) else: self.get_espn_pitcher_stats(row, key_start) def", "self.bats = player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id = '' self.mine", "self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine': mine, 'team_number': self.team } for", "'mlb_team': self.mlb_team, 'throws': self.throws, 'bats': self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine':", "+ '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text self.stats[key_start + '_bb'] =", "!= 'SP' self.stats = {} self.team = player['team_id'] def to_dict(self): mine = ''", "self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg']", "= {} self.team = player['team_id'] def to_dict(self): mine = '' if self.mine: mine", "= player['bats'] self.espn_id = str(int(player['espn_id'])) self.bref_id = player['bref_id'] self.fg_id = '' self.mine =", "self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg']", "= { 'name': self.name, 'position': self.position, 'mlb_team': self.mlb_team, 'throws': self.throws, 'bats': self.bats, 'espn_id':", "def get_espn_batter_stats(self, row, key_start): self.stats[key_start + '_ba'] = row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] =", "site == 'BR': self.get_br_stats(row, key) def get_br_stats(self, row, key_start): try: self.stats[key_start + '_ba']", "def __init__(self, player): self.name = player['espn_name'] self.position = player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws", "'SP' self.stats = {} self.team = player['team_id'] def to_dict(self): mine = '' if", "mine = '' if self.mine: mine = 'x' player_dict = { 'name': self.name,", "= row.find_element_by_xpath('.//td[2]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start", "self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[10]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_bb']", "row.find_element_by_xpath('.//td[14]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[15]').text self.stats[key_start + '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start +", "def get_stats(self, row, key_start, site): key = key_start + \"_\" + site if", "player['espn_pos'] self.mlb_team = player['mlb_team'] self.throws = player['throws'] self.bats = player['bats'] self.espn_id = str(int(player['espn_id']))", "self.position != 'RP' and self.position != 'SP' self.stats = {} self.team = player['team_id']", "+ '_ba'] = row.find_element_by_xpath('.//td[@data-stat=\"batting_avg\"]').text self.stats[key_start + '_obp'] = row.find_element_by_xpath('.//td[@data-stat=\"onbase_perc\"]').text self.stats[key_start + '_slg'] =", "value return player_dict def get_stats(self, row, key_start, site): key = key_start + \"_\"", "self.get_espn_stats(row, key) elif site == 'BR': self.get_br_stats(row, key) def get_br_stats(self, row, key_start): try:", "'_era'] = row.find_element_by_xpath('.//td[@data-stat=\"earned_run_avg\"]').text self.stats[key_start + '_ip'] = row.find_element_by_xpath('.//td[@data-stat=\"IP\"]').text self.stats[key_start + '_so'] = row.find_element_by_xpath('.//td[@data-stat=\"SO\"]').text", "and self.position != 'SP' self.stats = {} self.team = player['team_id'] def to_dict(self): mine", "= False self.batter = self.position != 'RP' and self.position != 'SP' self.stats =", "self.throws, 'bats': self.bats, 'espn_id': self.espn_id, 'bref_id': self.bref_id, 'fg_id': self.fg_id, 'mine': mine, 'team_number': self.team", "+ '_slg'] = row.find_element_by_xpath('.//td[16]').text self.stats[key_start + '_ops'] = row.find_element_by_xpath('.//td[17]').text def get_espn_pitcher_stats(self, row, key_start):" ]
[ "httplib2 import urllib import json import re import sys class Transport: \"\"\" Abstract", "of a transport class. Defines the supported API methods \"\"\" endpoint = \"platform.clickatell.com\"", "higher \"\"\" response['body'] = json.loads(response['body']) response['messages'] = response['body']['messages'] response['error'] = response['body']['error'] del response['body']", "API :param str action: The API action :param dict data: The request parameters", "headers (if any) :param str method: The HTTP method :return: The request response", "action url = (url + '?' + body) if (method == 'GET') else", "request response \"\"\" http = httplib2.Http() body = urllib.urlencode(data) if (sys.version_info[0] < 3)", "extra: Any extra parameters (see Clickatell documentation) :return dict :raises NotImplementedError \"\"\" raise", "list(entry.items()) return dict(values) def parseResponse(self, response): \"\"\" Parse the response from json. Remapping", "return dict(values) def parseResponse(self, response): \"\"\" Parse the response from json. Remapping error", "method: The HTTP method :return: The request response \"\"\" http = httplib2.Http() body", "and messages to be a level higher \"\"\" response['body'] = json.loads(response['body']) response['messages'] =", "'GET') else url resp, content = http.request(url, method, headers=headers, body=json.dumps(data)) return self.merge(resp, {'body':", "The request response \"\"\" http = httplib2.Http() body = urllib.urlencode(data) if (sys.version_info[0] <", "response['body'] return response def request(self, action, data={}, headers={}, method='GET'): \"\"\" Run the HTTP", "response['body']['error'] del response['body'] return response def request(self, action, data={}, headers={}, method='GET'): \"\"\" Run", "dict extra: Any extra parameters (see Clickatell documentation) :return dict :raises NotImplementedError \"\"\"", "def request(self, action, data={}, headers={}, method='GET'): \"\"\" Run the HTTP request against the", "level higher \"\"\" response['body'] = json.loads(response['body']) response['messages'] = response['body']['messages'] response['error'] = response['body']['error'] del", "API action :param dict data: The request parameters :param dict headers: The request", "The API action :param dict data: The request parameters :param dict headers: The", "= json.loads(response['body']) response['messages'] = response['body']['messages'] response['error'] = response['body']['error'] del response['body'] return response def", "request parameters :param dict headers: The request headers (if any) :param str method:", "values = values + list(entry.items()) return dict(values) def parseResponse(self, response): \"\"\" Parse the", "return response def request(self, action, data={}, headers={}, method='GET'): \"\"\" Run the HTTP request", "any) :param str method: The HTTP method :return: The request response \"\"\" http", "= \"platform.clickatell.com\" def __init__(self): \"\"\" Construct a new transportation instance. :param boolean secure:", "def merge(self, *args): \"\"\" Merge multiple dictionary objects into one. :param variadic args:", "json. Remapping error code and messages to be a level higher \"\"\" response['body']", "Parse the response from json. Remapping error code and messages to be a", "= response['body']['messages'] response['error'] = response['body']['error'] del response['body'] return response def request(self, action, data={},", "+ body) if (method == 'GET') else url resp, content = http.request(url, method,", "= values + list(entry.items()) return dict(values) def parseResponse(self, response): \"\"\" Parse the response", ":return: The request response \"\"\" http = httplib2.Http() body = urllib.urlencode(data) if (sys.version_info[0]", "\"\"\" values = [] for entry in args: values = values + list(entry.items())", "def __init__(self): \"\"\" Construct a new transportation instance. :param boolean secure: Should we", "from json. Remapping error code and messages to be a level higher \"\"\"", "in args: values = values + list(entry.items()) return dict(values) def parseResponse(self, response): \"\"\"", "\"\"\" http = httplib2.Http() body = urllib.urlencode(data) if (sys.version_info[0] < 3) else urllib.parse.urlencode(data)", "action :param dict data: The request parameters :param dict headers: The request headers", "method, headers=headers, body=json.dumps(data)) return self.merge(resp, {'body': content}) def sendMessage(self, to, message, extra={}): \"\"\"", "dict(values) def parseResponse(self, response): \"\"\" Parse the response from json. Remapping error code", "+ '/' + action url = (url + '?' + body) if (method", "action, data={}, headers={}, method='GET'): \"\"\" Run the HTTP request against the Clickatell API", "Construct a new transportation instance. :param boolean secure: Should we try and use", ":param dict headers: The request headers (if any) :param str method: The HTTP", "args: values = values + list(entry.items()) return dict(values) def parseResponse(self, response): \"\"\" Parse", "dict headers: The request headers (if any) :param str method: The HTTP method", "(list of strings, or one string) :param string message: The message you want", "data: The request parameters :param dict headers: The request headers (if any) :param", "method :return: The request response \"\"\" http = httplib2.Http() body = urllib.urlencode(data) if", "message, extra={}): \"\"\" Send a message. :param list to: The number you want", "string) :param string message: The message you want to send :param dict extra:", "body = urllib.urlencode(data) if (sys.version_info[0] < 3) else urllib.parse.urlencode(data) url = 'https://' +", "for entry in args: values = values + list(entry.items()) return dict(values) def parseResponse(self,", "Run the HTTP request against the Clickatell API :param str action: The API", "boolean secure: Should we try and use a secure connection \"\"\" pass def", "\"\"\" Run the HTTP request against the Clickatell API :param str action: The", "= response['body']['error'] del response['body'] return response def request(self, action, data={}, headers={}, method='GET'): \"\"\"", "content}) def sendMessage(self, to, message, extra={}): \"\"\" Send a message. :param list to:", "sendMessage(self, to, message, extra={}): \"\"\" Send a message. :param list to: The number", "API methods \"\"\" endpoint = \"platform.clickatell.com\" def __init__(self): \"\"\" Construct a new transportation", "want to send to (list of strings, or one string) :param string message:", "re import sys class Transport: \"\"\" Abstract representation of a transport class. Defines", "\"\"\" Abstract representation of a transport class. Defines the supported API methods \"\"\"", "we try and use a secure connection \"\"\" pass def merge(self, *args): \"\"\"", "url = 'https://' + self.endpoint + '/' + action url = (url +", "= http.request(url, method, headers=headers, body=json.dumps(data)) return self.merge(resp, {'body': content}) def sendMessage(self, to, message,", "\"\"\" Send a message. :param list to: The number you want to send", ":param dict data: The request parameters :param dict headers: The request headers (if", "code and messages to be a level higher \"\"\" response['body'] = json.loads(response['body']) response['messages']", "or one string) :param string message: The message you want to send :param", "response): \"\"\" Parse the response from json. Remapping error code and messages to", "request against the Clickatell API :param str action: The API action :param dict", "string message: The message you want to send :param dict extra: Any extra", "import urllib import json import re import sys class Transport: \"\"\" Abstract representation", ":param str method: The HTTP method :return: The request response \"\"\" http =", "The HTTP method :return: The request response \"\"\" http = httplib2.Http() body =", "{'body': content}) def sendMessage(self, to, message, extra={}): \"\"\" Send a message. :param list", "== 'GET') else url resp, content = http.request(url, method, headers=headers, body=json.dumps(data)) return self.merge(resp,", "def sendMessage(self, to, message, extra={}): \"\"\" Send a message. :param list to: The", "transport class. Defines the supported API methods \"\"\" endpoint = \"platform.clickatell.com\" def __init__(self):", "you want to send :param dict extra: Any extra parameters (see Clickatell documentation)", "response \"\"\" http = httplib2.Http() body = urllib.urlencode(data) if (sys.version_info[0] < 3) else", "resp, content = http.request(url, method, headers=headers, body=json.dumps(data)) return self.merge(resp, {'body': content}) def sendMessage(self,", "response from json. Remapping error code and messages to be a level higher", "(if any) :param str method: The HTTP method :return: The request response \"\"\"", "to send :param dict extra: Any extra parameters (see Clickatell documentation) :return dict", "headers={}, method='GET'): \"\"\" Run the HTTP request against the Clickatell API :param str", "number you want to send to (list of strings, or one string) :param", "headers=headers, body=json.dumps(data)) return self.merge(resp, {'body': content}) def sendMessage(self, to, message, extra={}): \"\"\" Send", "Merge multiple dictionary objects into one. :param variadic args: Multiple dictionary items :return", "url resp, content = http.request(url, method, headers=headers, body=json.dumps(data)) return self.merge(resp, {'body': content}) def", "url = (url + '?' + body) if (method == 'GET') else url", "else urllib.parse.urlencode(data) url = 'https://' + self.endpoint + '/' + action url =", "+ '?' + body) if (method == 'GET') else url resp, content =", "\"\"\" pass def merge(self, *args): \"\"\" Merge multiple dictionary objects into one. :param", "< 3) else urllib.parse.urlencode(data) url = 'https://' + self.endpoint + '/' + action", "the HTTP request against the Clickatell API :param str action: The API action", "+ action url = (url + '?' + body) if (method == 'GET')", ":param variadic args: Multiple dictionary items :return dict \"\"\" values = [] for", "messages to be a level higher \"\"\" response['body'] = json.loads(response['body']) response['messages'] = response['body']['messages']", "response def request(self, action, data={}, headers={}, method='GET'): \"\"\" Run the HTTP request against", "self.merge(resp, {'body': content}) def sendMessage(self, to, message, extra={}): \"\"\" Send a message. :param", "else url resp, content = http.request(url, method, headers=headers, body=json.dumps(data)) return self.merge(resp, {'body': content})", "methods \"\"\" endpoint = \"platform.clickatell.com\" def __init__(self): \"\"\" Construct a new transportation instance.", "class. Defines the supported API methods \"\"\" endpoint = \"platform.clickatell.com\" def __init__(self): \"\"\"", "\"\"\" response['body'] = json.loads(response['body']) response['messages'] = response['body']['messages'] response['error'] = response['body']['error'] del response['body'] return", "if (sys.version_info[0] < 3) else urllib.parse.urlencode(data) url = 'https://' + self.endpoint + '/'", "str method: The HTTP method :return: The request response \"\"\" http = httplib2.Http()", "(url + '?' + body) if (method == 'GET') else url resp, content", "against the Clickatell API :param str action: The API action :param dict data:", "request(self, action, data={}, headers={}, method='GET'): \"\"\" Run the HTTP request against the Clickatell", "the response from json. Remapping error code and messages to be a level", ":param str action: The API action :param dict data: The request parameters :param", "response['body'] = json.loads(response['body']) response['messages'] = response['body']['messages'] response['error'] = response['body']['error'] del response['body'] return response", "send :param dict extra: Any extra parameters (see Clickatell documentation) :return dict :raises", "'?' + body) if (method == 'GET') else url resp, content = http.request(url,", "Send a message. :param list to: The number you want to send to", "message: The message you want to send :param dict extra: Any extra parameters", "Clickatell API :param str action: The API action :param dict data: The request", "= 'https://' + self.endpoint + '/' + action url = (url + '?'", "*args): \"\"\" Merge multiple dictionary objects into one. :param variadic args: Multiple dictionary", "response['body']['messages'] response['error'] = response['body']['error'] del response['body'] return response def request(self, action, data={}, headers={},", "args: Multiple dictionary items :return dict \"\"\" values = [] for entry in", "httplib2.Http() body = urllib.urlencode(data) if (sys.version_info[0] < 3) else urllib.parse.urlencode(data) url = 'https://'", "Multiple dictionary items :return dict \"\"\" values = [] for entry in args:", "urllib import json import re import sys class Transport: \"\"\" Abstract representation of", "The request headers (if any) :param str method: The HTTP method :return: The", "str action: The API action :param dict data: The request parameters :param dict", "(sys.version_info[0] < 3) else urllib.parse.urlencode(data) url = 'https://' + self.endpoint + '/' +", ":return dict \"\"\" values = [] for entry in args: values = values", "the supported API methods \"\"\" endpoint = \"platform.clickatell.com\" def __init__(self): \"\"\" Construct a", "\"\"\" Construct a new transportation instance. :param boolean secure: Should we try and", "dictionary objects into one. :param variadic args: Multiple dictionary items :return dict \"\"\"", "action: The API action :param dict data: The request parameters :param dict headers:", "= urllib.urlencode(data) if (sys.version_info[0] < 3) else urllib.parse.urlencode(data) url = 'https://' + self.endpoint", "urllib.parse.urlencode(data) url = 'https://' + self.endpoint + '/' + action url = (url", "supported API methods \"\"\" endpoint = \"platform.clickatell.com\" def __init__(self): \"\"\" Construct a new", "to (list of strings, or one string) :param string message: The message you", "= (url + '?' + body) if (method == 'GET') else url resp,", "error code and messages to be a level higher \"\"\" response['body'] = json.loads(response['body'])", "= httplib2.Http() body = urllib.urlencode(data) if (sys.version_info[0] < 3) else urllib.parse.urlencode(data) url =", "body) if (method == 'GET') else url resp, content = http.request(url, method, headers=headers,", "\"\"\" Merge multiple dictionary objects into one. :param variadic args: Multiple dictionary items", ":param list to: The number you want to send to (list of strings,", "\"\"\" endpoint = \"platform.clickatell.com\" def __init__(self): \"\"\" Construct a new transportation instance. :param", "endpoint = \"platform.clickatell.com\" def __init__(self): \"\"\" Construct a new transportation instance. :param boolean", "'https://' + self.endpoint + '/' + action url = (url + '?' +", "http.request(url, method, headers=headers, body=json.dumps(data)) return self.merge(resp, {'body': content}) def sendMessage(self, to, message, extra={}):", "The message you want to send :param dict extra: Any extra parameters (see", "json.loads(response['body']) response['messages'] = response['body']['messages'] response['error'] = response['body']['error'] del response['body'] return response def request(self,", "data={}, headers={}, method='GET'): \"\"\" Run the HTTP request against the Clickatell API :param", "The number you want to send to (list of strings, or one string)", "message you want to send :param dict extra: Any extra parameters (see Clickatell", "representation of a transport class. Defines the supported API methods \"\"\" endpoint =", "list to: The number you want to send to (list of strings, or", "a new transportation instance. :param boolean secure: Should we try and use a", "items :return dict \"\"\" values = [] for entry in args: values =", "one string) :param string message: The message you want to send :param dict", "Should we try and use a secure connection \"\"\" pass def merge(self, *args):", "method='GET'): \"\"\" Run the HTTP request against the Clickatell API :param str action:", ":param string message: The message you want to send :param dict extra: Any", "a transport class. Defines the supported API methods \"\"\" endpoint = \"platform.clickatell.com\" def", "instance. :param boolean secure: Should we try and use a secure connection \"\"\"", "sys class Transport: \"\"\" Abstract representation of a transport class. Defines the supported", "to, message, extra={}): \"\"\" Send a message. :param list to: The number you", "parameters :param dict headers: The request headers (if any) :param str method: The", "entry in args: values = values + list(entry.items()) return dict(values) def parseResponse(self, response):", "parseResponse(self, response): \"\"\" Parse the response from json. Remapping error code and messages", "try and use a secure connection \"\"\" pass def merge(self, *args): \"\"\" Merge", "to: The number you want to send to (list of strings, or one", "be a level higher \"\"\" response['body'] = json.loads(response['body']) response['messages'] = response['body']['messages'] response['error'] =", "response['messages'] = response['body']['messages'] response['error'] = response['body']['error'] del response['body'] return response def request(self, action,", "headers: The request headers (if any) :param str method: The HTTP method :return:", "\"platform.clickatell.com\" def __init__(self): \"\"\" Construct a new transportation instance. :param boolean secure: Should", ":param boolean secure: Should we try and use a secure connection \"\"\" pass", "Remapping error code and messages to be a level higher \"\"\" response['body'] =", "to be a level higher \"\"\" response['body'] = json.loads(response['body']) response['messages'] = response['body']['messages'] response['error']", "merge(self, *args): \"\"\" Merge multiple dictionary objects into one. :param variadic args: Multiple", "multiple dictionary objects into one. :param variadic args: Multiple dictionary items :return dict", "import json import re import sys class Transport: \"\"\" Abstract representation of a", "secure: Should we try and use a secure connection \"\"\" pass def merge(self,", "body=json.dumps(data)) return self.merge(resp, {'body': content}) def sendMessage(self, to, message, extra={}): \"\"\" Send a", "def parseResponse(self, response): \"\"\" Parse the response from json. Remapping error code and", "use a secure connection \"\"\" pass def merge(self, *args): \"\"\" Merge multiple dictionary", "extra={}): \"\"\" Send a message. :param list to: The number you want to", "a level higher \"\"\" response['body'] = json.loads(response['body']) response['messages'] = response['body']['messages'] response['error'] = response['body']['error']", "urllib.urlencode(data) if (sys.version_info[0] < 3) else urllib.parse.urlencode(data) url = 'https://' + self.endpoint +", "(method == 'GET') else url resp, content = http.request(url, method, headers=headers, body=json.dumps(data)) return", "__init__(self): \"\"\" Construct a new transportation instance. :param boolean secure: Should we try", "into one. :param variadic args: Multiple dictionary items :return dict \"\"\" values =", "class Transport: \"\"\" Abstract representation of a transport class. Defines the supported API", "json import re import sys class Transport: \"\"\" Abstract representation of a transport", "HTTP request against the Clickatell API :param str action: The API action :param", "HTTP method :return: The request response \"\"\" http = httplib2.Http() body = urllib.urlencode(data)", "Defines the supported API methods \"\"\" endpoint = \"platform.clickatell.com\" def __init__(self): \"\"\" Construct", "import re import sys class Transport: \"\"\" Abstract representation of a transport class.", "values + list(entry.items()) return dict(values) def parseResponse(self, response): \"\"\" Parse the response from", "request headers (if any) :param str method: The HTTP method :return: The request", "dict data: The request parameters :param dict headers: The request headers (if any)", "if (method == 'GET') else url resp, content = http.request(url, method, headers=headers, body=json.dumps(data))", "strings, or one string) :param string message: The message you want to send", "to send to (list of strings, or one string) :param string message: The", "secure connection \"\"\" pass def merge(self, *args): \"\"\" Merge multiple dictionary objects into", "of strings, or one string) :param string message: The message you want to", "import httplib2 import urllib import json import re import sys class Transport: \"\"\"", "http = httplib2.Http() body = urllib.urlencode(data) if (sys.version_info[0] < 3) else urllib.parse.urlencode(data) url", "'/' + action url = (url + '?' + body) if (method ==", "3) else urllib.parse.urlencode(data) url = 'https://' + self.endpoint + '/' + action url", "message. :param list to: The number you want to send to (list of", "Transport: \"\"\" Abstract representation of a transport class. Defines the supported API methods", "pass def merge(self, *args): \"\"\" Merge multiple dictionary objects into one. :param variadic", "+ list(entry.items()) return dict(values) def parseResponse(self, response): \"\"\" Parse the response from json.", "import sys class Transport: \"\"\" Abstract representation of a transport class. Defines the", "you want to send to (list of strings, or one string) :param string", "a message. :param list to: The number you want to send to (list", "new transportation instance. :param boolean secure: Should we try and use a secure", "variadic args: Multiple dictionary items :return dict \"\"\" values = [] for entry", "a secure connection \"\"\" pass def merge(self, *args): \"\"\" Merge multiple dictionary objects", ":param dict extra: Any extra parameters (see Clickatell documentation) :return dict :raises NotImplementedError", "response['error'] = response['body']['error'] del response['body'] return response def request(self, action, data={}, headers={}, method='GET'):", "send to (list of strings, or one string) :param string message: The message", "and use a secure connection \"\"\" pass def merge(self, *args): \"\"\" Merge multiple", "Abstract representation of a transport class. Defines the supported API methods \"\"\" endpoint", "= [] for entry in args: values = values + list(entry.items()) return dict(values)", "self.endpoint + '/' + action url = (url + '?' + body) if", "content = http.request(url, method, headers=headers, body=json.dumps(data)) return self.merge(resp, {'body': content}) def sendMessage(self, to,", "\"\"\" Parse the response from json. Remapping error code and messages to be", "want to send :param dict extra: Any extra parameters (see Clickatell documentation) :return", "Any extra parameters (see Clickatell documentation) :return dict :raises NotImplementedError \"\"\" raise NotImplementedError()", "dict \"\"\" values = [] for entry in args: values = values +", "connection \"\"\" pass def merge(self, *args): \"\"\" Merge multiple dictionary objects into one.", "del response['body'] return response def request(self, action, data={}, headers={}, method='GET'): \"\"\" Run the", "[] for entry in args: values = values + list(entry.items()) return dict(values) def", "objects into one. :param variadic args: Multiple dictionary items :return dict \"\"\" values", "dictionary items :return dict \"\"\" values = [] for entry in args: values", "the Clickatell API :param str action: The API action :param dict data: The", "+ self.endpoint + '/' + action url = (url + '?' + body)", "values = [] for entry in args: values = values + list(entry.items()) return", "The request parameters :param dict headers: The request headers (if any) :param str", "transportation instance. :param boolean secure: Should we try and use a secure connection", "one. :param variadic args: Multiple dictionary items :return dict \"\"\" values = []", "return self.merge(resp, {'body': content}) def sendMessage(self, to, message, extra={}): \"\"\" Send a message." ]
[ "\"\"\" :return: Return yaml data as dictionary format \"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\")", "\"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\") as yf: return yaml.load(yf, Loader=yaml.FullLoader) def write(self, data:", "import os import yaml class YamlConfig: def __init__(self, file_path: str = \"./settings/config.yml\"): self.file_path", "\"./settings/config.yml\"): self.file_path = file_path def exists(self) -> bool: return os.path.exists(self.file_path) def load(self) ->", "open(self.file_path, \"r\", encoding=\"utf-8\") as yf: return yaml.load(yf, Loader=yaml.FullLoader) def write(self, data: dict) ->", "bool: return os.path.exists(self.file_path) def load(self) -> dict: \"\"\" :return: Return yaml data as", "return os.path.exists(self.file_path) def load(self) -> dict: \"\"\" :return: Return yaml data as dictionary", "yaml.load(yf, Loader=yaml.FullLoader) def write(self, data: dict) -> None: \"\"\" Export yaml :param data:", "return yaml.load(yf, Loader=yaml.FullLoader) def write(self, data: dict) -> None: \"\"\" Export yaml :param", "def write(self, data: dict) -> None: \"\"\" Export yaml :param data: A dictionary", "Export yaml :param data: A dictionary of data that will be output in", "dictionary of data that will be output in Yaml format \"\"\" with open(self.file_path,", ":param data: A dictionary of data that will be output in Yaml format", "as dictionary format \"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\") as yf: return yaml.load(yf, Loader=yaml.FullLoader)", "with open(self.file_path, \"r\", encoding=\"utf-8\") as yf: return yaml.load(yf, Loader=yaml.FullLoader) def write(self, data: dict)", "os.path.exists(self.file_path) def load(self) -> dict: \"\"\" :return: Return yaml data as dictionary format", "def __init__(self, file_path: str = \"./settings/config.yml\"): self.file_path = file_path def exists(self) -> bool:", "exists(self) -> bool: return os.path.exists(self.file_path) def load(self) -> dict: \"\"\" :return: Return yaml", "A dictionary of data that will be output in Yaml format \"\"\" with", "will be output in Yaml format \"\"\" with open(self.file_path, \"w\", encoding=\"utf-8\") as yf:", "None: \"\"\" Export yaml :param data: A dictionary of data that will be", "output in Yaml format \"\"\" with open(self.file_path, \"w\", encoding=\"utf-8\") as yf: yaml.dump(data, yf,", "in Yaml format \"\"\" with open(self.file_path, \"w\", encoding=\"utf-8\") as yf: yaml.dump(data, yf, default_flow_style=False)", "-> bool: return os.path.exists(self.file_path) def load(self) -> dict: \"\"\" :return: Return yaml data", ":return: Return yaml data as dictionary format \"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\") as", "dict: \"\"\" :return: Return yaml data as dictionary format \"\"\" with open(self.file_path, \"r\",", "data: dict) -> None: \"\"\" Export yaml :param data: A dictionary of data", "yf: return yaml.load(yf, Loader=yaml.FullLoader) def write(self, data: dict) -> None: \"\"\" Export yaml", "Loader=yaml.FullLoader) def write(self, data: dict) -> None: \"\"\" Export yaml :param data: A", "as yf: return yaml.load(yf, Loader=yaml.FullLoader) def write(self, data: dict) -> None: \"\"\" Export", "file_path: str = \"./settings/config.yml\"): self.file_path = file_path def exists(self) -> bool: return os.path.exists(self.file_path)", "-> dict: \"\"\" :return: Return yaml data as dictionary format \"\"\" with open(self.file_path,", "def load(self) -> dict: \"\"\" :return: Return yaml data as dictionary format \"\"\"", "of data that will be output in Yaml format \"\"\" with open(self.file_path, \"w\",", "write(self, data: dict) -> None: \"\"\" Export yaml :param data: A dictionary of", "load(self) -> dict: \"\"\" :return: Return yaml data as dictionary format \"\"\" with", "= \"./settings/config.yml\"): self.file_path = file_path def exists(self) -> bool: return os.path.exists(self.file_path) def load(self)", "dictionary format \"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\") as yf: return yaml.load(yf, Loader=yaml.FullLoader) def", "yaml class YamlConfig: def __init__(self, file_path: str = \"./settings/config.yml\"): self.file_path = file_path def", "self.file_path = file_path def exists(self) -> bool: return os.path.exists(self.file_path) def load(self) -> dict:", "YamlConfig: def __init__(self, file_path: str = \"./settings/config.yml\"): self.file_path = file_path def exists(self) ->", "= file_path def exists(self) -> bool: return os.path.exists(self.file_path) def load(self) -> dict: \"\"\"", "-> None: \"\"\" Export yaml :param data: A dictionary of data that will", "Return yaml data as dictionary format \"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\") as yf:", "data that will be output in Yaml format \"\"\" with open(self.file_path, \"w\", encoding=\"utf-8\")", "os import yaml class YamlConfig: def __init__(self, file_path: str = \"./settings/config.yml\"): self.file_path =", "format \"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\") as yf: return yaml.load(yf, Loader=yaml.FullLoader) def write(self,", "data: A dictionary of data that will be output in Yaml format \"\"\"", "be output in Yaml format \"\"\" with open(self.file_path, \"w\", encoding=\"utf-8\") as yf: yaml.dump(data,", "class YamlConfig: def __init__(self, file_path: str = \"./settings/config.yml\"): self.file_path = file_path def exists(self)", "yaml :param data: A dictionary of data that will be output in Yaml", "file_path def exists(self) -> bool: return os.path.exists(self.file_path) def load(self) -> dict: \"\"\" :return:", "str = \"./settings/config.yml\"): self.file_path = file_path def exists(self) -> bool: return os.path.exists(self.file_path) def", "that will be output in Yaml format \"\"\" with open(self.file_path, \"w\", encoding=\"utf-8\") as", "__init__(self, file_path: str = \"./settings/config.yml\"): self.file_path = file_path def exists(self) -> bool: return", "dict) -> None: \"\"\" Export yaml :param data: A dictionary of data that", "\"r\", encoding=\"utf-8\") as yf: return yaml.load(yf, Loader=yaml.FullLoader) def write(self, data: dict) -> None:", "def exists(self) -> bool: return os.path.exists(self.file_path) def load(self) -> dict: \"\"\" :return: Return", "\"\"\" Export yaml :param data: A dictionary of data that will be output", "import yaml class YamlConfig: def __init__(self, file_path: str = \"./settings/config.yml\"): self.file_path = file_path", "yaml data as dictionary format \"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\") as yf: return", "data as dictionary format \"\"\" with open(self.file_path, \"r\", encoding=\"utf-8\") as yf: return yaml.load(yf,", "encoding=\"utf-8\") as yf: return yaml.load(yf, Loader=yaml.FullLoader) def write(self, data: dict) -> None: \"\"\"" ]
[ "= ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict =", "= S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 =", "= ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry =", "S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def", "def focal_median(img): I = ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make", "= 1000, maxPixels = 6098838800, tileScale = 16 ) inPixelmean = vv.reduceRegion( reducer", "falseCase = S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size())", "maxPixels = 6098838800, tileScale = 16 ) lMean = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(),", "dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def maskByAngle(img): I = ee.Image(img) angle = I.select('angle'); mask1", "ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) lPixelmean =", "ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def maskByAngle(img): I", "Pixels************************************************************** def maskByAngle(img): I = ee.Image(img) angle = I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2", "img #****Round time********************************************************************* def Roundtime(img): I = ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate", "#****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 =", "vv = img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale", "img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI,", "waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI,", "to km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean =", "of dates for time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def make_datelist(n):", "\"\"\" ******************************************************************************* Google Earth Engine Setninel-1 Lake Area o Purpose: Estimate surface are", "makeBackScatterFromJRC(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not()", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) I", "6098838800, tileScale = 16, ).get('occurrence')) #****Create list of dates for time series******************************************** n_steps", "ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth')", "img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time********************************************************************* def Roundtime(img): I = ee.Image(img)", "Date_End = ee.Date('2020-01-01'); date_interval = ee.Number(1); #month angle_threshold_1 = ee.Number(45.4); angle_threshold_2 = ee.Number(31.66)", "= 16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time*********************************************************************", "tileScale = 16 ) wPixelStd = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI,", "with ascending pass surface areas 4) List of time steps ascoiated with descending", "= 100, maxPixels = 6098838800, tileScale = 16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError", "= S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase = S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median", "ID, 'WError': WError, 'LError': LError }) exportTable = ee.Feature(None, exportDict) return exportTable Export", "ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "of time steps ascoiated with descending pass surface areas Written by: <NAME>, <EMAIL>", "= Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels =", "16 ) inPixelStd = vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry = roi, scale =", "= S1.map(calcThresh) S1 = S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 =", "S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1 = S1.map(calcError)", "= S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1 =", "vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI_Diff, scale = 300, maxPixels = 6098838800,", "series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist);", "o Inputs: * ROI: Google Earth Engine geometry object describing the region of", "def makeBackscatterStats(img): img = ee.Image(img) wMask = img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean =", "roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval = ee.Number(1);", "MakeWaterMask(img): I = ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask')", "= S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1 = S1.map(Roundtime) S1 =", "ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date': time, 'WaterArea':", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) wStd =", "condition = S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase = S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI)", "#****Filter Edge Pixels************************************************************** def maskByAngle(img): I = ee.Image(img) angle = I.select('angle'); mask1 =", "ascoiated with ascending pass surface areas 4) List of time steps ascoiated with", "S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1", "Google Earth Engine geometry object describing the region of interest o Outputs: *", "I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "maxPixels = 6098838800, tileScale = 16 ) I = I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask')))", "= ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval = ee.Number(1); #month angle_threshold_1", "-*- coding: utf-8 -*- \"\"\" ******************************************************************************* Google Earth Engine Setninel-1 Lake Area o", ")) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI", "-*- \"\"\" ******************************************************************************* Google Earth Engine Setninel-1 Lake Area o Purpose: Estimate surface", "= 300, maxPixels = 6098838800, tileScale = 16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img", "maskByAngle(img): I = ee.Image(img) angle = I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2);", "= 6098838800, tileScale = 16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry", "= I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels =", ") img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth'))", "= img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident", "img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1", "= 16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI_Diff, scale", "scale = 100, maxPixels = 6098838800, tileScale = 16 ) lStd = vv.updateMask(landConfident).reduceRegion(", "S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc", "tileScale = 16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI,", "'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID': ID, 'WError': WError, 'LError': LError }) exportTable =", "(ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(),", "= ee.Number(1); #month angle_threshold_1 = ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get", "S1.map(calcThresh) S1 = S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2)", "img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img):", "ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh = ee.Number(img.get('wThresh'))", "I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100,", "S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract Time Series***************************************************************", "exportDict = ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID': ID, 'WError': WError,", "waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError", "= img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img", "maxPixels = 6098838800, tileScale = 16 ) wStd = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(),", "img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth'))", "Edge Pixels************************************************************** def maskByAngle(img): I = ee.Image(img) angle = I.select('angle'); mask1 = angle.lt(angle_threshold_1);", "focal_median(img): I = ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water", "geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('wError'))", "vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "}) exportTable = ee.Feature(None, exportDict) return exportTable Export = ee.Algorithms.If( condition = S1.size().gt(0),", "= vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels =", "I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask**************************************************************** def MakeWaterMask(img): I = ee.Image(img)", "6098838800, tileScale = 16 ) inPixelStd = vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry =", "end = ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI)", "object describing the region of interest o Outputs: * Results: List containing 4", "16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale =", "#month angle_threshold_1 = ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get WaterProb Threshold************************************************", "6098838800, tileScale = 16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img", "S1 = S1.map(focal_median) #S1 = S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1", "Roundtime(img): I = ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img): img", "ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd'))", "ee.Reducer.stdDev(), geometry = ROI_Diff, scale = 300, maxPixels = 6098838800, tileScale = 16", "100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) #****Create list of dates for", "region of interest o Outputs: * Results: List containing 4 elements (GEE objects):", "I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img): img = ee.Image(img) wMask", "16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale =", "S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1 = S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1", "# -*- coding: utf-8 -*- \"\"\" ******************************************************************************* Google Earth Engine Setninel-1 Lake Area", "(GEE objects): 1) List of lake surface areas from ascending passes 2) List", "reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale", "return(S1_median) #****Calc ROI Area********************************************************************** def calcArea(img): I = ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer", "#lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img): img = ee.Image(img) wError = ee.Number(img.get('wError'))", "ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(),", "= ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale =", "dates = ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def", "= ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) wPixelStd", "Inputs: * ROI: Google Earth Engine geometry object describing the region of interest", "I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1", "S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1 = S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC)", "objects): 1) List of lake surface areas from ascending passes 2) List of", "= ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh)", ".filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0),", "lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh)", "landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels", "time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates =", "elements (GEE objects): 1) List of lake surface areas from ascending passes 2)", "ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({", "Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA, inPixelStdA, outPixelmeanA, outPixelStdA,", "maxPixels = 6098838800, tileScale = 16 ) inPixelStd = vv.reduceRegion( reducer = ee.Reducer.stdDev(),", "= 6098838800, tileScale = 16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img", "= 6098838800, tileScale = 16 ) inPixelStd = vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry", "reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels = 6098838800, tileScale", "S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time", "******************************************************************************* \"\"\" import ee ee.Initialize() def GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI = roi.geometry()", "ROI_Diff = ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval = ee.Number(1); #month", "lError = ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions******************************************************************", "S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract", "S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1", "= ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry = ROI, scale = 100, maxPixels =", "Outputs: * Results: List containing 4 elements (GEE objects): 1) List of lake", "steps ascoiated with ascending pass surface areas 4) List of time steps ascoiated", "def Roundtime(img): I = ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img):", "= 16 ) wStd = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale", "Earth Engine cloud computing platform o Inputs: * ROI: Google Earth Engine geometry", "geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 )", "#****Round time********************************************************************* def Roundtime(img): I = ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold**************************************************************", "ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh')", "areas 4) List of time steps ascoiated with descending pass surface areas Written", ") outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI_Diff, scale = 300,", ".filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase =", "reducer = ee.Reducer.mean(), geometry = ROI_Diff, scale = 1000, maxPixels = 6098838800, tileScale", "reducer = ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale", ") lMean = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 100,", "passes 3) List of time steps ascoiated with ascending pass surface areas 4)", "waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer", "areas from ascending passes 2) List of lake surface areas from descending passes", "ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase = S1 )) S1_median =", "= img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry =", "= 6098838800, tileScale = 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img): I =", "= 100, maxPixels = 6098838800, tileScale = 16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img", "\"\"\" import ee ee.Initialize() def GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI = roi.geometry() ROI_Diff", "S1_median = S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area********************************************************************** def calcArea(img): I", "= I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img): img =", "tileScale = 16 ) inPixelStd = vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry = roi,", "ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID': ID, 'WError': WError, 'LError': LError", "lMean = ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return", "lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels", "List of time steps ascoiated with descending pass surface areas Written by: <NAME>,", "o Outputs: * Results: List containing 4 elements (GEE objects): 1) List of", "Purpose: Estimate surface are of lake from Sentinel-1 SAR date, using Google Earth", "def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean =", "lake surface areas from descending passes 3) List of time steps ascoiated with", "Image Collection******************************************************** def create_collection(d): start = ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end);", "ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16", "= ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase = S1 )) S1_median", "= ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval = ee.Number(1); #month angle_threshold_1 = ee.Number(45.4); angle_threshold_2", "S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1 = S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999))", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) landConfidentArea =", "= 16 ) inPixelStd = vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry = roi, scale", "mask2 = angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image Collection******************************************************** def create_collection(d):", "ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "6098838800, tileScale = 16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry =", "= vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels =", "I = ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale", "condition = S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase = None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA,", "= ee.Algorithms.If( condition = S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase = None ) return", "6098838800, tileScale = 16 ) lStd = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry =", "vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry = roi, scale = 1000, maxPixels = 6098838800,", "= img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img): img", "= ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer =", "= img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time********************************************************************* def Roundtime(img): I =", "= ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date': time,", "start = ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\", "= ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1", "scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) #****Create list of", "ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) inPixelmean =", "Estimate surface are of lake from Sentinel-1 SAR date, using Google Earth Engine", "= img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img =", "maxPixels = 6098838800, tileScale = 16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence')", ") outPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI_Diff, scale = 1000,", "img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident =", "= I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make", "containing 4 elements (GEE objects): 1) List of lake surface areas from ascending", "WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd", "3) List of time steps ascoiated with ascending pass surface areas 4) List", "ee.Number(1); #month angle_threshold_1 = ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get WaterProb", "S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1 = S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999))", "= (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img): img =", "ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 =", "= vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = roi, scale = 1000, maxPixels =", "= S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 =", ".filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase =", "S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats)", "= ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID': ID, 'WError': WError, 'LError':", "exportDict) return exportTable Export = ee.Algorithms.If( condition = S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase", "time********************************************************************* def Roundtime(img): I = ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def", "img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return", "maxPixels = 6098838800, tileScale = 16 ) lStd = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(),", "img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time********************************************************************* def Roundtime(img): I = ee.Image(img) time", "List of time steps ascoiated with ascending pass surface areas 4) List of", "S1 = ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase = S1 ))", "WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry =", "ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion(", "#****Make Water Mask**************************************************************** def MakeWaterMask(img): I = ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb =", "= S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1 = S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 =", "GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI = roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start = ee.Date('2017-01-01');", "geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence'))", "reducer = ee.Reducer.mean(), geometry = roi, scale = 1000, maxPixels = 6098838800, tileScale", "S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def extractTimeSeries(collection): WaterArea", "return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident", "= ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels =", "ROI_Diff, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) outPixelStd =", "16 ) outPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI_Diff, scale =", "steps ascoiated with descending pass surface areas Written by: <NAME>, <EMAIL> Version 0.3", "100, maxPixels = 6098838800, tileScale = 16 ) wStd = vv.updateMask(waterConfident).reduceRegion( reducer =", "= ee.Image(img) wError = ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError =", "I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask**************************************************************** def MakeWaterMask(img): I = ee.Image(img) wThresh = ee.Number(I.get('wThresh'))", "#****Caclulate Errors************************************************************* def calcError(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh)", "= ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh =", "= S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def extractTimeSeries(collection):", "scale = 100, maxPixels = 6098838800, tileScale = 16 ) wStd = vv.updateMask(waterConfident).reduceRegion(", "def calcThresh(img): img = ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean =", "computing platform o Inputs: * ROI: Google Earth Engine geometry object describing the", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" ******************************************************************************* Google Earth Engine Setninel-1", "= 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img): I = ee.Image(img) #fm =", "ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) wPixelStd =", "S1 Image Collection******************************************************** def create_collection(d): start = ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range =", "wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA, inPixelStdA, outPixelmeanA, outPixelStdA, inPixelmeanD, inPixelStdD, outPixelmeanD, outPixelStdD ])", "scale = 1000, maxPixels = 6098838800, tileScale = 16 ) outPixelmean = vv.reduceRegion(", ") lStd = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100,", "100, maxPixels = 6098838800, tileScale = 16 ) lStd = vv.updateMask(landConfident).reduceRegion( reducer =", "= ee.Date('2020-01-01'); date_interval = ee.Number(1); #month angle_threshold_1 = ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg", "= ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) inPixelmean", "def create_collection(d): start = ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1 =", "ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 =", "I = ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask****************************************************************", "0.3 ******************************************************************************* \"\"\" import ee ee.Initialize() def GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI =", "ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion(", "S1 = S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1", "lStd = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels", "ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area********************************************************************** def calcArea(img):", "= ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img): img = ee.Image(img) wMean = ee.Number(img.get('wMean'))", "ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img): img = ee.Image(img) waterProb", "Sentinel-1 SAR date, using Google Earth Engine cloud computing platform o Inputs: *", "Mask**************************************************************** def MakeWaterMask(img): I = ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask", "maxPixels = 6098838800, tileScale = 16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(),", "S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1 = S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999))", "Setninel-1 Lake Area o Purpose: Estimate surface are of lake from Sentinel-1 SAR", "100, maxPixels = 6098838800, tileScale = 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img):", "ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI,", "geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('occurrence'))", "= 6098838800, tileScale = 16 ) wStd = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry", "falseCase = None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD,", "img = ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd", "= ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd =", "vv = img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale", "img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img): img = ee.Image(img)", "'LError': LError }) exportTable = ee.Feature(None, exportDict) return exportTable Export = ee.Algorithms.If( condition", "ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16", "img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence')", "= angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image Collection******************************************************** def create_collection(d): start", "= 16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer", "'WError': WError, 'LError': LError }) exportTable = ee.Feature(None, exportDict) return exportTable Export =", "tileScale = 16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI,", "time, 'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID': ID, 'WError': WError, 'LError': LError }) exportTable", "#Conversion to km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean", "are of lake from Sentinel-1 SAR date, using Google Earth Engine cloud computing", "angle = I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2))", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('wError')) lError", "o Purpose: Estimate surface are of lake from Sentinel-1 SAR date, using Google", "= I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img): img = ee.Image(img) wMask =", "S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area********************************************************************** def calcArea(img): I = ee.Image(img)", "16 ) wStd = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale =", "scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh)", "6098838800, tileScale = 16 ) wStd = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry =", "= 100, maxPixels = 6098838800, tileScale = 16 ) lMean = vv.updateMask(landConfident).reduceRegion( reducer", "waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry", "return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA, inPixelStdA, outPixelmeanA,", "= 16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale", "= img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img =", "'LakeID': ID, 'WError': WError, 'LError': LError }) exportTable = ee.Feature(None, exportDict) return exportTable", "areas Written by: <NAME>, <EMAIL> Version 0.3 ******************************************************************************* \"\"\" import ee ee.Initialize() def", "maxPixels = 6098838800, tileScale = 16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(),", "S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999))", "makeBackscatterStats(img): img = ee.Image(img) wMask = img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion(", "Engine cloud computing platform o Inputs: * ROI: Google Earth Engine geometry object", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('VV') return(I.set('ROI_area',area))", "= I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask**************************************************************** def MakeWaterMask(img): I = ee.Image(img) wThresh =", "S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1 = S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1", "lMean = ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh", "wStd = ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh", "= ee.Reducer.mean(), geometry = ROI_Diff, scale = 1000, maxPixels = 6098838800, tileScale =", "reducer = ee.Reducer.stdDev(), geometry = ROI_Diff, scale = 300, maxPixels = 6098838800, tileScale", "waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean", "(ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI,", "mask1 = angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image", "Area********************************************************************** def calcArea(img): I = ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry", "16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale =", "= ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\", "= ROI_Diff, scale = 300, maxPixels = 6098838800, tileScale = 16 ) img", "S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW'))", "= 6098838800, tileScale = 16 ) lMean = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry", "landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale", "geometry = roi, scale = 1000, maxPixels = 6098838800, tileScale = 16 )", ".filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition", "#****Make S1 Image Collection******************************************************** def create_collection(d): start = ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range", "wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry = ROI, scale = 100, maxPixels", "= img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale =", "img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img", "of interest o Outputs: * Results: List containing 4 elements (GEE objects): 1)", "vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels = 6098838800,", "I = I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img): img", "return I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img): img = ee.Image(img) wMask = img.select('WaterMask') vv", "ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16", "\\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition =", "= 6098838800, tileScale = 16 ) lStd = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry", "ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd'))", "lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA, inPixelStdA, outPixelmeanA, outPixelStdA, inPixelmeanD, inPixelStdD, outPixelmeanD,", "time = ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd", "ROI: Google Earth Engine geometry object describing the region of interest o Outputs:", ").get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100,", "ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2')))", "from descending passes 3) List of time steps ascoiated with ascending pass surface", "img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000,", "surface areas 4) List of time steps ascoiated with descending pass surface areas", "= S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2", "Time Series*************************************************************** def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time = ee.Array(collection.aggregate_array('system:time_start'))", "ee.Reducer.max(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16", "1000, maxPixels = 6098838800, tileScale = 16 ) inPixelStd = vv.reduceRegion( reducer =", "S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999))", "= S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase = None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA,", "S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1", "vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = roi, scale = 1000, maxPixels = 6098838800,", "S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1", "pass surface areas Written by: <NAME>, <EMAIL> Version 0.3 ******************************************************************************* \"\"\" import ee", "def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def maskByAngle(img): I =", "exportTable = ee.Feature(None, exportDict) return exportTable Export = ee.Algorithms.If( condition = S1.size().gt(0), trueCase", "wMean = ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x", "scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion(", "img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) landConfidentArea", "16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer =", "= ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh =", "vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI_Diff, scale = 1000, maxPixels = 6098838800,", "= roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval =", "landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer", "= 6098838800, tileScale = 16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return", "6098838800, tileScale = 16 ) wPixelStd = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry =", "S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1 = S1.map(calcError) S1", "scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion(", "= ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img): img = ee.Image(img)", ") inPixelStd = vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry = roi, scale = 1000,", "descending passes 3) List of time steps ascoiated with ascending pass surface areas", "WError, 'LError': LError }) exportTable = ee.Feature(None, exportDict) return exportTable Export = ee.Algorithms.If(", "= 16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img", "ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "geometry object describing the region of interest o Outputs: * Results: List containing", "ee.Feature(extractTimeSeries(S1)), falseCase = None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD,", "= ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels = 6098838800, tileScale =", "img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI,", "n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter", "= ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale =", "= ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer =", "#****Create list of dates for time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1);", "= vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI_Diff, scale = 1000, maxPixels =", "300, maxPixels = 6098838800, tileScale = 16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img =", "= S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 =", "exportTable Export = ee.Algorithms.If( condition = S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase = None", "angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image Collection******************************************************** def create_collection(d): start =", "= 16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale", ") return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA, inPixelStdA,", "= S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1 =", ").get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img): img =", "wThresh = ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer", "tileScale = 16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI_Diff,", "wError = wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True))", "S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase = None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA,", "ascoiated with descending pass surface areas Written by: <NAME>, <EMAIL> Version 0.3 *******************************************************************************", "waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh", "= S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 =", "S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999))", "ee.Initialize() def GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI = roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start", "lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels", "= vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels =", "= ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh =", "tileScale = 16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round", "= ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv =", "lStd = ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors*************************************************************", "calcArea(img): I = ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI,", "= S1.map(maskByAngle), falseCase = S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median", "Filter********************************************************************** def focal_median(img): I = ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm))", "wMask = img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry", "= ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd =", "= ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) lPixelStd", "= 16 ) outPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI_Diff, scale", "vv = img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry", "* ROI: Google Earth Engine geometry object describing the region of interest o", "descending pass surface areas Written by: <NAME>, <EMAIL> Version 0.3 ******************************************************************************* \"\"\" import", "= ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError =", "wProbThresh = collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError", "S1 = S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1", "ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval = ee.Number(1); #month angle_threshold_1 =", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('wError')) lError =", "= 16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale", "Earth Engine geometry object describing the region of interest o Outputs: * Results:", "List containing 4 elements (GEE objects): 1) List of lake surface areas from", "areas from descending passes 3) List of time steps ascoiated with ascending pass", "'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase = S1", "= vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels =", "extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean'))", "= img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img): img = ee.Image(img) waterProb", "ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100,", "maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) #****Create list of dates for time", "= (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale =", "= ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd =", "def makeBackScatterFromJRC(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident =", "100, maxPixels = 6098838800, tileScale = 16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img =", "= S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1 =", "S1.map(focal_median) #S1 = S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999))", "return exportTable Export = ee.Algorithms.If( condition = S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase =", "S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area********************************************************************** def calcArea(img): I = ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion(", "maxPixels = 6098838800, tileScale = 16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError))", "maxPixels = 6098838800, tileScale = 16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(),", "of lake surface areas from ascending passes 2) List of lake surface areas", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply", "tileScale = 16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI,", "Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea)", "img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident =", "maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(),", "#****Caclulate Threshold************************************************************** def calcThresh(img): img = ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd'))", "List of lake surface areas from ascending passes 2) List of lake surface", "calcError2(img): img = ee.Image(img) wError = ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError))", "ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry = ROI, scale = 100,", "= 6098838800, tileScale = 16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry", "roi, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) outPixelmean =", "ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16", "= lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img): img = ee.Image(img) wError = ee.Number(img.get('wError')) lError", "passes 2) List of lake surface areas from descending passes 3) List of", "= S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1 =", "= I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image Collection******************************************************** def create_collection(d): start = ee.Date(d); end", "Area o Purpose: Estimate surface are of lake from Sentinel-1 SAR date, using", "ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x))", "img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img", "= collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError =", "= ee.Reducer.stdDev(), geometry = roi, scale = 1000, maxPixels = 6098838800, tileScale =", "time steps ascoiated with descending pass surface areas Written by: <NAME>, <EMAIL> Version", "List of lake surface areas from descending passes 3) List of time steps", "ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation',", "Engine geometry object describing the region of interest o Outputs: * Results: List", "= vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI_Diff, scale = 300, maxPixels =", "waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry = ROI, scale", "Google Earth Engine cloud computing platform o Inputs: * ROI: Google Earth Engine", "AreaImg = ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer", "return img #****Round time********************************************************************* def Roundtime(img): I = ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time))", "utf-8 -*- \"\"\" ******************************************************************************* Google Earth Engine Setninel-1 Lake Area o Purpose: Estimate", "ee.Reducer.mean(), geometry = ROI_Diff, scale = 1000, maxPixels = 6098838800, tileScale = 16", "scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError))", "= img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry =", "4) List of time steps ascoiated with descending pass surface areas Written by:", "surface areas Written by: <NAME>, <EMAIL> Version 0.3 ******************************************************************************* \"\"\" import ee ee.Initialize()", "ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16,", "maxPixels = 6098838800, tileScale = 16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth'))", ").get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(),", "import ee ee.Initialize() def GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI = roi.geometry() ROI_Diff =", "ee.Algorithms.If( condition = S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase = None ) return Export", "6098838800, tileScale = 16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry =", "WaterArea, 'WThresh': WThresh, 'LakeID': ID, 'WError': WError, 'LError': LError }) exportTable = ee.Feature(None,", "6098838800, tileScale = 16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry =", "= 6098838800, tileScale = 16 ) inPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry", "img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth'))", "S1 = S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1", "= 6098838800, tileScale = 16, ).get('occurrence')) #****Create list of dates for time series********************************************", "= vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels =", "def calcError2(img): img = ee.Image(img) wError = ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError =", "lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError", "scale = 1000, maxPixels = 6098838800, tileScale = 16 ) wPixelStd = vv.updateMask(wMask).reduceRegion(", "return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img): img = ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd =", "tileScale = 16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def", "return img def makeBackScatterFromJRC(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh)", "def GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI = roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start =", "1000, maxPixels = 6098838800, tileScale = 16 ) wPixelStd = vv.updateMask(wMask).reduceRegion( reducer =", "maxPixels = 6098838800, tileScale = 16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth'))", "lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels", "100, maxPixels = 6098838800, tileScale = 16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError =", "WThresh, 'LakeID': ID, 'WError': WError, 'LError': LError }) exportTable = ee.Feature(None, exportDict) return", "= 1000, maxPixels = 6098838800, tileScale = 16 ) outPixelmean = vv.reduceRegion( reducer", "geometry = ROI_Diff, scale = 300, maxPixels = 6098838800, tileScale = 16 )", "= S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract Time", "S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area**********************************************************************", "area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels", "scale = 1000, maxPixels = 6098838800, tileScale = 16 ) inPixelStd = vv.reduceRegion(", "= None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD,", "#S1 = S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to", "6098838800, tileScale = 16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry =", "16 ) wPixelStd = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale =", "geometry = ROI_Diff, scale = 1000, maxPixels = 6098838800, tileScale = 16 )", "def maskByAngle(img): I = ee.Image(img) angle = I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2 =", "S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion", "= lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1", "vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels = 6098838800,", "calcError(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not()", "LError }) exportTable = ee.Feature(None, exportDict) return exportTable Export = ee.Algorithms.If( condition =", "waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry", "tileScale = 16 ) I = I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round", "wPixelStd = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels", "= ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1", "ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID': ID, 'WError':", "= ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError)", "S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999))", "= 6098838800, tileScale = 16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry", "img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth'))", "16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time********************************************************************* def", "#****Extract Time Series*************************************************************** def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time =", "'Date': time, 'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID': ID, 'WError': WError, 'LError': LError })", "wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img): img = ee.Image(img) wError =", "interest o Outputs: * Results: List containing 4 elements (GEE objects): 1) List", "maxPixels = 6098838800, tileScale = 16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(),", "trueCase = ee.Feature(extractTimeSeries(S1)), falseCase = None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA,", "Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter Edge Pixels**************************************************************", "dates for time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month'))", "surface areas from descending passes 3) List of time steps ascoiated with ascending", ") img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time********************************************************************* def Roundtime(img):", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) img", "wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence')", "6098838800, tileScale = 16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry =", "= WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea, 'WThresh':", "WThresh = ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date':", "using Google Earth Engine cloud computing platform o Inputs: * ROI: Google Earth", "Water Mask**************************************************************** def MakeWaterMask(img): I = ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence')", "ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img): img = ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd", "x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img): img", "thresh = ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale", "6098838800, tileScale = 16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError)", "= 100, maxPixels = 6098838800, tileScale = 16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident", "vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "tileScale = 16 ) lStd = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI,", "ee.Reducer.stdDev(), geometry = roi, scale = 1000, maxPixels = 6098838800, tileScale = 16", "S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median)", "img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img): img =", "ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion(", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) wStd", "wStd = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels", "I = ee.Image(img) angle = I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I", "'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase = S1.map(maskByAngle),", "ee ee.Initialize() def GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI = roi.geometry() ROI_Diff = ROI.difference(roi)", "100, maxPixels = 6098838800, tileScale = 16 ) I = I.set('water_pixels',Sum.get('WaterMask')) I =", "= ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels =", "img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth')) img = img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time********************************************************************* def Roundtime(img): I", "scale = 1000, maxPixels = 6098838800, tileScale = 16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion(", "16 ) I = I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time********************************************************************* def", "lake from Sentinel-1 SAR date, using Google Earth Engine cloud computing platform o", "tileScale = 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img): I = ee.Image(img) #fm", "= ROI_Diff, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) outPixelStd", "ee.Image(img) angle = I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I = I.updateMask(mask1)", "Lake Area o Purpose: Estimate surface are of lake from Sentinel-1 SAR date,", "wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 =", "ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img):", "#****Get WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry", "waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels", "= img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale =", "img = ee.Image(img) wMask = img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer", "the region of interest o Outputs: * Results: List containing 4 elements (GEE", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) #****Create", "scale = 100, maxPixels = 6098838800, tileScale = 16 ) lMean = vv.updateMask(landConfident).reduceRegion(", "by: <NAME>, <EMAIL> Version 0.3 ******************************************************************************* \"\"\" import ee ee.Initialize() def GetS1ResTimeSeries(roi): ID", "ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate", "ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict", "4 elements (GEE objects): 1) List of lake surface areas from ascending passes", "tileScale = 16, ).get('occurrence')) #****Create list of dates for time series******************************************** n_steps =", "roi.get('ID') ROI = roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01');", "= 16 ) wPixelStd = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale", "def calcArea(img): I = ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry =", "scale = 300, maxPixels = 6098838800, tileScale = 16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth'))", "= 16 ) inPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = roi, scale", "Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry = ROI,", "= ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x =", "= ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb =", "outPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI_Diff, scale = 1000, maxPixels", "= ee.Reducer.max(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale =", "1000, maxPixels = 6098838800, tileScale = 16 ) outPixelmean = vv.reduceRegion( reducer =", "= ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh =", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('lError')) #wError =", "wMean = ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh", "return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0))", "= S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1 = S1.map(calcError) S1 =", "= ee.Reducer.mean(), geometry = roi, scale = 1000, maxPixels = 6098838800, tileScale =", ").get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100,", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('occurrence')) waterConfident", "\\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase", "= img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img =", "* Results: List containing 4 elements (GEE objects): 1) List of lake surface", "= ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh =", "python3 # -*- coding: utf-8 -*- \"\"\" ******************************************************************************* Google Earth Engine Setninel-1 Lake", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('lError')) #wError", "surface areas from ascending passes 2) List of lake surface areas from descending", "WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea,", "6098838800, tileScale = 16 ) inPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry =", "= ee.Image(img) wMask = img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer =", "6098838800, tileScale = 16 ) outPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry =", "6098838800, tileScale = 16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img =", "return img.set('wError',wError).set('lError',lError) def calcError2(img): img = ee.Image(img) wError = ee.Number(img.get('wError')) lError = ee.Number(img.get('lError'))", "= 1000, maxPixels = 6098838800, tileScale = 16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer", "return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img): I = ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm =", "img = ee.Image(img) wError = ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError", "scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter**********************************************************************", "= S1.map(focal_median) #S1 = S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 =", "= 6098838800, tileScale = 16 ) wPixelStd = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry", "WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea, 'WThresh': WThresh,", "= 1000, maxPixels = 6098838800, tileScale = 16 ) inPixelStd = vv.reduceRegion( reducer", "S1 = S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1", "cloud computing platform o Inputs: * ROI: Google Earth Engine geometry object describing", "= roi, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) outPixelmean", "#S1 = S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1", "= 6098838800, tileScale = 16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry", "Collection******************************************************** def create_collection(d): start = ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1", ").get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img): I = ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm", "= ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask**************************************************************** def", "ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence')", "16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img): I = ee.Image(img) #fm = I.select('VV').rename('VV_smooth')", "fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask**************************************************************** def MakeWaterMask(img): I = ee.Image(img) wThresh", "= vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels =", "1000, maxPixels = 6098838800, tileScale = 16 ) inPixelmean = vv.reduceRegion( reducer =", "Errors************************************************************* def calcError(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident", "img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def", "tileScale = 16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion(", "= vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry = roi, scale = 1000, maxPixels =", "vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1", "= vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels =", "= 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer", "platform o Inputs: * ROI: Google Earth Engine geometry object describing the region", "from Sentinel-1 SAR date, using Google Earth Engine cloud computing platform o Inputs:", "ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\", "maxPixels = 6098838800, tileScale = 16 ) outPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(),", "= wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img): img = ee.Image(img) wError", "img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time********************************************************************* def Roundtime(img): I = ee.Image(img) time = ee.Number(I.get('system:time_start')).round()", "lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img): img = ee.Image(img) wError = ee.Number(img.get('wError')) lError =", ") inPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = roi, scale = 1000,", "img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img", "= ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID': ID,", "1000, maxPixels = 6098838800, tileScale = 16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer =", "tileScale = 16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth'))", "ee.Image(img) wMask = img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(),", "angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image Collection******************************************************** def", "geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('lError'))", "ID = roi.get('ID') ROI = roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End", "= 100, maxPixels = 6098838800, tileScale = 16 ) I = I.set('water_pixels',Sum.get('WaterMask')) I", "from ascending passes 2) List of lake surface areas from descending passes 3)", "= ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range)", "= ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI) \\", "= 100, maxPixels = 6098838800, tileScale = 16 ) wStd = vv.updateMask(waterConfident).reduceRegion( reducer", "= img.set('wStd',wStd.get('VV_smooth')).set('lStd',lStd.get('VV_smooth')) return img #****Round time********************************************************************* def Roundtime(img): I = ee.Image(img) time =", "Earth Engine Setninel-1 Lake Area o Purpose: Estimate surface are of lake from", "img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img = img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth'))", "(lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img): img = ee.Image(img)", "= wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def calcError(img): img = ee.Image(img) waterProb =", "= (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer =", "Version 0.3 ******************************************************************************* \"\"\" import ee ee.Initialize() def GetS1ResTimeSeries(roi): ID = roi.get('ID') ROI", "None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA,", "= S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1 = S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 =", "= I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale =", "pass surface areas 4) List of time steps ascoiated with descending pass surface", "100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) landConfidentArea = ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer =", "= ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale =", "Google Earth Engine Setninel-1 Lake Area o Purpose: Estimate surface are of lake", ") I = I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img):", ") lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000,", "tileScale = 16 ) lMean = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI,", "= 1000, maxPixels = 6098838800, tileScale = 16 ) wPixelStd = vv.updateMask(wMask).reduceRegion( reducer", "wError = ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return", "maxPixels = 6098838800, tileScale = 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img): I", "S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1 = S1.map(Roundtime)", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) I =", "img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv", "Series*************************************************************** def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001) #Conversion to km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean", "Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale", "\\ .filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If(", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) lMean =", "100, maxPixels = 6098838800, tileScale = 16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer =", "lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA, inPixelStdA, outPixelmeanA, outPixelStdA, inPixelmeanD, inPixelStdD, outPixelmeanD, outPixelStdD", "lake surface areas from ascending passes 2) List of lake surface areas from", "wPixelmean = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels", "S1 = S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1 = S1.map(Roundtime) S1", "= 6098838800, tileScale = 16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return", "= 16, ).get('occurrence')) #****Create list of dates for time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round();", ").get('occurrence')) #****Create list of dates for time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates =", "of time steps ascoiated with ascending pass surface areas 4) List of time", "<EMAIL> Version 0.3 ******************************************************************************* \"\"\" import ee ee.Initialize() def GetS1ResTimeSeries(roi): ID = roi.get('ID')", "= ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) lPixelmean", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) lMean", "S1 = S1.map(calcThresh) S1 = S1.map(calcError) S1 = S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1", "2) List of lake surface areas from descending passes 3) List of time", "collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh')) WError = WaterArea.multiply(ee.Array(collection.aggregate_array('wError2'))) LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea))", "******************************************************************************* Google Earth Engine Setninel-1 Lake Area o Purpose: Estimate surface are of", "calcThresh(img): img = ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean'))", "= waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError =", "= ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea =", "date, using Google Earth Engine cloud computing platform o Inputs: * ROI: Google", "6098838800, tileScale = 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def focal_median(img): I = ee.Image(img)", "= ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale =", "16, ).get('occurrence')) #****Create list of dates for time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates", "outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI_Diff, scale = 300, maxPixels", "dates = dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def maskByAngle(img): I = ee.Image(img) angle =", "Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 100,", "Written by: <NAME>, <EMAIL> Version 0.3 ******************************************************************************* \"\"\" import ee ee.Initialize() def GetS1ResTimeSeries(roi):", "Threshold************************************************************** def calcThresh(img): img = ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean", "= ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd)) wThresh = wMean.add(wStd.multiply(x)) return img.set('wThresh',wThresh) #****Caclulate Errors************************************************************* def", "= wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1", "of lake from Sentinel-1 SAR date, using Google Earth Engine cloud computing platform", "= S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def extractTimeSeries(collection): WaterArea = ee.Array(collection.aggregate_array('Water_Area')).multiply(0.000001)", "I = ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img): img =", "ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100,", "inPixelStd = vv.reduceRegion( reducer = ee.Reducer.stdDev(), geometry = roi, scale = 1000, maxPixels", "scale = 100, maxPixels = 6098838800, tileScale = 16 ) img = img.set('wMean',wMean.get('VV_smooth')).set('lMean',lMean.get('VV_smooth'))", "16 ) lMean = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale =", "reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale", "ROI = roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval", "= 6098838800, tileScale = 16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea", "tileScale = 16 ) inPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = roi,", "= 16 ) lStd = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale", "<NAME>, <EMAIL> Version 0.3 ******************************************************************************* \"\"\" import ee ee.Initialize() def GetS1ResTimeSeries(roi): ID =", "= ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum =", "= 6098838800, tileScale = 16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) img =", "= ee.Number(landConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels =", "geometry = ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 )", "I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img): img = ee.Image(img) wMask = img.select('WaterMask')", "ee.Date('2020-01-01'); date_interval = ee.Number(1); #month angle_threshold_1 = ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg =", "1) List of lake surface areas from ascending passes 2) List of lake", "I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img): img = ee.Image(img) wMask = img.select('WaterMask') vv =", "= S1.filter(ee.Filter.lt('wError',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 =", "reducer = ee.Reducer.max(), geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale", "= 100, maxPixels = 6098838800, tileScale = 16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer", "= ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels = 6098838800, tileScale =", "return(I.updateMask(mask2)) #****Make S1 Image Collection******************************************************** def create_collection(d): start = ee.Date(d); end = ee.Date(d).advance(date_interval,'month');", "(ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100,", "time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img): img = ee.Image(img) wMean =", "S1.filter(ee.Filter.lt('lError',9999999999999)) S1 = S1.map(calcError2) S1 = S1.filter(ee.Filter.lt('wError2',9999999999999)) S1 = S1.filter(ee.Filter.lt('lError2',9999999999999)) S1 = S1.map(MakeWaterMask)", "SAR date, using Google Earth Engine cloud computing platform o Inputs: * ROI:", "img.set('outPixelmean',outPixelmean.get('VV_smooth')) img = img.set('outPixelStd',outPixelStd.get('VV_smooth')) return img def makeBackScatterFromJRC(img): img = ee.Image(img) waterProb =", "ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001) WThresh = ee.Array(collection.aggregate_array('wThresh'))", "angle_threshold_1 = ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb", "#****Calc ROI Area********************************************************************** def calcArea(img): I = ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer =", "Sum = Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels", "ee.Image(img) wError = ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError))", "= dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def maskByAngle(img): I = ee.Image(img) angle = I.select('angle');", "16 ) img = img.set('wPixelmean',wPixelmean.get('VV_smooth')) img = img.set('wPixelStd',wPixelStd.get('VV_smooth')) img = img.set('lPixelmean',lPixelmean.get('VV_smooth')) img =", "ROI Area********************************************************************** def calcArea(img): I = ee.Image(img) area = I.select('VV').lt(99999999).multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(),", "reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels = 6098838800, tileScale", "6098838800, tileScale = 16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea =", "km^2 time = ee.Array(collection.aggregate_array('system:time_start')) wMean = ee.Array(collection.aggregate_array('wMean')) wStd = ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean'))", "ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.eq('instrumentMode',", "'WThresh': WThresh, 'LakeID': ID, 'WError': WError, 'LError': LError }) exportTable = ee.Feature(None, exportDict)", "inPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = roi, scale = 1000, maxPixels", "reducer = ee.Reducer.stdDev(), geometry = roi, scale = 1000, maxPixels = 6098838800, tileScale", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ).get('occurrence')) waterConfident =", "roi, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) inPixelStd =", "Results: List containing 4 elements (GEE objects): 1) List of lake surface areas", "= waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer =", "date_interval = ee.Number(1); #month angle_threshold_1 = ee.Number(45.4); angle_threshold_2 = ee.Number(31.66) AreaImg = ee.Image.pixelArea()", "img.set('wError',wError).set('lError',lError) def calcError2(img): img = ee.Image(img) wError = ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError", "ee.Reducer.mean(), geometry = roi, scale = 1000, maxPixels = 6098838800, tileScale = 16", "tileScale = 16 ) outPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI_Diff,", "I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time********************************************************************* def makeBackscatterStats(img): img = ee.Image(img)", "#wError = wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img): img = ee.Image(img)", "= 6098838800, tileScale = 16 ) I = I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return", "ee.Image(img) wMean = ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd'))", "maxPixels = 6098838800, tileScale = 16 ) inPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(),", "= vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels =", "100, maxPixels = 6098838800, tileScale = 16 ) lMean = vv.updateMask(landConfident).reduceRegion( reducer =", "= ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh = ee.Number(ee.Image.constant(0).blend(waterProb).rename('occurrence').reduceRegion( reducer = ee.Reducer.max(), geometry = ROI, scale =", "angle_threshold_2 = ee.Number(31.66) AreaImg = ee.Image.pixelArea() #****Get WaterProb Threshold************************************************ waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') wProbThresh", "= Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter Edge", "I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image Collection******************************************************** def create_collection(d): start = ee.Date(d);", "time steps ascoiated with ascending pass surface areas 4) List of time steps", "ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16", "ROI_Diff, scale = 300, maxPixels = 6098838800, tileScale = 16 ) img =", "#****Round time********************************************************************* def makeBackscatterStats(img): img = ee.Image(img) wMask = img.select('WaterMask') vv = img.select('VV_smooth')", "ee.Number(img.get('wMean')) wStd = ee.Number(img.get('wStd')) lMean = ee.Number(img.get('lMean')) lStd = ee.Number(img.get('lStd')) x = (lMean.subtract(wMean)).divide(wStd.add(lStd))", "wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels", "#fm = I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask**************************************************************** def MakeWaterMask(img): I", "def MakeWaterMask(img): I = ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask =", "of lake surface areas from descending passes 3) List of time steps ascoiated", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) #****Create list", "wStd = ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea", "= 16 ) I = I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask) #****Round time*********************************************************************", "ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask**************************************************************** def MakeWaterMask(img):", "ee.Image(img) time = ee.Number(I.get('system:time_start')).round() return(I.set('system:time_start',time)) #****Caclulate Threshold************************************************************** def calcThresh(img): img = ee.Image(img) wMean", "ee.Number(img.get('wError')) lError = ee.Number(img.get('lError')) wError = wError.divide(waterConfidentArea.subtract(wError)) lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run", "= ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean =", ") wPixelStd = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000,", "16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale =", "LError = ee.Array(collection.aggregate_array('lError2')).multiply(ROIArea.subtract(WaterArea)) exportDict = ee.Dictionary({ 'Date': time, 'WaterArea': WaterArea, 'WThresh': WThresh, 'LakeID':", "= 16 ).get('wError')) lError = ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale", "= roi, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) inPixelStd", "16 ) lStd = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale =", "scale = 1000, maxPixels = 6098838800, tileScale = 16 ) inPixelmean = vv.reduceRegion(", "100, maxPixels = 6098838800, tileScale = 16 ).get('occurrence')) waterConfident = waterProb.gte(wProbThresh) landConfident =", "= 100, maxPixels = 6098838800, tileScale = 16 ) lStd = vv.updateMask(landConfident).reduceRegion( reducer", "= 1000, maxPixels = 6098838800, tileScale = 16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer", "wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA, inPixelStdA, outPixelmeanA, outPixelStdA, inPixelmeanD, inPixelStdD,", "= img.set('lPixelmean',lPixelmean.get('VV_smooth')) img = img.set('lPixelStd',lPixelStd.get('VV_smooth')) img = img.set('inPixelmean',inPixelmean.get('VV_smooth')) img = img.set('inPixelStd',inPixelStd.get('VV_smooth')) img =", "= (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry =", "tileScale = 16 ) wStd = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI,", "#****Apply Filter********************************************************************** def focal_median(img): I = ee.Image(img) #fm = I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth')", "= ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale =", "S1.map(maskByAngle), falseCase = S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median =", "= 6098838800, tileScale = 16 ) outPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry", "= S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area********************************************************************** def calcArea(img): I = ee.Image(img) area =", "ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum = Mask.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(),", "lMean = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels", "ascending passes 2) List of lake surface areas from descending passes 3) List", "ee.Array(collection.aggregate_array('wStd')) lMean = ee.Array(collection.aggregate_array('lMean')) lStd = ee.Array(collection.aggregate_array('lStd')) wProbThresh = collection.get('wProbThresh') ROIArea = ee.Array(collection.aggregate_array('ROI_area')).multiply(0.000001)", "for time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates", "= I.select('VV').rename('VV_smooth') fm = I.select('VV').focal_median(50,'circle','meters').rename('VV_smooth') return(I.addBands(fm)) #****Make Water Mask**************************************************************** def MakeWaterMask(img): I =", "= ee.List.sequence(0,n_steps,1); def make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def maskByAngle(img):", "scale = 1000, maxPixels = 6098838800, tileScale = 16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion(", "Engine Setninel-1 Lake Area o Purpose: Estimate surface are of lake from Sentinel-1", "= angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I = I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image Collection********************************************************", "S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase = S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median =", "ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1 = S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95))))", "img def makeBackScatterFromJRC(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident", "= ee.Feature(None, exportDict) return exportTable Export = ee.Algorithms.If( condition = S1.size().gt(0), trueCase =", "wMean = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 100, maxPixels", "6098838800, tileScale = 16 ) lMean = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry =", ") lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000,", "= ee.Reducer.stdDev(), geometry = ROI_Diff, scale = 300, maxPixels = 6098838800, tileScale =", "= ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area********************************************************************** def", "= 100, maxPixels = 6098838800, tileScale = 16, ).get('VV') return(I.set('ROI_area',area)) #****Apply Filter********************************************************************** def", "= 100, maxPixels = 6098838800, tileScale = 16, ).get('occurrence')) #****Create list of dates", "Date_Start = ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval = ee.Number(1); #month angle_threshold_1 = ee.Number(45.4);", "= S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median)", "= 16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img):", "landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry", "ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) lStd =", "= ee.Feature(extractTimeSeries(S1)), falseCase = None ) return Export #return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD,", "scale = 100, maxPixels = 6098838800, tileScale = 16 ) I = I.set('water_pixels',Sum.get('WaterMask'))", "waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') wMean = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.mean(),", "= ROI, scale = 100, maxPixels = 6098838800, tileScale = 16 ) lStd", "make_datelist(n): return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def maskByAngle(img): I = ee.Image(img)", "geometry = ROI, scale = 100, maxPixels = 6098838800, tileScale = 16, ).get('VV')", "vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale = 1000, maxPixels = 6098838800,", "16 ).get('lError')) #wError = wError.divide(waterConfidentArea.subtract(wError)) #lError = lError.divide(landConfidentArea.subtract(lError)) return img.set('wError',wError).set('lError',lError) def calcError2(img): img", "time********************************************************************* def makeBackscatterStats(img): img = ee.Image(img) wMask = img.select('WaterMask') vv = img.select('VV_smooth') wPixelmean", "describing the region of interest o Outputs: * Results: List containing 4 elements", "#return([WaterAreaA,WaterAreaD,timeA,timeD,wPixelmeanA, wPixelStdA, lPixelmeanA, lPixelStdA, wPixelmeanD, wPixelStdD, lPixelmeanD, lPixelStdD, inPixelmeanA, inPixelStdA, outPixelmeanA, outPixelStdA, inPixelmeanD,", "ascending pass surface areas 4) List of time steps ascoiated with descending pass", "maxPixels = 6098838800, tileScale = 16 ) wPixelStd = vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(),", ") wStd = vv.updateMask(waterConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100,", "\\ .filter(ee.Filter.eq('instrumentMode', 'IW')) S1 = ee.ImageCollection(ee.Algorithms.If( condition = S1.size().gt(0), trueCase = S1.map(maskByAngle), falseCase", "1000, maxPixels = 6098838800, tileScale = 16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer =", "list of dates for time series******************************************** n_steps = Date_End.difference(Date_Start,'month').divide(date_interval).round(); dates = ee.List.sequence(0,n_steps,1); def", "return(Date_Start.advance(ee.Number(n).multiply(date_interval),'month')) dates = dates.map(make_datelist); #****Filter Edge Pixels************************************************************** def maskByAngle(img): I = ee.Image(img) angle", "ee.Feature(None, exportDict) return exportTable Export = ee.Algorithms.If( condition = S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)),", "I = ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') Mask = I.select('VV_smooth').updateMask(waterProb).lt(wThresh).rename('WaterMask') Sum", "= S1.filter(ee.Filter.gt('ROI_area',ee.Number(ROI.area().multiply(0.95)))) S1 = S1.map(focal_median) #S1 = S1.map(Roundtime) S1 = S1.map(makeBackScatterFromJRC) S1 =", "surface are of lake from Sentinel-1 SAR date, using Google Earth Engine cloud", "= ee.Image(img) angle = I.select('angle'); mask1 = angle.lt(angle_threshold_1); mask2 = angle.gt(angle_threshold_2); I =", "= roi.get('ID') ROI = roi.geometry() ROI_Diff = ROI.difference(roi) Date_Start = ee.Date('2017-01-01'); Date_End =", "return(I.addBands(fm)) #****Make Water Mask**************************************************************** def MakeWaterMask(img): I = ee.Image(img) wThresh = ee.Number(I.get('wThresh')) waterProb", "scale = 1000, maxPixels = 6098838800, tileScale = 16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion(", "= 16 ) lMean = vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI, scale", "1000, maxPixels = 6098838800, tileScale = 16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer =", "16 ) outPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI_Diff, scale =", "ROI, scale = 1000, maxPixels = 6098838800, tileScale = 16 ) lPixelStd =", "Export = ee.Algorithms.If( condition = S1.size().gt(0), trueCase = ee.Feature(extractTimeSeries(S1)), falseCase = None )", "date_range = ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD') \\ .filterDate(date_range) \\ .filterBounds(ROI) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV'))", "vv.updateMask(landConfident).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 100, maxPixels = 6098838800,", "S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh) S1", "= ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1 = S1.filter(ee.Filter.gt('Number_of_images',0)) S1 = S1.map(calcArea) S1 =", "tileScale = 16 ) lPixelmean = vv.updateMask(wMask.Not()).reduceRegion( reducer = ee.Reducer.mean(), geometry = ROI,", "trueCase = S1.map(maskByAngle), falseCase = S1 )) S1_median = ee.Image(S1.select('VV').mean()).clip(ROI) S1_median = S1_median.set('system:time_start',start.millis())", "= ee.Number(vv.lt(thresh).updateMask(landConfident).rename('lError').multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry = ROI, scale = 100, maxPixels =", "lError.divide(landConfidentArea.subtract(lError)) return img.set('wError2',wError).set('lError2',lError) #****Run Functions****************************************************************** S1 = ee.ImageCollection(dates.map(create_collection,True)) S1 = S1.set('wProbThresh',wProbThresh) S1 =", "create_collection(d): start = ee.Date(d); end = ee.Date(d).advance(date_interval,'month'); date_range = ee.DateRange(start,end); S1 = ee.ImageCollection('COPERNICUS/S1_GRD')", "= 1000, maxPixels = 6098838800, tileScale = 16 ) lPixelStd = vv.updateMask(wMask.Not()).reduceRegion( reducer", "coding: utf-8 -*- \"\"\" ******************************************************************************* Google Earth Engine Setninel-1 Lake Area o Purpose:", "vv.updateMask(wMask).reduceRegion( reducer = ee.Reducer.stdDev(), geometry = ROI, scale = 1000, maxPixels = 6098838800,", "ee.Date('2017-01-01'); Date_End = ee.Date('2020-01-01'); date_interval = ee.Number(1); #month angle_threshold_1 = ee.Number(45.4); angle_threshold_2 =", "= S1_median.set('system:time_start',start.millis()) S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area********************************************************************** def calcArea(img): I =", "S1.filter(ee.Filter.gt('wMean',-9999)) S1 = S1.filter(ee.Filter.gt('lMean',-9999)) S1 = S1.filter(ee.Filter.gt('wStd',-9999)) S1 = S1.filter(ee.Filter.gt('lStd',-9999)) S1 = S1.map(calcThresh)", "S1 = S1.map(MakeWaterMask) #S1 = S1.map(makeBackscatterStats) #****Extract Time Series*************************************************************** def extractTimeSeries(collection): WaterArea =", "def calcError(img): img = ee.Image(img) waterProb = ee.Image('JRC/GSW1_1/GlobalSurfaceWater').select('occurrence') waterConfident = waterProb.gte(wProbThresh) landConfident =", "waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not() vv = img.select('VV_smooth') thresh = ee.Number(img.get('wThresh')) wError = ee.Number(vv.gt(thresh).updateMask(waterConfident).rename('wError').multiply(AreaImg).reduceRegion(", "with descending pass surface areas Written by: <NAME>, <EMAIL> Version 0.3 ******************************************************************************* \"\"\"", "16 ) inPixelmean = vv.reduceRegion( reducer = ee.Reducer.mean(), geometry = roi, scale =", "S1_median = S1_median.set('Number_of_images',S1.size()) return(S1_median) #****Calc ROI Area********************************************************************** def calcArea(img): I = ee.Image(img) area", "= waterProb.gte(wProbThresh) landConfident = (ee.Image.constant(0).blend(waterProb)).Not().rename('occurrence') waterConfidentArea = ee.Number(waterConfident.multiply(AreaImg).reduceRegion( reducer = ee.Reducer.sum(), geometry =", "I.updateMask(mask1) return(I.updateMask(mask2)) #****Make S1 Image Collection******************************************************** def create_collection(d): start = ee.Date(d); end =", "6098838800, tileScale = 16 ) I = I.set('water_pixels',Sum.get('WaterMask')) I = I.set('Water_Area',ee.Number(Sum.get('WaterMask'))) return I.addBands(Mask)" ]
[ "to the equation without setting it in the system. This should return a", "the system. This should return a NameError \"\"\" # Create system system =", "numpy as np from psecas import Solver, System from psecas import ChebyshevExtremaGrid import", "+ 2*A*f\") with pytest.raises(NameError) as e_info: solver = Solver(grid, system) if verbose: print(str(e_info.value))", "add the value B to the boundary without setting it in the system.", "as e_info: solver = Solver(grid, system) if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here", "Create grid N = 32 grid = ChebyshevExtremaGrid(N, -1, 1) # Create a", "return a NameError \"\"\" # Create system system = System(grid, variables='f', eigenvalue='sigma') #", "the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\") with pytest.raises(NameError) as", "ChebyshevExtremaGrid import pytest \"\"\" We set up systems with errors, and see if", "pytest.raises(NameError) as e_info: solver = Solver(grid, system) if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\"", "set up systems with errors, and see if Psecas gives a reasonable error,", "pytest \"\"\" We set up systems with errors, and see if Psecas gives", "with errors, and see if Psecas gives a reasonable error, i.e., a NameError.", "value A to the equation without setting it in the system. This should", "error, i.e., a NameError. \"\"\" # Create grid N = 32 grid =", "method is called solver.solve() if verbose: print(str(e_info.value)) if __name__ == '__main__': test_parser_findmatrices(True) test_parser_boundaries(True)", "dz(dz(f)) + 2*A*f\") with pytest.raises(NameError) as e_info: solver = Solver(grid, system) if verbose:", "This should return a NameError \"\"\" # Create system system = System(grid, variables='f',", "first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f = 0') solver", "the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f = 0')", "# Create grid N = 32 grid = ChebyshevExtremaGrid(N, -1, 1) # Create", "= ChebyshevExtremaGrid(N, -1, 1) # Create a solver object def test_parser_findmatrices(verbose=False): \"\"\" Here", "Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f =", "= System(grid, variables='f', eigenvalue='sigma') # Add the first (and only) equation system.add_equation(\"sigma*z*f =", "from psecas import Solver, System from psecas import ChebyshevExtremaGrid import pytest \"\"\" We", "= Solver(grid, system) with pytest.raises(NameError) as e_info: # The error is found when", "'Dirichlet', 'B*f = 0') solver = Solver(grid, system) with pytest.raises(NameError) as e_info: #", "\"\"\" Here we add the value B to the boundary without setting it", "Create a solver object def test_parser_findmatrices(verbose=False): \"\"\" Here we add the value A", "The error is found when the solve method is called solver.solve() if verbose:", "# Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\") with", "equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f = 0') solver = Solver(grid, system)", "import Solver, System from psecas import ChebyshevExtremaGrid import pytest \"\"\" We set up", "verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here we add the value B to the", "ChebyshevExtremaGrid(N, -1, 1) # Create a solver object def test_parser_findmatrices(verbose=False): \"\"\" Here we", "only) equation system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\") with pytest.raises(NameError) as e_info: solver =", "system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\") with pytest.raises(NameError) as e_info: solver = Solver(grid, system)", "a NameError. \"\"\" # Create grid N = 32 grid = ChebyshevExtremaGrid(N, -1,", "= dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f = 0') solver = Solver(grid, system) with pytest.raises(NameError)", "we add the value B to the boundary without setting it in the", "eigenvalue='sigma') # Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet',", "found when the solve method is called solver.solve() if verbose: print(str(e_info.value)) if __name__", "equation without setting it in the system. This should return a NameError \"\"\"", "def test_parser_findmatrices(verbose=False): \"\"\" Here we add the value A to the equation without", "see if Psecas gives a reasonable error, i.e., a NameError. \"\"\" # Create", "a NameError \"\"\" # Create system system = System(grid, variables='f', eigenvalue='sigma') # Add", "up systems with errors, and see if Psecas gives a reasonable error, i.e.,", "system. This should return a NameError \"\"\" # Create system system = System(grid,", "Solver(grid, system) with pytest.raises(NameError) as e_info: # The error is found when the", "Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\") with pytest.raises(NameError)", "when the solve method is called solver.solve() if verbose: print(str(e_info.value)) if __name__ ==", "systems with errors, and see if Psecas gives a reasonable error, i.e., a", "np from psecas import Solver, System from psecas import ChebyshevExtremaGrid import pytest \"\"\"", "value B to the boundary without setting it in the system. This should", "Psecas gives a reasonable error, i.e., a NameError. \"\"\" # Create grid N", "object def test_parser_findmatrices(verbose=False): \"\"\" Here we add the value A to the equation", "with pytest.raises(NameError) as e_info: # The error is found when the solve method", "System from psecas import ChebyshevExtremaGrid import pytest \"\"\" We set up systems with", "\"\"\" # Create system system = System(grid, variables='f', eigenvalue='sigma') # Add the first", "the solve method is called solver.solve() if verbose: print(str(e_info.value)) if __name__ == '__main__':", "# Create a solver object def test_parser_findmatrices(verbose=False): \"\"\" Here we add the value", "variables='f', eigenvalue='sigma') # Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f',", "the equation without setting it in the system. This should return a NameError", "A to the equation without setting it in the system. This should return", "NameError \"\"\" # Create system system = System(grid, variables='f', eigenvalue='sigma') # Add the", "test_parser_boundaries(verbose=False): \"\"\" Here we add the value B to the boundary without setting", "a solver object def test_parser_findmatrices(verbose=False): \"\"\" Here we add the value A to", "# The error is found when the solve method is called solver.solve() if", "\"\"\" # Create grid N = 32 grid = ChebyshevExtremaGrid(N, -1, 1) #", "psecas import ChebyshevExtremaGrid import pytest \"\"\" We set up systems with errors, and", "is found when the solve method is called solver.solve() if verbose: print(str(e_info.value)) if", "# Create system system = System(grid, variables='f', eigenvalue='sigma') # Add the first (and", "System(grid, variables='f', eigenvalue='sigma') # Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\")", "with pytest.raises(NameError) as e_info: solver = Solver(grid, system) if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False):", "solver = Solver(grid, system) if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here we add", "e_info: solver = Solver(grid, system) if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here we", "the value B to the boundary without setting it in the system. This", "as np from psecas import Solver, System from psecas import ChebyshevExtremaGrid import pytest", "should return a NameError \"\"\" # Create system system = System(grid, variables='f', eigenvalue='sigma')", "Solver, System from psecas import ChebyshevExtremaGrid import pytest \"\"\" We set up systems", "0') solver = Solver(grid, system) with pytest.raises(NameError) as e_info: # The error is", "system = System(grid, variables='f', eigenvalue='sigma') # Add the first (and only) equation system.add_equation(\"sigma*z*f", "boundary without setting it in the system. This should return a NameError \"\"\"", "We set up systems with errors, and see if Psecas gives a reasonable", "solver = Solver(grid, system) with pytest.raises(NameError) as e_info: # The error is found", "\"\"\" We set up systems with errors, and see if Psecas gives a", "i.e., a NameError. \"\"\" # Create grid N = 32 grid = ChebyshevExtremaGrid(N,", "to the boundary without setting it in the system. This should return a", "-1, 1) # Create a solver object def test_parser_findmatrices(verbose=False): \"\"\" Here we add", "= Solver(grid, system) if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here we add the", "2*A*f\") with pytest.raises(NameError) as e_info: solver = Solver(grid, system) if verbose: print(str(e_info.value)) def", "psecas import Solver, System from psecas import ChebyshevExtremaGrid import pytest \"\"\" We set", "<filename>tests/test_error_messages.py import numpy as np from psecas import Solver, System from psecas import", "setting it in the system. This should return a NameError \"\"\" # Create", "system) if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here we add the value B", "errors, and see if Psecas gives a reasonable error, i.e., a NameError. \"\"\"", "grid N = 32 grid = ChebyshevExtremaGrid(N, -1, 1) # Create a solver", "Solver(grid, system) if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here we add the value", "system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f = 0') solver = Solver(grid, system) with", "32 grid = ChebyshevExtremaGrid(N, -1, 1) # Create a solver object def test_parser_findmatrices(verbose=False):", "add the value A to the equation without setting it in the system.", "dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f = 0') solver = Solver(grid, system) with pytest.raises(NameError) as", "the value A to the equation without setting it in the system. This", "equation system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\") with pytest.raises(NameError) as e_info: solver = Solver(grid,", "solver object def test_parser_findmatrices(verbose=False): \"\"\" Here we add the value A to the", "import ChebyshevExtremaGrid import pytest \"\"\" We set up systems with errors, and see", "# Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f", "gives a reasonable error, i.e., a NameError. \"\"\" # Create grid N =", "print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here we add the value B to the boundary", "the boundary without setting it in the system. This should return a NameError", "= dz(dz(f)) + 2*A*f\") with pytest.raises(NameError) as e_info: solver = Solver(grid, system) if", "Here we add the value A to the equation without setting it in", "first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\") with pytest.raises(NameError) as e_info:", "grid = ChebyshevExtremaGrid(N, -1, 1) # Create a solver object def test_parser_findmatrices(verbose=False): \"\"\"", "variables='f', eigenvalue='sigma') # Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f)) +", "NameError. \"\"\" # Create grid N = 32 grid = ChebyshevExtremaGrid(N, -1, 1)", "eigenvalue='sigma') # Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\")", "system.add_boundary('f', 'Dirichlet', 'B*f = 0') solver = Solver(grid, system) with pytest.raises(NameError) as e_info:", "= 0') solver = Solver(grid, system) with pytest.raises(NameError) as e_info: # The error", "N = 32 grid = ChebyshevExtremaGrid(N, -1, 1) # Create a solver object", "System(grid, variables='f', eigenvalue='sigma') # Add the first (and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))", "if Psecas gives a reasonable error, i.e., a NameError. \"\"\" # Create grid", "system) with pytest.raises(NameError) as e_info: # The error is found when the solve", "test_parser_findmatrices(verbose=False): \"\"\" Here we add the value A to the equation without setting", "1) # Create a solver object def test_parser_findmatrices(verbose=False): \"\"\" Here we add the", "\"\"\" Here we add the value A to the equation without setting it", "(and only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f = 0') solver =", "import pytest \"\"\" We set up systems with errors, and see if Psecas", "a reasonable error, i.e., a NameError. \"\"\" # Create grid N = 32", "import numpy as np from psecas import Solver, System from psecas import ChebyshevExtremaGrid", "in the system. This should return a NameError \"\"\" # Create system system", "if verbose: print(str(e_info.value)) def test_parser_boundaries(verbose=False): \"\"\" Here we add the value B to", "B to the boundary without setting it in the system. This should return", "reasonable error, i.e., a NameError. \"\"\" # Create grid N = 32 grid", "without setting it in the system. This should return a NameError \"\"\" #", "pytest.raises(NameError) as e_info: # The error is found when the solve method is", "as e_info: # The error is found when the solve method is called", "it in the system. This should return a NameError \"\"\" # Create system", "(and only) equation system.add_equation(\"sigma*z*f = dz(dz(f)) + 2*A*f\") with pytest.raises(NameError) as e_info: solver", "e_info: # The error is found when the solve method is called solver.solve()", "= 32 grid = ChebyshevExtremaGrid(N, -1, 1) # Create a solver object def", "Here we add the value B to the boundary without setting it in", "solve method is called solver.solve() if verbose: print(str(e_info.value)) if __name__ == '__main__': test_parser_findmatrices(True)", "only) equation system.add_equation(\"sigma*z*f = dz(dz(f))\") system.add_boundary('f', 'Dirichlet', 'B*f = 0') solver = Solver(grid,", "system system = System(grid, variables='f', eigenvalue='sigma') # Add the first (and only) equation", "and see if Psecas gives a reasonable error, i.e., a NameError. \"\"\" #", "'B*f = 0') solver = Solver(grid, system) with pytest.raises(NameError) as e_info: # The", "def test_parser_boundaries(verbose=False): \"\"\" Here we add the value B to the boundary without", "error is found when the solve method is called solver.solve() if verbose: print(str(e_info.value))", "we add the value A to the equation without setting it in the", "Create system system = System(grid, variables='f', eigenvalue='sigma') # Add the first (and only)", "from psecas import ChebyshevExtremaGrid import pytest \"\"\" We set up systems with errors," ]
[ "<reponame>BioinfoTongLI/deepBlink \"\"\"CLI submodule for checking image shapes.\"\"\" import logging import os import textwrap", "---------- 3. By default we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this is incorrect,", "single 2D image used for one prediction \\U000027A1 z: third (height) dimension \\U000027A1", "is incorrect, please provide the proper shape using the --shape flag to the", "t: time dimension \\U000027A1 3: RGB color stack ---------- 3. By default we", "If this is incorrect, please provide the proper shape using the --shape flag", "image.\"\"\" print( textwrap.dedent( f\"\"\" 1. Your image has a shape of: {self.image.shape} ----------", "we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this is incorrect, please provide the proper", "shape of: {self.image.shape} ---------- 2. Possible parameters \\U000027A1 x, y: single 2D image", "\\U000027A1 z: third (height) dimension \\U000027A1 c: color channels \\U000027A1 t: time dimension", "\"({predict_shape(self.image.shape)})\" \\U0001F449 If this is incorrect, please provide the proper shape using the", "checking submodule\") self.abs_input = os.path.abspath(self.raw_input) def __call__(self) -> None: \"\"\"Run check for input", "provide the proper shape using the --shape flag to the submodule predict in", "from ..io import load_image from ..util import predict_shape class HandleCheck: \"\"\"Handle checking submodule", "---------- 2. Possible parameters \\U000027A1 x, y: single 2D image used for one", "image has a shape of: {self.image.shape} ---------- 2. Possible parameters \\U000027A1 x, y:", "using the --shape flag to the submodule predict in deepblink's command line interface", "RGB color stack ---------- 3. By default we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If", "self.logger = logger self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input = os.path.abspath(self.raw_input) def __call__(self) ->", "proper shape using the --shape flag to the submodule predict in deepblink's command", "predict_shape class HandleCheck: \"\"\"Handle checking submodule for CLI. Args: arg_input: Path to image.", "time dimension \\U000027A1 3: RGB color stack ---------- 3. By default we would", "logger: logging.Logger): self.raw_input = arg_input self.logger = logger self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input", "import predict_shape class HandleCheck: \"\"\"Handle checking submodule for CLI. Args: arg_input: Path to", "y: single 2D image used for one prediction \\U000027A1 z: third (height) dimension", "in deepblink's command line interface \"\"\" ) ) @property def image(self): \"\"\"Load a", "the proper shape using the --shape flag to the submodule predict in deepblink's", "arg_input: str, logger: logging.Logger): self.raw_input = arg_input self.logger = logger self.logger.info(\"\\U0001F537 starting checking", "color stack ---------- 3. By default we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this", "please provide the proper shape using the --shape flag to the submodule predict", "..util import predict_shape class HandleCheck: \"\"\"Handle checking submodule for CLI. Args: arg_input: Path", "used for one prediction \\U000027A1 z: third (height) dimension \\U000027A1 c: color channels", "By default we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this is incorrect, please provide", "from ..util import predict_shape class HandleCheck: \"\"\"Handle checking submodule for CLI. Args: arg_input:", "logger: Verbose logger. \"\"\" def __init__(self, arg_input: str, logger: logging.Logger): self.raw_input = arg_input", "interface \"\"\" ) ) @property def image(self): \"\"\"Load a single image.\"\"\" return load_image(self.abs_input)", "Args: arg_input: Path to image. logger: Verbose logger. \"\"\" def __init__(self, arg_input: str,", "2. Possible parameters \\U000027A1 x, y: single 2D image used for one prediction", "self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input = os.path.abspath(self.raw_input) def __call__(self) -> None: \"\"\"Run check", "z: third (height) dimension \\U000027A1 c: color channels \\U000027A1 t: time dimension \\U000027A1", "os import textwrap from ..io import load_image from ..util import predict_shape class HandleCheck:", "f\"\"\" 1. Your image has a shape of: {self.image.shape} ---------- 2. Possible parameters", "shape using the --shape flag to the submodule predict in deepblink's command line", "the --shape flag to the submodule predict in deepblink's command line interface \"\"\"", "class HandleCheck: \"\"\"Handle checking submodule for CLI. Args: arg_input: Path to image. logger:", "CLI. Args: arg_input: Path to image. logger: Verbose logger. \"\"\" def __init__(self, arg_input:", "import logging import os import textwrap from ..io import load_image from ..util import", "would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this is incorrect, please provide the proper shape", "os.path.abspath(self.raw_input) def __call__(self) -> None: \"\"\"Run check for input image.\"\"\" print( textwrap.dedent( f\"\"\"", "def __call__(self) -> None: \"\"\"Run check for input image.\"\"\" print( textwrap.dedent( f\"\"\" 1.", "\\U000027A1 t: time dimension \\U000027A1 3: RGB color stack ---------- 3. By default", "\"\"\"Handle checking submodule for CLI. Args: arg_input: Path to image. logger: Verbose logger.", "deepblink's command line interface \"\"\" ) ) @property def image(self): \"\"\"Load a single", "-> None: \"\"\"Run check for input image.\"\"\" print( textwrap.dedent( f\"\"\" 1. Your image", "to image. logger: Verbose logger. \"\"\" def __init__(self, arg_input: str, logger: logging.Logger): self.raw_input", "None: \"\"\"Run check for input image.\"\"\" print( textwrap.dedent( f\"\"\" 1. Your image has", "logger self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input = os.path.abspath(self.raw_input) def __call__(self) -> None: \"\"\"Run", "__call__(self) -> None: \"\"\"Run check for input image.\"\"\" print( textwrap.dedent( f\"\"\" 1. Your", "line interface \"\"\" ) ) @property def image(self): \"\"\"Load a single image.\"\"\" return", "def __init__(self, arg_input: str, logger: logging.Logger): self.raw_input = arg_input self.logger = logger self.logger.info(\"\\U0001F537", "logger. \"\"\" def __init__(self, arg_input: str, logger: logging.Logger): self.raw_input = arg_input self.logger =", "HandleCheck: \"\"\"Handle checking submodule for CLI. Args: arg_input: Path to image. logger: Verbose", "arg_input: Path to image. logger: Verbose logger. \"\"\" def __init__(self, arg_input: str, logger:", "{self.image.shape} ---------- 2. Possible parameters \\U000027A1 x, y: single 2D image used for", "checking submodule for CLI. Args: arg_input: Path to image. logger: Verbose logger. \"\"\"", "Verbose logger. \"\"\" def __init__(self, arg_input: str, logger: logging.Logger): self.raw_input = arg_input self.logger", "parameters \\U000027A1 x, y: single 2D image used for one prediction \\U000027A1 z:", "flag to the submodule predict in deepblink's command line interface \"\"\" ) )", "submodule predict in deepblink's command line interface \"\"\" ) ) @property def image(self):", "dimension \\U000027A1 3: RGB color stack ---------- 3. By default we would assign:", "\"\"\" def __init__(self, arg_input: str, logger: logging.Logger): self.raw_input = arg_input self.logger = logger", "command line interface \"\"\" ) ) @property def image(self): \"\"\"Load a single image.\"\"\"", "c: color channels \\U000027A1 t: time dimension \\U000027A1 3: RGB color stack ----------", "Possible parameters \\U000027A1 x, y: single 2D image used for one prediction \\U000027A1", "for checking image shapes.\"\"\" import logging import os import textwrap from ..io import", "Path to image. logger: Verbose logger. \"\"\" def __init__(self, arg_input: str, logger: logging.Logger):", "str, logger: logging.Logger): self.raw_input = arg_input self.logger = logger self.logger.info(\"\\U0001F537 starting checking submodule\")", "(height) dimension \\U000027A1 c: color channels \\U000027A1 t: time dimension \\U000027A1 3: RGB", "predict in deepblink's command line interface \"\"\" ) ) @property def image(self): \"\"\"Load", "channels \\U000027A1 t: time dimension \\U000027A1 3: RGB color stack ---------- 3. By", "print( textwrap.dedent( f\"\"\" 1. Your image has a shape of: {self.image.shape} ---------- 2.", "a shape of: {self.image.shape} ---------- 2. Possible parameters \\U000027A1 x, y: single 2D", "\\U000027A1 3: RGB color stack ---------- 3. By default we would assign: \"({predict_shape(self.image.shape)})\"", "prediction \\U000027A1 z: third (height) dimension \\U000027A1 c: color channels \\U000027A1 t: time", "dimension \\U000027A1 c: color channels \\U000027A1 t: time dimension \\U000027A1 3: RGB color", "incorrect, please provide the proper shape using the --shape flag to the submodule", "\\U0001F449 If this is incorrect, please provide the proper shape using the --shape", "stack ---------- 3. By default we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this is", "submodule\") self.abs_input = os.path.abspath(self.raw_input) def __call__(self) -> None: \"\"\"Run check for input image.\"\"\"", "check for input image.\"\"\" print( textwrap.dedent( f\"\"\" 1. Your image has a shape", "import os import textwrap from ..io import load_image from ..util import predict_shape class", "input image.\"\"\" print( textwrap.dedent( f\"\"\" 1. Your image has a shape of: {self.image.shape}", "image. logger: Verbose logger. \"\"\" def __init__(self, arg_input: str, logger: logging.Logger): self.raw_input =", "for CLI. Args: arg_input: Path to image. logger: Verbose logger. \"\"\" def __init__(self,", "submodule for checking image shapes.\"\"\" import logging import os import textwrap from ..io", "shapes.\"\"\" import logging import os import textwrap from ..io import load_image from ..util", "--shape flag to the submodule predict in deepblink's command line interface \"\"\" )", "third (height) dimension \\U000027A1 c: color channels \\U000027A1 t: time dimension \\U000027A1 3:", "= os.path.abspath(self.raw_input) def __call__(self) -> None: \"\"\"Run check for input image.\"\"\" print( textwrap.dedent(", "textwrap from ..io import load_image from ..util import predict_shape class HandleCheck: \"\"\"Handle checking", "\"\"\"CLI submodule for checking image shapes.\"\"\" import logging import os import textwrap from", "__init__(self, arg_input: str, logger: logging.Logger): self.raw_input = arg_input self.logger = logger self.logger.info(\"\\U0001F537 starting", "textwrap.dedent( f\"\"\" 1. Your image has a shape of: {self.image.shape} ---------- 2. Possible", "checking image shapes.\"\"\" import logging import os import textwrap from ..io import load_image", "import load_image from ..util import predict_shape class HandleCheck: \"\"\"Handle checking submodule for CLI.", "import textwrap from ..io import load_image from ..util import predict_shape class HandleCheck: \"\"\"Handle", "= logger self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input = os.path.abspath(self.raw_input) def __call__(self) -> None:", "logging.Logger): self.raw_input = arg_input self.logger = logger self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input =", "one prediction \\U000027A1 z: third (height) dimension \\U000027A1 c: color channels \\U000027A1 t:", "3. By default we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this is incorrect, please", "logging import os import textwrap from ..io import load_image from ..util import predict_shape", "starting checking submodule\") self.abs_input = os.path.abspath(self.raw_input) def __call__(self) -> None: \"\"\"Run check for", "this is incorrect, please provide the proper shape using the --shape flag to", "to the submodule predict in deepblink's command line interface \"\"\" ) ) @property", "of: {self.image.shape} ---------- 2. Possible parameters \\U000027A1 x, y: single 2D image used", "3: RGB color stack ---------- 3. By default we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449", "Your image has a shape of: {self.image.shape} ---------- 2. Possible parameters \\U000027A1 x,", "1. Your image has a shape of: {self.image.shape} ---------- 2. Possible parameters \\U000027A1", "self.raw_input = arg_input self.logger = logger self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input = os.path.abspath(self.raw_input)", "\\U000027A1 x, y: single 2D image used for one prediction \\U000027A1 z: third", "the submodule predict in deepblink's command line interface \"\"\" ) ) @property def", "arg_input self.logger = logger self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input = os.path.abspath(self.raw_input) def __call__(self)", "default we would assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this is incorrect, please provide the", "image shapes.\"\"\" import logging import os import textwrap from ..io import load_image from", "has a shape of: {self.image.shape} ---------- 2. Possible parameters \\U000027A1 x, y: single", "= arg_input self.logger = logger self.logger.info(\"\\U0001F537 starting checking submodule\") self.abs_input = os.path.abspath(self.raw_input) def", "load_image from ..util import predict_shape class HandleCheck: \"\"\"Handle checking submodule for CLI. Args:", "x, y: single 2D image used for one prediction \\U000027A1 z: third (height)", "for one prediction \\U000027A1 z: third (height) dimension \\U000027A1 c: color channels \\U000027A1", "self.abs_input = os.path.abspath(self.raw_input) def __call__(self) -> None: \"\"\"Run check for input image.\"\"\" print(", "\"\"\"Run check for input image.\"\"\" print( textwrap.dedent( f\"\"\" 1. Your image has a", "color channels \\U000027A1 t: time dimension \\U000027A1 3: RGB color stack ---------- 3.", "assign: \"({predict_shape(self.image.shape)})\" \\U0001F449 If this is incorrect, please provide the proper shape using", "submodule for CLI. Args: arg_input: Path to image. logger: Verbose logger. \"\"\" def", "..io import load_image from ..util import predict_shape class HandleCheck: \"\"\"Handle checking submodule for", "\\U000027A1 c: color channels \\U000027A1 t: time dimension \\U000027A1 3: RGB color stack", "for input image.\"\"\" print( textwrap.dedent( f\"\"\" 1. Your image has a shape of:", "2D image used for one prediction \\U000027A1 z: third (height) dimension \\U000027A1 c:", "image used for one prediction \\U000027A1 z: third (height) dimension \\U000027A1 c: color" ]
[ "= Field({(1992, ...): 'V9910', (..., 1990): None, }, descr='') occupation_first = Field({(1992, ...):", "'V91', 1976: None, }, descr='') income_pension_other = IncomeField({ (1992, ...): 'V1261', (..., 1990):", "and 'V7125' in df: T = IncomeField.remove_missing total = sum_na(total, T(df.V7122), T(df.V7125)) return", "import IncomeField, FunctionField, sum_na, Field class IncomeDataMixin: \"\"\" All income-related variables \"\"\" year:", "# Family and household # income_household = IncomeField( {(1992, ...): 'V4721', (1981, 1990):", "income_work_secondary_money_variable = IncomeField( {(1980, ...): None, 1979: 'V2457', (..., 1978): None, }, descr='Salary", "1990): None, 1979: 'V2349', 1978: 'V2468', 1977: 'V86', 1976: None, }, descr='') income_work_extra_products", "due to labor\"\"\" # Also computed in PNAD as V4719 (yr > 1992)", "occupation_year = Field({(1992, ...): 'V9971', (..., 1990): None, }, descr='') occupation_secondary = Field({(1992,", "'V1273', (..., 1990): None, # does it have a better description? # OUTR.", "df): # @NoSelf \"\"\"Sum of all income sources due to labor\"\"\" # Also", "None, }, descr='') income_household_per_capta = IncomeField( {(1992, ...): 'V4742', (1981, 1990): None, (...,", "...): 'V1298', (..., 1990): None, }, descr='') occupation_father = Field({(1992, ...): 'V1293', (...,", "}, descr='') is_occupied = Field({(1992, ...): 'V4705', (..., 1990): None, }, descr='') is_active", "occupation_father_previous = Field({(1992, ...): 'V1258', (..., 1990): None, }, descr='') is_occupied = Field({(1992,", "this is retirement + pension }, descr='') income_retirement_other = IncomeField({ (1992, ...): 'V1258',", "None, # do not ask this in recent surveys 1979: 'V2338', 1978: 'V2446',", "df): return sum_na(df.income_donation, df.income_other) # # Total incomes # @FunctionField def income_work(self, df):", "IncomeDataMixin: \"\"\" All income-related variables \"\"\" year: int # # Main job #", "a better description? # OUTR. REC. EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483', 1977: 'V95',", "\"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField", "'V95', 1976: None, }, descr='All sources of financial yield except for rents') @FunctionField", "sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary job # income_work_secondary_money_fixed = IncomeField( {(1992, ...): 'V9982',", "None, }, descr='') class OccupationDataMixin: occupation_week = Field({(1992, ...): 'V9906', (..., 1990): 'V503',", "'V1258', (..., 1990): None, }, descr='') is_occupied = Field({(1992, ...): 'V4705', (..., 1990):", "main work\"\"\" # Also computed in PNAD as V4718 (yr > 1992) return", "job (variable)') income_work_secondary_products = IncomeField( {(1992, ...): 'V9985', (1980, 1990): None, 1979: 'V2458',", "IncomeField({ (1992, ...): 'V1255', (1981, 1990): 'V579', 1979: None, 1978: 'V2480', 1977: 'V91',", "'V1267', (1981, 1990): 'V581', 1979: 'V2363', 1978: 'V2482', 1977: 'V93', 1976: 'V2363', },", "@FunctionField def income_work_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\"", "want to declare each job separately if self.year > 1992 and 'V7122' in", "= IncomeField( {(1992, ...): 'V9982', (1980, 1990): None, 1979: 'V2427', (..., 1978): None,", "...): 'V9990', (..., 1990): None, }, descr='') occupation_previous = Field({(1992, ...): 'V9910', (...,", "(1981, 1990): 'V549', 1979: 'V2319', 1978: 'V2428', 1977: 'V85', 1976: 'V2362', }, descr='')", "jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df):", "...): None, (1981, 1990): None, 1979: 'V2349', 1978: 'V2468', 1977: 'V86', 1976: None,", "job # income_work_main_money_fixed = IncomeField({ (1992, ...): 'V9532', (1981, 1990): 'V537', 1979: 'V2318',", "income_investments = IncomeField({ (1992, ...): 'V1273', (..., 1990): None, # does it have", "def income_work_main(self, df): \"\"\"Total income from main work\"\"\" # Also computed in PNAD", "1978): None, }, descr='Salary of secondary job (variable)') income_work_secondary_products = IncomeField( {(1992, ...):", "income sources #################################################### income_other = IncomeField({ (1992, ...): None, (1981, 1990): 'V582', (1978,", "def income_social(self, df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # # Capital income # income_rent", "= Field({(1992, ...): 'V1258', (..., 1990): None, }, descr='') is_occupied = Field({(1992, ...):", "\"\"\" All income-related variables \"\"\" year: int # # Main job # income_work_main_money_fixed", "'V7122' in df and 'V7125' in df: T = IncomeField.remove_missing total = sum_na(total,", "None, 1979: 'V2349', 1978: 'V2468', 1977: 'V86', 1976: None, }, descr='') income_work_extra_products =", "than primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df): \"\"\"Total income", "income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField", "1977: 'V75', 1976: 'V2308', }, descr='Fixed monthly salary') income_work_main_money_variable = IncomeField({ (1981, ...):", "Field({(1992, ...): 'V1258', (..., 1990): None, }, descr='') is_occupied = Field({(1992, ...): 'V4705',", "...): 'V1258', (..., 1990): None, }, descr='') is_occupied = Field({(1992, ...): 'V4705', (...,", "better description? # OUTR. REC. EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483', 1977: 'V95', 1976:", "# # Main job # income_work_main_money_fixed = IncomeField({ (1992, ...): 'V9532', (1981, 1990):", "1979: 'V2349', 1978: 'V2468', 1977: 'V86', 1976: None, }, descr='') income_work_extra_products = IncomeField({", "1990): None, }, descr='') is_occupied = Field({(1992, ...): 'V4705', (..., 1990): None, },", "= IncomeField({ (1992, ...): None, (1981, 1990): 'V582', (1978, 1979): None, 1977: 'V96',", "variable money income from main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df):", "# Capital income # income_rent = IncomeField({ (1992, ...): 'V1267', (1981, 1990): 'V581',", "other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self, df): \"\"\"Total", "'V9990', (..., 1990): None, }, descr='') occupation_previous = Field({(1992, ...): 'V9910', (..., 1990):", "None, 1979: 'V2362', 1978: 'V2481', 1977: 'V92', 1976: 'V2364', }, descr='') @FunctionField def", "job # income_work_secondary_money_fixed = IncomeField( {(1992, ...): 'V9982', (1980, 1990): None, 1979: 'V2427',", "this in recent surveys 1979: 'V2338', 1978: 'V2446', 1977: 'V76', 1976: 'V2358', },", "None, 1979: 'V2457', (..., 1978): None, }, descr='Salary of secondary job (variable)') income_work_secondary_products", "as V4718 (yr > 1992) return sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary job #", "primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self, df): \"\"\"Total income from", "df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # # Capital income # income_rent = IncomeField({", "...): 'V1258', (..., 1990): None, }, descr='') income_pension_main = IncomeField({ (1992, ...): 'V1255',", "from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self,", "return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self,", "salary') income_work_main_money_variable = IncomeField({ (1981, ...): None, # do not ask this in", "Field({(1992, ...): 'V4705', (..., 1990): None, }, descr='') is_active = Field({(1992, ...): 'V4704',", "'V4722', (1981, 1990): 'V5010', (..., 1979): None, }, descr='') income_household_per_capta = IncomeField( {(1992,", "descr='') work_duration = Field({(1992, ...): 'V4707', (..., 1990): None, }, descr='') @FunctionField def", "None, }, descr='') occupation_previous = Field({(1992, ...): 'V9910', (..., 1990): None, }, descr='')", "from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self,", "df.income_work_main_products) # # Secondary job # income_work_secondary_money_fixed = IncomeField( {(1992, ...): 'V9982', (1980,", "(..., 1990): None, }, descr='') @FunctionField def occupation(self, df): return df.occupation_week # TODO:", "(1981, 1990): None, 1979: 'V2362', 1978: 'V2481', 1977: 'V92', 1976: 'V2364', }, descr='')", "...): 'V4707', (..., 1990): None, }, descr='') @FunctionField def occupation(self, df): return df.occupation_week", "descr='') occupation_first = Field({(1992, ...): 'V1298', (..., 1990): None, }, descr='') occupation_father =", "ask this in recent surveys 1979: 'V2338', 1978: 'V2446', 1977: 'V76', 1976: 'V2358',", "None, }, descr='') income_pension_main = IncomeField({ (1992, ...): 'V1255', (1981, 1990): 'V579', 1979:", "income_work_main_money_fixed = IncomeField({ (1992, ...): 'V9532', (1981, 1990): 'V537', 1979: 'V2318', 1978: 'V2426',", "1977: sum_na(df.V94, df.V97) return total # Other income sources #################################################### income_other = IncomeField({", "from main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df): \"\"\"Total income from", "income_family_per_capta = IncomeField( {(1992, ...): 'V4750', (1981, 1990): None, (..., 1979): None, },", "= Field({(1992, ...): 'V4705', (..., 1990): None, }, descr='') is_active = Field({(1992, ...):", "...): 'V4750', (1981, 1990): None, (..., 1979): None, }, descr='') class OccupationDataMixin: occupation_week", "1979: 'V2339', 1978: 'V2447', 1977: 'V77', 1976: 'V2359', }, descr='Salary received in products')", "total = sum_na(df.income_work_main, df.income_work_other) # These are used to quantify total income due", "monthly salary') income_work_main_money_variable = IncomeField({ (1981, ...): None, # do not ask this", "= IncomeField( {(1992, ...): 'V1264', (1981, 1990): 'V580', (..., 1979): None}, descr='Paid to", "in PNAD as V4719 (yr > 1992) total = sum_na(df.income_work_main, df.income_work_other) # These", "1977: 'V86', 1976: None, }, descr='') income_work_extra_products = IncomeField({ (1992, ...): 'V1025', (1981,", "None, (..., 1979): None, }, descr='') class OccupationDataMixin: occupation_week = Field({(1992, ...): 'V9906',", "'V4707', (..., 1990): None, }, descr='') @FunctionField def occupation(self, df): return df.occupation_week #", "'V75', 1976: 'V2308', }, descr='Fixed monthly salary') income_work_main_money_variable = IncomeField({ (1981, ...): None,", "of monthly salary') income_work_main_products = IncomeField({ (1992, ...): 'V9535', (1981, 1990): 'V538', 1979:", "income_work_secondary_money(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self,", "None}, descr='Paid to workers that can retire, but decide to continue working', )", "def income_work_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return", "df.income_work_other_products) @FunctionField def income_work_money(self, df): \"\"\"Total income from jobs other than primary and", "from main work\"\"\" # Also computed in PNAD as V4718 (yr > 1992)", "sum_na(total, T(df.V7122), T(df.V7125)) return total @FunctionField def income(self, df): \"\"\"Total income of an", "V4718 (yr > 1992) return sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary job # income_work_secondary_money_fixed", "income_misc(self, df): return sum_na(df.income_donation, df.income_other) # # Total incomes # @FunctionField def income_work(self,", "'V1293', (..., 1990): None, }, descr='') occupation_father_previous = Field({(1992, ...): 'V1258', (..., 1990):", "'V2482', 1977: 'V93', 1976: 'V2363', }, descr='') income_investments = IncomeField({ (1992, ...): 'V1273',", "descr='') @FunctionField def income_misc(self, df): return sum_na(df.income_donation, df.income_other) # # Total incomes #", "do not ask this in recent surveys 1979: 'V2338', 1978: 'V2446', 1977: 'V76',", "(1980, 1990): None, 1979: 'V2427', (..., 1978): None, }, descr='Salary of secondary job", "1976: 'V2364', }, descr='') @FunctionField def income_misc(self, df): return sum_na(df.income_donation, df.income_other) # #", "Field({(1992, ...): 'V1298', (..., 1990): None, }, descr='') occupation_father = Field({(1992, ...): 'V1293',", "= IncomeField({ (1992, ...): 'V1261', (..., 1990): None, }, descr='') income_permanence_bonus = IncomeField(", "(1981, 1990): 'V410', (..., 1979): None, }, descr='') income_family = IncomeField( {(1992, ...):", "jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self, df):", "'V1025', (1981, 1990): 'V550', 1979: 'V2350', 1978: 'V2469', 1977: 'V87', 1976: None, },", "income_household_per_capta = IncomeField( {(1992, ...): 'V4742', (1981, 1990): None, (..., 1979): None, },", "other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self, df): \"\"\"Total", "income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def", "income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def", "'V410', (..., 1979): None, }, descr='') income_family = IncomeField( {(1992, ...): 'V4722', (1981,", "1976: 'V2366', }, descr='') income_donation = IncomeField({ (1992, ...): 'V1270', (1981, 1990): None,", "descr='Occupation at the week the survey was taken') occupation_year = Field({(1992, ...): 'V9971',", "other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df): \"\"\"Total", "'V1252', (1981, 1990): 'V578', 1979: 'V2350', 1978: 'V2479', 1977: 'V90', 1976: 'V2365', #", "# income_household = IncomeField( {(1992, ...): 'V4721', (1981, 1990): 'V410', (..., 1979): None,", "}, descr='Fixed monthly salary') income_work_main_money_variable = IncomeField({ (1981, ...): None, # do not", "}, descr='Salary of secondary job (products)') @FunctionField def income_work_secondary_money(self, df): \"\"\"Total income from", "None, }, descr='') @FunctionField def income_work_extra_money(self, df): \"\"\"Total income from jobs other than", "than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df): \"\"\"Total income", "...): 'V4721', (1981, 1990): 'V410', (..., 1979): None, }, descr='') income_family = IncomeField(", "financial yield except for rents') @FunctionField def income_capital(self, df): \"\"\"All sources of capital", "in df and 'V7125' in df: T = IncomeField.remove_missing total = sum_na(total, T(df.V7122),", "income from main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df): \"\"\"Total income", "income_work_secondary_money_fixed = IncomeField( {(1992, ...): 'V9982', (1980, 1990): None, 1979: 'V2427', (..., 1978):", "money income from main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df): \"\"\"Total", "except for rents') @FunctionField def income_capital(self, df): \"\"\"All sources of capital income\"\"\" total", "descr='All sources of financial yield except for rents') @FunctionField def income_capital(self, df): \"\"\"All", "income_work_secondary(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other", "1976: 'V2363', }, descr='') income_investments = IncomeField({ (1992, ...): 'V1273', (..., 1990): None,", "to labor\"\"\" # Also computed in PNAD as V4719 (yr > 1992) total", "...): 'V1273', (..., 1990): None, # does it have a better description? #", "descr='Salary of secondary job (fixed part)') income_work_secondary_money_variable = IncomeField( {(1980, ...): None, 1979:", "to work for people who # do not want to declare each job", "\"\"\"Total income of an individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) # # Family", "df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def", "the survey was taken') occupation_year = Field({(1992, ...): 'V9971', (..., 1990): None, },", "working', ) @FunctionField def income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self, df):", "'V1270', (1981, 1990): None, 1979: 'V2362', 1978: 'V2481', 1977: 'V92', 1976: 'V2364', },", "1977: 'V92', 1976: 'V2364', }, descr='') @FunctionField def income_misc(self, df): return sum_na(df.income_donation, df.income_other)", "sources #################################################### income_other = IncomeField({ (1992, ...): None, (1981, 1990): 'V582', (1978, 1979):", "df: T = IncomeField.remove_missing total = sum_na(total, T(df.V7122), T(df.V7125)) return total @FunctionField def", "df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other jobs", "of all income sources due to labor\"\"\" # Also computed in PNAD as", "other than primary and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self, df): \"\"\"Total", "return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self, df): \"\"\"Total income from jobs other than", "return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self, df): \"\"\"Total income from jobs other than", "an individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) # # Family and household #", "(1992, ...): None, (1981, 1990): 'V582', (1978, 1979): None, 1977: 'V96', 1976: 'V2366',", "df.income_permanence_bonus) # # Capital income # income_rent = IncomeField({ (1992, ...): 'V1267', (1981,", "survey was taken') occupation_year = Field({(1992, ...): 'V9971', (..., 1990): None, }, descr='')", "occupation_first = Field({(1992, ...): 'V1298', (..., 1990): None, }, descr='') occupation_father = Field({(1992,", "'V2363', 1978: 'V2482', 1977: 'V93', 1976: 'V2363', }, descr='') income_investments = IncomeField({ (1992,", "(1981, 1990): 'V550', 1979: 'V2350', 1978: 'V2469', 1977: 'V87', 1976: None, }, descr='')", "}, descr='') income_household_per_capta = IncomeField( {(1992, ...): 'V4742', (1981, 1990): None, (..., 1979):", "primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self, df): \"\"\"Total income from", "for rents') @FunctionField def income_capital(self, df): \"\"\"All sources of capital income\"\"\" total =", "salary') income_work_main_products = IncomeField({ (1992, ...): 'V9535', (1981, 1990): 'V538', 1979: 'V2339', 1978:", "(1992, ...): 'V1273', (..., 1990): None, # does it have a better description?", "income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def", "None, }, descr='') occupation_secondary = Field({(1992, ...): 'V9990', (..., 1990): None, }, descr='')", ") @FunctionField def income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self, df): return", "def income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self, df): return sum_na(df.income_pension, df.income_retirement,", "and 'V7122' in df and 'V7125' in df: T = IncomeField.remove_missing total =", "'V2365', # actually, this is retirement + pension }, descr='') income_retirement_other = IncomeField({", "year: int # # Main job # income_work_main_money_fixed = IncomeField({ (1992, ...): 'V9532',", "occupation_week = Field({(1992, ...): 'V9906', (..., 1990): 'V503', }, descr='Occupation at the week", "{(1992, ...): 'V9982', (1980, 1990): None, 1979: 'V2427', (..., 1978): None, }, descr='Salary", "...): 'V1252', (1981, 1990): 'V578', 1979: 'V2350', 1978: 'V2479', 1977: 'V90', 1976: 'V2365',", "df.income_pension_other) @FunctionField def income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self, df): return", "'V9906', (..., 1990): 'V503', }, descr='Occupation at the week the survey was taken')", "'V1264', (1981, 1990): 'V580', (..., 1979): None}, descr='Paid to workers that can retire,", "total income due to work for people who # do not want to", "None, }, descr='Salary of secondary job (variable)') income_work_secondary_products = IncomeField( {(1992, ...): 'V9985',", "}, descr='') income_work_extra_products = IncomeField({ (1992, ...): 'V1025', (1981, 1990): 'V550', 1979: 'V2350',", "def income_work_other(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return", "@NoSelf \"\"\"Sum of all income sources due to labor\"\"\" # Also computed in", "sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df): \"\"\"Total income from main work\"\"\" # Also", "None, }, descr='') occupation_father = Field({(1992, ...): 'V1293', (..., 1990): None, }, descr='')", "...): 'V9906', (..., 1990): 'V503', }, descr='Occupation at the week the survey was", "'V2358', }, descr='Variable part of monthly salary') income_work_main_products = IncomeField({ (1992, ...): 'V9535',", "descr='') income_donation = IncomeField({ (1992, ...): 'V1270', (1981, 1990): None, 1979: 'V2362', 1978:", "df): \"\"\"Total income from main work\"\"\" # Also computed in PNAD as V4718", "}, descr='All sources of financial yield except for rents') @FunctionField def income_capital(self, df):", "from secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other jobs # income_work_extra_money_fixed =", "# # Other jobs # income_work_extra_money_fixed = IncomeField({ (1992, ...): 'V1022', (1981, 1990):", "sources of capital income\"\"\" total = sum_na(df.income_rent, df.income_investiments) if self.year == 1977: sum_na(df.V94,", "T(df.V7122), T(df.V7125)) return total @FunctionField def income(self, df): \"\"\"Total income of an individual\"\"\"", "1992) total = sum_na(df.income_work_main, df.income_work_other) # These are used to quantify total income", "all income sources due to labor\"\"\" # Also computed in PNAD as V4719", "sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) # # Family and household # income_household = IncomeField(", "actually, this is retirement + pension }, descr='') income_retirement_other = IncomeField({ (1992, ...):", "def income_misc(self, df): return sum_na(df.income_donation, df.income_other) # # Total incomes # @FunctionField def", "part)') income_work_secondary_money_variable = IncomeField( {(1980, ...): None, 1979: 'V2457', (..., 1978): None, },", "IncomeField.remove_missing total = sum_na(total, T(df.V7122), T(df.V7125)) return total @FunctionField def income(self, df): \"\"\"Total", "}, descr='Salary received in products') @FunctionField def income_work_main_money(self, df): \"\"\"Sum of fixed +", "}, descr='') income_permanence_bonus = IncomeField( {(1992, ...): 'V1264', (1981, 1990): 'V580', (..., 1979):", "'V96', 1976: 'V2366', }, descr='') income_donation = IncomeField({ (1992, ...): 'V1270', (1981, 1990):", "1979): None, }, descr='') income_family_per_capta = IncomeField( {(1992, ...): 'V4750', (1981, 1990): None,", "income from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df): \"\"\"Total income", "occupation_secondary = Field({(1992, ...): 'V9990', (..., 1990): None, }, descr='') occupation_previous = Field({(1992,", "df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products)", "job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df): \"\"\"Total income from secondary job\"\"\"", "IncomeField, FunctionField, sum_na, Field class IncomeDataMixin: \"\"\" All income-related variables \"\"\" year: int", "retirement + pension }, descr='') income_retirement_other = IncomeField({ (1992, ...): 'V1258', (..., 1990):", "(..., 1990): None, }, descr='') occupation_previous = Field({(1992, ...): 'V9910', (..., 1990): None,", "}, descr='') income_work_extra_money_variable = IncomeField({ (1992, ...): None, (1981, 1990): None, 1979: 'V2349',", "...): None, 1979: 'V2457', (..., 1978): None, }, descr='Salary of secondary job (variable)')", "from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self,", "df.V97) return total # Other income sources #################################################### income_other = IncomeField({ (1992, ...):", "(1981, 1990): 'V538', 1979: 'V2339', 1978: 'V2447', 1977: 'V77', 1976: 'V2359', }, descr='Salary", "def income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other)", "1990): None, }, descr='') occupation_previous = Field({(1992, ...): 'V9910', (..., 1990): None, },", "= IncomeField( {(1992, ...): 'V4721', (1981, 1990): 'V410', (..., 1979): None, }, descr='')", "= Field({(1992, ...): 'V9971', (..., 1990): None, }, descr='') occupation_secondary = Field({(1992, ...):", "IncomeField( {(1992, ...): 'V4722', (1981, 1990): 'V5010', (..., 1979): None, }, descr='') income_household_per_capta", "'V2349', 1978: 'V2468', 1977: 'V86', 1976: None, }, descr='') income_work_extra_products = IncomeField({ (1992,", "{(1980, ...): None, 1979: 'V2457', (..., 1978): None, }, descr='Salary of secondary job", "'V9971', (..., 1990): None, }, descr='') occupation_secondary = Field({(1992, ...): 'V9990', (..., 1990):", "other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df): \"\"\"Total", "to declare each job separately if self.year > 1992 and 'V7122' in df", "df.income_work_main_products) # # Social security # income_retirement_main = IncomeField({ (1992, ...): 'V1252', (1981,", "IncomeField({ (1992, ...): 'V1261', (..., 1990): None, }, descr='') income_permanence_bonus = IncomeField( {(1992,", "(fixed part)') income_work_secondary_money_variable = IncomeField( {(1980, ...): None, 1979: 'V2457', (..., 1978): None,", "1979): None, }, descr='') income_household_per_capta = IncomeField( {(1992, ...): 'V4742', (1981, 1990): None,", "descr='Salary received in products') @FunctionField def income_work_main_money(self, df): \"\"\"Sum of fixed + variable", "}, descr='') occupation_previous = Field({(1992, ...): 'V9910', (..., 1990): None, }, descr='') occupation_first", "primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self, df): \"\"\"Total income from", "'V549', 1979: 'V2319', 1978: 'V2428', 1977: 'V85', 1976: 'V2362', }, descr='') income_work_extra_money_variable =", "'V503', }, descr='Occupation at the week the survey was taken') occupation_year = Field({(1992,", "(1992, ...): 'V1252', (1981, 1990): 'V578', 1979: 'V2350', 1978: 'V2479', 1977: 'V90', 1976:", "secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df): \"\"\"Total income from secondary", "}, descr='') occupation_father_previous = Field({(1992, ...): 'V1258', (..., 1990): None, }, descr='') is_occupied", "# # Family and household # income_household = IncomeField( {(1992, ...): 'V4721', (1981,", "}, descr='') occupation_secondary = Field({(1992, ...): 'V9990', (..., 1990): None, }, descr='') occupation_previous", "'V2338', 1978: 'V2446', 1977: 'V76', 1976: 'V2358', }, descr='Variable part of monthly salary')", "from .base import IncomeField, FunctionField, sum_na, Field class IncomeDataMixin: \"\"\" All income-related variables", "{(1992, ...): 'V9985', (1980, 1990): None, 1979: 'V2458', (..., 1978): None, }, descr='Salary", "None, }, descr='Salary of secondary job (products)') @FunctionField def income_work_secondary_money(self, df): \"\"\"Total income", "'V4721', (1981, 1990): 'V410', (..., 1979): None, }, descr='') income_family = IncomeField( {(1992,", "# income_work_extra_money_fixed = IncomeField({ (1992, ...): 'V1022', (1981, 1990): 'V549', 1979: 'V2319', 1978:", "...): 'V1022', (1981, 1990): 'V549', 1979: 'V2319', 1978: 'V2428', 1977: 'V85', 1976: 'V2362',", "IncomeField({ (1992, ...): 'V1258', (..., 1990): None, }, descr='') income_pension_main = IncomeField({ (1992,", "1990): 'V581', 1979: 'V2363', 1978: 'V2482', 1977: 'V93', 1976: 'V2363', }, descr='') income_investments", "1977: 'V90', 1976: 'V2365', # actually, this is retirement + pension }, descr='')", "df.income_other) # # Total incomes # @FunctionField def income_work(self, df): # @NoSelf \"\"\"Sum", "}, descr='') income_pension_other = IncomeField({ (1992, ...): 'V1261', (..., 1990): None, }, descr='')", "# Total incomes # @FunctionField def income_work(self, df): # @NoSelf \"\"\"Sum of all", "'V4750', (1981, 1990): None, (..., 1979): None, }, descr='') class OccupationDataMixin: occupation_week =", "= IncomeField({ (1992, ...): None, (1981, 1990): None, 1979: 'V2349', 1978: 'V2468', 1977:", "Also computed in PNAD as V4719 (yr > 1992) total = sum_na(df.income_work_main, df.income_work_other)", "'V9985', (1980, 1990): None, 1979: 'V2458', (..., 1978): None, }, descr='Salary of secondary", "1976: 'V2362', }, descr='') income_work_extra_money_variable = IncomeField({ (1992, ...): None, (1981, 1990): None,", "1990): None, (..., 1979): None, }, descr='') income_family_per_capta = IncomeField( {(1992, ...): 'V4750',", "'V86', 1976: None, }, descr='') income_work_extra_products = IncomeField({ (1992, ...): 'V1025', (1981, 1990):", "def income_work_extra_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return", "'V9535', (1981, 1990): 'V538', 1979: 'V2339', 1978: 'V2447', 1977: 'V77', 1976: 'V2359', },", "def income_work_other_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return", "Field({(1992, ...): 'V1293', (..., 1990): None, }, descr='') occupation_father_previous = Field({(1992, ...): 'V1258',", "return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other jobs # income_work_extra_money_fixed = IncomeField({ (1992, ...):", "income_work_other_products(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products,", "IncomeField({ (1992, ...): 'V9532', (1981, 1990): 'V537', 1979: 'V2318', 1978: 'V2426', 1977: 'V75',", "1977: 'V91', 1976: None, }, descr='') income_pension_other = IncomeField({ (1992, ...): 'V1261', (...,", "@FunctionField def income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self, df): return sum_na(df.income_pension,", "1979): None}, descr='Paid to workers that can retire, but decide to continue working',", "security # income_retirement_main = IncomeField({ (1992, ...): 'V1252', (1981, 1990): 'V578', 1979: 'V2350',", "sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self, df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # # Capital", "(..., 1990): None, }, descr='') occupation_father = Field({(1992, ...): 'V1293', (..., 1990): None,", "= Field({(1992, ...): 'V4704', (..., 1990): None, }, descr='') work_duration = Field({(1992, ...):", "(1981, 1990): None, 1979: 'V2349', 1978: 'V2468', 1977: 'V86', 1976: None, }, descr='')", "income_work_main_money(self, df): \"\"\"Sum of fixed + variable money income from main job\"\"\" return", "of secondary job (products)') @FunctionField def income_work_secondary_money(self, df): \"\"\"Total income from secondary job\"\"\"", "income\"\"\" total = sum_na(df.income_rent, df.income_investiments) if self.year == 1977: sum_na(df.V94, df.V97) return total", "1992) return sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary job # income_work_secondary_money_fixed = IncomeField( {(1992,", "secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df): \"\"\"Total income from jobs other", "it have a better description? # OUTR. REC. EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483',", ".base import IncomeField, FunctionField, sum_na, Field class IncomeDataMixin: \"\"\" All income-related variables \"\"\"", "(1981, 1990): 'V537', 1979: 'V2318', 1978: 'V2426', 1977: 'V75', 1976: 'V2308', }, descr='Fixed", "These are used to quantify total income due to work for people who", "primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df): \"\"\"Total income from", "'V1255', (1981, 1990): 'V579', 1979: None, 1978: 'V2480', 1977: 'V91', 1976: None, },", "None, # does it have a better description? # OUTR. REC. EMPREG.CAPITA 1979:", "'V90', 1976: 'V2365', # actually, this is retirement + pension }, descr='') income_retirement_other", "return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) # # Family and household # income_household =", "capital income\"\"\" total = sum_na(df.income_rent, df.income_investiments) if self.year == 1977: sum_na(df.V94, df.V97) return", "df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self, df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) #", "> 1992 and 'V7122' in df and 'V7125' in df: T = IncomeField.remove_missing", "Other jobs # income_work_extra_money_fixed = IncomeField({ (1992, ...): 'V1022', (1981, 1990): 'V549', 1979:", "df.income_retirement_other) @FunctionField def income_social(self, df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # # Capital income", "return total # Other income sources #################################################### income_other = IncomeField({ (1992, ...): None,", "}, descr='') income_retirement_other = IncomeField({ (1992, ...): 'V1258', (..., 1990): None, }, descr='')", "= IncomeField( {(1992, ...): 'V9985', (1980, 1990): None, 1979: 'V2458', (..., 1978): None,", "...): 'V4705', (..., 1990): None, }, descr='') is_active = Field({(1992, ...): 'V4704', (...,", "'V2362', 1978: 'V2481', 1977: 'V92', 1976: 'V2364', }, descr='') @FunctionField def income_misc(self, df):", "def income_work_secondary_money(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def", "(..., 1979): None, }, descr='') income_family_per_capta = IncomeField( {(1992, ...): 'V4750', (1981, 1990):", "1979: 'V2458', (..., 1978): None, }, descr='Salary of secondary job (products)') @FunctionField def", "and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df): \"\"\"Total income from jobs", "total # Other income sources #################################################### income_other = IncomeField({ (1992, ...): None, (1981,", "None, }, descr='') income_family = IncomeField( {(1992, ...): 'V4722', (1981, 1990): 'V5010', (...,", "work\"\"\" # Also computed in PNAD as V4718 (yr > 1992) return sum_na(df.income_work_main_money,", "IncomeField({ (1981, ...): None, # do not ask this in recent surveys 1979:", "def income_work_secondary(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # #", "sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self, df): \"\"\"Total income from jobs other than primary", "secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self, df): \"\"\"Total income from jobs other", "1990): 'V410', (..., 1979): None, }, descr='') income_family = IncomeField( {(1992, ...): 'V4722',", "descr='') income_retirement_other = IncomeField({ (1992, ...): 'V1258', (..., 1990): None, }, descr='') income_pension_main", "...): 'V9532', (1981, 1990): 'V537', 1979: 'V2318', 1978: 'V2426', 1977: 'V75', 1976: 'V2308',", "def income(self, df): \"\"\"Total income of an individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc)", "secondary job (fixed part)') income_work_secondary_money_variable = IncomeField( {(1980, ...): None, 1979: 'V2457', (...,", "# Also computed in PNAD as V4719 (yr > 1992) total = sum_na(df.income_work_main,", "...): 'V1025', (1981, 1990): 'V550', 1979: 'V2350', 1978: 'V2469', 1977: 'V87', 1976: None,", "(1980, 1990): None, 1979: 'V2458', (..., 1978): None, }, descr='Salary of secondary job", "None, 1979: 'V2427', (..., 1978): None, }, descr='Salary of secondary job (fixed part)')", "secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self, df): \"\"\"Total income from jobs other", "'V550', 1979: 'V2350', 1978: 'V2469', 1977: 'V87', 1976: None, }, descr='') @FunctionField def", "{(1992, ...): 'V1264', (1981, 1990): 'V580', (..., 1979): None}, descr='Paid to workers that", "def income_capital(self, df): \"\"\"All sources of capital income\"\"\" total = sum_na(df.income_rent, df.income_investiments) if", "\"\"\"All sources of capital income\"\"\" total = sum_na(df.income_rent, df.income_investiments) if self.year == 1977:", "@FunctionField def income_work_other(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\"", "All income-related variables \"\"\" year: int # # Main job # income_work_main_money_fixed =", "job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df): \"\"\"Total income from main work\"\"\"", "'V2359', }, descr='Salary received in products') @FunctionField def income_work_main_money(self, df): \"\"\"Sum of fixed", "1979: 'V2363', 1978: 'V2482', 1977: 'V93', 1976: 'V2363', }, descr='') income_investments = IncomeField({", "return sum_na(df.income_donation, df.income_other) # # Total incomes # @FunctionField def income_work(self, df): #", "'V2447', 1977: 'V77', 1976: 'V2359', }, descr='Salary received in products') @FunctionField def income_work_main_money(self,", "description? # OUTR. REC. EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483', 1977: 'V95', 1976: None,", "job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other jobs # income_work_extra_money_fixed = IncomeField({ (1992,", "None, }, descr='') @FunctionField def occupation(self, df): return df.occupation_week # TODO: improve this!", "\"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField", "return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # # Capital income # income_rent = IncomeField({ (1992,", "1978): None, }, descr='Salary of secondary job (products)') @FunctionField def income_work_secondary_money(self, df): \"\"\"Total", "Also computed in PNAD as V4718 (yr > 1992) return sum_na(df.income_work_main_money, df.income_work_main_products) #", "= IncomeField({ (1992, ...): 'V1258', (..., 1990): None, }, descr='') income_pension_main = IncomeField({", "IncomeField({ (1992, ...): 'V9535', (1981, 1990): 'V538', 1979: 'V2339', 1978: 'V2447', 1977: 'V77',", "income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def", "'V93', 1976: 'V2363', }, descr='') income_investments = IncomeField({ (1992, ...): 'V1273', (..., 1990):", "(..., 1978): None, }, descr='Salary of secondary job (fixed part)') income_work_secondary_money_variable = IncomeField(", "1978: 'V2428', 1977: 'V85', 1976: 'V2362', }, descr='') income_work_extra_money_variable = IncomeField({ (1992, ...):", "Field class IncomeDataMixin: \"\"\" All income-related variables \"\"\" year: int # # Main", "(1992, ...): 'V9532', (1981, 1990): 'V537', 1979: 'V2318', 1978: 'V2426', 1977: 'V75', 1976:", "income from secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other jobs # income_work_extra_money_fixed", "1978: 'V2426', 1977: 'V75', 1976: 'V2308', }, descr='Fixed monthly salary') income_work_main_money_variable = IncomeField({", "}, descr='Occupation at the week the survey was taken') occupation_year = Field({(1992, ...):", "Capital income # income_rent = IncomeField({ (1992, ...): 'V1267', (1981, 1990): 'V581', 1979:", "job (products)') @FunctionField def income_work_secondary_money(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed,", "(1992, ...): 'V1258', (..., 1990): None, }, descr='') income_pension_main = IncomeField({ (1992, ...):", "df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products)", "descr='Salary of secondary job (variable)') income_work_secondary_products = IncomeField( {(1992, ...): 'V9985', (1980, 1990):", "1978: 'V2479', 1977: 'V90', 1976: 'V2365', # actually, this is retirement + pension", "'V4705', (..., 1990): None, }, descr='') is_active = Field({(1992, ...): 'V4704', (..., 1990):", "'V2361', 1978: 'V2483', 1977: 'V95', 1976: None, }, descr='All sources of financial yield", "int # # Main job # income_work_main_money_fixed = IncomeField({ (1992, ...): 'V9532', (1981,", "jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df):", "income_work_extra_money_variable = IncomeField({ (1992, ...): None, (1981, 1990): None, 1979: 'V2349', 1978: 'V2468',", "1976: None, }, descr='') income_work_extra_products = IncomeField({ (1992, ...): 'V1025', (1981, 1990): 'V550',", "1979: 'V2338', 1978: 'V2446', 1977: 'V76', 1976: 'V2358', }, descr='Variable part of monthly", "# Social security # income_retirement_main = IncomeField({ (1992, ...): 'V1252', (1981, 1990): 'V578',", "income_social(self, df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # # Capital income # income_rent =", "df): \"\"\"Total income of an individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) # #", "def income_work_products(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return", "\"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField", "Field({(1992, ...): 'V4707', (..., 1990): None, }, descr='') @FunctionField def occupation(self, df): return", "(..., 1978): None, }, descr='Salary of secondary job (products)') @FunctionField def income_work_secondary_money(self, df):", "jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self, df):", "# income_retirement_main = IncomeField({ (1992, ...): 'V1252', (1981, 1990): 'V578', 1979: 'V2350', 1978:", "None, 1978: 'V2480', 1977: 'V91', 1976: None, }, descr='') income_pension_other = IncomeField({ (1992,", "@FunctionField def income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self, df): return sum_na(df.income_retirement_main,", "df.income_retirement, df.income_permanence_bonus) # # Capital income # income_rent = IncomeField({ (1992, ...): 'V1267',", "None, 1977: 'V96', 1976: 'V2366', }, descr='') income_donation = IncomeField({ (1992, ...): 'V1270',", "1990): None, }, descr='') income_pension_main = IncomeField({ (1992, ...): 'V1255', (1981, 1990): 'V579',", "'V580', (..., 1979): None}, descr='Paid to workers that can retire, but decide to", "Field({(1992, ...): 'V4704', (..., 1990): None, }, descr='') work_duration = Field({(1992, ...): 'V4707',", "(1992, ...): 'V1255', (1981, 1990): 'V579', 1979: None, 1978: 'V2480', 1977: 'V91', 1976:", "None, }, descr='') is_occupied = Field({(1992, ...): 'V4705', (..., 1990): None, }, descr='')", "# Other jobs # income_work_extra_money_fixed = IncomeField({ (1992, ...): 'V1022', (1981, 1990): 'V549',", "'V2362', }, descr='') income_work_extra_money_variable = IncomeField({ (1992, ...): None, (1981, 1990): None, 1979:", "income_work_extra_products = IncomeField({ (1992, ...): 'V1025', (1981, 1990): 'V550', 1979: 'V2350', 1978: 'V2469',", "REC. EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483', 1977: 'V95', 1976: None, }, descr='All sources", "from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self,", "OUTR. REC. EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483', 1977: 'V95', 1976: None, }, descr='All", "(1992, ...): 'V1267', (1981, 1990): 'V581', 1979: 'V2363', 1978: 'V2482', 1977: 'V93', 1976:", "df.income_capital, df.income_misc) # # Family and household # income_household = IncomeField( {(1992, ...):", "declare each job separately if self.year > 1992 and 'V7122' in df and", "sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money,", "jobs # income_work_extra_money_fixed = IncomeField({ (1992, ...): 'V1022', (1981, 1990): 'V549', 1979: 'V2319',", "yield except for rents') @FunctionField def income_capital(self, df): \"\"\"All sources of capital income\"\"\"", "(1981, 1990): 'V578', 1979: 'V2350', 1978: 'V2479', 1977: 'V90', 1976: 'V2365', # actually,", "(..., 1990): None, }, descr='') occupation_father_previous = Field({(1992, ...): 'V1258', (..., 1990): None,", "\"\"\" year: int # # Main job # income_work_main_money_fixed = IncomeField({ (1992, ...):", "descr='') income_household_per_capta = IncomeField( {(1992, ...): 'V4742', (1981, 1990): None, (..., 1979): None,", "@FunctionField def income_work_extra(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\"", "(..., 1979): None, }, descr='') class OccupationDataMixin: occupation_week = Field({(1992, ...): 'V9906', (...,", "...): 'V9910', (..., 1990): None, }, descr='') occupation_first = Field({(1992, ...): 'V1298', (...,", "> 1992) return sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary job # income_work_secondary_money_fixed = IncomeField(", "\"\"\"Sum of all income sources due to labor\"\"\" # Also computed in PNAD", "'V2428', 1977: 'V85', 1976: 'V2362', }, descr='') income_work_extra_money_variable = IncomeField({ (1992, ...): None,", "1990): 'V549', 1979: 'V2319', 1978: 'V2428', 1977: 'V85', 1976: 'V2362', }, descr='') income_work_extra_money_variable", "sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # # Capital income # income_rent = IncomeField({ (1992, ...):", "income_work_main_money_variable = IncomeField({ (1981, ...): None, # do not ask this in recent", "from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self,", "1990): None, }, descr='') occupation_first = Field({(1992, ...): 'V1298', (..., 1990): None, },", "1990): None, }, descr='') @FunctionField def occupation(self, df): return df.occupation_week # TODO: improve", "'V2483', 1977: 'V95', 1976: None, }, descr='All sources of financial yield except for", "1979: None, 1978: 'V2480', 1977: 'V91', 1976: None, }, descr='') income_pension_other = IncomeField({", "1990): None, # does it have a better description? # OUTR. REC. EMPREG.CAPITA", "= IncomeField({ (1992, ...): 'V9535', (1981, 1990): 'V538', 1979: 'V2339', 1978: 'V2447', 1977:", "IncomeField({ (1992, ...): None, (1981, 1990): 'V582', (1978, 1979): None, 1977: 'V96', 1976:", "sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self, df): \"\"\"Total income from jobs other than primary", "secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df): \"\"\"Total income from jobs other", "df.income_investiments) if self.year == 1977: sum_na(df.V94, df.V97) return total # Other income sources", "not want to declare each job separately if self.year > 1992 and 'V7122'", "of an individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) # # Family and household", "= sum_na(df.income_work_main, df.income_work_other) # These are used to quantify total income due to", "was taken') occupation_year = Field({(1992, ...): 'V9971', (..., 1990): None, }, descr='') occupation_secondary", "income_work_main(self, df): \"\"\"Total income from main work\"\"\" # Also computed in PNAD as", "}, descr='') occupation_father = Field({(1992, ...): 'V1293', (..., 1990): None, }, descr='') occupation_father_previous", "1979: 'V2362', 1978: 'V2481', 1977: 'V92', 1976: 'V2364', }, descr='') @FunctionField def income_misc(self,", "Total incomes # @FunctionField def income_work(self, df): # @NoSelf \"\"\"Sum of all income", "PNAD as V4719 (yr > 1992) total = sum_na(df.income_work_main, df.income_work_other) # These are", "(variable)') income_work_secondary_products = IncomeField( {(1992, ...): 'V9985', (1980, 1990): None, 1979: 'V2458', (...,", "'V2457', (..., 1978): None, }, descr='Salary of secondary job (variable)') income_work_secondary_products = IncomeField(", "'V1022', (1981, 1990): 'V549', 1979: 'V2319', 1978: 'V2428', 1977: 'V85', 1976: 'V2362', },", "df.income_work_main_money) @FunctionField def income_work_products(self, df): \"\"\"Total income from jobs other than primary and", "# # Total incomes # @FunctionField def income_work(self, df): # @NoSelf \"\"\"Sum of", "sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self, df):", "but decide to continue working', ) @FunctionField def income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other)", "None, (1981, 1990): None, 1979: 'V2349', 1978: 'V2468', 1977: 'V86', 1976: None, },", "sources of financial yield except for rents') @FunctionField def income_capital(self, df): \"\"\"All sources", "'V85', 1976: 'V2362', }, descr='') income_work_extra_money_variable = IncomeField({ (1992, ...): None, (1981, 1990):", "IncomeField({ (1992, ...): 'V1025', (1981, 1990): 'V550', 1979: 'V2350', 1978: 'V2469', 1977: 'V87',", "}, descr='') @FunctionField def income_misc(self, df): return sum_na(df.income_donation, df.income_other) # # Total incomes", "}, descr='') class OccupationDataMixin: occupation_week = Field({(1992, ...): 'V9906', (..., 1990): 'V503', },", "1990): None, }, descr='') occupation_father_previous = Field({(1992, ...): 'V1258', (..., 1990): None, },", "return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self, df): \"\"\"Total income from jobs other than", "'V1261', (..., 1990): None, }, descr='') income_permanence_bonus = IncomeField( {(1992, ...): 'V1264', (1981,", "sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other jobs # income_work_extra_money_fixed = IncomeField({ (1992, ...): 'V1022',", "(1981, ...): None, # do not ask this in recent surveys 1979: 'V2338',", "(1978, 1979): None, 1977: 'V96', 1976: 'V2366', }, descr='') income_donation = IncomeField({ (1992,", "...): 'V1293', (..., 1990): None, }, descr='') occupation_father_previous = Field({(1992, ...): 'V1258', (...,", "(1981, 1990): 'V579', 1979: None, 1978: 'V2480', 1977: 'V91', 1976: None, }, descr='')", "secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self, df): \"\"\"Total income from jobs other", "= Field({(1992, ...): 'V4707', (..., 1990): None, }, descr='') @FunctionField def occupation(self, df):", "class OccupationDataMixin: occupation_week = Field({(1992, ...): 'V9906', (..., 1990): 'V503', }, descr='Occupation at", "that can retire, but decide to continue working', ) @FunctionField def income_pension(self, df):", "# actually, this is retirement + pension }, descr='') income_retirement_other = IncomeField({ (1992,", "return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df): \"\"\"Total income from main work\"\"\" #", "is_active = Field({(1992, ...): 'V4704', (..., 1990): None, }, descr='') work_duration = Field({(1992,", "sum_na, Field class IncomeDataMixin: \"\"\" All income-related variables \"\"\" year: int # #", "1990): None, (..., 1979): None, }, descr='') class OccupationDataMixin: occupation_week = Field({(1992, ...):", "...): 'V9535', (1981, 1990): 'V538', 1979: 'V2339', 1978: 'V2447', 1977: 'V77', 1976: 'V2359',", "and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self, df): \"\"\"Total income from jobs", "(..., 1990): 'V503', }, descr='Occupation at the week the survey was taken') occupation_year", "None, (..., 1979): None, }, descr='') income_family_per_capta = IncomeField( {(1992, ...): 'V4750', (1981,", "...): 'V4704', (..., 1990): None, }, descr='') work_duration = Field({(1992, ...): 'V4707', (...,", "return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df): \"\"\"Total income from secondary job\"\"\" return", "than primary and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self, df): \"\"\"Total income", "'V87', 1976: None, }, descr='') @FunctionField def income_work_extra_money(self, df): \"\"\"Total income from jobs", "1976: 'V2365', # actually, this is retirement + pension }, descr='') income_retirement_other =", "(..., 1990): None, }, descr='') work_duration = Field({(1992, ...): 'V4707', (..., 1990): None,", "descr='') income_permanence_bonus = IncomeField( {(1992, ...): 'V1264', (1981, 1990): 'V580', (..., 1979): None},", "descr='') income_pension_main = IncomeField({ (1992, ...): 'V1255', (1981, 1990): 'V579', 1979: None, 1978:", "= IncomeField({ (1992, ...): 'V1252', (1981, 1990): 'V578', 1979: 'V2350', 1978: 'V2479', 1977:", "None, }, descr='') income_pension_other = IncomeField({ (1992, ...): 'V1261', (..., 1990): None, },", "who # do not want to declare each job separately if self.year >", "1978: 'V2483', 1977: 'V95', 1976: None, }, descr='All sources of financial yield except", "FunctionField, sum_na, Field class IncomeDataMixin: \"\"\" All income-related variables \"\"\" year: int #", "1990): None, }, descr='') income_permanence_bonus = IncomeField( {(1992, ...): 'V1264', (1981, 1990): 'V580',", "None, }, descr='') income_permanence_bonus = IncomeField( {(1992, ...): 'V1264', (1981, 1990): 'V580', (...,", "(1992, ...): 'V1270', (1981, 1990): None, 1979: 'V2362', 1978: 'V2481', 1977: 'V92', 1976:", "of secondary job (variable)') income_work_secondary_products = IncomeField( {(1992, ...): 'V9985', (1980, 1990): None,", "df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products)", "def income_work_main_money(self, df): \"\"\"Sum of fixed + variable money income from main job\"\"\"", "separately if self.year > 1992 and 'V7122' in df and 'V7125' in df:", "df): \"\"\"Sum of fixed + variable money income from main job\"\"\" return sum_na(df.income_work_main_money_variable,", "is retirement + pension }, descr='') income_retirement_other = IncomeField({ (1992, ...): 'V1258', (...,", "}, descr='') income_family_per_capta = IncomeField( {(1992, ...): 'V4750', (1981, 1990): None, (..., 1979):", "\"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField", "= IncomeField( {(1992, ...): 'V4742', (1981, 1990): None, (..., 1979): None, }, descr='')", "total = sum_na(total, T(df.V7122), T(df.V7125)) return total @FunctionField def income(self, df): \"\"\"Total income", "= Field({(1992, ...): 'V1293', (..., 1990): None, }, descr='') occupation_father_previous = Field({(1992, ...):", "from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self,", "if self.year > 1992 and 'V7122' in df and 'V7125' in df: T", "'V581', 1979: 'V2363', 1978: 'V2482', 1977: 'V93', 1976: 'V2363', }, descr='') income_investments =", "'V77', 1976: 'V2359', }, descr='Salary received in products') @FunctionField def income_work_main_money(self, df): \"\"\"Sum", "secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other jobs # income_work_extra_money_fixed = IncomeField({", "'V2350', 1978: 'V2479', 1977: 'V90', 1976: 'V2365', # actually, this is retirement +", "IncomeField( {(1992, ...): 'V4742', (1981, 1990): None, (..., 1979): None, }, descr='') income_family_per_capta", "self.year == 1977: sum_na(df.V94, df.V97) return total # Other income sources #################################################### income_other", "workers that can retire, but decide to continue working', ) @FunctionField def income_pension(self,", "'V7125' in df: T = IncomeField.remove_missing total = sum_na(total, T(df.V7122), T(df.V7125)) return total", "...): 'V1267', (1981, 1990): 'V581', 1979: 'V2363', 1978: 'V2482', 1977: 'V93', 1976: 'V2363',", "week the survey was taken') occupation_year = Field({(1992, ...): 'V9971', (..., 1990): None,", "part of monthly salary') income_work_main_products = IncomeField({ (1992, ...): 'V9535', (1981, 1990): 'V538',", "None, 1979: 'V2458', (..., 1978): None, }, descr='Salary of secondary job (products)') @FunctionField", "in PNAD as V4718 (yr > 1992) return sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary", "return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df): \"\"\"Total income from jobs other than", "'V2366', }, descr='') income_donation = IncomeField({ (1992, ...): 'V1270', (1981, 1990): None, 1979:", "secondary job (products)') @FunctionField def income_work_secondary_money(self, df): \"\"\"Total income from secondary job\"\"\" return", "= Field({(1992, ...): 'V1298', (..., 1990): None, }, descr='') occupation_father = Field({(1992, ...):", "from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social", "descr='') class OccupationDataMixin: occupation_week = Field({(1992, ...): 'V9906', (..., 1990): 'V503', }, descr='Occupation", "and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social security # income_retirement_main = IncomeField({", "= IncomeField( {(1980, ...): None, 1979: 'V2457', (..., 1978): None, }, descr='Salary of", "IncomeField( {(1992, ...): 'V9985', (1980, 1990): None, 1979: 'V2458', (..., 1978): None, },", "(..., 1990): None, }, descr='') income_permanence_bonus = IncomeField( {(1992, ...): 'V1264', (1981, 1990):", "(1981, 1990): 'V580', (..., 1979): None}, descr='Paid to workers that can retire, but", "# @NoSelf \"\"\"Sum of all income sources due to labor\"\"\" # Also computed", "= IncomeField({ (1992, ...): 'V1267', (1981, 1990): 'V581', 1979: 'V2363', 1978: 'V2482', 1977:", "# income_work_secondary_money_fixed = IncomeField( {(1992, ...): 'V9982', (1980, 1990): None, 1979: 'V2427', (...,", "@FunctionField def income(self, df): \"\"\"Total income of an individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital,", "primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df): \"\"\"Total income from", "Family and household # income_household = IncomeField( {(1992, ...): 'V4721', (1981, 1990): 'V410',", "\"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) #", "= IncomeField({ (1992, ...): 'V9532', (1981, 1990): 'V537', 1979: 'V2318', 1978: 'V2426', 1977:", "(1992, ...): 'V1261', (..., 1990): None, }, descr='') income_permanence_bonus = IncomeField( {(1992, ...):", "is_occupied = Field({(1992, ...): 'V4705', (..., 1990): None, }, descr='') is_active = Field({(1992,", "income_other = IncomeField({ (1992, ...): None, (1981, 1990): 'V582', (1978, 1979): None, 1977:", "income-related variables \"\"\" year: int # # Main job # income_work_main_money_fixed = IncomeField({", "(1992, ...): None, (1981, 1990): None, 1979: 'V2349', 1978: 'V2468', 1977: 'V86', 1976:", "descr='') is_active = Field({(1992, ...): 'V4704', (..., 1990): None, }, descr='') work_duration =", "rents') @FunctionField def income_capital(self, df): \"\"\"All sources of capital income\"\"\" total = sum_na(df.income_rent,", "1979: 'V2361', 1978: 'V2483', 1977: 'V95', 1976: None, }, descr='All sources of financial", "1977: 'V87', 1976: None, }, descr='') @FunctionField def income_work_extra_money(self, df): \"\"\"Total income from", "descr='') occupation_secondary = Field({(1992, ...): 'V9990', (..., 1990): None, }, descr='') occupation_previous =", "# income_work_main_money_fixed = IncomeField({ (1992, ...): 'V9532', (1981, 1990): 'V537', 1979: 'V2318', 1978:", "Field({(1992, ...): 'V9906', (..., 1990): 'V503', }, descr='Occupation at the week the survey", "1979: 'V2427', (..., 1978): None, }, descr='Salary of secondary job (fixed part)') income_work_secondary_money_variable", "of fixed + variable money income from main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField", "IncomeField( {(1980, ...): None, 1979: 'V2457', (..., 1978): None, }, descr='Salary of secondary", "@FunctionField def income_work_extra_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\"", "and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self, df): \"\"\"Total income from jobs", "job (fixed part)') income_work_secondary_money_variable = IncomeField( {(1980, ...): None, 1979: 'V2457', (..., 1978):", "...): None, # do not ask this in recent surveys 1979: 'V2338', 1978:", "None, }, descr='Salary of secondary job (fixed part)') income_work_secondary_money_variable = IncomeField( {(1980, ...):", "Social security # income_retirement_main = IncomeField({ (1992, ...): 'V1252', (1981, 1990): 'V578', 1979:", "Secondary job # income_work_secondary_money_fixed = IncomeField( {(1992, ...): 'V9982', (1980, 1990): None, 1979:", "'V2469', 1977: 'V87', 1976: None, }, descr='') @FunctionField def income_work_extra_money(self, df): \"\"\"Total income", "can retire, but decide to continue working', ) @FunctionField def income_pension(self, df): return", "# does it have a better description? # OUTR. REC. EMPREG.CAPITA 1979: 'V2361',", "than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social security # income_retirement_main", "if self.year == 1977: sum_na(df.V94, df.V97) return total # Other income sources ####################################################", "have a better description? # OUTR. REC. EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483', 1977:", "(1981, 1990): 'V581', 1979: 'V2363', 1978: 'V2482', 1977: 'V93', 1976: 'V2363', }, descr='')", "than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self, df): \"\"\"Total income", "...): 'V1270', (1981, 1990): None, 1979: 'V2362', 1978: 'V2481', 1977: 'V92', 1976: 'V2364',", "'V2318', 1978: 'V2426', 1977: 'V75', 1976: 'V2308', }, descr='Fixed monthly salary') income_work_main_money_variable =", "}, descr='') income_pension_main = IncomeField({ (1992, ...): 'V1255', (1981, 1990): 'V579', 1979: None,", "}, descr='') is_active = Field({(1992, ...): 'V4704', (..., 1990): None, }, descr='') work_duration", "decide to continue working', ) @FunctionField def income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField", "...): None, (1981, 1990): 'V582', (1978, 1979): None, 1977: 'V96', 1976: 'V2366', },", "= IncomeField({ (1992, ...): 'V1022', (1981, 1990): 'V549', 1979: 'V2319', 1978: 'V2428', 1977:", "1977: 'V76', 1976: 'V2358', }, descr='Variable part of monthly salary') income_work_main_products = IncomeField({", "job separately if self.year > 1992 and 'V7122' in df and 'V7125' in", "T(df.V7125)) return total @FunctionField def income(self, df): \"\"\"Total income of an individual\"\"\" return", "than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self, df): \"\"\"Total income", "= IncomeField( {(1992, ...): 'V4750', (1981, 1990): None, (..., 1979): None, }, descr='')", "{(1992, ...): 'V4750', (1981, 1990): None, (..., 1979): None, }, descr='') class OccupationDataMixin:", "variables \"\"\" year: int # # Main job # income_work_main_money_fixed = IncomeField({ (1992,", "'V9910', (..., 1990): None, }, descr='') occupation_first = Field({(1992, ...): 'V1298', (..., 1990):", "@FunctionField def income_work_main(self, df): \"\"\"Total income from main work\"\"\" # Also computed in", "@FunctionField def income_work_secondary_money(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField", "1978: 'V2469', 1977: 'V87', 1976: None, }, descr='') @FunctionField def income_work_extra_money(self, df): \"\"\"Total", "for people who # do not want to declare each job separately if", "IncomeField({ (1992, ...): 'V1267', (1981, 1990): 'V581', 1979: 'V2363', 1978: 'V2482', 1977: 'V93',", "(..., 1990): None, }, descr='') occupation_first = Field({(1992, ...): 'V1298', (..., 1990): None,", "in recent surveys 1979: 'V2338', 1978: 'V2446', 1977: 'V76', 1976: 'V2358', }, descr='Variable", "income_retirement(self, df): return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self, df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus)", "the week the survey was taken') occupation_year = Field({(1992, ...): 'V9971', (..., 1990):", "@FunctionField def income_work_products(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\"", "IncomeField( {(1992, ...): 'V1264', (1981, 1990): 'V580', (..., 1979): None}, descr='Paid to workers", "1979): None, }, descr='') class OccupationDataMixin: occupation_week = Field({(1992, ...): 'V9906', (..., 1990):", "@FunctionField def income_work_secondary(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) #", "from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df): \"\"\"Total income from", "received in products') @FunctionField def income_work_main_money(self, df): \"\"\"Sum of fixed + variable money", "}, descr='Variable part of monthly salary') income_work_main_products = IncomeField({ (1992, ...): 'V9535', (1981,", "descr='') income_work_extra_products = IncomeField({ (1992, ...): 'V1025', (1981, 1990): 'V550', 1979: 'V2350', 1978:", "# do not want to declare each job separately if self.year > 1992", "'V538', 1979: 'V2339', 1978: 'V2447', 1977: 'V77', 1976: 'V2359', }, descr='Salary received in", "computed in PNAD as V4718 (yr > 1992) return sum_na(df.income_work_main_money, df.income_work_main_products) # #", "income_work_main_products = IncomeField({ (1992, ...): 'V9535', (1981, 1990): 'V538', 1979: 'V2339', 1978: 'V2447',", "# income_rent = IncomeField({ (1992, ...): 'V1267', (1981, 1990): 'V581', 1979: 'V2363', 1978:", "None, }, descr='') occupation_first = Field({(1992, ...): 'V1298', (..., 1990): None, }, descr='')", "primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social security # income_retirement_main =", "work_duration = Field({(1992, ...): 'V4707', (..., 1990): None, }, descr='') @FunctionField def occupation(self,", "income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def", "1977: 'V95', 1976: None, }, descr='All sources of financial yield except for rents')", "None, (1981, 1990): 'V582', (1978, 1979): None, 1977: 'V96', 1976: 'V2366', }, descr='')", "descr='Variable part of monthly salary') income_work_main_products = IncomeField({ (1992, ...): 'V9535', (1981, 1990):", "1979: 'V2319', 1978: 'V2428', 1977: 'V85', 1976: 'V2362', }, descr='') income_work_extra_money_variable = IncomeField({", "total @FunctionField def income(self, df): \"\"\"Total income of an individual\"\"\" return sum_na(df.income_work, df.income_social,", "@FunctionField def income_misc(self, df): return sum_na(df.income_donation, df.income_other) # # Total incomes # @FunctionField", "\"\"\"Sum of fixed + variable money income from main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed)", "income_work_extra_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed,", "'V578', 1979: 'V2350', 1978: 'V2479', 1977: 'V90', 1976: 'V2365', # actually, this is", "sum_na(df.income_rent, df.income_investiments) if self.year == 1977: sum_na(df.V94, df.V97) return total # Other income", "}, descr='') @FunctionField def income_work_extra_money(self, df): \"\"\"Total income from jobs other than primary", "and household # income_household = IncomeField( {(1992, ...): 'V4721', (1981, 1990): 'V410', (...,", "monthly salary') income_work_main_products = IncomeField({ (1992, ...): 'V9535', (1981, 1990): 'V538', 1979: 'V2339',", "\"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField", "income_rent = IncomeField({ (1992, ...): 'V1267', (1981, 1990): 'V581', 1979: 'V2363', 1978: 'V2482',", "df): \"\"\"All sources of capital income\"\"\" total = sum_na(df.income_rent, df.income_investiments) if self.year ==", "\"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products) # # Other jobs #", "and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self, df): \"\"\"Total income from jobs", "income # income_rent = IncomeField({ (1992, ...): 'V1267', (1981, 1990): 'V581', 1979: 'V2363',", "# OUTR. REC. EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483', 1977: 'V95', 1976: None, },", "(..., 1990): None, }, descr='') occupation_secondary = Field({(1992, ...): 'V9990', (..., 1990): None,", "return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df): \"\"\"Total income from jobs other than", "as V4719 (yr > 1992) total = sum_na(df.income_work_main, df.income_work_other) # These are used", "people who # do not want to declare each job separately if self.year", "descr='') income_family_per_capta = IncomeField( {(1992, ...): 'V4750', (1981, 1990): None, (..., 1979): None,", "1990): 'V550', 1979: 'V2350', 1978: 'V2469', 1977: 'V87', 1976: None, }, descr='') @FunctionField", "and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self, df): \"\"\"Total income from jobs", "1977: 'V77', 1976: 'V2359', }, descr='Salary received in products') @FunctionField def income_work_main_money(self, df):", "1979: 'V2318', 1978: 'V2426', 1977: 'V75', 1976: 'V2308', }, descr='Fixed monthly salary') income_work_main_money_variable", "'V1298', (..., 1990): None, }, descr='') occupation_father = Field({(1992, ...): 'V1293', (..., 1990):", "jobs other than primary and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self, df):", "None, }, descr='') income_family_per_capta = IncomeField( {(1992, ...): 'V4750', (1981, 1990): None, (...,", "'V9532', (1981, 1990): 'V537', 1979: 'V2318', 1978: 'V2426', 1977: 'V75', 1976: 'V2308', },", "sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df): \"\"\"Total income from jobs other than primary", "= IncomeField({ (1992, ...): 'V1273', (..., 1990): None, # does it have a", "1990): 'V582', (1978, 1979): None, 1977: 'V96', 1976: 'V2366', }, descr='') income_donation =", "OccupationDataMixin: occupation_week = Field({(1992, ...): 'V9906', (..., 1990): 'V503', }, descr='Occupation at the", "and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df): \"\"\"Total income from jobs", "{(1992, ...): 'V4722', (1981, 1990): 'V5010', (..., 1979): None, }, descr='') income_household_per_capta =", "1990): 'V578', 1979: 'V2350', 1978: 'V2479', 1977: 'V90', 1976: 'V2365', # actually, this", "income_work(self, df): # @NoSelf \"\"\"Sum of all income sources due to labor\"\"\" #", "primary and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self, df): \"\"\"Total income from", "jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self, df):", "incomes # @FunctionField def income_work(self, df): # @NoSelf \"\"\"Sum of all income sources", "'V4742', (1981, 1990): None, (..., 1979): None, }, descr='') income_family_per_capta = IncomeField( {(1992,", "return total @FunctionField def income(self, df): \"\"\"Total income of an individual\"\"\" return sum_na(df.income_work,", "do not want to declare each job separately if self.year > 1992 and", "'V2427', (..., 1978): None, }, descr='Salary of secondary job (fixed part)') income_work_secondary_money_variable =", "1979: 'V2457', (..., 1978): None, }, descr='Salary of secondary job (variable)') income_work_secondary_products =", "{(1992, ...): 'V4742', (1981, 1990): None, (..., 1979): None, }, descr='') income_family_per_capta =", "'V2458', (..., 1978): None, }, descr='Salary of secondary job (products)') @FunctionField def income_work_secondary_money(self,", "Field({(1992, ...): 'V9910', (..., 1990): None, }, descr='') occupation_first = Field({(1992, ...): 'V1298',", "pension }, descr='') income_retirement_other = IncomeField({ (1992, ...): 'V1258', (..., 1990): None, },", "1979: 'V2350', 1978: 'V2469', 1977: 'V87', 1976: None, }, descr='') @FunctionField def income_work_extra_money(self,", "1976: None, }, descr='') income_pension_other = IncomeField({ (1992, ...): 'V1261', (..., 1990): None,", "= IncomeField({ (1981, ...): None, # do not ask this in recent surveys", "IncomeField({ (1992, ...): 'V1022', (1981, 1990): 'V549', 1979: 'V2319', 1978: 'V2428', 1977: 'V85',", "not ask this in recent surveys 1979: 'V2338', 1978: 'V2446', 1977: 'V76', 1976:", "df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df): \"\"\"Total income from jobs other than primary and", "IncomeField({ (1992, ...): None, (1981, 1990): None, 1979: 'V2349', 1978: 'V2468', 1977: 'V86',", "descr='') income_pension_other = IncomeField({ (1992, ...): 'V1261', (..., 1990): None, }, descr='') income_permanence_bonus", "are used to quantify total income due to work for people who #", "1976: 'V2359', }, descr='Salary received in products') @FunctionField def income_work_main_money(self, df): \"\"\"Sum of", "df.income_work_extra_products) @FunctionField def income_work_other_money(self, df): \"\"\"Total income from jobs other than primary and", "V4719 (yr > 1992) total = sum_na(df.income_work_main, df.income_work_other) # These are used to", "occupation_father = Field({(1992, ...): 'V1293', (..., 1990): None, }, descr='') occupation_father_previous = Field({(1992,", "(..., 1990): None, # does it have a better description? # OUTR. REC.", "df.income_misc) # # Family and household # income_household = IncomeField( {(1992, ...): 'V4721',", "1990): 'V503', }, descr='Occupation at the week the survey was taken') occupation_year =", "df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df):", "1977: 'V96', 1976: 'V2366', }, descr='') income_donation = IncomeField({ (1992, ...): 'V1270', (1981,", "1978: 'V2480', 1977: 'V91', 1976: None, }, descr='') income_pension_other = IncomeField({ (1992, ...):", "1990): 'V579', 1979: None, 1978: 'V2480', 1977: 'V91', 1976: None, }, descr='') income_pension_other", "def income_work(self, df): # @NoSelf \"\"\"Sum of all income sources due to labor\"\"\"", "class IncomeDataMixin: \"\"\" All income-related variables \"\"\" year: int # # Main job", "'V1258', (..., 1990): None, }, descr='') income_pension_main = IncomeField({ (1992, ...): 'V1255', (1981,", "income sources due to labor\"\"\" # Also computed in PNAD as V4719 (yr", "@FunctionField def income_work_other_products(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\"", "(products)') @FunctionField def income_work_secondary_money(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable)", "1978: 'V2468', 1977: 'V86', 1976: None, }, descr='') income_work_extra_products = IncomeField({ (1992, ...):", "secondary job (variable)') income_work_secondary_products = IncomeField( {(1992, ...): 'V9985', (1980, 1990): None, 1979:", "(1981, 1990): 'V582', (1978, 1979): None, 1977: 'V96', 1976: 'V2366', }, descr='') income_donation", "# # Secondary job # income_work_secondary_money_fixed = IncomeField( {(1992, ...): 'V9982', (1980, 1990):", "computed in PNAD as V4719 (yr > 1992) total = sum_na(df.income_work_main, df.income_work_other) #", "df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_secondary_money)", "sources due to labor\"\"\" # Also computed in PNAD as V4719 (yr >", "return sum_na(df.income_work_other_money, df.income_work_other_products) @FunctionField def income_work_money(self, df): \"\"\"Total income from jobs other than", "sum_na(df.V94, df.V97) return total # Other income sources #################################################### income_other = IncomeField({ (1992,", "(1992, ...): 'V1022', (1981, 1990): 'V549', 1979: 'V2319', 1978: 'V2428', 1977: 'V85', 1976:", "df and 'V7125' in df: T = IncomeField.remove_missing total = sum_na(total, T(df.V7122), T(df.V7125))", "than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self, df): \"\"\"Total income", "...): 'V1264', (1981, 1990): 'V580', (..., 1979): None}, descr='Paid to workers that can", "self.year > 1992 and 'V7122' in df and 'V7125' in df: T =", "(..., 1990): None, }, descr='') is_active = Field({(1992, ...): 'V4704', (..., 1990): None,", "(yr > 1992) total = sum_na(df.income_work_main, df.income_work_other) # These are used to quantify", "to continue working', ) @FunctionField def income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def", "'V4704', (..., 1990): None, }, descr='') work_duration = Field({(1992, ...): 'V4707', (..., 1990):", "1990): None, }, descr='') is_active = Field({(1992, ...): 'V4704', (..., 1990): None, },", "1978: 'V2446', 1977: 'V76', 1976: 'V2358', }, descr='Variable part of monthly salary') income_work_main_products", "continue working', ) @FunctionField def income_pension(self, df): return sum_na(df.income_pension_main, df.income_pension_other) @FunctionField def income_retirement(self,", "@FunctionField def income_work(self, df): # @NoSelf \"\"\"Sum of all income sources due to", "@FunctionField def income_work_main_money(self, df): \"\"\"Sum of fixed + variable money income from main", "df.income_work_secondary_products) @FunctionField def income_work_other(self, df): \"\"\"Total income from jobs other than primary and", "'V92', 1976: 'V2364', }, descr='') @FunctionField def income_misc(self, df): return sum_na(df.income_donation, df.income_other) #", "income_work_extra(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money,", "@FunctionField def income_work_other_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\"", "(1992, ...): 'V9535', (1981, 1990): 'V538', 1979: 'V2339', 1978: 'V2447', 1977: 'V77', 1976:", "'V2480', 1977: 'V91', 1976: None, }, descr='') income_pension_other = IncomeField({ (1992, ...): 'V1261',", "'V2319', 1978: 'V2428', 1977: 'V85', 1976: 'V2362', }, descr='') income_work_extra_money_variable = IncomeField({ (1992,", "df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_other_money, df.income_work_other_products)", "products') @FunctionField def income_work_main_money(self, df): \"\"\"Sum of fixed + variable money income from", "at the week the survey was taken') occupation_year = Field({(1992, ...): 'V9971', (...,", "1977: 'V93', 1976: 'V2363', }, descr='') income_investments = IncomeField({ (1992, ...): 'V1273', (...,", "None, }, descr='') work_duration = Field({(1992, ...): 'V4707', (..., 1990): None, }, descr='')", "def income_work_other_products(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return", "other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social security #", "'V2350', 1978: 'V2469', 1977: 'V87', 1976: None, }, descr='') @FunctionField def income_work_extra_money(self, df):", "(..., 1979): None, }, descr='') income_family = IncomeField( {(1992, ...): 'V4722', (1981, 1990):", "(1981, 1990): None, (..., 1979): None, }, descr='') class OccupationDataMixin: occupation_week = Field({(1992,", "'V579', 1979: None, 1978: 'V2480', 1977: 'V91', 1976: None, }, descr='') income_pension_other =", "= IncomeField.remove_missing total = sum_na(total, T(df.V7122), T(df.V7125)) return total @FunctionField def income(self, df):", "= sum_na(total, T(df.V7122), T(df.V7125)) return total @FunctionField def income(self, df): \"\"\"Total income of", "}, descr='') occupation_first = Field({(1992, ...): 'V1298', (..., 1990): None, }, descr='') occupation_father", "1976: None, }, descr='All sources of financial yield except for rents') @FunctionField def", "+ variable money income from main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self,", "PNAD as V4718 (yr > 1992) return sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary job", "'V5010', (..., 1979): None, }, descr='') income_household_per_capta = IncomeField( {(1992, ...): 'V4742', (1981,", "Field({(1992, ...): 'V9971', (..., 1990): None, }, descr='') occupation_secondary = Field({(1992, ...): 'V9990',", "+ pension }, descr='') income_retirement_other = IncomeField({ (1992, ...): 'V1258', (..., 1990): None,", "1990): 'V5010', (..., 1979): None, }, descr='') income_household_per_capta = IncomeField( {(1992, ...): 'V4742',", "descr='Paid to workers that can retire, but decide to continue working', ) @FunctionField", "df.income_work_extra_money_variable) @FunctionField def income_work_extra(self, df): \"\"\"Total income from jobs other than primary and", "'V582', (1978, 1979): None, 1977: 'V96', 1976: 'V2366', }, descr='') income_donation = IncomeField({", "}, descr='') income_investments = IncomeField({ (1992, ...): 'V1273', (..., 1990): None, # does", "income_donation = IncomeField({ (1992, ...): 'V1270', (1981, 1990): None, 1979: 'V2362', 1978: 'V2481',", "= IncomeField( {(1992, ...): 'V4722', (1981, 1990): 'V5010', (..., 1979): None, }, descr='')", "(1981, 1990): 'V5010', (..., 1979): None, }, descr='') income_household_per_capta = IncomeField( {(1992, ...):", "income_work_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money,", "IncomeField( {(1992, ...): 'V9982', (1980, 1990): None, 1979: 'V2427', (..., 1978): None, },", "Field({(1992, ...): 'V9990', (..., 1990): None, }, descr='') occupation_previous = Field({(1992, ...): 'V9910',", "'V537', 1979: 'V2318', 1978: 'V2426', 1977: 'V75', 1976: 'V2308', }, descr='Fixed monthly salary')", "def income_work_extra(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return", "'V9982', (1980, 1990): None, 1979: 'V2427', (..., 1978): None, }, descr='Salary of secondary", "1992 and 'V7122' in df and 'V7125' in df: T = IncomeField.remove_missing total", "1976: 'V2358', }, descr='Variable part of monthly salary') income_work_main_products = IncomeField({ (1992, ...):", "1978: 'V2447', 1977: 'V77', 1976: 'V2359', }, descr='Salary received in products') @FunctionField def", "# do not ask this in recent surveys 1979: 'V2338', 1978: 'V2446', 1977:", "Other income sources #################################################### income_other = IncomeField({ (1992, ...): None, (1981, 1990): 'V582',", "\"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable) @FunctionField", "1990): None, 1979: 'V2458', (..., 1978): None, }, descr='Salary of secondary job (products)')", "individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) # # Family and household # income_household", "'V2446', 1977: 'V76', 1976: 'V2358', }, descr='Variable part of monthly salary') income_work_main_products =", "'V2426', 1977: 'V75', 1976: 'V2308', }, descr='Fixed monthly salary') income_work_main_money_variable = IncomeField({ (1981,", "income_retirement_other = IncomeField({ (1992, ...): 'V1258', (..., 1990): None, }, descr='') income_pension_main =", "df.income_social, df.income_capital, df.income_misc) # # Family and household # income_household = IncomeField( {(1992,", "secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social security # income_retirement_main = IncomeField({ (1992,", "income_work_extra_money_fixed = IncomeField({ (1992, ...): 'V1022', (1981, 1990): 'V549', 1979: 'V2319', 1978: 'V2428',", "descr='') @FunctionField def income_work_extra_money(self, df): \"\"\"Total income from jobs other than primary and", "1990): None, }, descr='') work_duration = Field({(1992, ...): 'V4707', (..., 1990): None, },", "1977: 'V85', 1976: 'V2362', }, descr='') income_work_extra_money_variable = IncomeField({ (1992, ...): None, (1981,", "descr='Salary of secondary job (products)') @FunctionField def income_work_secondary_money(self, df): \"\"\"Total income from secondary", "'V2364', }, descr='') @FunctionField def income_misc(self, df): return sum_na(df.income_donation, df.income_other) # # Total", "sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def income_work_other_money(self, df): \"\"\"Total income from jobs other than primary", "of secondary job (fixed part)') income_work_secondary_money_variable = IncomeField( {(1980, ...): None, 1979: 'V2457',", "income_work_other_money(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money,", "descr='') income_work_extra_money_variable = IncomeField({ (1992, ...): None, (1981, 1990): None, 1979: 'V2349', 1978:", "1978: 'V2481', 1977: 'V92', 1976: 'V2364', }, descr='') @FunctionField def income_misc(self, df): return", "each job separately if self.year > 1992 and 'V7122' in df and 'V7125'", "= Field({(1992, ...): 'V9906', (..., 1990): 'V503', }, descr='Occupation at the week the", "occupation_previous = Field({(1992, ...): 'V9910', (..., 1990): None, }, descr='') occupation_first = Field({(1992,", "1979: 'V2350', 1978: 'V2479', 1977: 'V90', 1976: 'V2365', # actually, this is retirement", "'V2363', }, descr='') income_investments = IncomeField({ (1992, ...): 'V1273', (..., 1990): None, #", "...): 'V1255', (1981, 1990): 'V579', 1979: None, 1978: 'V2480', 1977: 'V91', 1976: None,", "income(self, df): \"\"\"Total income of an individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) #", "IncomeField({ (1992, ...): 'V1252', (1981, 1990): 'V578', 1979: 'V2350', 1978: 'V2479', 1977: 'V90',", "labor\"\"\" # Also computed in PNAD as V4719 (yr > 1992) total =", "taken') occupation_year = Field({(1992, ...): 'V9971', (..., 1990): None, }, descr='') occupation_secondary =", "to quantify total income due to work for people who # do not", "1979): None, 1977: 'V96', 1976: 'V2366', }, descr='') income_donation = IncomeField({ (1992, ...):", "None, }, descr='') is_active = Field({(1992, ...): 'V4704', (..., 1990): None, }, descr='')", "(..., 1990): None, }, descr='') income_pension_main = IncomeField({ (1992, ...): 'V1255', (1981, 1990):", "1990): None, 1979: 'V2427', (..., 1978): None, }, descr='Salary of secondary job (fixed", "(yr > 1992) return sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary job # income_work_secondary_money_fixed =", "descr='') occupation_previous = Field({(1992, ...): 'V9910', (..., 1990): None, }, descr='') occupation_first =", "}, descr='') income_family = IncomeField( {(1992, ...): 'V4722', (1981, 1990): 'V5010', (..., 1979):", "'V76', 1976: 'V2358', }, descr='Variable part of monthly salary') income_work_main_products = IncomeField({ (1992,", "'V2468', 1977: 'V86', 1976: None, }, descr='') income_work_extra_products = IncomeField({ (1992, ...): 'V1025',", "df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money_fixed, df.income_work_extra_money_variable)", "# These are used to quantify total income due to work for people", "1978: 'V2482', 1977: 'V93', 1976: 'V2363', }, descr='') income_investments = IncomeField({ (1992, ...):", "income_capital(self, df): \"\"\"All sources of capital income\"\"\" total = sum_na(df.income_rent, df.income_investiments) if self.year", "T = IncomeField.remove_missing total = sum_na(total, T(df.V7122), T(df.V7125)) return total @FunctionField def income(self,", "= IncomeField({ (1992, ...): 'V1255', (1981, 1990): 'V579', 1979: None, 1978: 'V2480', 1977:", "== 1977: sum_na(df.V94, df.V97) return total # Other income sources #################################################### income_other =", "main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df): \"\"\"Total income from main", "retire, but decide to continue working', ) @FunctionField def income_pension(self, df): return sum_na(df.income_pension_main,", "'V2308', }, descr='Fixed monthly salary') income_work_main_money_variable = IncomeField({ (1981, ...): None, # do", "in products') @FunctionField def income_work_main_money(self, df): \"\"\"Sum of fixed + variable money income", "income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) # #", "(..., 1978): None, }, descr='Salary of secondary job (variable)') income_work_secondary_products = IncomeField( {(1992,", "jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social security", "does it have a better description? # OUTR. REC. EMPREG.CAPITA 1979: 'V2361', 1978:", "...): 'V4722', (1981, 1990): 'V5010', (..., 1979): None, }, descr='') income_household_per_capta = IncomeField(", "used to quantify total income due to work for people who # do", "1990): None, }, descr='') occupation_secondary = Field({(1992, ...): 'V9990', (..., 1990): None, },", "return sum_na(df.income_work_main_money, df.income_work_main_products) # # Secondary job # income_work_secondary_money_fixed = IncomeField( {(1992, ...):", "descr='Fixed monthly salary') income_work_main_money_variable = IncomeField({ (1981, ...): None, # do not ask", "1990): 'V580', (..., 1979): None}, descr='Paid to workers that can retire, but decide", "income_work_secondary_products = IncomeField( {(1992, ...): 'V9985', (1980, 1990): None, 1979: 'V2458', (..., 1978):", "income_pension_main = IncomeField({ (1992, ...): 'V1255', (1981, 1990): 'V579', 1979: None, 1978: 'V2480',", "sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self, df): \"\"\"Total income from jobs other than primary", "1990): None, 1979: 'V2362', 1978: 'V2481', 1977: 'V92', 1976: 'V2364', }, descr='') @FunctionField", "income of an individual\"\"\" return sum_na(df.income_work, df.income_social, df.income_capital, df.income_misc) # # Family and", "IncomeField( {(1992, ...): 'V4750', (1981, 1990): None, (..., 1979): None, }, descr='') class", "income_work_other(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_other_money,", "IncomeField({ (1992, ...): 'V1270', (1981, 1990): None, 1979: 'V2362', 1978: 'V2481', 1977: 'V92',", "household # income_household = IncomeField( {(1992, ...): 'V4721', (1981, 1990): 'V410', (..., 1979):", "descr='') income_family = IncomeField( {(1992, ...): 'V4722', (1981, 1990): 'V5010', (..., 1979): None,", "sum_na(df.income_work_extra_money, df.income_work_secondary_money) @FunctionField def income_work_other_products(self, df): \"\"\"Total income from jobs other than primary", "# Secondary job # income_work_secondary_money_fixed = IncomeField( {(1992, ...): 'V9982', (1980, 1990): None,", "...): 'V9971', (..., 1990): None, }, descr='') occupation_secondary = Field({(1992, ...): 'V9990', (...,", "# # Capital income # income_rent = IncomeField({ (1992, ...): 'V1267', (1981, 1990):", "work for people who # do not want to declare each job separately", "= Field({(1992, ...): 'V9990', (..., 1990): None, }, descr='') occupation_previous = Field({(1992, ...):", "sum_na(df.income_donation, df.income_other) # # Total incomes # @FunctionField def income_work(self, df): # @NoSelf", "(..., 1990): None, }, descr='') is_occupied = Field({(1992, ...): 'V4705', (..., 1990): None,", "surveys 1979: 'V2338', 1978: 'V2446', 1977: 'V76', 1976: 'V2358', }, descr='Variable part of", "return sum_na(df.income_retirement_main, df.income_retirement_other) @FunctionField def income_social(self, df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # #", "income_retirement_main = IncomeField({ (1992, ...): 'V1252', (1981, 1990): 'V578', 1979: 'V2350', 1978: 'V2479',", "1976: 'V2308', }, descr='Fixed monthly salary') income_work_main_money_variable = IncomeField({ (1981, ...): None, #", "(..., 1979): None}, descr='Paid to workers that can retire, but decide to continue", "Main job # income_work_main_money_fixed = IncomeField({ (1992, ...): 'V9532', (1981, 1990): 'V537', 1979:", "...): 'V9982', (1980, 1990): None, 1979: 'V2427', (..., 1978): None, }, descr='Salary of", "# Other income sources #################################################### income_other = IncomeField({ (1992, ...): None, (1981, 1990):", "income_family = IncomeField( {(1992, ...): 'V4722', (1981, 1990): 'V5010', (..., 1979): None, },", "}, descr='') work_duration = Field({(1992, ...): 'V4707', (..., 1990): None, }, descr='') @FunctionField", "fixed + variable money income from main job\"\"\" return sum_na(df.income_work_main_money_variable, df.income_work_main_money_fixed) @FunctionField def", "df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money)", "# @FunctionField def income_work(self, df): # @NoSelf \"\"\"Sum of all income sources due", "return sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social security # income_retirement_main = IncomeField({ (1992, ...):", "df.income_work_secondary_products) # # Other jobs # income_work_extra_money_fixed = IncomeField({ (1992, ...): 'V1022', (1981,", "income_work_products(self, df): \"\"\"Total income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products,", "sum_na(df.income_work_main, df.income_work_other) # These are used to quantify total income due to work", "descr='') is_occupied = Field({(1992, ...): 'V4705', (..., 1990): None, }, descr='') is_active =", "income_permanence_bonus = IncomeField( {(1992, ...): 'V1264', (1981, 1990): 'V580', (..., 1979): None}, descr='Paid", "df.income_work_main_money_fixed) @FunctionField def income_work_main(self, df): \"\"\"Total income from main work\"\"\" # Also computed", "df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df): \"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money, df.income_work_secondary_products)", "...): 'V9985', (1980, 1990): None, 1979: 'V2458', (..., 1978): None, }, descr='Salary of", "None, }, descr='All sources of financial yield except for rents') @FunctionField def income_capital(self,", "'V2479', 1977: 'V90', 1976: 'V2365', # actually, this is retirement + pension },", "}, descr='Salary of secondary job (fixed part)') income_work_secondary_money_variable = IncomeField( {(1980, ...): None,", "income_pension_other = IncomeField({ (1992, ...): 'V1261', (..., 1990): None, }, descr='') income_permanence_bonus =", "'V2481', 1977: 'V92', 1976: 'V2364', }, descr='') @FunctionField def income_misc(self, df): return sum_na(df.income_donation,", "# # Social security # income_retirement_main = IncomeField({ (1992, ...): 'V1252', (1981, 1990):", "@FunctionField def income_social(self, df): return sum_na(df.income_pension, df.income_retirement, df.income_permanence_bonus) # # Capital income #", "recent surveys 1979: 'V2338', 1978: 'V2446', 1977: 'V76', 1976: 'V2358', }, descr='Variable part", "of financial yield except for rents') @FunctionField def income_capital(self, df): \"\"\"All sources of", "'V2339', 1978: 'V2447', 1977: 'V77', 1976: 'V2359', }, descr='Salary received in products') @FunctionField", "descr='') occupation_father_previous = Field({(1992, ...): 'V1258', (..., 1990): None, }, descr='') is_occupied =", "1978): None, }, descr='Salary of secondary job (fixed part)') income_work_secondary_money_variable = IncomeField( {(1980,", "1990): 'V537', 1979: 'V2318', 1978: 'V2426', 1977: 'V75', 1976: 'V2308', }, descr='Fixed monthly", "sum_na(df.income_work_extra_products, df.income_work_main_products) # # Social security # income_retirement_main = IncomeField({ (1992, ...): 'V1252',", "in df: T = IncomeField.remove_missing total = sum_na(total, T(df.V7122), T(df.V7125)) return total @FunctionField", "...): 'V4742', (1981, 1990): None, (..., 1979): None, }, descr='') income_family_per_capta = IncomeField(", "total = sum_na(df.income_rent, df.income_investiments) if self.year == 1977: sum_na(df.V94, df.V97) return total #", "(..., 1979): None, }, descr='') income_household_per_capta = IncomeField( {(1992, ...): 'V4742', (1981, 1990):", "None, }, descr='') income_work_extra_products = IncomeField({ (1992, ...): 'V1025', (1981, 1990): 'V550', 1979:", "income from jobs other than primary and secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_extra_products) @FunctionField def", "}, descr='') income_donation = IncomeField({ (1992, ...): 'V1270', (1981, 1990): None, 1979: 'V2362',", "income from main work\"\"\" # Also computed in PNAD as V4718 (yr >", "...): 'V1261', (..., 1990): None, }, descr='') income_permanence_bonus = IncomeField( {(1992, ...): 'V1264',", "descr='') occupation_father = Field({(1992, ...): 'V1293', (..., 1990): None, }, descr='') occupation_father_previous =", "1990): 'V538', 1979: 'V2339', 1978: 'V2447', 1977: 'V77', 1976: 'V2359', }, descr='Salary received", "to workers that can retire, but decide to continue working', ) @FunctionField def", "@FunctionField def income_capital(self, df): \"\"\"All sources of capital income\"\"\" total = sum_na(df.income_rent, df.income_investiments)", "\"\"\"Total income from main work\"\"\" # Also computed in PNAD as V4718 (yr", "= IncomeField({ (1992, ...): 'V1270', (1981, 1990): None, 1979: 'V2362', 1978: 'V2481', 1977:", "\"\"\"Total income from secondary job\"\"\" return sum_na(df.income_work_secondary_money_fixed, df.income_work_secondary_money_variable) @FunctionField def income_work_secondary(self, df): \"\"\"Total", "# Also computed in PNAD as V4718 (yr > 1992) return sum_na(df.income_work_main_money, df.income_work_main_products)", "IncomeField( {(1992, ...): 'V4721', (1981, 1990): 'V410', (..., 1979): None, }, descr='') income_family", "EMPREG.CAPITA 1979: 'V2361', 1978: 'V2483', 1977: 'V95', 1976: None, }, descr='All sources of", "of capital income\"\"\" total = sum_na(df.income_rent, df.income_investiments) if self.year == 1977: sum_na(df.V94, df.V97)", "}, descr='Salary of secondary job (variable)') income_work_secondary_products = IncomeField( {(1992, ...): 'V9985', (1980,", "#################################################### income_other = IncomeField({ (1992, ...): None, (1981, 1990): 'V582', (1978, 1979): None,", "df.income_work_other) # These are used to quantify total income due to work for", "1990): None, }, descr='') occupation_father = Field({(1992, ...): 'V1293', (..., 1990): None, },", "None, }, descr='') occupation_father_previous = Field({(1992, ...): 'V1258', (..., 1990): None, }, descr='')", "# Main job # income_work_main_money_fixed = IncomeField({ (1992, ...): 'V9532', (1981, 1990): 'V537',", "income due to work for people who # do not want to declare", "due to work for people who # do not want to declare each", "income_household = IncomeField( {(1992, ...): 'V4721', (1981, 1990): 'V410', (..., 1979): None, },", "secondary\"\"\" return sum_na(df.income_work_extra_money, df.income_work_main_money) @FunctionField def income_work_products(self, df): \"\"\"Total income from jobs other", "{(1992, ...): 'V4721', (1981, 1990): 'V410', (..., 1979): None, }, descr='') income_family =", "= sum_na(df.income_rent, df.income_investiments) if self.year == 1977: sum_na(df.V94, df.V97) return total # Other", "> 1992) total = sum_na(df.income_work_main, df.income_work_other) # These are used to quantify total", "(1981, 1990): None, (..., 1979): None, }, descr='') income_family_per_capta = IncomeField( {(1992, ...):", "(1992, ...): 'V1025', (1981, 1990): 'V550', 1979: 'V2350', 1978: 'V2469', 1977: 'V87', 1976:", "1976: None, }, descr='') @FunctionField def income_work_extra_money(self, df): \"\"\"Total income from jobs other", "1979): None, }, descr='') income_family = IncomeField( {(1992, ...): 'V4722', (1981, 1990): 'V5010',", "quantify total income due to work for people who # do not want", "other than primary and secondary\"\"\" return sum_na(df.income_work_extra_products, df.income_work_secondary_products) @FunctionField def income_work_other(self, df): \"\"\"Total", "descr='') income_investments = IncomeField({ (1992, ...): 'V1273', (..., 1990): None, # does it", "IncomeField({ (1992, ...): 'V1273', (..., 1990): None, # does it have a better", "= IncomeField({ (1992, ...): 'V1025', (1981, 1990): 'V550', 1979: 'V2350', 1978: 'V2469', 1977:" ]
[ "__init__(self): \"\"\" Los indicadores de empleo y desocupacion se basan en gran medida", "#transform string to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set", "de los salarios de la economia Base octubre 2016 Returns ------- pd.DataFrame(). \"\"\"", "index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\" Se calcula", "def __init__(self): \"\"\" Los indicadores de empleo y desocupacion se basan en gran", "df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaEmpleo(self, periodo = \"Anual\"): \"\"\"", "medida en la EPC (encuesta permanente de hogares) en 31 aglomeraciones urbanas. \"\"\"", "urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 0 #si no", "url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources']", "def getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada demandante/PEA Parameters", "getIndiceSalariosBase2016(self): \"\"\" Es un indice que estima la evolucion de los salarios de", "getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada NO demandante/PEA Parameters", "requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform string to datetime df_temp['indice_tiempo'] =", "if periodo == \"Trimestral\" else 0 #si no es trimestral siempre es anual", "class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los indicadores de empleo y desocupacion se basan", "format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaDesocupacion(self,", "\"Anual\", \"Trimestral\") DESCRIPTION. The default is \"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la", "{}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url con cvs y generar pandas dataframe contenidoCVS", "periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada NO demandante/PEA Parameters ----------", "de actividad es PEA/PoblacionTotal Se considera como una tasa indicadora de la oferta", "objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo == \"Trimestral\"", "DESCRIPTION. The default is \"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de", "\"Anual\"): \"\"\" La tasa de actividad es PEA/PoblacionTotal Se considera como una tasa", "empleo se calcula como poblacion ocupada/poblacion total Se concidera como una tasa representativa", "empleo y desocupacion se basan en gran medida en la EPC (encuesta permanente", "los trabajadores. Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION.", "selector = 1 if periodo == \"Trimestral\" else 0 #si no es trimestral", "print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url con cvs y generar pandas dataframe contenidoCVS =", "inplace=True) return df_temp def getTasaEmpleo(self, periodo = \"Anual\"): \"\"\" La tasa de empleo", "del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 0", "df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\"", "o mensual siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion =", "index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula", "evolucion de los salarios de la economia Base octubre 2016 Returns ------- pd.DataFrame().", "de la demanda laboral ejercida por la empresas. Parameters ---------- periodo : str,", "index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getIndiceSalariosBase2016(self): \"\"\" Es un indice que estima", "= io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform string to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d',", "de los trabajadores. Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\")", "de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector", "== \"Trimestral\" else 0 #si no es trimestral siempre es anual ultimoResultado =", "df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getIndiceSalariosBase2016(self): \"\"\" Es un indice", "= df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaEmpleo(self, periodo = \"Anual\"):", "#si no es trimestral siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url']", "como poblacion desocupada demandante/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\",", "\"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\"", "as pd import io import requests import json class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\"", "empresas. Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The", "df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaEmpleo(self, periodo = \"Anual\"): \"\"\" La tasa de", "La tasa de empleo se calcula como poblacion ocupada/poblacion total Se concidera como", "url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources']", "string to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index", "cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if", "------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson", "indicadores de empleo y desocupacion se basan en gran medida en la EPC", "df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaEmpleo(self, periodo =", "de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector", "return df_temp def getIndiceSalariosBase2016(self): \"\"\" Es un indice que estima la evolucion de", "y generar pandas dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS)", "PEA/PoblacionTotal Se considera como una tasa indicadora de la oferta laboral por parte", "\"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s)", "\"Anual\"): \"\"\" Se calcula como: poblacion desocupada/PEA Parameters ---------- periodo : str, optional", "la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado =", "trimestral siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description']", "= json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo == \"Trimestral\" else", "\"\"\" La tasa de empleo se calcula como poblacion ocupada/poblacion total Se concidera", "Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content", "\"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\"", "url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources']", "df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\"", "pd.read_csv(flujoCVS) #transform string to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date", "pass def getTasaActividad(self, periodo = \"Anual\"): \"\"\" La tasa de actividad es PEA/PoblacionTotal", "resultado = objJson['result']['resources'] selector = 0 #si no es trimestral o mensual siempre", "EPC (encuesta permanente de hogares) en 31 aglomeraciones urbanas. \"\"\" pass def getTasaActividad(self,", "se calcula como poblacion ocupada/poblacion total Se concidera como una tasa representativa de", "\"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\"", "permanente de hogares) en 31 aglomeraciones urbanas. \"\"\" pass def getTasaActividad(self, periodo =", "\"Anual\"): \"\"\" Se calcula como poblacion desocupada NO demandante/PEA Parameters ---------- periodo :", "Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content", "pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson =", "#set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\" Se", "periodo = \"Anual\"): \"\"\" La tasa de actividad es PEA/PoblacionTotal Se considera como", "urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo", "total Se concidera como una tasa representativa de la demanda laboral ejercida por", "cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if", "indicadora de la oferta laboral por parte de los trabajadores. Parameters ---------- periodo", "= requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform string to datetime df_temp['indice_tiempo']", "Se calcula como poblacion desocupada demandante/PEA Parameters ---------- periodo : str, optional (puede", "economia Base octubre 2016 Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga", "\"\"\" Los indicadores de empleo y desocupacion se basan en gran medida en", "de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector", "#Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado", "\"Trimestral\") DESCRIPTION. The default is \"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url", "\"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s)", "mensual siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description']", "requests import json class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los indicadores de empleo y", "= df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionDemandante(self, periodo = \"Anual\"):", "ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url con cvs y generar pandas", "format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionDemandante(self,", "def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada NO demandante/PEA", "is \"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs", "errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionDemandante(self, periodo", "<reponame>alejivo/Macroeconomics import pandas as pd import io import requests import json class IndicadoresEmpleoDesocupacion:", "Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content", "#set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaEmpleo(self, periodo = \"Anual\"): \"\"\" La", "str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The default is \"Anual\". Returns -------", "index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula", "inplace=True) return df_temp def getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion", "trabajadores. Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The", "hogares) en 31 aglomeraciones urbanas. \"\"\" pass def getTasaActividad(self, periodo = \"Anual\"): \"\"\"", "de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector", "\"Anual\"): \"\"\" La tasa de empleo se calcula como poblacion ocupada/poblacion total Se", "inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion", "31 aglomeraciones urbanas. \"\"\" pass def getTasaActividad(self, periodo = \"Anual\"): \"\"\" La tasa", "= 0 #si no es trimestral o mensual siempre es anual ultimoResultado =", "pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def", "como: poblacion desocupada/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\")", "objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 0 #si no es trimestral", "IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los indicadores de empleo y desocupacion se basan en", "por parte de los trabajadores. Parameters ---------- periodo : str, optional (puede ser", "2016 Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\"", "s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo ==", "#set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\" Se", "------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson", "urbanas. \"\"\" pass def getTasaActividad(self, periodo = \"Anual\"): \"\"\" La tasa de actividad", "la empresas. Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION.", "pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson =", "de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector", "del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1", "de la economia Base octubre 2016 Returns ------- pd.DataFrame(). \"\"\" #Obtener la url", "cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 0 #si", "#Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado", "def getIndiceSalariosBase2016(self): \"\"\" Es un indice que estima la evolucion de los salarios", "es PEA/PoblacionTotal Se considera como una tasa indicadora de la oferta laboral por", "#set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getIndiceSalariosBase2016(self): \"\"\" Es un indice que", "descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector =", "los salarios de la economia Base octubre 2016 Returns ------- pd.DataFrame(). \"\"\" #Obtener", "#si no es trimestral o mensual siempre es anual ultimoResultado = resultado[selector] urlDescarga", "format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaEmpleo(self,", "objJson['result']['resources'] selector = 1 if periodo == \"Trimestral\" else 0 #si no es", "desocupacion se basan en gran medida en la EPC (encuesta permanente de hogares)", "actividad es PEA/PoblacionTotal Se considera como una tasa indicadora de la oferta laboral", "\"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s)", "la EPC (encuesta permanente de hogares) en 31 aglomeraciones urbanas. \"\"\" pass def", "------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson", "\"Trimestral\" else 0 #si no es trimestral siempre es anual ultimoResultado = resultado[selector]", "se basan en gran medida en la EPC (encuesta permanente de hogares) en", "= df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"):", "la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado =", "descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector =", "La tasa de actividad es PEA/PoblacionTotal Se considera como una tasa indicadora de", "------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson", "0 #si no es trimestral o mensual siempre es anual ultimoResultado = resultado[selector]", "df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaDesocupacion(self, periodo =", "= \"Anual\"): \"\"\" La tasa de actividad es PEA/PoblacionTotal Se considera como una", ": str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The default is \"Anual\". Returns", "= \"Anual\"): \"\"\" Se calcula como: poblacion desocupada/PEA Parameters ---------- periodo : str,", "salarios de la economia Base octubre 2016 Returns ------- pd.DataFrame(). \"\"\" #Obtener la", "en gran medida en la EPC (encuesta permanente de hogares) en 31 aglomeraciones", "periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The default is \"Anual\".", "Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The default", "def getTasaEmpleo(self, periodo = \"Anual\"): \"\"\" La tasa de empleo se calcula como", "urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo", "ocupada/poblacion total Se concidera como una tasa representativa de la demanda laboral ejercida", "urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo", "trimestral o mensual siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion", "la oferta laboral por parte de los trabajadores. Parameters ---------- periodo : str,", "0 #si no es trimestral siempre es anual ultimoResultado = resultado[selector] urlDescarga =", "descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector =", "optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The default is \"Anual\". Returns ------- pd.DataFrame().", "#Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado", "en 31 aglomeraciones urbanas. \"\"\" pass def getTasaActividad(self, periodo = \"Anual\"): \"\"\" La", "de la oferta laboral por parte de los trabajadores. Parameters ---------- periodo :", "calcula como poblacion desocupada demandante/PEA Parameters ---------- periodo : str, optional (puede ser", "laboral por parte de los trabajadores. Parameters ---------- periodo : str, optional (puede", "json class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los indicadores de empleo y desocupacion se", "estima la evolucion de los salarios de la economia Base octubre 2016 Returns", "pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson =", "laboral ejercida por la empresas. Parameters ---------- periodo : str, optional (puede ser", "= df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getIndiceSalariosBase2016(self): \"\"\" Es un", "periodo == \"Trimestral\" else 0 #si no es trimestral siempre es anual ultimoResultado", "default is \"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del", "calcula como poblacion ocupada/poblacion total Se concidera como una tasa representativa de la", "es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion))", "como poblacion desocupada NO demandante/PEA Parameters ---------- periodo : str, optional (puede ser", "def getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\" Se calcula como: poblacion desocupada/PEA Parameters ----------", "poblacion desocupada NO demandante/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\",", "\"\"\" Se calcula como: poblacion desocupada/PEA Parameters ---------- periodo : str, optional (puede", "y desocupacion se basan en gran medida en la EPC (encuesta permanente de", "un indice que estima la evolucion de los salarios de la economia Base", "= \"Anual\"): \"\"\" La tasa de empleo se calcula como poblacion ocupada/poblacion total", "Es un indice que estima la evolucion de los salarios de la economia", "dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform string to", "parte de los trabajadores. Parameters ---------- periodo : str, optional (puede ser \"Anual\",", "aglomeraciones urbanas. \"\"\" pass def getTasaActividad(self, periodo = \"Anual\"): \"\"\" La tasa de", "import requests import json class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los indicadores de empleo", "Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content", "no es trimestral siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion", "tasa de actividad es PEA/PoblacionTotal Se considera como una tasa indicadora de la", "io import requests import json class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los indicadores de", "url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources']", "pandas dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform string", "getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\" Se calcula como: poblacion desocupada/PEA Parameters ---------- periodo", "= \"Anual\"): \"\"\" Se calcula como poblacion desocupada demandante/PEA Parameters ---------- periodo :", "como poblacion ocupada/poblacion total Se concidera como una tasa representativa de la demanda", "del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1", "else 0 #si no es trimestral siempre es anual ultimoResultado = resultado[selector] urlDescarga", "return df_temp def getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada", "la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado =", "la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado =", "basan en gran medida en la EPC (encuesta permanente de hogares) en 31", "inplace=True) return df_temp def getIndiceSalariosBase2016(self): \"\"\" Es un indice que estima la evolucion", "= ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url con", "demanda laboral ejercida por la empresas. Parameters ---------- periodo : str, optional (puede", "que estima la evolucion de los salarios de la economia Base octubre 2016", "no es trimestral o mensual siempre es anual ultimoResultado = resultado[selector] urlDescarga =", "= json.loads(s) resultado = objJson['result']['resources'] selector = 0 #si no es trimestral o", "pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson =", "la url con cvs y generar pandas dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS =", "del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1", "octubre 2016 Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs", "generar pandas dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform", "df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como", "pandas as pd import io import requests import json class IndicadoresEmpleoDesocupacion: def __init__(self):", "Base octubre 2016 Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del", "la economia Base octubre 2016 Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de", "de empleo se calcula como poblacion ocupada/poblacion total Se concidera como una tasa", "The default is \"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga", "flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform string to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'],", "periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada demandante/PEA Parameters ---------- periodo", "como una tasa indicadora de la oferta laboral por parte de los trabajadores.", "df_temp def getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada demandante/PEA", "def getTasaActividad(self, periodo = \"Anual\"): \"\"\" La tasa de actividad es PEA/PoblacionTotal Se", "\"\"\" pass def getTasaActividad(self, periodo = \"Anual\"): \"\"\" La tasa de actividad es", "descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector =", "con cvs y generar pandas dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp", "errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaEmpleo(self, periodo", "= ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url con cvs y generar", "desocupada NO demandante/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\")", "datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True)", "poblacion ocupada/poblacion total Se concidera como una tasa representativa de la demanda laboral", "inplace=True) return df_temp def getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\" Se calcula como: poblacion", "errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getIndiceSalariosBase2016(self): \"\"\"", "Se considera como una tasa indicadora de la oferta laboral por parte de", "(puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The default is \"Anual\". Returns ------- pd.DataFrame(). \"\"\"", "pd import io import requests import json class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los", "anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo:", "df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\" Se calcula como:", "format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getIndiceSalariosBase2016(self):", "= \"Anual\"): \"\"\" Se calcula como poblacion desocupada NO demandante/PEA Parameters ---------- periodo", "cvs y generar pandas dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp =", "de empleo y desocupacion se basan en gran medida en la EPC (encuesta", "url con cvs y generar pandas dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8'))", "getTasaEmpleo(self, periodo = \"Anual\"): \"\"\" La tasa de empleo se calcula como poblacion", "urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo", "getTasaActividad(self, periodo = \"Anual\"): \"\"\" La tasa de actividad es PEA/PoblacionTotal Se considera", "= objJson['result']['resources'] selector = 0 #si no es trimestral o mensual siempre es", "\"\"\" La tasa de actividad es PEA/PoblacionTotal Se considera como una tasa indicadora", "#Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado", "import json class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los indicadores de empleo y desocupacion", "s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 0 #si no es", "df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionDemandante(self, periodo =", "desocupada demandante/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION.", "Se calcula como: poblacion desocupada/PEA Parameters ---------- periodo : str, optional (puede ser", "cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if", "json.loads(s) resultado = objJson['result']['resources'] selector = 0 #si no es trimestral o mensual", "la demanda laboral ejercida por la empresas. Parameters ---------- periodo : str, optional", "df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self, periodo =", "desocupada/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The", "= pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp", "la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado =", "periodo = \"Anual\"): \"\"\" La tasa de empleo se calcula como poblacion ocupada/poblacion", "return df_temp def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada", "df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\"", "de hogares) en 31 aglomeraciones urbanas. \"\"\" pass def getTasaActividad(self, periodo = \"Anual\"):", "#Descargar la url con cvs y generar pandas dataframe contenidoCVS = requests.get(urlDescarga).content flujoCVS", "cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if", "\"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s)", "siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando:", "oferta laboral por parte de los trabajadores. Parameters ---------- periodo : str, optional", "indice que estima la evolucion de los salarios de la economia Base octubre", "descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector =", "#set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\" Se", "= objJson['result']['resources'] selector = 1 if periodo == \"Trimestral\" else 0 #si no", "url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources']", "objJson['result']['resources'] selector = 0 #si no es trimestral o mensual siempre es anual", "= 1 if periodo == \"Trimestral\" else 0 #si no es trimestral siempre", "representativa de la demanda laboral ejercida por la empresas. Parameters ---------- periodo :", "considera como una tasa indicadora de la oferta laboral por parte de los", "poblacion desocupada/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION.", "es trimestral o mensual siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url']", "errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaDesocupacion(self, periodo", "format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self,", "------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson", "df_temp = pd.read_csv(flujoCVS) #transform string to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo']", "pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson =", "return df_temp def getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\" Se calcula como: poblacion desocupada/PEA", "df_temp def getTasaDesocupacion(self, periodo = \"Anual\"): \"\"\" Se calcula como: poblacion desocupada/PEA Parameters", "return df_temp def getTasaEmpleo(self, periodo = \"Anual\"): \"\"\" La tasa de empleo se", "contenidoCVS = requests.get(urlDescarga).content flujoCVS = io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform string to datetime", "tasa representativa de la demanda laboral ejercida por la empresas. Parameters ---------- periodo", "ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga))", "descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector =", "es trimestral siempre es anual ultimoResultado = resultado[selector] urlDescarga = ultimoResultado['url'] descripcion =", "\"\"\" Es un indice que estima la evolucion de los salarios de la", "Se concidera como una tasa representativa de la demanda laboral ejercida por la", "urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo", "= resultado[selector] urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar", "concidera como una tasa representativa de la demanda laboral ejercida por la empresas.", "Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content", "del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1", "df_temp def getIndiceSalariosBase2016(self): \"\"\" Es un indice que estima la evolucion de los", "= pd.read_csv(flujoCVS) #transform string to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] =", "#Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado", "una tasa indicadora de la oferta laboral por parte de los trabajadores. Parameters", "resultado = objJson['result']['resources'] selector = 1 if periodo == \"Trimestral\" else 0 #si", "urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url", "------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson", "tasa de empleo se calcula como poblacion ocupada/poblacion total Se concidera como una", "\"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s)", "import pandas as pd import io import requests import json class IndicadoresEmpleoDesocupacion: def", "\"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\"", "\"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\"", "url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources']", "1 if periodo == \"Trimestral\" else 0 #si no es trimestral siempre es", "gran medida en la EPC (encuesta permanente de hogares) en 31 aglomeraciones urbanas.", "= df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaDesocupacion(self, periodo = \"Anual\"):", "una tasa representativa de la demanda laboral ejercida por la empresas. Parameters ----------", "tasa indicadora de la oferta laboral por parte de los trabajadores. Parameters ----------", "selector = 0 #si no es trimestral o mensual siempre es anual ultimoResultado", "descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url con cvs y", "---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The default is", "Returns ------- pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-demandante\" s=requests.get(urlPackage).content", "ejercida por la empresas. Parameters ---------- periodo : str, optional (puede ser \"Anual\",", "NO demandante/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION.", "del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1", "como una tasa representativa de la demanda laboral ejercida por la empresas. Parameters", "resultado[selector] urlDescarga = ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la", "df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getIndiceSalariosBase2016(self): \"\"\" Es", "ultimoResultado['url'] descripcion = ultimoResultado['description'] print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url con cvs", "calcula como: poblacion desocupada/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\",", "errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionNoDemandante(self, periodo", "poblacion desocupada demandante/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\")", "io.StringIO(contenidoCVS.decode('utf-8')) df_temp = pd.read_csv(flujoCVS) #transform string to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore')", "getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada demandante/PEA Parameters ----------", "calcula como poblacion desocupada NO demandante/PEA Parameters ---------- periodo : str, optional (puede", "df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo', inplace=True) return", "df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getIndiceSalariosBase2016(self): \"\"\" Es un indice que estima la", "\"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s)", "df_temp def getTasaSubocupacionNoDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como poblacion desocupada NO", "Los indicadores de empleo y desocupacion se basan en gran medida en la", "la evolucion de los salarios de la economia Base octubre 2016 Returns -------", "(encuesta permanente de hogares) en 31 aglomeraciones urbanas. \"\"\" pass def getTasaActividad(self, periodo", "index df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaEmpleo(self, periodo = \"Anual\"): \"\"\" La tasa", "Se calcula como poblacion desocupada NO demandante/PEA Parameters ---------- periodo : str, optional", "\"\"\" Se calcula como poblacion desocupada NO demandante/PEA Parameters ---------- periodo : str,", "import io import requests import json class IndicadoresEmpleoDesocupacion: def __init__(self): \"\"\" Los indicadores", "to datetime df_temp['indice_tiempo'] = pd.to_datetime(df_temp['indice_tiempo'], format='%Y-%m-%d', errors='ignore') df_temp['indice_tiempo'] = df_temp['indice_tiempo'].dt.date #set index df_temp.set_index('indice_tiempo',", "demandante/PEA Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\") DESCRIPTION. The", "print(\"Descargando: {}\".format(descripcion)) print(\"Archivo: {}\".format(urlDescarga)) #Descargar la url con cvs y generar pandas dataframe", "\"Anual\"): \"\"\" Se calcula como poblacion desocupada demandante/PEA Parameters ---------- periodo : str,", "pd.DataFrame(). \"\"\" #Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-empleo\" s=requests.get(urlPackage).content objJson =", "df_temp def getTasaEmpleo(self, periodo = \"Anual\"): \"\"\" La tasa de empleo se calcula", "df_temp.set_index('indice_tiempo', inplace=True) return df_temp def getTasaSubocupacionDemandante(self, periodo = \"Anual\"): \"\"\" Se calcula como", "\"\"\" Se calcula como poblacion desocupada demandante/PEA Parameters ---------- periodo : str, optional", "#Obtener la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-desempleo\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado", "en la EPC (encuesta permanente de hogares) en 31 aglomeraciones urbanas. \"\"\" pass", "por la empresas. Parameters ---------- periodo : str, optional (puede ser \"Anual\", \"Trimestral\")", "json.loads(s) resultado = objJson['result']['resources'] selector = 1 if periodo == \"Trimestral\" else 0", "la url de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-indice-salarios-base-octubre-2016\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado =", "ser \"Anual\", \"Trimestral\") DESCRIPTION. The default is \"Anual\". Returns ------- pd.DataFrame(). \"\"\" #Obtener", "{}\".format(urlDescarga)) #Descargar la url con cvs y generar pandas dataframe contenidoCVS = requests.get(urlDescarga).content", "cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-subocupacion-no-demandante\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector = 1 if", "de descarga del cvs urlPackage=\"https://datos.gob.ar/api/3/action/package_show?id=sspm-principales-variables-ocupacionales-eph-continua-actividad\" s=requests.get(urlPackage).content objJson = json.loads(s) resultado = objJson['result']['resources'] selector", "periodo = \"Anual\"): \"\"\" Se calcula como: poblacion desocupada/PEA Parameters ---------- periodo :" ]
[ "private TreeNode insert(TreeNode root, int val) { if (root == null) return new", "integer array nums, # which contains initial elements from the stream. For each", "that nums length >= k-1 and k >= 1. # import unittest class", "} } public int add(int val) { root = insert(root, val); return findKthLargest(k,", "mVal = val; mRightSum = rightSum; } } } /** * Your KthLargest", "returns 5 # kthLargest.add(10); // returns 5 # kthLargest.add(9); // returns 8 #", "private class TreeNode { int mVal; int mRightSum; TreeNode left; TreeNode right; TreeNode(int", "} } } /** * Your KthLargest object will be instantiated and called", "Design a class to find the kth largest element in a stream. #", "k; public KthLargest(int k, int[] nums) { this.k = k; this.pq = new", "# # Example: # # int k = 3; # int[] arr =", "this.k = k; this.pq = new PriorityQueue<>(); for (int num : nums) {", "# import unittest class Solution(object): pass # your function here class TestMethods(unittest.TestCase): def", "nums) { this.k = k; this.pq = new PriorityQueue<>(); for (int num :", "as such: * KthLargest obj = new KthLargest(k, nums); * int param_1 =", "k, TreeNode root) { if (root == null) return -1; if (root.mRightSum ==", "a constructor which accepts an integer k and an integer array nums, #", "(root.mRightSum == k) return root.mVal; if (root.mRightSum > k) { return findKthLargest(k, root.right);", "test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' # Thought:", "O() # Space: O() # # Description: Leetcode # 703. Kth Largest Element", "TreeNode { int mVal; int mRightSum; TreeNode left; TreeNode right; TreeNode(int val, int", "You may assume that nums length >= k-1 and k >= 1. #", "num : nums) { pq.offer(num); if (pq.size() > k) pq.poll(); } } public", "} public int add(int val) { pq.offer(val); if (pq.size() > k) pq.poll(); return", "returns 8 # kthLargest.add(4); // returns 8 # Note: # You may assume", "that it is the kth largest element in the sorted order, not the", "if (pq.size() > k) pq.poll(); return pq.peek(); } } # use BST #", "TreeNode root; private int k; public KthLargest(int k, int[] nums) { this.k =", "0); if (val < root.mVal) { root.left = insert(root.left, val); } else {", "1) if __name__ == '__main__': unittest.main() Java = ''' # Thought: # use", "called as such: * KthLargest obj = new KthLargest(k, nums); * int param_1", "} return root; } private class TreeNode { int mVal; int mRightSum; TreeNode", "= insert(root.left, val); } else { root.mRightSum++; root.right = insert(root.right, val); } return", "= new KthLargest(3, arr); # kthLargest.add(3); // returns 4 # kthLargest.add(5); // returns", "== '__main__': unittest.main() Java = ''' # Thought: # use PQ # 77ms", "# kthLargest.add(4); // returns 8 # Note: # You may assume that nums", "// returns 5 # kthLargest.add(10); // returns 5 # kthLargest.add(9); // returns 8", "} # use BST # 428ms 5.74% class KthLargest { TreeNode root; private", "insert(root, val); return findKthLargest(k, root); } private int findKthLargest(int k, TreeNode root) {", "root, int val) { if (root == null) return new TreeNode(val, 0); if", "# 77ms 83.97% class KthLargest { private PriorityQueue<Integer> pq; private int k; public", "class TreeNode { int mVal; int mRightSum; TreeNode left; TreeNode right; TreeNode(int val,", "8 # kthLargest.add(4); // returns 8 # Note: # You may assume that", "> k) { return findKthLargest(k, root.right); } else { return findKthLargest(k - root.mRightSum", "array nums, # which contains initial elements from the stream. For each call", "rightSum) { mVal = val; mRightSum = rightSum; } } } /** *", "root.left); } } private TreeNode insert(TreeNode root, int val) { if (root ==", "in a Stream # # Design a class to find the kth largest", "will have a constructor which accepts an integer k and an integer array", "class KthLargest { private PriorityQueue<Integer> pq; private int k; public KthLargest(int k, int[]", "it is the kth largest element in the sorted order, not the kth", "largest element in the sorted order, not the kth distinct element. # #", "kthLargest.add(3); // returns 4 # kthLargest.add(5); // returns 5 # kthLargest.add(10); // returns", "class KthLargest { TreeNode root; private int k; public KthLargest(int k, int[] nums)", "# 703. Kth Largest Element in a Stream # # Design a class", "TreeNode(int val, int rightSum) { mVal = val; mRightSum = rightSum; } }", "# Your KthLargest class will have a constructor which accepts an integer k", "findKthLargest(k, root); } private int findKthLargest(int k, TreeNode root) { if (root ==", "int k = 3; # int[] arr = [4,5,8,2]; # KthLargest kthLargest =", "for (int num : nums) { pq.offer(num); if (pq.size() > k) pq.poll(); }", "contains initial elements from the stream. For each call to the method KthLargest.add,", "sorted order, not the kth distinct element. # # Your KthLargest class will", "PQ # 77ms 83.97% class KthLargest { private PriorityQueue<Integer> pq; private int k;", "int[] arr = [4,5,8,2]; # KthLargest kthLargest = new KthLargest(3, arr); # kthLargest.add(3);", "kthLargest.add(4); // returns 8 # Note: # You may assume that nums length", "1. # import unittest class Solution(object): pass # your function here class TestMethods(unittest.TestCase):", "root.right = insert(root.right, val); } return root; } private class TreeNode { int", "else { root.mRightSum++; root.right = insert(root.right, val); } return root; } private class", "int k; public KthLargest(int k, int[] nums) { this.k = k; this.pq =", "pq.poll(); return pq.peek(); } } # use BST # 428ms 5.74% class KthLargest", "Element in a Stream # # Design a class to find the kth", "''' # Thought: # use PQ # 77ms 83.97% class KthLargest { private", "{ if (root == null) return new TreeNode(val, 0); if (val < root.mVal)", "new KthLargest(3, arr); # kthLargest.add(3); // returns 4 # kthLargest.add(5); // returns 5", "be instantiated and called as such: * KthLargest obj = new KthLargest(k, nums);", "in the sorted order, not the kth distinct element. # # Your KthLargest", "instantiated and called as such: * KthLargest obj = new KthLargest(k, nums); *", "use BST # 428ms 5.74% class KthLargest { TreeNode root; private int k;", "if (val < root.mVal) { root.left = insert(root.left, val); } else { root.mRightSum++;", "KthLargest { TreeNode root; private int k; public KthLargest(int k, int[] nums) {", "Time: O() # Space: O() # # Description: Leetcode # 703. Kth Largest", "{ root = insert(root, val); return findKthLargest(k, root); } private int findKthLargest(int k,", "return the element representing the kth largest element in the stream. # #", "class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java =", "k) pq.poll(); return pq.peek(); } } # use BST # 428ms 5.74% class", "k = 3; # int[] arr = [4,5,8,2]; # KthLargest kthLargest = new", "TreeNode right; TreeNode(int val, int rightSum) { mVal = val; mRightSum = rightSum;", "root = insert(root, n); } } public int add(int val) { root =", "Your KthLargest class will have a constructor which accepts an integer k and", "return findKthLargest(k, root.right); } else { return findKthLargest(k - root.mRightSum - 1, root.left);", "returns 5 # kthLargest.add(9); // returns 8 # kthLargest.add(4); // returns 8 #", "5.74% class KthLargest { TreeNode root; private int k; public KthLargest(int k, int[]", "the element representing the kth largest element in the stream. # # Example:", "val, int rightSum) { mVal = val; mRightSum = rightSum; } } }", "public int add(int val) { pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek();", "kthLargest = new KthLargest(3, arr); # kthLargest.add(3); // returns 4 # kthLargest.add(5); //", "stream. # # Example: # # int k = 3; # int[] arr", "the sorted order, not the kth distinct element. # # Your KthLargest class", "# # Description: Leetcode # 703. Kth Largest Element in a Stream #", "each call to the method KthLargest.add, # return the element representing the kth", "element. # # Your KthLargest class will have a constructor which accepts an", "class to find the kth largest element in a stream. # Note that", "Note: # You may assume that nums length >= k-1 and k >=", "return root.mVal; if (root.mRightSum > k) { return findKthLargest(k, root.right); } else {", "{ root = insert(root, n); } } public int add(int val) { root", "KthLargest(int k, int[] nums) { this.k = k - 1; for (int n", "k, int[] nums) { this.k = k - 1; for (int n :", "int val) { if (root == null) return new TreeNode(val, 0); if (val", "{ return findKthLargest(k - root.mRightSum - 1, root.left); } } private TreeNode insert(TreeNode", "unittest.main() Java = ''' # Thought: # use PQ # 77ms 83.97% class", "= insert(root, val); return findKthLargest(k, root); } private int findKthLargest(int k, TreeNode root)", "{ root.mRightSum++; root.right = insert(root.right, val); } return root; } private class TreeNode", "= new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size() >", "kth largest element in the stream. # # Example: # # int k", "mRightSum; TreeNode left; TreeNode right; TreeNode(int val, int rightSum) { mVal = val;", "* KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */", "return root; } private class TreeNode { int mVal; int mRightSum; TreeNode left;", "BST # 428ms 5.74% class KthLargest { TreeNode root; private int k; public", "arr); # kthLargest.add(3); // returns 4 # kthLargest.add(5); // returns 5 # kthLargest.add(10);", "Description: Leetcode # 703. Kth Largest Element in a Stream # # Design", "in a stream. # Note that it is the kth largest element in", "assume that nums length >= k-1 and k >= 1. # import unittest", "int add(int val) { pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek(); }", "Solution(object): pass # your function here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if", "element in the stream. # # Example: # # int k = 3;", "public KthLargest(int k, int[] nums) { this.k = k - 1; for (int", "import unittest class Solution(object): pass # your function here class TestMethods(unittest.TestCase): def test_Local(self):", "pq.offer(num); if (pq.size() > k) pq.poll(); } } public int add(int val) {", "(root.mRightSum > k) { return findKthLargest(k, root.right); } else { return findKthLargest(k -", "} else { return findKthLargest(k - root.mRightSum - 1, root.left); } } private", "not the kth distinct element. # # Your KthLargest class will have a", "unittest class Solution(object): pass # your function here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1,", "= ''' # Thought: # use PQ # 77ms 83.97% class KthLargest {", "the kth largest element in the sorted order, not the kth distinct element.", "mVal; int mRightSum; TreeNode left; TreeNode right; TreeNode(int val, int rightSum) { mVal", "largest element in the stream. # # Example: # # int k =", "int[] nums) { this.k = k; this.pq = new PriorityQueue<>(); for (int num", "the stream. # # Example: # # int k = 3; # int[]", "Largest Element in a Stream # # Design a class to find the", "(val < root.mVal) { root.left = insert(root.left, val); } else { root.mRightSum++; root.right", "for (int n : nums) { root = insert(root, n); } } public", "= k; this.pq = new PriorityQueue<>(); for (int num : nums) { pq.offer(num);", "insert(TreeNode root, int val) { if (root == null) return new TreeNode(val, 0);", "from the stream. For each call to the method KthLargest.add, # return the", "arr = [4,5,8,2]; # KthLargest kthLargest = new KthLargest(3, arr); # kthLargest.add(3); //", "KthLargest class will have a constructor which accepts an integer k and an", "> k) pq.poll(); return pq.peek(); } } # use BST # 428ms 5.74%", "428ms 5.74% class KthLargest { TreeNode root; private int k; public KthLargest(int k,", "largest element in a stream. # Note that it is the kth largest", "1; for (int n : nums) { root = insert(root, n); } }", "TreeNode insert(TreeNode root, int val) { if (root == null) return new TreeNode(val,", "stream. # Note that it is the kth largest element in the sorted", "an integer k and an integer array nums, # which contains initial elements", "int k; public KthLargest(int k, int[] nums) { this.k = k - 1;", "= rightSum; } } } /** * Your KthLargest object will be instantiated", "nums) { this.k = k - 1; for (int n : nums) {", "private int findKthLargest(int k, TreeNode root) { if (root == null) return -1;", "} public int add(int val) { root = insert(root, val); return findKthLargest(k, root);", "kthLargest.add(10); // returns 5 # kthLargest.add(9); // returns 8 # kthLargest.add(4); // returns", "1, root.left); } } private TreeNode insert(TreeNode root, int val) { if (root", "TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = '''", "right; TreeNode(int val, int rightSum) { mVal = val; mRightSum = rightSum; }", "return findKthLargest(k, root); } private int findKthLargest(int k, TreeNode root) { if (root", "the kth distinct element. # # Your KthLargest class will have a constructor", "k - 1; for (int n : nums) { root = insert(root, n);", "is the kth largest element in the sorted order, not the kth distinct", "find the kth largest element in a stream. # Note that it is", "TreeNode left; TreeNode right; TreeNode(int val, int rightSum) { mVal = val; mRightSum", "KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */ '''", "# Time: O() # Space: O() # # Description: Leetcode # 703. Kth", "here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java", "and an integer array nums, # which contains initial elements from the stream.", "k and an integer array nums, # which contains initial elements from the", "order, not the kth distinct element. # # Your KthLargest class will have", "KthLargest.add, # return the element representing the kth largest element in the stream.", "# Example: # # int k = 3; # int[] arr = [4,5,8,2];", "a stream. # Note that it is the kth largest element in the", "{ return findKthLargest(k, root.right); } else { return findKthLargest(k - root.mRightSum - 1,", "nums length >= k-1 and k >= 1. # import unittest class Solution(object):", "// returns 5 # kthLargest.add(9); // returns 8 # kthLargest.add(4); // returns 8", "use PQ # 77ms 83.97% class KthLargest { private PriorityQueue<Integer> pq; private int", "to find the kth largest element in a stream. # Note that it", "nums, # which contains initial elements from the stream. For each call to", "# kthLargest.add(9); // returns 8 # kthLargest.add(4); // returns 8 # Note: #", "TreeNode root) { if (root == null) return -1; if (root.mRightSum == k)", "# You may assume that nums length >= k-1 and k >= 1.", "For each call to the method KthLargest.add, # return the element representing the", "def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' #", "the kth largest element in the stream. # # Example: # # int", "Kth Largest Element in a Stream # # Design a class to find", "TreeNode(val, 0); if (val < root.mVal) { root.left = insert(root.left, val); } else", "return new TreeNode(val, 0); if (val < root.mVal) { root.left = insert(root.left, val);", "== k) return root.mVal; if (root.mRightSum > k) { return findKthLargest(k, root.right); }", "pq; private int k; public KthLargest(int k, int[] nums) { this.k = k;", "an integer array nums, # which contains initial elements from the stream. For", "KthLargest { private PriorityQueue<Integer> pq; private int k; public KthLargest(int k, int[] nums)", "== null) return new TreeNode(val, 0); if (val < root.mVal) { root.left =", "(int n : nums) { root = insert(root, n); } } public int", "null) return -1; if (root.mRightSum == k) return root.mVal; if (root.mRightSum > k)", "val) { pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek(); } } #", "# kthLargest.add(10); // returns 5 # kthLargest.add(9); // returns 8 # kthLargest.add(4); //", "4 # kthLargest.add(5); // returns 5 # kthLargest.add(10); // returns 5 # kthLargest.add(9);", "# which contains initial elements from the stream. For each call to the", ">= k-1 and k >= 1. # import unittest class Solution(object): pass #", "Your KthLargest object will be instantiated and called as such: * KthLargest obj", "3; # int[] arr = [4,5,8,2]; # KthLargest kthLargest = new KthLargest(3, arr);", "# use BST # 428ms 5.74% class KthLargest { TreeNode root; private int", "left; TreeNode right; TreeNode(int val, int rightSum) { mVal = val; mRightSum =", "77ms 83.97% class KthLargest { private PriorityQueue<Integer> pq; private int k; public KthLargest(int", "new TreeNode(val, 0); if (val < root.mVal) { root.left = insert(root.left, val); }", "insert(root, n); } } public int add(int val) { root = insert(root, val);", "findKthLargest(k - root.mRightSum - 1, root.left); } } private TreeNode insert(TreeNode root, int", "if (root == null) return new TreeNode(val, 0); if (val < root.mVal) {", "# return the element representing the kth largest element in the stream. #", "> k) pq.poll(); } } public int add(int val) { pq.offer(val); if (pq.size()", "# Note that it is the kth largest element in the sorted order,", "(root == null) return -1; if (root.mRightSum == k) return root.mVal; if (root.mRightSum", "findKthLargest(int k, TreeNode root) { if (root == null) return -1; if (root.mRightSum", "/** * Your KthLargest object will be instantiated and called as such: *", "[4,5,8,2]; # KthLargest kthLargest = new KthLargest(3, arr); # kthLargest.add(3); // returns 4", "int rightSum) { mVal = val; mRightSum = rightSum; } } } /**", "root; } private class TreeNode { int mVal; int mRightSum; TreeNode left; TreeNode", "findKthLargest(k, root.right); } else { return findKthLargest(k - root.mRightSum - 1, root.left); }", "insert(root.left, val); } else { root.mRightSum++; root.right = insert(root.right, val); } return root;", "{ if (root == null) return -1; if (root.mRightSum == k) return root.mVal;", "__source__ = 'https://leetcode.com/problems/kth-largest-element-in-a-stream/' # Time: O() # Space: O() # # Description: Leetcode", "# Description: Leetcode # 703. Kth Largest Element in a Stream # #", "Java = ''' # Thought: # use PQ # 77ms 83.97% class KthLargest", "{ private PriorityQueue<Integer> pq; private int k; public KthLargest(int k, int[] nums) {", "{ TreeNode root; private int k; public KthLargest(int k, int[] nums) { this.k", "Leetcode # 703. Kth Largest Element in a Stream # # Design a", "null) return new TreeNode(val, 0); if (val < root.mVal) { root.left = insert(root.left,", "private int k; public KthLargest(int k, int[] nums) { this.k = k; this.pq", "root.mRightSum - 1, root.left); } } private TreeNode insert(TreeNode root, int val) {", "pq.peek(); } } # use BST # 428ms 5.74% class KthLargest { TreeNode", "a Stream # # Design a class to find the kth largest element", "k) { return findKthLargest(k, root.right); } else { return findKthLargest(k - root.mRightSum -", "KthLargest object will be instantiated and called as such: * KthLargest obj =", "returns 4 # kthLargest.add(5); // returns 5 # kthLargest.add(10); // returns 5 #", "# Note: # You may assume that nums length >= k-1 and k", "and called as such: * KthLargest obj = new KthLargest(k, nums); * int", "representing the kth largest element in the stream. # # Example: # #", "which contains initial elements from the stream. For each call to the method", "} } public int add(int val) { pq.offer(val); if (pq.size() > k) pq.poll();", "{ int mVal; int mRightSum; TreeNode left; TreeNode right; TreeNode(int val, int rightSum)", "in the stream. # # Example: # # int k = 3; #", "val) { if (root == null) return new TreeNode(val, 0); if (val <", "< root.mVal) { root.left = insert(root.left, val); } else { root.mRightSum++; root.right =", "class Solution(object): pass # your function here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1)", "call to the method KthLargest.add, # return the element representing the kth largest", "# # Design a class to find the kth largest element in a", "= [4,5,8,2]; # KthLargest kthLargest = new KthLargest(3, arr); # kthLargest.add(3); // returns", "= 'https://leetcode.com/problems/kth-largest-element-in-a-stream/' # Time: O() # Space: O() # # Description: Leetcode #", "kthLargest.add(9); // returns 8 # kthLargest.add(4); // returns 8 # Note: # You", "your function here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__':", "* Your KthLargest object will be instantiated and called as such: * KthLargest", "root = insert(root, val); return findKthLargest(k, root); } private int findKthLargest(int k, TreeNode", "# your function here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ ==", "and k >= 1. # import unittest class Solution(object): pass # your function", "= insert(root.right, val); } return root; } private class TreeNode { int mVal;", "(pq.size() > k) pq.poll(); } } public int add(int val) { pq.offer(val); if", "{ pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek(); } } # use", "element in a stream. # Note that it is the kth largest element", "k, int[] nums) { this.k = k; this.pq = new PriorityQueue<>(); for (int", "// returns 8 # Note: # You may assume that nums length >=", "{ this.k = k; this.pq = new PriorityQueue<>(); for (int num : nums)", "} private TreeNode insert(TreeNode root, int val) { if (root == null) return", "k >= 1. # import unittest class Solution(object): pass # your function here", "pass # your function here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__", "function here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main()", "kth largest element in the sorted order, not the kth distinct element. #", "- 1, root.left); } } private TreeNode insert(TreeNode root, int val) { if", "703. Kth Largest Element in a Stream # # Design a class to", "} } private TreeNode insert(TreeNode root, int val) { if (root == null)", "initial elements from the stream. For each call to the method KthLargest.add, #", "# Space: O() # # Description: Leetcode # 703. Kth Largest Element in", "} /** * Your KthLargest object will be instantiated and called as such:", "returns 8 # Note: # You may assume that nums length >= k-1", "elements from the stream. For each call to the method KthLargest.add, # return", "# Design a class to find the kth largest element in a stream.", "5 # kthLargest.add(10); // returns 5 # kthLargest.add(9); // returns 8 # kthLargest.add(4);", "constructor which accepts an integer k and an integer array nums, # which", "kth distinct element. # # Your KthLargest class will have a constructor which", "if (root.mRightSum == k) return root.mVal; if (root.mRightSum > k) { return findKthLargest(k,", "Thought: # use PQ # 77ms 83.97% class KthLargest { private PriorityQueue<Integer> pq;", "val); return findKthLargest(k, root); } private int findKthLargest(int k, TreeNode root) { if", "int[] nums) { this.k = k - 1; for (int n : nums)", "will be instantiated and called as such: * KthLargest obj = new KthLargest(k,", "PriorityQueue<Integer> pq; private int k; public KthLargest(int k, int[] nums) { this.k =", "self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' # Thought: #", ": nums) { pq.offer(num); if (pq.size() > k) pq.poll(); } } public int", "k-1 and k >= 1. # import unittest class Solution(object): pass # your", "private PriorityQueue<Integer> pq; private int k; public KthLargest(int k, int[] nums) { this.k", "= insert(root, n); } } public int add(int val) { root = insert(root,", "element representing the kth largest element in the stream. # # Example: #", "private int k; public KthLargest(int k, int[] nums) { this.k = k -", "length >= k-1 and k >= 1. # import unittest class Solution(object): pass", "= val; mRightSum = rightSum; } } } /** * Your KthLargest object", "pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek(); } } # use BST", "accepts an integer k and an integer array nums, # which contains initial", "// returns 4 # kthLargest.add(5); // returns 5 # kthLargest.add(10); // returns 5", "- 1; for (int n : nums) { root = insert(root, n); }", "return pq.peek(); } } # use BST # 428ms 5.74% class KthLargest {", "Stream # # Design a class to find the kth largest element in", "{ this.k = k - 1; for (int n : nums) { root", "object will be instantiated and called as such: * KthLargest obj = new", "PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size() > k) pq.poll();", "= k - 1; for (int n : nums) { root = insert(root,", "to the method KthLargest.add, # return the element representing the kth largest element", "# kthLargest.add(3); // returns 4 # kthLargest.add(5); // returns 5 # kthLargest.add(10); //", "return -1; if (root.mRightSum == k) return root.mVal; if (root.mRightSum > k) {", "int add(int val) { root = insert(root, val); return findKthLargest(k, root); } private", "== null) return -1; if (root.mRightSum == k) return root.mVal; if (root.mRightSum >", "k) pq.poll(); } } public int add(int val) { pq.offer(val); if (pq.size() >", "} } /** * Your KthLargest object will be instantiated and called as", "# int k = 3; # int[] arr = [4,5,8,2]; # KthLargest kthLargest", "else { return findKthLargest(k - root.mRightSum - 1, root.left); } } private TreeNode", "{ root.left = insert(root.left, val); } else { root.mRightSum++; root.right = insert(root.right, val);", "- root.mRightSum - 1, root.left); } } private TreeNode insert(TreeNode root, int val)", "new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size() > k)", "method KthLargest.add, # return the element representing the kth largest element in the", "root.right); } else { return findKthLargest(k - root.mRightSum - 1, root.left); } }", "the kth largest element in a stream. # Note that it is the", "root); } private int findKthLargest(int k, TreeNode root) { if (root == null)", "val); } else { root.mRightSum++; root.right = insert(root.right, val); } return root; }", "Example: # # int k = 3; # int[] arr = [4,5,8,2]; #", "kth largest element in a stream. # Note that it is the kth", "= 3; # int[] arr = [4,5,8,2]; # KthLargest kthLargest = new KthLargest(3,", "kthLargest.add(5); // returns 5 # kthLargest.add(10); // returns 5 # kthLargest.add(9); // returns", "element in the sorted order, not the kth distinct element. # # Your", "# # int k = 3; # int[] arr = [4,5,8,2]; # KthLargest", "nums) { pq.offer(num); if (pq.size() > k) pq.poll(); } } public int add(int", "} private int findKthLargest(int k, TreeNode root) { if (root == null) return", "} } # use BST # 428ms 5.74% class KthLargest { TreeNode root;", "public KthLargest(int k, int[] nums) { this.k = k; this.pq = new PriorityQueue<>();", "k; this.pq = new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if", "root.mRightSum++; root.right = insert(root.right, val); } return root; } private class TreeNode {", "if __name__ == '__main__': unittest.main() Java = ''' # Thought: # use PQ", "the stream. For each call to the method KthLargest.add, # return the element", "may assume that nums length >= k-1 and k >= 1. # import", "have a constructor which accepts an integer k and an integer array nums,", "insert(root.right, val); } return root; } private class TreeNode { int mVal; int", "O() # # Description: Leetcode # 703. Kth Largest Element in a Stream", "class will have a constructor which accepts an integer k and an integer", "83.97% class KthLargest { private PriorityQueue<Integer> pq; private int k; public KthLargest(int k,", "public int add(int val) { root = insert(root, val); return findKthLargest(k, root); }", "'__main__': unittest.main() Java = ''' # Thought: # use PQ # 77ms 83.97%", "k; public KthLargest(int k, int[] nums) { this.k = k - 1; for", "Space: O() # # Description: Leetcode # 703. Kth Largest Element in a", "# KthLargest kthLargest = new KthLargest(3, arr); # kthLargest.add(3); // returns 4 #", "int mVal; int mRightSum; TreeNode left; TreeNode right; TreeNode(int val, int rightSum) {", "int findKthLargest(int k, TreeNode root) { if (root == null) return -1; if", "distinct element. # # Your KthLargest class will have a constructor which accepts", "# # Your KthLargest class will have a constructor which accepts an integer", "n : nums) { root = insert(root, n); } } public int add(int", "nums) { root = insert(root, n); } } public int add(int val) {", "8 # Note: # You may assume that nums length >= k-1 and", "5 # kthLargest.add(9); // returns 8 # kthLargest.add(4); // returns 8 # Note:", "{ pq.offer(num); if (pq.size() > k) pq.poll(); } } public int add(int val)", "# kthLargest.add(5); // returns 5 # kthLargest.add(10); // returns 5 # kthLargest.add(9); //", "} else { root.mRightSum++; root.right = insert(root.right, val); } return root; } private", "# int[] arr = [4,5,8,2]; # KthLargest kthLargest = new KthLargest(3, arr); #", "Note that it is the kth largest element in the sorted order, not", "such: * KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val);", ">= 1. # import unittest class Solution(object): pass # your function here class", "# use PQ # 77ms 83.97% class KthLargest { private PriorityQueue<Integer> pq; private", "val) { root = insert(root, val); return findKthLargest(k, root); } private int findKthLargest(int", "-1; if (root.mRightSum == k) return root.mVal; if (root.mRightSum > k) { return", "root.mVal) { root.left = insert(root.left, val); } else { root.mRightSum++; root.right = insert(root.right,", "(int num : nums) { pq.offer(num); if (pq.size() > k) pq.poll(); } }", "root.mVal; if (root.mRightSum > k) { return findKthLargest(k, root.right); } else { return", "return findKthLargest(k - root.mRightSum - 1, root.left); } } private TreeNode insert(TreeNode root,", "val; mRightSum = rightSum; } } } /** * Your KthLargest object will", "(root == null) return new TreeNode(val, 0); if (val < root.mVal) { root.left", "# Thought: # use PQ # 77ms 83.97% class KthLargest { private PriorityQueue<Integer>", "mRightSum = rightSum; } } } /** * Your KthLargest object will be", "n); } } public int add(int val) { root = insert(root, val); return", "KthLargest(3, arr); # kthLargest.add(3); // returns 4 # kthLargest.add(5); // returns 5 #", "pq.poll(); } } public int add(int val) { pq.offer(val); if (pq.size() > k)", "which accepts an integer k and an integer array nums, # which contains", "add(int val) { pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek(); } }", "root) { if (root == null) return -1; if (root.mRightSum == k) return", "KthLargest(int k, int[] nums) { this.k = k; this.pq = new PriorityQueue<>(); for", "'https://leetcode.com/problems/kth-largest-element-in-a-stream/' # Time: O() # Space: O() # # Description: Leetcode # 703.", "integer k and an integer array nums, # which contains initial elements from", "__name__ == '__main__': unittest.main() Java = ''' # Thought: # use PQ #", "if (root == null) return -1; if (root.mRightSum == k) return root.mVal; if", "k) return root.mVal; if (root.mRightSum > k) { return findKthLargest(k, root.right); } else", "add(int val) { root = insert(root, val); return findKthLargest(k, root); } private int", "stream. For each call to the method KthLargest.add, # return the element representing", "KthLargest kthLargest = new KthLargest(3, arr); # kthLargest.add(3); // returns 4 # kthLargest.add(5);", "int mRightSum; TreeNode left; TreeNode right; TreeNode(int val, int rightSum) { mVal =", "if (pq.size() > k) pq.poll(); } } public int add(int val) { pq.offer(val);", ": nums) { root = insert(root, n); } } public int add(int val)", "root; private int k; public KthLargest(int k, int[] nums) { this.k = k", "# 428ms 5.74% class KthLargest { TreeNode root; private int k; public KthLargest(int", "root.left = insert(root.left, val); } else { root.mRightSum++; root.right = insert(root.right, val); }", "} private class TreeNode { int mVal; int mRightSum; TreeNode left; TreeNode right;", "{ mVal = val; mRightSum = rightSum; } } } /** * Your", "this.k = k - 1; for (int n : nums) { root =", "val); } return root; } private class TreeNode { int mVal; int mRightSum;", "rightSum; } } } /** * Your KthLargest object will be instantiated and", "the method KthLargest.add, # return the element representing the kth largest element in", "(pq.size() > k) pq.poll(); return pq.peek(); } } # use BST # 428ms", "if (root.mRightSum > k) { return findKthLargest(k, root.right); } else { return findKthLargest(k", "a class to find the kth largest element in a stream. # Note", "this.pq = new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size()", "// returns 8 # kthLargest.add(4); // returns 8 # Note: # You may" ]
[ "job scripts for compiler module: ' + compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules')", "script does a test of a particular nvidia compiler on Myriad import sys", "', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name", "', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name + 'cudaf' #", "print('Generating job scripts for compiler module: ' + compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules')", "'/' + tmp_dir status = gepy.executor.run(['git', 'clone', repo, tmp_dir + '/pi_examples']) if (status.returncode", "[])) cudaf_job.name = template_job.name + 'cudaf' # openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir']))", "status = gepy.executor.run(['git', 'clone', repo, tmp_dir + '/pi_examples']) if (status.returncode != 0): sys.exit('Error", "', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name + 'doconc' # cuda fortran test", "= copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) # do concurrent test doconc_job.workload.append(gepy.serial_command('cd", "= 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' + tmp_dir status = gepy.executor.run(['git', 'clone', repo,", "copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) # do concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ',", "openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad',", "openmp_job = copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) # do concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir']))", "[])) openacc_job.name = template_job.name + 'openacc' print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t =", "import copy import time import gepy import gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo =", "(status.returncode != 0): sys.exit('Error cloning repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) #", "['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name + 'doconc' # cuda", "cloned and a template job created. doconc_job = copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job", "template job created. doconc_job = copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job", "', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name + 'cudaf' # openmp fortran test", "openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name + 'openmp' # openacc fortran", "'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name + 'openacc' print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script())", "copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) # do concurrent", "Right, that's the repo cloned and a template job created. doconc_job = copy.deepcopy(template_job)", "['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name + 'openmp' # openacc fortran test openacc_job.workload.append(gepy.serial_command('cd", "+ '/pi_examples']) if (status.returncode != 0): sys.exit('Error cloning repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd", "!= 0): sys.exit('Error cloning repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right,", "the repo cloned and a template job created. doconc_job = copy.deepcopy(template_job) cudaf_job =", "+ 'openacc' print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t = gepy.executor.qsub(cudaf_job.get_job_script()) j,t = gepy.executor.qsub(openmp_job.get_job_script())", "openacc_job = copy.deepcopy(template_job) # do concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean']))", "# Right, that's the repo cloned and a template job created. doconc_job =", "[])) doconc_job.name = template_job.name + 'doconc' # cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir']))", "'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1): compiler_module = sys.argv[1] print('Generating job scripts for compiler", "+ 'cudaf' # openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make", "', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name + 'openmp' # openacc fortran test", "template_job.name + 'openmp' # openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean']))", "cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name + 'cudaf' # openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ',", "['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name =", "[])) openmp_job.name = template_job.name + 'openmp' # openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir']))", "= template_job.name + 'openacc' print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t = gepy.executor.qsub(cudaf_job.get_job_script()) j,t", "= copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) # do", "for compiler module: ' + compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1')", "nvidia compiler on Myriad import sys import os import copy import time import", "This script does a test of a particular nvidia compiler on Myriad import", "tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' + tmp_dir status = gepy.executor.run(['git', 'clone',", "test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi',", "repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1): compiler_module = sys.argv[1] print('Generating job scripts", "template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' +", "os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' + tmp_dir status = gepy.executor.run(['git', 'clone', repo, tmp_dir +", "created. doconc_job = copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job)", "['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name +", "= gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() +", "# do concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc']))", "# cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', []))", "test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name", "jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t = gepy.executor.qsub(cudaf_job.get_job_script()) j,t = gepy.executor.qsub(openmp_job.get_job_script()) j,t = gepy.executor.qsub(openacc_job.get_job_script())", "# This script does a test of a particular nvidia compiler on Myriad", "template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' + tmp_dir", "0): sys.exit('Error cloning repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right, that's", "= template_job.name + 'doconc' # cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ',", "cudaf_job = copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) # do concurrent test", "cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name =", "template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' + tmp_dir status", "compiler_module = sys.argv[1] print('Generating job scripts for compiler module: ' + compiler_module) template_job", "doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name + 'doconc' # cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ',", "# openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload']))", "if (len(sys.argv) > 1): compiler_module = sys.argv[1] print('Generating job scripts for compiler module:", "<gh_stars>0 #/usr/bin/env python3 # This script does a test of a particular nvidia", "['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name + 'openmp' # openacc", "repo, tmp_dir + '/pi_examples']) if (status.returncode != 0): sys.exit('Error cloning repo: ' +", "= template_job.name + 'cudaf' # openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ',", "', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name", "# openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f'", "j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t = gepy.executor.qsub(cudaf_job.get_job_script()) j,t = gepy.executor.qsub(openmp_job.get_job_script()) j,t = gepy.executor.qsub(openacc_job.get_job_script()) print('Done')", "compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir)", "1): compiler_module = sys.argv[1] print('Generating job scripts for compiler module: ' + compiler_module)", "template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' + tmp_dir status = gepy.executor.run(['git',", "copy.deepcopy(template_job) # do concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ',", "template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd()", "gepy import gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1):", "Myriad import sys import os import copy import time import gepy import gepy.executor", "a particular nvidia compiler on Myriad import sys import os import copy import", "doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name + 'doconc' # cuda fortran", "+ '/' + tmp_dir status = gepy.executor.run(['git', 'clone', repo, tmp_dir + '/pi_examples']) if", "'openmp' # openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ',", "['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name + 'openacc' print('Submitting jobs') j,t", "#/usr/bin/env python3 # This script does a test of a particular nvidia compiler", "repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right, that's the repo cloned", "['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name + 'doconc' # cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd", "gepy.executor.run(['git', 'clone', repo, tmp_dir + '/pi_examples']) if (status.returncode != 0): sys.exit('Error cloning repo:", "+ status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right, that's the repo cloned and a", "(len(sys.argv) > 1): compiler_module = sys.argv[1] print('Generating job scripts for compiler module: '", "import gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1): compiler_module", "', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name", "fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', []))", "', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name", "cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name + 'cudaf'", "fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi']))", "concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', []))", "python3 # This script does a test of a particular nvidia compiler on", "import os import copy import time import gepy import gepy.executor compiler_module = 'compilers/nvhpc/21.11'", "['pi_examples'])) # Right, that's the repo cloned and a template job created. doconc_job", "' + status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right, that's the repo cloned and", "sys import os import copy import time import gepy import gepy.executor compiler_module =", "['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name + 'openacc'", "job created. doconc_job = copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job =", "copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) # do concurrent test doconc_job.workload.append(gepy.serial_command('cd ',", "particular nvidia compiler on Myriad import sys import os import copy import time", "openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name + 'openacc' print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t", "compiler on Myriad import sys import os import copy import time import gepy", "if (status.returncode != 0): sys.exit('Error cloning repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples']))", "sys.exit('Error cloning repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right, that's the", "= gepy.executor.run(['git', 'clone', repo, tmp_dir + '/pi_examples']) if (status.returncode != 0): sys.exit('Error cloning", "openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name + 'openmp'", "repo cloned and a template job created. doconc_job = copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job)", "and a template job created. doconc_job = copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job =", "= copy.deepcopy(template_job) # do concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make", "scripts for compiler module: ' + compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module)", "a template job created. doconc_job = copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job)", "of a particular nvidia compiler on Myriad import sys import os import copy", "+ compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time())", "on Myriad import sys import os import copy import time import gepy import", "openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name + 'openmp' # openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ',", "compiler_module = 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1): compiler_module = sys.argv[1]", "openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name", "compiler module: ' + compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL')", "['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name +", "gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1): compiler_module =", "template_job.name + 'cudaf' # openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean']))", "does a test of a particular nvidia compiler on Myriad import sys import", "'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' + tmp_dir status = gepy.executor.run(['git', 'clone', repo, tmp_dir", "module: ' + compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir", "+ 'openmp' # openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make", "'/pi_examples']) if (status.returncode != 0): sys.exit('Error cloning repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd ',", "test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name", "openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', []))", "openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name =", "= sys.argv[1] print('Generating job scripts for compiler module: ' + compiler_module) template_job =", "doconc_job.name = template_job.name + 'doconc' # cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make", "= 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1): compiler_module = sys.argv[1] print('Generating", "cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi',", "doconc_job = copy.deepcopy(template_job) cudaf_job = copy.deepcopy(template_job) openmp_job = copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) #", "status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right, that's the repo cloned and a template", "', ['pi_examples'])) # Right, that's the repo cloned and a template job created.", "test of a particular nvidia compiler on Myriad import sys import os import", "' + compiler_module) template_job = gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir =", "> 1): compiler_module = sys.argv[1] print('Generating job scripts for compiler module: ' +", "a test of a particular nvidia compiler on Myriad import sys import os", "test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name", "', ['clean'])) openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name +", "cudaf_job.name = template_job.name + 'cudaf' # openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make", "+ tmp_dir status = gepy.executor.run(['git', 'clone', repo, tmp_dir + '/pi_examples']) if (status.returncode !=", "template_job.location=os.getcwd() + '/' + tmp_dir status = gepy.executor.run(['git', 'clone', repo, tmp_dir + '/pi_examples'])", "time import gepy import gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv)", "fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', []))", "= template_job.name + 'openmp' # openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make ',", "do concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi',", "template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right, that's the repo cloned and a template job", "', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name + 'doconc' #", "openacc_job.name = template_job.name + 'openacc' print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t = gepy.executor.qsub(cudaf_job.get_job_script())", "'clone', repo, tmp_dir + '/pi_examples']) if (status.returncode != 0): sys.exit('Error cloning repo: '", "', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name + 'openacc' print('Submitting jobs')", "openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu',", "that's the repo cloned and a template job created. doconc_job = copy.deepcopy(template_job) cudaf_job", "'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name + 'openacc' print('Submitting jobs') j,t =", "sys.argv[1] print('Generating job scripts for compiler module: ' + compiler_module) template_job = gepy.job(name='nvtest')", "template_job.name + 'doconc' # cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean']))", "tmp_dir + '/pi_examples']) if (status.returncode != 0): sys.exit('Error cloning repo: ' + status.stderr)", "openmp_job.name = template_job.name + 'openmp' # openacc fortran test openacc_job.workload.append(gepy.serial_command('cd ', ['fortran_openacc_pi_dir'])) openacc_job.workload.append(gepy.serial_command('make", "= copy.deepcopy(template_job) openacc_job = copy.deepcopy(template_job) # do concurrent test doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make", "'doconc' # cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make ',", "= 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1): compiler_module = sys.argv[1] print('Generating job scripts for", "tmp_dir status = gepy.executor.run(['git', 'clone', repo, tmp_dir + '/pi_examples']) if (status.returncode != 0):", "cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name + 'cudaf' # openmp fortran", "+ 'doconc' # cuda fortran test cudaf_job.workload.append(gepy.serial_command('cd ', ['cudafortran_pi_dir'])) cudaf_job.workload.append(gepy.serial_command('make ', ['clean'])) cudaf_job.workload.append(gepy.serial_command('make", "copy import time import gepy import gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git'", "import gepy import gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) >", "template_job.name + 'openacc' print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t = gepy.executor.qsub(cudaf_job.get_job_script()) j,t =", "import sys import os import copy import time import gepy import gepy.executor compiler_module", "os import copy import time import gepy import gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo", "cloning repo: ' + status.stderr) template_job.workload.append(gepy.serial_command('cd ', ['pi_examples'])) # Right, that's the repo", "'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if (len(sys.argv) > 1): compiler_module = sys.argv[1] print('Generating job", "doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name = template_job.name + 'doconc'", "['clean'])) cudaf_job.workload.append(gepy.serial_command('make ', [])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name + 'cudaf' # openmp", "['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name +", "', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ', ['nvhpc_offload'])) openmp_job.workload.append(gepy.serial_command('./pi_gpu', [])) openmp_job.name = template_job.name + 'openmp' #", "'openacc' print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t = gepy.executor.qsub(cudaf_job.get_job_script()) j,t = gepy.executor.qsub(openmp_job.get_job_script()) j,t", "doconc_job.workload.append(gepy.serial_command('cd ', ['fortran_do_concurrent_pi_dir'])) doconc_job.workload.append(gepy.serial_command('make ', ['clean'])) doconc_job.workload.append(gepy.serial_command('make ', ['nvhpc'])) doconc_job.workload.append(gepy.serial_command('./pi', [])) doconc_job.name =", "print('Submitting jobs') j,t = gepy.executor.qsub(doconc_job.get_job_script()) j,t = gepy.executor.qsub(cudaf_job.get_job_script()) j,t = gepy.executor.qsub(openmp_job.get_job_script()) j,t =", "template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/' + tmp_dir status =", "import time import gepy import gepy.executor compiler_module = 'compilers/nvhpc/21.11' repo = 'https://github.com/UCL-RITS/pi_examples.git' if", "[])) cudaf_job.workload.append(gepy.serial_command('./pi', [])) cudaf_job.name = template_job.name + 'cudaf' # openmp fortran test openmp_job.workload.append(gepy.serial_command('cd", "gepy.job(name='nvtest') template_job.modules.append('personal-modules') template_job.modules.append('testing-modules') template_job.modules.append(compiler_module) template_job.add_resource('gpu','1') template_job.set_node_classes('EFL') tmp_dir = 'nvtest_'+str(time.time()) os.mkdir(tmp_dir) template_job.location=os.getcwd() + '/'", "'cudaf' # openmp fortran test openmp_job.workload.append(gepy.serial_command('cd ', ['fortran_omp_pi_dir'])) openmp_job.workload.append(gepy.serial_command('make ', ['clean'])) openmp_job.workload.append(gepy.serial_command('make ',", "openacc_job.workload.append(gepy.serial_command('make ', ['-f' 'Makefile.myriad', 'pi'])) openacc_job.workload.append(gepy.serial_command('./pi', [])) openacc_job.name = template_job.name + 'openacc' print('Submitting" ]
[ "self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) #", "self.left = v_l self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 #", "self.dr])) # Assigning the calculated velocities to each motors self.right = v_r self.left", "idle.sleep() def spinOnce(self): # Calculating the individual motor velocity for a motion command", "v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) # Assigning the calculated velocities to", "that publishes target velocity to the PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor", "to the PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor", "self.left = 0 self.right = 0 self.back = 0 def spin(self): r =", "self.ticks_since_target = self.timeout_ticks while not rospy.is_shutdown(): while not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks:", "msg.linear.x self.dr = msg.angular.z self.dy = msg.linear.y if __name__ == '__main__': \"\"\" main", "def spinOnce(self): # Calculating the individual motor velocity for a motion command angle_mat", "= msg.linear.x self.dr = msg.angular.z self.dy = msg.linear.y if __name__ == '__main__': \"\"\"", "velocity to the PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10)", "rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to the velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback,", "motor velocity for a motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))],", "import roslib import math from std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool, String from geometry_msgs.msg", "geometry_msgs.msg import Twist from sensor_msgs.msg import Range import numpy as np from numpy", "def spin(self): r = rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while not", "class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s started\" % nodename) self.M_PI", "= al.inv(angle_mat) [v_r, v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) # Assigning the", "Float32,Int32, UInt8MultiArray, Bool, String from geometry_msgs.msg import Twist from sensor_msgs.msg import Range import", "commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks =", "def twistCallback(self,msg): self.ticks_since_target = 0 self.dx = msg.linear.x self.dr = msg.angular.z self.dy =", "= np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) # Assigning the calculated velocities to each motors", "self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def spinOnce(self): # Calculating the individual motor", "Subscribe to the velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate =", "= 0 self.right = 0 self.back = 0 def spin(self): r = rospy.Rate(self.rate)", "np.array([self.dx, self.dy, self.dr])) # Assigning the calculated velocities to each motors self.right =", "self.ticks_since_target += 1 # Callback function def twistCallback(self,msg): self.ticks_since_target = 0 self.dx =", "<filename>robotino_ros/src/twist_motor_omni.py #!/usr/bin/env python import rospy import roslib import math from std_msgs.msg import Float32,Int32,", "Float32,queue_size=10) # Subscribe to the velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10)", "function def twistCallback(self,msg): self.ticks_since_target = 0 self.dx = msg.linear.x self.dr = msg.angular.z self.dy", "self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to the velocity", "Twist, self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left =", "Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to the", "= rospy.get_name() rospy.loginfo(\"%s started\" % nodename) self.M_PI = math.pi self.motor_velocities = [] #", "0 def spin(self): r = rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while", "and self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def spinOnce(self): # Calculating the individual", "from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\",", "self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left = 0 self.right =", "self.right = v_r self.left = v_l self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target", "= msg.angular.z self.dy = msg.linear.y if __name__ == '__main__': \"\"\" main \"\"\" twistToMotors", "rospy.get_name() rospy.loginfo(\"%s started\" % nodename) self.M_PI = math.pi self.motor_velocities = [] # Create", "self.dx = msg.linear.x self.dr = msg.angular.z self.dy = msg.linear.y if __name__ == '__main__':", "controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10)", "+= 1 # Callback function def twistCallback(self,msg): self.ticks_since_target = 0 self.dx = msg.linear.x", "self.motor_velocities = [] # Create publishers that publishes target velocity to the PID", "r.sleep() idle.sleep() def spinOnce(self): # Calculating the individual motor velocity for a motion", "twistCallback(self,msg): self.ticks_since_target = 0 self.dx = msg.linear.x self.dr = msg.angular.z self.dy = msg.linear.y", "numpy import linalg as al class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name()", "Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to the velocity commands from teleop", "not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def spinOnce(self): # Calculating", "the velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\", 100)", "Assigning the calculated velocities to each motors self.right = v_r self.left = v_l", "while not rospy.is_shutdown(): while not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep()", "# Calculating the individual motor velocity for a motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)),", "each motors self.right = v_r self.left = v_l self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right)", "to the velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\",", "def __init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s started\" % nodename) self.M_PI = math.pi", "idle = rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while not rospy.is_shutdown(): while not rospy.is_shutdown() and", "numpy as np from numpy import linalg as al class TwistToMotors(): def __init__(self):", "= rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe", "linalg as al class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s started\"", "rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to", "TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s started\" % nodename) self.M_PI =", "rospy.get_param(\"~timeout_ticks\", 100) self.left = 0 self.right = 0 self.back = 0 def spin(self):", "[-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv = al.inv(angle_mat) [v_r, v_l, v_b] = np.dot(angle_mat_inv,", "msg.angular.z self.dy = msg.linear.y if __name__ == '__main__': \"\"\" main \"\"\" twistToMotors =", "= rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left = 0 self.right = 0", "[v_r, v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) # Assigning the calculated velocities", "self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 # Callback function def twistCallback(self,msg): self.ticks_since_target = 0", "Calculating the individual motor velocity for a motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)),", "the PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor =", "import Range import numpy as np from numpy import linalg as al class", "self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 # Callback function def twistCallback(self,msg): self.ticks_since_target =", "= msg.linear.y if __name__ == '__main__': \"\"\" main \"\"\" twistToMotors = TwistToMotors() twistToMotors.spin()", "nodename) self.M_PI = math.pi self.motor_velocities = [] # Create publishers that publishes target", "Callback function def twistCallback(self,msg): self.ticks_since_target = 0 self.dx = msg.linear.x self.dr = msg.angular.z", "from sensor_msgs.msg import Range import numpy as np from numpy import linalg as", "rospy.is_shutdown(): while not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def spinOnce(self):", "= rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to the velocity commands", "= v_l self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 # Callback", "= rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while not rospy.is_shutdown(): while not rospy.is_shutdown() and self.ticks_since_target", "self.dy = msg.linear.y if __name__ == '__main__': \"\"\" main \"\"\" twistToMotors = TwistToMotors()", "target velocity to the PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget',", "0 self.right = 0 self.back = 0 def spin(self): r = rospy.Rate(self.rate) idle", "self.right = 0 self.back = 0 def spin(self): r = rospy.Rate(self.rate) idle =", "import rospy import roslib import math from std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool, String", "as al class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s started\" %", "= [] # Create publishers that publishes target velocity to the PID controller", "sensor_msgs.msg import Range import numpy as np from numpy import linalg as al", "Create publishers that publishes target velocity to the PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget',", "rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to the velocity commands from", "individual motor velocity for a motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)),", "= math.pi self.motor_velocities = [] # Create publishers that publishes target velocity to", "a motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]])", "Range import numpy as np from numpy import linalg as al class TwistToMotors():", "rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s started\" % nodename) self.M_PI = math.pi self.motor_velocities =", "# Callback function def twistCallback(self,msg): self.ticks_since_target = 0 self.dx = msg.linear.x self.dr =", "Twist from sensor_msgs.msg import Range import numpy as np from numpy import linalg", "String from geometry_msgs.msg import Twist from sensor_msgs.msg import Range import numpy as np", "v_r self.left = v_l self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1", "al.inv(angle_mat) [v_r, v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) # Assigning the calculated", "= v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 # Callback function def twistCallback(self,msg):", "from numpy import linalg as al class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename =", "nodename = rospy.get_name() rospy.loginfo(\"%s started\" % nodename) self.M_PI = math.pi self.motor_velocities = []", "= np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv = al.inv(angle_mat) [v_r,", "< self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def spinOnce(self): # Calculating the individual motor velocity", "from geometry_msgs.msg import Twist from sensor_msgs.msg import Range import numpy as np from", "velocities to each motors self.right = v_r self.left = v_l self.back = v_b", "velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks", "math from std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool, String from geometry_msgs.msg import Twist from", "spinOnce(self): # Calculating the individual motor velocity for a motion command angle_mat =", "publishes target velocity to the PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor =", "angle_mat_inv = al.inv(angle_mat) [v_r, v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) # Assigning", "self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left = 0 self.right = 0 self.back = 0", "= v_r self.left = v_l self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target +=", "al class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s started\" % nodename)", "np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) # Assigning the calculated velocities to each motors self.right", "self.dr = msg.angular.z self.dy = msg.linear.y if __name__ == '__main__': \"\"\" main \"\"\"", "from std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool, String from geometry_msgs.msg import Twist from sensor_msgs.msg", "for a motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1,", "0 self.dx = msg.linear.x self.dr = msg.angular.z self.dy = msg.linear.y if __name__ ==", "1]]) angle_mat_inv = al.inv(angle_mat) [v_r, v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) #", "= rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while not rospy.is_shutdown(): while not", "__init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s started\" % nodename) self.M_PI = math.pi self.motor_velocities", "roslib import math from std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool, String from geometry_msgs.msg import", "self.timeout_ticks while not rospy.is_shutdown(): while not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep()", "rospy import roslib import math from std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool, String from", "not rospy.is_shutdown(): while not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def", "np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv = al.inv(angle_mat) [v_r, v_l,", "0 self.back = 0 def spin(self): r = rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target", "= rospy.get_param(\"~timeout_ticks\", 100) self.left = 0 self.right = 0 self.back = 0 def", "1 # Callback function def twistCallback(self,msg): self.ticks_since_target = 0 self.dx = msg.linear.x self.dr", "v_l self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 # Callback function", "motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv", "calculated velocities to each motors self.right = v_r self.left = v_l self.back =", "command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv =", "rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while not rospy.is_shutdown(): while not rospy.is_shutdown() and self.ticks_since_target <", "python import rospy import roslib import math from std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool,", "-math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv = al.inv(angle_mat) [v_r, v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx,", "queue_size=10) self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left = 0 self.right", "self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def spinOnce(self): # Calculating the individual motor velocity for", "= 0 def spin(self): r = rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target = self.timeout_ticks", "motors self.right = v_r self.left = v_l self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back)", "#!/usr/bin/env python import rospy import roslib import math from std_msgs.msg import Float32,Int32, UInt8MultiArray,", "rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left", "to each motors self.right = v_r self.left = v_l self.back = v_b self.pub_lmotor.publish(self.left)", "self.dy, self.dr])) # Assigning the calculated velocities to each motors self.right = v_r", "math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv = al.inv(angle_mat) [v_r, v_l, v_b] =", "spin(self): r = rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while not rospy.is_shutdown():", "self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left = 0", "std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool, String from geometry_msgs.msg import Twist from sensor_msgs.msg import", "velocity for a motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1,", "100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left = 0 self.right = 0 self.back =", "Bool, String from geometry_msgs.msg import Twist from sensor_msgs.msg import Range import numpy as", "= self.timeout_ticks while not rospy.is_shutdown(): while not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks: self.spinOnce()", "math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv = al.inv(angle_mat) [v_r, v_l, v_b]", "r = rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while not rospy.is_shutdown(): while", "[] # Create publishers that publishes target velocity to the PID controller self.pub_lmotor", "import linalg as al class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename = rospy.get_name() rospy.loginfo(\"%s", "rospy.loginfo(\"%s started\" % nodename) self.M_PI = math.pi self.motor_velocities = [] # Create publishers", "started\" % nodename) self.M_PI = math.pi self.motor_velocities = [] # Create publishers that", "publishers that publishes target velocity to the PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10)", "rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100) self.left = 0 self.right = 0 self.back", "rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def spinOnce(self): # Calculating the", "# Create publishers that publishes target velocity to the PID controller self.pub_lmotor =", "self.pub_bmotor = rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to the velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel',", "self.spinOnce() r.sleep() idle.sleep() def spinOnce(self): # Calculating the individual motor velocity for a", "[1, 1, 1]]) angle_mat_inv = al.inv(angle_mat) [v_r, v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy,", "1, 1]]) angle_mat_inv = al.inv(angle_mat) [v_r, v_l, v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr]))", "100) self.left = 0 self.right = 0 self.back = 0 def spin(self): r", "self.back = v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 # Callback function def", "import Float32,Int32, UInt8MultiArray, Bool, String from geometry_msgs.msg import Twist from sensor_msgs.msg import Range", "UInt8MultiArray, Bool, String from geometry_msgs.msg import Twist from sensor_msgs.msg import Range import numpy", "v_b] = np.dot(angle_mat_inv, np.array([self.dx, self.dy, self.dr])) # Assigning the calculated velocities to each", "import math from std_msgs.msg import Float32,Int32, UInt8MultiArray, Bool, String from geometry_msgs.msg import Twist", "np from numpy import linalg as al class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\") nodename", "= rospy.Publisher('bwheel_vtarget', Float32,queue_size=10) # Subscribe to the velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist,", "while not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks: self.spinOnce() r.sleep() idle.sleep() def spinOnce(self): #", "angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))], [-math.sin(30*(self.M_PI/180)), -math.sin(150*(self.M_PI/180)),math.sin(90*(self.M_PI/180))], [1, 1, 1]]) angle_mat_inv = al.inv(angle_mat)", "self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 # Callback function def twistCallback(self,msg): self.ticks_since_target = 0 self.dx", "PID controller self.pub_lmotor = rospy.Publisher('lwheel_vtarget', Float32,queue_size=10) self.pub_rmotor = rospy.Publisher('rwheel_vtarget', Float32,queue_size=10) self.pub_bmotor = rospy.Publisher('bwheel_vtarget',", "= 0 self.dx = msg.linear.x self.dr = msg.angular.z self.dy = msg.linear.y if __name__", "self.back = 0 def spin(self): r = rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target =", "rospy.Rate(self.rate) idle = rospy.Rate(100) self.ticks_since_target = self.timeout_ticks while not rospy.is_shutdown(): while not rospy.is_shutdown()", "teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate = rospy.get_param(\"~rate\", 100) self.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 100)", "# Assigning the calculated velocities to each motors self.right = v_r self.left =", "self.ticks_since_target = 0 self.dx = msg.linear.x self.dr = msg.angular.z self.dy = msg.linear.y if", "as np from numpy import linalg as al class TwistToMotors(): def __init__(self): rospy.init_node(\"twist_to_motors\")", "# Subscribe to the velocity commands from teleop rospy.Subscriber('/robotino/cmd_vel', Twist, self.twistCallback, queue_size=10) self.rate", "the individual motor velocity for a motion command angle_mat = np.array([[math.cos(30*(self.M_PI/180)), math.cos(150*(self.M_PI/180)), math.cos(90*(self.M_PI/180))],", "v_b self.pub_lmotor.publish(self.left) self.pub_rmotor.publish(self.right) self.pub_bmotor.publish(self.back) self.ticks_since_target += 1 # Callback function def twistCallback(self,msg): self.ticks_since_target", "import Twist from sensor_msgs.msg import Range import numpy as np from numpy import", "self.M_PI = math.pi self.motor_velocities = [] # Create publishers that publishes target velocity", "= 0 self.back = 0 def spin(self): r = rospy.Rate(self.rate) idle = rospy.Rate(100)", "math.pi self.motor_velocities = [] # Create publishers that publishes target velocity to the", "the calculated velocities to each motors self.right = v_r self.left = v_l self.back", "% nodename) self.M_PI = math.pi self.motor_velocities = [] # Create publishers that publishes", "import numpy as np from numpy import linalg as al class TwistToMotors(): def" ]
[ "in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final, promotion_piece = move[:2],", "stockfish = Stockfish() move_list = [] for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return", "initial[1], initial[0] f_x, f_y = final[1], final[0] i_y = ord(i_y) - ord(\"a\") f_y", "= [] for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial,", "def long_algebraic_to_coordinate(move): initial, final, promotion_piece = move[:2], move[2:4], move[4:] i_x, i_y = initial[1],", "ord(f_y) - ord(\"a\") i_x = 8 - int(i_x) f_x = 8 - int(f_x)", "i_y = initial[1], initial[0] f_x, f_y = final[1], final[0] i_y = ord(i_y) -", "= Stockfish() move_list = [] for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move())", "long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final, promotion_piece = move[:2], move[2:4], move[4:] i_x, i_y =", "move[2:4], move[4:] i_x, i_y = initial[1], initial[0] f_x, f_y = final[1], final[0] i_y", "- ord(\"a\") f_y = ord(f_y) - ord(\"a\") i_x = 8 - int(i_x) f_x", "move[:2], move[2:4], move[4:] i_x, i_y = initial[1], initial[0] f_x, f_y = final[1], final[0]", "final[0] i_y = ord(i_y) - ord(\"a\") f_y = ord(f_y) - ord(\"a\") i_x =", "move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final, promotion_piece = move[:2], move[2:4], move[4:]", "get_best_move(board): stockfish = Stockfish() move_list = [] for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list)", "move_list = [] for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move):", "return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final, promotion_piece = move[:2], move[2:4], move[4:] i_x, i_y", "ord(\"a\") f_y = ord(f_y) - ord(\"a\") i_x = 8 - int(i_x) f_x =", "ord(\"a\") i_x = 8 - int(i_x) f_x = 8 - int(f_x) return ((i_x,", "f_x, f_y = final[1], final[0] i_y = ord(i_y) - ord(\"a\") f_y = ord(f_y)", "= final[1], final[0] i_y = ord(i_y) - ord(\"a\") f_y = ord(f_y) - ord(\"a\")", "ord(i_y) - ord(\"a\") f_y = ord(f_y) - ord(\"a\") i_x = 8 - int(i_x)", "- int(i_x) f_x = 8 - int(f_x) return ((i_x, i_y), (f_x, f_y), promotion_piece)", "i_x = 8 - int(i_x) f_x = 8 - int(f_x) return ((i_x, i_y),", "move[4:] i_x, i_y = initial[1], initial[0] f_x, f_y = final[1], final[0] i_y =", "= ord(i_y) - ord(\"a\") f_y = ord(f_y) - ord(\"a\") i_x = 8 -", "long_algebraic_to_coordinate(move): initial, final, promotion_piece = move[:2], move[2:4], move[4:] i_x, i_y = initial[1], initial[0]", "= 8 - int(i_x) f_x = 8 - int(f_x) return ((i_x, i_y), (f_x,", "Stockfish() move_list = [] for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def", "<gh_stars>1-10 from stockfish import Stockfish def get_best_move(board): stockfish = Stockfish() move_list = []", "from stockfish import Stockfish def get_best_move(board): stockfish = Stockfish() move_list = [] for", "= initial[1], initial[0] f_x, f_y = final[1], final[0] i_y = ord(i_y) - ord(\"a\")", "= ord(f_y) - ord(\"a\") i_x = 8 - int(i_x) f_x = 8 -", "- ord(\"a\") i_x = 8 - int(i_x) f_x = 8 - int(f_x) return", "i_x, i_y = initial[1], initial[0] f_x, f_y = final[1], final[0] i_y = ord(i_y)", "i_y = ord(i_y) - ord(\"a\") f_y = ord(f_y) - ord(\"a\") i_x = 8", "f_y = ord(f_y) - ord(\"a\") i_x = 8 - int(i_x) f_x = 8", "Stockfish def get_best_move(board): stockfish = Stockfish() move_list = [] for move in board.moves:", "[] for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final,", "= move[:2], move[2:4], move[4:] i_x, i_y = initial[1], initial[0] f_x, f_y = final[1],", "final, promotion_piece = move[:2], move[2:4], move[4:] i_x, i_y = initial[1], initial[0] f_x, f_y", "final[1], final[0] i_y = ord(i_y) - ord(\"a\") f_y = ord(f_y) - ord(\"a\") i_x", "f_y = final[1], final[0] i_y = ord(i_y) - ord(\"a\") f_y = ord(f_y) -", "move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final, promotion_piece =", "import Stockfish def get_best_move(board): stockfish = Stockfish() move_list = [] for move in", "initial, final, promotion_piece = move[:2], move[2:4], move[4:] i_x, i_y = initial[1], initial[0] f_x,", "initial[0] f_x, f_y = final[1], final[0] i_y = ord(i_y) - ord(\"a\") f_y =", "stockfish import Stockfish def get_best_move(board): stockfish = Stockfish() move_list = [] for move", "board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final, promotion_piece = move[:2], move[2:4],", "promotion_piece = move[:2], move[2:4], move[4:] i_x, i_y = initial[1], initial[0] f_x, f_y =", "def get_best_move(board): stockfish = Stockfish() move_list = [] for move in board.moves: move_list.append(move.to_long_algebraic())", "8 - int(i_x) f_x = 8 - int(f_x) return ((i_x, i_y), (f_x, f_y),", "for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final, promotion_piece", "stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move()) def long_algebraic_to_coordinate(move): initial, final, promotion_piece = move[:2], move[2:4], move[4:] i_x," ]
[ "from ..gameModel import GameModel from ..appLib.messageFormatters import msgWelcome async def start(cls: GameModel) ->", "GameModel from ..appLib.messageFormatters import msgWelcome async def start(cls: GameModel) -> None: return msgWelcome()", "<gh_stars>0 from ..gameModel import GameModel from ..appLib.messageFormatters import msgWelcome async def start(cls: GameModel)", "..gameModel import GameModel from ..appLib.messageFormatters import msgWelcome async def start(cls: GameModel) -> None:", "import GameModel from ..appLib.messageFormatters import msgWelcome async def start(cls: GameModel) -> None: return" ]
[ "multiplicação desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import * from numeros import", "print() resposta = ' ' while resposta not in 'SN': resposta = ler_resposta('\\nDeseja", "resposta = ler_resposta('\\nDeseja rodar o programa de novo? [S/N] ') if resposta ==", "in 'SN': resposta = ler_resposta('\\nDeseja rodar o programa de novo? [S/N] ') if", "programa retorna a tabuada de multiplicação desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem", "tabuada de multiplicação desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import * from", "inteiro e programa retorna a tabuada de multiplicação desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos')", "Descrição: Usuário digita um número inteiro e programa retorna a tabuada de multiplicação", "retorna a tabuada de multiplicação desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import", "import * from numeros import ler_num_nat ler_cabecalho('tabuada de multiplicação') while True: num =", "e programa retorna a tabuada de multiplicação desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from", "= 1 for i in range(i, 10): print(f'{num:4} x {i} = {num*i}') print()", "for i in range(i, 10): print(f'{num:4} x {i} = {num*i}') print() resposta =", "print(f'{num:4} x {i} = {num*i}') print() resposta = ' ' while resposta not", "= {num*i}') print() resposta = ' ' while resposta not in 'SN': resposta", "True: num = ler_num_nat('Digite um número: ') i = 1 for i in", "* from numeros import ler_num_nat ler_cabecalho('tabuada de multiplicação') while True: num = ler_num_nat('Digite", "python3.8 ######## # autora: <EMAIL> # repositório: https://github.com/danielle8farias # Descrição: Usuário digita um", "repositório: https://github.com/danielle8farias # Descrição: Usuário digita um número inteiro e programa retorna a", "https://github.com/danielle8farias # Descrição: Usuário digita um número inteiro e programa retorna a tabuada", "rodar o programa de novo? [S/N] ') if resposta == 'N': break criar_linha()", "') i = 1 for i in range(i, 10): print(f'{num:4} x {i} =", "10): print(f'{num:4} x {i} = {num*i}') print() resposta = ' ' while resposta", "ler_num_nat ler_cabecalho('tabuada de multiplicação') while True: num = ler_num_nat('Digite um número: ') i", "i in range(i, 10): print(f'{num:4} x {i} = {num*i}') print() resposta = '", "ler_resposta('\\nDeseja rodar o programa de novo? [S/N] ') if resposta == 'N': break", "i = 1 for i in range(i, 10): print(f'{num:4} x {i} = {num*i}')", "range(i, 10): print(f'{num:4} x {i} = {num*i}') print() resposta = ' ' while", "Usuário digita um número inteiro e programa retorna a tabuada de multiplicação desse.", "sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import * from numeros import ler_num_nat ler_cabecalho('tabuada de multiplicação') while", "<gh_stars>0 #!/usr/bin/env python3.8 ######## # autora: <EMAIL> # repositório: https://github.com/danielle8farias # Descrição: Usuário", "######## # autora: <EMAIL> # repositório: https://github.com/danielle8farias # Descrição: Usuário digita um número", "num = ler_num_nat('Digite um número: ') i = 1 for i in range(i,", "a tabuada de multiplicação desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import *", "x {i} = {num*i}') print() resposta = ' ' while resposta not in", "ler_num_nat('Digite um número: ') i = 1 for i in range(i, 10): print(f'{num:4}", "de multiplicação') while True: num = ler_num_nat('Digite um número: ') i = 1", "1 for i in range(i, 10): print(f'{num:4} x {i} = {num*i}') print() resposta", "um número inteiro e programa retorna a tabuada de multiplicação desse. ######## import", "import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import * from numeros import ler_num_nat ler_cabecalho('tabuada de", "######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import * from numeros import ler_num_nat ler_cabecalho('tabuada", "{num*i}') print() resposta = ' ' while resposta not in 'SN': resposta =", "' while resposta not in 'SN': resposta = ler_resposta('\\nDeseja rodar o programa de", "= ler_resposta('\\nDeseja rodar o programa de novo? [S/N] ') if resposta == 'N':", "= ' ' while resposta not in 'SN': resposta = ler_resposta('\\nDeseja rodar o", "= ler_num_nat('Digite um número: ') i = 1 for i in range(i, 10):", "número inteiro e programa retorna a tabuada de multiplicação desse. ######## import sys", "while True: num = ler_num_nat('Digite um número: ') i = 1 for i", "{i} = {num*i}') print() resposta = ' ' while resposta not in 'SN':", "'SN': resposta = ler_resposta('\\nDeseja rodar o programa de novo? [S/N] ') if resposta", "autora: <EMAIL> # repositório: https://github.com/danielle8farias # Descrição: Usuário digita um número inteiro e", "mensagem import * from numeros import ler_num_nat ler_cabecalho('tabuada de multiplicação') while True: num", "from mensagem import * from numeros import ler_num_nat ler_cabecalho('tabuada de multiplicação') while True:", "resposta not in 'SN': resposta = ler_resposta('\\nDeseja rodar o programa de novo? [S/N]", "multiplicação') while True: num = ler_num_nat('Digite um número: ') i = 1 for", "# repositório: https://github.com/danielle8farias # Descrição: Usuário digita um número inteiro e programa retorna", "número: ') i = 1 for i in range(i, 10): print(f'{num:4} x {i}", "# Descrição: Usuário digita um número inteiro e programa retorna a tabuada de", "' ' while resposta not in 'SN': resposta = ler_resposta('\\nDeseja rodar o programa", "digita um número inteiro e programa retorna a tabuada de multiplicação desse. ########", "#!/usr/bin/env python3.8 ######## # autora: <EMAIL> # repositório: https://github.com/danielle8farias # Descrição: Usuário digita", "<EMAIL> # repositório: https://github.com/danielle8farias # Descrição: Usuário digita um número inteiro e programa", "de multiplicação desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import * from numeros", "sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import * from numeros import ler_num_nat ler_cabecalho('tabuada de multiplicação')", "um número: ') i = 1 for i in range(i, 10): print(f'{num:4} x", "numeros import ler_num_nat ler_cabecalho('tabuada de multiplicação') while True: num = ler_num_nat('Digite um número:", "import ler_num_nat ler_cabecalho('tabuada de multiplicação') while True: num = ler_num_nat('Digite um número: ')", "in range(i, 10): print(f'{num:4} x {i} = {num*i}') print() resposta = ' '", "resposta = ' ' while resposta not in 'SN': resposta = ler_resposta('\\nDeseja rodar", "o programa de novo? [S/N] ') if resposta == 'N': break criar_linha() criar_rodape()", "desse. ######## import sys sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos') from mensagem import * from numeros import ler_num_nat", "from numeros import ler_num_nat ler_cabecalho('tabuada de multiplicação') while True: num = ler_num_nat('Digite um", "while resposta not in 'SN': resposta = ler_resposta('\\nDeseja rodar o programa de novo?", "ler_cabecalho('tabuada de multiplicação') while True: num = ler_num_nat('Digite um número: ') i =", "not in 'SN': resposta = ler_resposta('\\nDeseja rodar o programa de novo? [S/N] ')", "# autora: <EMAIL> # repositório: https://github.com/danielle8farias # Descrição: Usuário digita um número inteiro" ]
[ "= ( ('VeryMild', 'Very mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild +'), ) temperature_choices =", "bean_amount_choices = ( ('VeryMild', 'Very mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild +'), ) temperature_choices", "models here. class Beverage(models.Model): \"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name =", "class Beverage(models.Model): \"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) key", "'Very mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild +'), ) temperature_choices = ( ('88C', '88", "= models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps = models.IntegerField() def __str__(self): return str(self.name) class", ") created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices,", "('92C', '92 °C'), ) created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount", "null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature = models.CharField(max_length=100, choices=temperature_choices,", "('88C', '88 °C'), ('90C', '90 °C'), ('92C', '92 °C'), ) created_by = models.ForeignKey('auth.User',", "created_at = models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature = models.CharField(max_length=100, choices=temperature_choices, default='90C')", "temperature_choices = ( ('88C', '88 °C'), ('90C', '90 °C'), ('92C', '92 °C'), )", "models.IntegerField() fill_quantity_steps = models.IntegerField() def __str__(self): return str(self.name) class BeverageHistory(models.Model): bean_amount_choices = (", "= models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature = models.CharField(max_length=100, choices=temperature_choices, default='90C') beverage", "timezone # Create your models here. class Beverage(models.Model): \"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User',", "key = models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps", "def __str__(self): return str(self.name) class BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild', 'Very mild'), ('Mild',", "\"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) key = models.CharField(max_length=100)", "= models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps = models.IntegerField() def __str__(self):", "django.db import models from django.utils import timezone # Create your models here. class", "BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild', 'Very mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild +'), )", "return str(self.name) class BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild', 'Very mild'), ('Mild', 'Mild'), ('MildPlus',", "('90C', '90 °C'), ('92C', '92 °C'), ) created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at", "models.IntegerField() def __str__(self): return str(self.name) class BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild', 'Very mild'),", "__str__(self): return str(self.name) class BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild', 'Very mild'), ('Mild', 'Mild'),", "'Mild +'), ) temperature_choices = ( ('88C', '88 °C'), ('90C', '90 °C'), ('92C',", "null=True) name = models.CharField(max_length=100) key = models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min = models.IntegerField()", "class BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild', 'Very mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild +'),", "models from django.utils import timezone # Create your models here. class Beverage(models.Model): \"\"\"(", "= models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature = models.CharField(max_length=100, choices=temperature_choices, default='90C') beverage = models.ForeignKey(Beverage, on_delete=models.CASCADE)", "°C'), ('90C', '90 °C'), ('92C', '92 °C'), ) created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True)", "= models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature", "bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature = models.CharField(max_length=100, choices=temperature_choices, default='90C') beverage = models.ForeignKey(Beverage,", "( ('VeryMild', 'Very mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild +'), ) temperature_choices = (", "here. class Beverage(models.Model): \"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100)", "created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) key = models.CharField(max_length=100) description =", "models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature =", "('Mild', 'Mild'), ('MildPlus', 'Mild +'), ) temperature_choices = ( ('88C', '88 °C'), ('90C',", "from django.utils import timezone # Create your models here. class Beverage(models.Model): \"\"\"( description)\"\"\"", "fill_quantity_steps = models.IntegerField() def __str__(self): return str(self.name) class BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild',", "on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature = models.CharField(max_length=100,", "= models.IntegerField() fill_quantity_steps = models.IntegerField() def __str__(self): return str(self.name) class BeverageHistory(models.Model): bean_amount_choices =", "( ('88C', '88 °C'), ('90C', '90 °C'), ('92C', '92 °C'), ) created_by =", "django.utils import timezone # Create your models here. class Beverage(models.Model): \"\"\"( description)\"\"\" created_by", "= models.CharField(max_length=100) key = models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max =", "created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild')", "fill_quantity_min = models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps = models.IntegerField() def __str__(self): return str(self.name)", "models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) key = models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min", "= models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) key = models.CharField(max_length=100) description = models.CharField(max_length=200)", "description = models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps = models.IntegerField() def", "= ( ('88C', '88 °C'), ('90C', '90 °C'), ('92C', '92 °C'), ) created_by", "'88 °C'), ('90C', '90 °C'), ('92C', '92 °C'), ) created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL,", "models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps = models.IntegerField()", "models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps = models.IntegerField() def __str__(self): return str(self.name) class BeverageHistory(models.Model):", "str(self.name) class BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild', 'Very mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild", "import models from django.utils import timezone # Create your models here. class Beverage(models.Model):", "models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100, choices=bean_amount_choices, default='Mild') temperature = models.CharField(max_length=100, choices=temperature_choices, default='90C') beverage =", "your models here. class Beverage(models.Model): \"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name", "models.CharField(max_length=100) key = models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max = models.IntegerField()", "°C'), ) created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount = models.CharField(max_length=100,", "'Mild'), ('MildPlus', 'Mild +'), ) temperature_choices = ( ('88C', '88 °C'), ('90C', '90", "Beverage(models.Model): \"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) key =", "'90 °C'), ('92C', '92 °C'), ) created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at =", "import timezone # Create your models here. class Beverage(models.Model): \"\"\"( description)\"\"\" created_by =", "description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) key = models.CharField(max_length=100) description", "mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild +'), ) temperature_choices = ( ('88C', '88 °C'),", "from django.db import models from django.utils import timezone # Create your models here.", "on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) key = models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min =", "'92 °C'), ) created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now) bean_amount =", ") temperature_choices = ( ('88C', '88 °C'), ('90C', '90 °C'), ('92C', '92 °C'),", "+'), ) temperature_choices = ( ('88C', '88 °C'), ('90C', '90 °C'), ('92C', '92", "Create your models here. class Beverage(models.Model): \"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True)", "('VeryMild', 'Very mild'), ('Mild', 'Mild'), ('MildPlus', 'Mild +'), ) temperature_choices = ( ('88C',", "= models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps =", "name = models.CharField(max_length=100) key = models.CharField(max_length=100) description = models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max", "models.CharField(max_length=200) fill_quantity_min = models.IntegerField() fill_quantity_max = models.IntegerField() fill_quantity_steps = models.IntegerField() def __str__(self): return", "('MildPlus', 'Mild +'), ) temperature_choices = ( ('88C', '88 °C'), ('90C', '90 °C'),", "°C'), ('92C', '92 °C'), ) created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=timezone.now)", "fill_quantity_max = models.IntegerField() fill_quantity_steps = models.IntegerField() def __str__(self): return str(self.name) class BeverageHistory(models.Model): bean_amount_choices", "# Create your models here. class Beverage(models.Model): \"\"\"( description)\"\"\" created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL,", "= models.IntegerField() def __str__(self): return str(self.name) class BeverageHistory(models.Model): bean_amount_choices = ( ('VeryMild', 'Very" ]
[ "parse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+', help='Path to the source", "or path.lower().endswith('.yaml'): with open(path, 'r') as f: return yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path,", "required=True, dest='sources', nargs='+', help='Path to the source file') parser.add_argument('-e', '--use-env', action='store_true', help='Use environment", "file') parser.add_argument('-o', '--output', required=True, help='Path for output file') return parser.parse_args() def main(): args", "import argparse import json import yaml import os import logging from collections import", "import logging from collections import OrderedDict from glu.util import OrderedDictYamlLoader from glu import", "help='Path to the source file') parser.add_argument('-e', '--use-env', action='store_true', help='Use environment variable') parser.add_argument('-t', '--template',", "path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path, 'r') as f: return yaml.load(f, Loader=OrderedDictYamlLoader) else: with", "Loader=OrderedDictYamlLoader) else: with open(path, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri):", "in params.split('&')) scope.load(load_file(path), **params) def parse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources',", "params = file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&')) scope.load(load_file(path), **params) def", "{} if '?' in file_uri: path, params = file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for", "**params) def parse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+', help='Path to", "source file') parser.add_argument('-e', '--use-env', action='store_true', help='Use environment variable') parser.add_argument('-t', '--template', required=True, help='Path to", "main(): args = parse() scope = create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri", "load_scope_from_file(scope, file_uri): path = file_uri params = {} if '?' in file_uri: path,", "def parse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+', help='Path to the", "'--output', required=True, help='Path for output file') return parser.parse_args() def main(): args = parse()", "yaml import os import logging from collections import OrderedDict from glu.util import OrderedDictYamlLoader", "json import yaml import os import logging from collections import OrderedDict from glu.util", "params = {} if '?' in file_uri: path, params = file_uri.split('?') params =", "= create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri in args.sources: load_scope_from_file(scope, file_uri) template", "help='Path for output file') return parser.parse_args() def main(): args = parse() scope =", "parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+', help='Path to the source file') parser.add_argument('-e', '--use-env', action='store_true',", "file_uri params = {} if '?' in file_uri: path, params = file_uri.split('?') params", "to the source file') parser.add_argument('-e', '--use-env', action='store_true', help='Use environment variable') parser.add_argument('-t', '--template', required=True,", "import os import logging from collections import OrderedDict from glu.util import OrderedDictYamlLoader from", "create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri in args.sources: load_scope_from_file(scope, file_uri) template =", "import OrderedDict from glu.util import OrderedDictYamlLoader from glu import create_scope def load_file(path): if", "import yaml import os import logging from collections import OrderedDict from glu.util import", "os import logging from collections import OrderedDict from glu.util import OrderedDictYamlLoader from glu", "in args.sources: load_scope_from_file(scope, file_uri) template = load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with", "help='Use environment variable') parser.add_argument('-t', '--template', required=True, help='Path to the template file') parser.add_argument('-o', '--output',", "template = load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w') as f:", "'r') as f: return yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path, 'r') as f: return", "file_uri: path, params = file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&')) scope.load(load_file(path),", "as f: return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path = file_uri params =", "args = parse() scope = create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri in", "from glu.util import OrderedDictYamlLoader from glu import create_scope def load_file(path): if path.lower().endswith('.yml') or", "import OrderedDictYamlLoader from glu import create_scope def load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with", "for field_and_value in params.split('&')) scope.load(load_file(path), **params) def parse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source',", "with open(path, 'r') as f: return yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path, 'r') as", "if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri in args.sources: load_scope_from_file(scope, file_uri) template = load_file(args.template)", "path = file_uri params = {} if '?' in file_uri: path, params =", "file') return parser.parse_args() def main(): args = parse() scope = create_scope() if args.use_env:", "parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+', help='Path to the source file')", "import create_scope def load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path, 'r') as f:", "return yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict) def", "= load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w') as f: json.dump(res,", "file') parser.add_argument('-e', '--use-env', action='store_true', help='Use environment variable') parser.add_argument('-t', '--template', required=True, help='Path to the", "required=True, help='Path for output file') return parser.parse_args() def main(): args = parse() scope", "load_scope_from_file(scope, file_uri) template = load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w')", "parse() scope = create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri in args.sources: load_scope_from_file(scope,", "def main(): args = parse() scope = create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for", "= parse() scope = create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri in args.sources:", "def load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path, 'r') as f: return yaml.load(f,", "logging from collections import OrderedDict from glu.util import OrderedDictYamlLoader from glu import create_scope", "def load_scope_from_file(scope, file_uri): path = file_uri params = {} if '?' in file_uri:", "scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w') as f: json.dump(res, f, indent=2, separators=(',', ':", "return parser.parse_args() def main(): args = parse() scope = create_scope() if args.use_env: scope.load(dict(os.environ.items()),", "'r') as f: return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path = file_uri params", "output file') return parser.parse_args() def main(): args = parse() scope = create_scope() if", "= {} if '?' in file_uri: path, params = file_uri.split('?') params = dict(tuple(field_and_value.split('='))", "parser.add_argument('-o', '--output', required=True, help='Path for output file') return parser.parse_args() def main(): args =", "file_uri) template = load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w') as", "if '?' in file_uri: path, params = file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for field_and_value", "'--use-env', action='store_true', help='Use environment variable') parser.add_argument('-t', '--template', required=True, help='Path to the template file')", "args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri in args.sources: load_scope_from_file(scope, file_uri) template = load_file(args.template) res", "with open(path, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path =", "parser.add_argument('-t', '--template', required=True, help='Path to the template file') parser.add_argument('-o', '--output', required=True, help='Path for", "f: return yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict)", "'?' in file_uri: path, params = file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for field_and_value in", "load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path, 'r') as f: return yaml.load(f, Loader=OrderedDictYamlLoader)", "import json import yaml import os import logging from collections import OrderedDict from", "indent=2))) with open(args.output, 'w') as f: json.dump(res, f, indent=2, separators=(',', ': ')) f.write('\\n')", "scope.load(dict(os.environ.items()), load_to='@env') for file_uri in args.sources: load_scope_from_file(scope, file_uri) template = load_file(args.template) res =", "= argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+', help='Path to the source file') parser.add_argument('-e',", "required=True, help='Path to the template file') parser.add_argument('-o', '--output', required=True, help='Path for output file')", "file_uri in args.sources: load_scope_from_file(scope, file_uri) template = load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2)))", "template file') parser.add_argument('-o', '--output', required=True, help='Path for output file') return parser.parse_args() def main():", "params.split('&')) scope.load(load_file(path), **params) def parse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+',", "path, params = file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&')) scope.load(load_file(path), **params)", "in file_uri: path, params = file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&'))", "field_and_value in params.split('&')) scope.load(load_file(path), **params) def parse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True,", "from glu import create_scope def load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path, 'r')", "logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w') as f: json.dump(res, f, indent=2, separators=(',', ': '))", "argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+', help='Path to the source file') parser.add_argument('-e', '--use-env',", "object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path = file_uri params = {} if '?' in", "as f: return yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path, 'r') as f: return json.load(f,", "'--template', required=True, help='Path to the template file') parser.add_argument('-o', '--output', required=True, help='Path for output", "args.sources: load_scope_from_file(scope, file_uri) template = load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output,", "scope.load(load_file(path), **params) def parse(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', required=True, dest='sources', nargs='+', help='Path", "parser.parse_args() def main(): args = parse() scope = create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env')", "argparse import json import yaml import os import logging from collections import OrderedDict", "help='Path to the template file') parser.add_argument('-o', '--output', required=True, help='Path for output file') return", "glu.util import OrderedDictYamlLoader from glu import create_scope def load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'):", "if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path, 'r') as f: return yaml.load(f, Loader=OrderedDictYamlLoader) else:", "the template file') parser.add_argument('-o', '--output', required=True, help='Path for output file') return parser.parse_args() def", "= file_uri params = {} if '?' in file_uri: path, params = file_uri.split('?')", "scope = create_scope() if args.use_env: scope.load(dict(os.environ.items()), load_to='@env') for file_uri in args.sources: load_scope_from_file(scope, file_uri)", "the source file') parser.add_argument('-e', '--use-env', action='store_true', help='Use environment variable') parser.add_argument('-t', '--template', required=True, help='Path", "json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path = file_uri params = {} if '?'", "<reponame>chongkong/glu import argparse import json import yaml import os import logging from collections", "yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope,", "variable') parser.add_argument('-t', '--template', required=True, help='Path to the template file') parser.add_argument('-o', '--output', required=True, help='Path", "action='store_true', help='Use environment variable') parser.add_argument('-t', '--template', required=True, help='Path to the template file') parser.add_argument('-o',", "= scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w') as f: json.dump(res, f, indent=2, separators=(',',", "parser.add_argument('-e', '--use-env', action='store_true', help='Use environment variable') parser.add_argument('-t', '--template', required=True, help='Path to the template", "'--source', required=True, dest='sources', nargs='+', help='Path to the source file') parser.add_argument('-e', '--use-env', action='store_true', help='Use", "load_to='@env') for file_uri in args.sources: load_scope_from_file(scope, file_uri) template = load_file(args.template) res = scope.glue(template)", "open(path, 'r') as f: return yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path, 'r') as f:", "f: return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path = file_uri params = {}", "OrderedDict from glu.util import OrderedDictYamlLoader from glu import create_scope def load_file(path): if path.lower().endswith('.yml')", "file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&')) scope.load(load_file(path), **params) def parse(): parser", "environment variable') parser.add_argument('-t', '--template', required=True, help='Path to the template file') parser.add_argument('-o', '--output', required=True,", "load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w') as f: json.dump(res, f,", "path.lower().endswith('.yaml'): with open(path, 'r') as f: return yaml.load(f, Loader=OrderedDictYamlLoader) else: with open(path, 'r')", "collections import OrderedDict from glu.util import OrderedDictYamlLoader from glu import create_scope def load_file(path):", "OrderedDictYamlLoader from glu import create_scope def load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path,", "else: with open(path, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path", "dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&')) scope.load(load_file(path), **params) def parse(): parser = argparse.ArgumentParser() parser.add_argument('-s',", "to the template file') parser.add_argument('-o', '--output', required=True, help='Path for output file') return parser.parse_args()", "glu import create_scope def load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path, 'r') as", "for file_uri in args.sources: load_scope_from_file(scope, file_uri) template = load_file(args.template) res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res,", "dest='sources', nargs='+', help='Path to the source file') parser.add_argument('-e', '--use-env', action='store_true', help='Use environment variable')", "params = dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&')) scope.load(load_file(path), **params) def parse(): parser =", "return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path = file_uri params = {} if", "res = scope.glue(template) logging.info('Result:\\n{}'.format(json.dumps(res, indent=2))) with open(args.output, 'w') as f: json.dump(res, f, indent=2,", "for output file') return parser.parse_args() def main(): args = parse() scope = create_scope()", "= dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&')) scope.load(load_file(path), **params) def parse(): parser = argparse.ArgumentParser()", "from collections import OrderedDict from glu.util import OrderedDictYamlLoader from glu import create_scope def", "create_scope def load_file(path): if path.lower().endswith('.yml') or path.lower().endswith('.yaml'): with open(path, 'r') as f: return", "open(path, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict) def load_scope_from_file(scope, file_uri): path = file_uri", "file_uri): path = file_uri params = {} if '?' in file_uri: path, params", "= file_uri.split('?') params = dict(tuple(field_and_value.split('=')) for field_and_value in params.split('&')) scope.load(load_file(path), **params) def parse():", "nargs='+', help='Path to the source file') parser.add_argument('-e', '--use-env', action='store_true', help='Use environment variable') parser.add_argument('-t'," ]
[ "class TestCase003(TestCase): def __init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State Transfer Duration.", "TestCase003(TestCase): def __init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State Transfer Duration. 58", "id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State Transfer Duration. 58 Byte Packets', pps=1000, packet_size=58,", "PPS. Increasing State Transfer Duration. 58 Byte Packets', pps=1000, packet_size=58, state_duration=[0, 1, 0.1],", "from ._base import * class TestCase003(TestCase): def __init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS.", "__init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State Transfer Duration. 58 Byte Packets',", "import * class TestCase003(TestCase): def __init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State", "def __init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State Transfer Duration. 58 Byte", "* class TestCase003(TestCase): def __init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State Transfer", "TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State Transfer Duration. 58 Byte Packets', pps=1000,", "description='Fixed PPS. Increasing State Transfer Duration. 58 Byte Packets', pps=1000, packet_size=58, state_duration=[0, 1,", "<gh_stars>1-10 from ._base import * class TestCase003(TestCase): def __init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed", "Increasing State Transfer Duration. 58 Byte Packets', pps=1000, packet_size=58, state_duration=[0, 1, 0.1], reports=STD_REPORTS)", "._base import * class TestCase003(TestCase): def __init__(self): TestCase.__init__(self, id='003', alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing", "alt_id='fixed_pps_increasing_pps_58_bytes', description='Fixed PPS. Increasing State Transfer Duration. 58 Byte Packets', pps=1000, packet_size=58, state_duration=[0," ]
[ "__init__(self): self.X = None def forward(self, X): # TODO: Implement forward pass #", "1:\", target_index - 1); it = np.nditer(target_index - 1, flags = ['c_index'] )", "self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); # self.W.init = self.W.value; # self.B.init", "implement softmax with cross-entropy #One-dimension option if predictions.ndim == 1: predictions_ = predictions", "some information about X # to use it later in the backward pass", "def __init__(self, value): #self.init = value.copy(); self.value = value; self.grad = np.zeros_like(value); class", "any loops self.X = X; #if np.any(self.W.init != self.W.value) or np.any(self.B.init != self.B.value):", "log def l2_regularization(W, reg_strength): \"\"\" Computes L2 regularization loss on weights and its", "true class for given sample(s) Returns: loss: single value ''' # TODO implement", "= sum(dprediction); dprediction /= summ; loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1] -=", "= \", it[0]); dprediction[it.index, it[0]] -= 1 it.iternext() dprediction /= len(target_index); #print(\"dprediction after", "loss dprediction, np array same shape as predictions - gradient of predictions by", "n_output): self.W = Param(0.01 * np.random.randn(n_input, n_output)) self.B = Param(0.01 * np.random.randn(1, n_output))", "-= 1; return loss, dprediction; else: predictions_ = predictions - np.max(predictions, axis =", "- 1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax and cross-entropy loss for model", "np array (batch_size, num_features) - gradient with respect to input \"\"\" # TODO:", "Arguments: d_out, np array (batch_size, n_output) - gradient of loss function with respect", "loss value \"\"\" # TODO: Copy from the previous assignment # TODO implement", "value - l2 regularization loss gradient, np.array same shape as W - gradient", "of loss function with respect to output Returns: d_result: np array (batch_size, num_features)", "1)[:, np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction", "== 1: predictions_ = predictions - np.max(predictions); dprediction = np.array(list(map(exp, predictions_))); summ =", "= np.zeros_like(value); class ReLULayer: def __init__(self): self.X = None def forward(self, X): #", "function with respect to output Returns: d_result: np array (batch_size, n_input) - gradient", "assignment dW = np.dot(self.X.T, d_out); dB = np.dot(np.ones((1, d_out.shape[0])), d_out); d_input = np.dot(d_out,", "input \"\"\" # TODO: Implement backward pass # Your final implementation shouldn't have", "Doesn't have any parameters return {} class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W", "or (batch_size) - index of the true class for given sample(s) Returns: loss:", "= Param(0.01 * np.random.randn(n_input, n_output)) self.B = Param(0.01 * np.random.randn(1, n_output)) self.X =", "Returns: loss: single value ''' # TODO implement cross-entropy #print(\"probs:\", probs); return -log(probs[target_index", "predictions_ = predictions - np.max(predictions); dprediction = np.array(list(map(exp, predictions_))); summ = sum(dprediction); dprediction", "every class target_index: np array of int, shape is (1) or (batch_size) -", "dprediction); summ = sum(dprediction.T); #print(\"summ: \", summ); dprediction /= summ[:, np.newaxis]; #print(\"dprediction after", "np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction, target_index)]); #print(\"loss: \", loss); #print(\"target_index - 1:\", target_index", "= X; return (X > 0)*X; def backward(self, d_out): \"\"\" Backward pass Arguments:", "\"\"\" Computes L2 regularization loss on weights and its gradient Arguments: W, np", "loss Arguments: probs, np array, shape is either (N) or (batch_size, N) -", "pretty similar to linear classifier from # the previous assignment dW = np.dot(self.X.T,", "respect to output Returns: d_result: np array (batch_size, n_input) - gradient with respect", "- probabilities for every class target_index: np array of int, shape is (1)", "return -log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax and cross-entropy loss", "assignment loss = reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return loss, grad def cross_entropy_loss(probs, target_index):", "#print(\"loss: \", loss); #print(\"target_index - 1:\", target_index - 1); it = np.nditer(target_index -", "(batch_size, num_features) - gradient with respect to input \"\"\" # TODO: Implement backward", "def backward(self, d_out): \"\"\" Backward pass Computes gradient with respect to input and", "predictions - np.max(predictions); dprediction = np.array(list(map(exp, predictions_))); summ = sum(dprediction); dprediction /= summ;", "# TODO implement cross-entropy #print(\"probs:\", probs); return -log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions, target_index):", "{} class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W = Param(0.01 * np.random.randn(n_input, n_output))", "array (batch_size, n_output) - gradient of loss function with respect to output Returns:", "self.B.grad = np.zeros_like(self.B.value); # self.W.init = self.W.value; # self.B.init = self.B.value; return np.dot(self.X,", "weight by l2 loss \"\"\" # TODO: Copy from the previous assignment loss", "W and B # Add gradients of W and B to their `grad`", "summ = sum(dprediction); dprediction /= summ; loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1]", "np.nditer(target_index - 1, flags = ['c_index'] ) while not it.finished: #print(\"it[0] = \",", "np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before", "of loss function with respect to output Returns: d_result: np array (batch_size, n_input)", "it.finished: #print(\"it[0] = \", it[0]); dprediction[it.index, it[0]] -= 1 it.iternext() dprediction /= len(target_index);", "d_out, np array (batch_size, n_output) - gradient of loss function with respect to", "(N, batch_size) - classifier output target_index: np array of int, shape is (1)", "/= summ; loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1] -= 1; return loss,", "self.value = value; self.grad = np.zeros_like(value); class ReLULayer: def __init__(self): self.X = None", "it[0]); dprediction[it.index, it[0]] -= 1 it.iternext() dprediction /= len(target_index); #print(\"dprediction after subtraction: \",", "Implement backward pass # Compute both gradient with respect to input # and", "Implement backward pass # Your final implementation shouldn't have any loops return (self.X", "= self.W.value; # self.B.init = self.B.value; return np.dot(self.X, self.W.value) + self.B.value; def backward(self,", "of int, shape is (1) or (batch_size) - index of the true class", "final implementation shouldn't have any loops self.X = X; #if np.any(self.W.init != self.W.value)", "division: \", dprediction); loss = np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction, target_index)]); #print(\"loss: \",", "to save some information about X # to use it later in the", "(X > 0)*X; def backward(self, d_out): \"\"\" Backward pass Arguments: d_out, np array", "X; return (X > 0)*X; def backward(self, d_out): \"\"\" Backward pass Arguments: d_out,", "from # the previous assignment dW = np.dot(self.X.T, d_out); dB = np.dot(np.ones((1, d_out.shape[0])),", "value and the gradient \"\"\" def __init__(self, value): #self.init = value.copy(); self.value =", "\"\"\" def __init__(self, value): #self.init = value.copy(); self.value = value; self.grad = np.zeros_like(value);", "np.max(predictions); dprediction = np.array(list(map(exp, predictions_))); summ = sum(dprediction); dprediction /= summ; loss =", "def forward(self, X): # TODO: Implement forward pass # Your final implementation shouldn't", "given sample(s) Returns: loss, single value - cross-entropy loss dprediction, np array same", "value; self.grad = np.zeros_like(value); class ReLULayer: def __init__(self): self.X = None def forward(self,", "target_index): ''' Computes cross-entropy loss Arguments: probs, np array, shape is either (N)", "- l2 regularization loss gradient, np.array same shape as W - gradient of", "TODO: Implement forward pass # Your final implementation shouldn't have any loops self.X", "return loss, dprediction; else: predictions_ = predictions - np.max(predictions, axis = 1)[:, np.newaxis];", "# TODO: Implement forward pass # Your final implementation shouldn't have any loops", "summ = sum(dprediction.T); #print(\"summ: \", summ); dprediction /= summ[:, np.newaxis]; #print(\"dprediction after division:", "cross-entropy #One-dimension option if predictions.ndim == 1: predictions_ = predictions - np.max(predictions); dprediction", "dprediction /= len(target_index); #print(\"dprediction after subtraction: \", dprediction); return loss.mean(), dprediction; raise Exception(\"Not", "dW = np.dot(self.X.T, d_out); dB = np.dot(np.ones((1, d_out.shape[0])), d_out); d_input = np.dot(d_out, self.W.value.T);", "= cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1] -= 1; return loss, dprediction; else: predictions_", "probs); return -log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax and cross-entropy", "to output Returns: d_result: np array (batch_size, n_input) - gradient with respect to", "cross-entropy loss for model predictions, including the gradient Arguments: predictions, np array, shape", "the previous assignment # TODO implement softmax with cross-entropy #One-dimension option if predictions.ndim", "output target_index: np array of int, shape is (1) or (batch_size) - index", "softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax and cross-entropy loss for model predictions, including the", "pass # Hint: you'll need to save some information about X # to", "pass # Compute both gradient with respect to input # and gradients with", "sum(dprediction.T); #print(\"summ: \", summ); dprediction /= summ[:, np.newaxis]; #print(\"dprediction after division: \", dprediction);", "Arguments: probs, np array, shape is either (N) or (batch_size, N) - probabilities", "backward(self, d_out): \"\"\" Backward pass Computes gradient with respect to input and accumulates", "same shape as W - gradient of weight by l2 loss \"\"\" #", "respect to input # and gradients with respect to W and B #", "Captures both parameter value and the gradient \"\"\" def __init__(self, value): #self.init =", "or (N, batch_size) - classifier output target_index: np array of int, shape is", "np.newaxis]; #print(\"dprediction after division: \", dprediction); loss = np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction,", "np.max(predictions, axis = 1)[:, np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec,", "n_output) - gradient of loss function with respect to output Returns: d_result: np", "regularization loss gradient, np.array same shape as W - gradient of weight by", "\"\"\" Trainable parameter of the model Captures both parameter value and the gradient", "and the gradient \"\"\" def __init__(self, value): #self.init = value.copy(); self.value = value;", "loops return (self.X > 0)*d_out; def params(self): # ReLU Doesn't have any parameters", "forward pass # Hint: you'll need to save some information about X #", "B # Add gradients of W and B to their `grad` attribute #", "self.X = X; #if np.any(self.W.init != self.W.value) or np.any(self.B.init != self.B.value): self.W.grad =", "the gradient Arguments: predictions, np array, shape is either (N) or (N, batch_size)", "predictions, np array, shape is either (N) or (N, batch_size) - classifier output", "shouldn't have any loops return (self.X > 0)*d_out; def params(self): # ReLU Doesn't", "of predictions by loss value \"\"\" # TODO: Copy from the previous assignment", "- gradient of loss function with respect to output Returns: d_result: np array", "= np.array(list(map(exp, predictions_))); summ = sum(dprediction); dprediction /= summ; loss = cross_entropy_loss(dprediction, target_index);", "parameter of the model Captures both parameter value and the gradient \"\"\" def", "TODO: Implement backward pass # Compute both gradient with respect to input #", "L2 regularization loss on weights and its gradient Arguments: W, np array -", "gradient of weight by l2 loss \"\"\" # TODO: Copy from the previous", "as predictions - gradient of predictions by loss value \"\"\" # TODO: Copy", "final implementation shouldn't have any loops return (self.X > 0)*d_out; def params(self): #", "= value; self.grad = np.zeros_like(value); class ReLULayer: def __init__(self): self.X = None def", "Computes softmax and cross-entropy loss for model predictions, including the gradient Arguments: predictions,", "previous assignment # TODO implement softmax with cross-entropy #One-dimension option if predictions.ndim ==", "target_index: np array of int, shape is (1) or (batch_size) - index of", "input # and gradients with respect to W and B # Add gradients", "is (1) or (batch_size) - index of the true class for given sample(s)", "= np.dot(np.ones((1, d_out.shape[0])), d_out); d_input = np.dot(d_out, self.W.value.T); self.W.grad += dW; self.B.grad +=", "forward(self, X): # TODO: Implement forward pass # Your final implementation shouldn't have", "parameters return {} class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W = Param(0.01 *", "within self.W and self.B Arguments: d_out, np array (batch_size, n_output) - gradient of", "1; return loss, dprediction; else: predictions_ = predictions - np.max(predictions, axis = 1)[:,", "(self.X > 0)*d_out; def params(self): # ReLU Doesn't have any parameters return {}", "respect to output Returns: d_result: np array (batch_size, num_features) - gradient with respect", "dB = np.dot(np.ones((1, d_out.shape[0])), d_out); d_input = np.dot(d_out, self.W.value.T); self.W.grad += dW; self.B.grad", "dprediction[it.index, it[0]] -= 1 it.iternext() dprediction /= len(target_index); #print(\"dprediction after subtraction: \", dprediction);", "cross-entropy loss Arguments: probs, np array, shape is either (N) or (batch_size, N)", "np array of int, shape is (1) or (batch_size) - index of the", "array, shape is either (N) or (N, batch_size) - classifier output target_index: np", "output Returns: d_result: np array (batch_size, n_input) - gradient with respect to input", "It should be pretty similar to linear classifier from # the previous assignment", "int, shape is (1) or (batch_size) - index of the true class for", "the true class for given sample(s) Returns: loss: single value ''' # TODO", "linear classifier from # the previous assignment dW = np.dot(self.X.T, d_out); dB =", "\", dprediction); summ = sum(dprediction.T); #print(\"summ: \", summ); dprediction /= summ[:, np.newaxis]; #print(\"dprediction", "while not it.finished: #print(\"it[0] = \", it[0]); dprediction[it.index, it[0]] -= 1 it.iternext() dprediction", "1 it.iternext() dprediction /= len(target_index); #print(\"dprediction after subtraction: \", dprediction); return loss.mean(), dprediction;", "Implement forward pass # Your final implementation shouldn't have any loops self.X =", "it = np.nditer(target_index - 1, flags = ['c_index'] ) while not it.finished: #print(\"it[0]", "= predictions - np.max(predictions); dprediction = np.array(list(map(exp, predictions_))); summ = sum(dprediction); dprediction /=", "to output Returns: d_result: np array (batch_size, num_features) - gradient with respect to", "previous assignment loss = reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return loss, grad def cross_entropy_loss(probs,", "single value - cross-entropy loss dprediction, np array same shape as predictions -", "dprediction[target_index - 1] -= 1; return loss, dprediction; else: predictions_ = predictions -", "predictions - np.max(predictions, axis = 1)[:, np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction", "predictions_); #print(\"dprediction before division: \", dprediction); summ = sum(dprediction.T); #print(\"summ: \", summ); dprediction", "= np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction, target_index)]); #print(\"loss: \", loss); #print(\"target_index - 1:\",", "np.zeros_like(value); class ReLULayer: def __init__(self): self.X = None def forward(self, X): # TODO:", "dW; self.B.grad += dB; return d_input; def params(self): return {'W': self.W, 'B': self.B}", "\"\"\" # TODO: Implement backward pass # Your final implementation shouldn't have any", "loss = np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction, target_index)]); #print(\"loss: \", loss); #print(\"target_index -", "/= len(target_index); #print(\"dprediction after subtraction: \", dprediction); return loss.mean(), dprediction; raise Exception(\"Not implemented!\")", "W and B to their `grad` attribute # It should be pretty similar", "self.W.value; # self.B.init = self.B.value; return np.dot(self.X, self.W.value) + self.B.value; def backward(self, d_out):", "value \"\"\" # TODO: Copy from the previous assignment # TODO implement softmax", "gradient \"\"\" def __init__(self, value): #self.init = value.copy(); self.value = value; self.grad =", "# TODO: Copy from the previous assignment loss = reg_strength*sum(sum(W**2)); grad = reg_strength*2*W;", "\", summ); dprediction /= summ[:, np.newaxis]; #print(\"dprediction after division: \", dprediction); loss =", "with cross-entropy #One-dimension option if predictions.ndim == 1: predictions_ = predictions - np.max(predictions);", "function with respect to output Returns: d_result: np array (batch_size, num_features) - gradient", "Your final implementation shouldn't have any loops self.X = X; #if np.any(self.W.init !=", "to their `grad` attribute # It should be pretty similar to linear classifier", "self.grad = np.zeros_like(value); class ReLULayer: def __init__(self): self.X = None def forward(self, X):", "class for given sample(s) Returns: loss: single value ''' # TODO implement cross-entropy", "dprediction); return loss.mean(), dprediction; raise Exception(\"Not implemented!\") class Param: \"\"\" Trainable parameter of", "# Your final implementation shouldn't have any loops return (self.X > 0)*d_out; def", "any loops return (self.X > 0)*d_out; def params(self): # ReLU Doesn't have any", "- weights reg_strength - float value Returns: loss, single value - l2 regularization", "self.W = Param(0.01 * np.random.randn(n_input, n_output)) self.B = Param(0.01 * np.random.randn(1, n_output)) self.X", "gradient with respect to input and accumulates gradients within self.W and self.B Arguments:", "their `grad` attribute # It should be pretty similar to linear classifier from", "1] -= 1; return loss, dprediction; else: predictions_ = predictions - np.max(predictions, axis", "np array, shape is either (N) or (N, batch_size) - classifier output target_index:", "gradient, np.array same shape as W - gradient of weight by l2 loss", "X # to use it later in the backward pass self.X = X;", "and self.B Arguments: d_out, np array (batch_size, n_output) - gradient of loss function", "<gh_stars>1-10 import numpy as np from math import exp, log def l2_regularization(W, reg_strength):", "sum(dprediction); dprediction /= summ; loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1] -= 1;", "- 1); it = np.nditer(target_index - 1, flags = ['c_index'] ) while not", "have any loops return (self.X > 0)*d_out; def params(self): # ReLU Doesn't have", "np.any(self.W.init != self.W.value) or np.any(self.B.init != self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value);", "as W - gradient of weight by l2 loss \"\"\" # TODO: Copy", "# TODO: Implement backward pass # Compute both gradient with respect to input", "to input \"\"\" # TODO: Implement backward pass # Your final implementation shouldn't", "np.array(list(map(exp, predictions_))); summ = sum(dprediction); dprediction /= summ; loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index", "loss); #print(\"target_index - 1:\", target_index - 1); it = np.nditer(target_index - 1, flags", "regularization loss on weights and its gradient Arguments: W, np array - weights", "(batch_size) - index of the true class for given sample(s) Returns: loss: single", "# Your final implementation shouldn't have any loops self.X = X; #if np.any(self.W.init", "from math import exp, log def l2_regularization(W, reg_strength): \"\"\" Computes L2 regularization loss", "1, flags = ['c_index'] ) while not it.finished: #print(\"it[0] = \", it[0]); dprediction[it.index,", "output Returns: d_result: np array (batch_size, num_features) - gradient with respect to input", "class ReLULayer: def __init__(self): self.X = None def forward(self, X): # TODO: Implement", "= value.copy(); self.value = value; self.grad = np.zeros_like(value); class ReLULayer: def __init__(self): self.X", "not it.finished: #print(\"it[0] = \", it[0]); dprediction[it.index, it[0]] -= 1 it.iternext() dprediction /=", "same shape as predictions - gradient of predictions by loss value \"\"\" #", "d_input = np.dot(d_out, self.W.value.T); self.W.grad += dW; self.B.grad += dB; return d_input; def", "index of the true class for given sample(s) Returns: loss: single value '''", "(batch_size, num_features) - gradient of loss function with respect to output Returns: d_result:", "Computes L2 regularization loss on weights and its gradient Arguments: W, np array", "later in the backward pass self.X = X; return (X > 0)*X; def", "(batch_size) - index of the true class for given sample(s) Returns: loss, single", "pass Computes gradient with respect to input and accumulates gradients within self.W and", "def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np array, shape is", "loss function with respect to output Returns: d_result: np array (batch_size, n_input) -", "summ; loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1] -= 1; return loss, dprediction;", "predictions, including the gradient Arguments: predictions, np array, shape is either (N) or", "dprediction; raise Exception(\"Not implemented!\") class Param: \"\"\" Trainable parameter of the model Captures", "def __init__(self, n_input, n_output): self.W = Param(0.01 * np.random.randn(n_input, n_output)) self.B = Param(0.01", "= np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); # self.W.init = self.W.value; # self.B.init = self.B.value;", "num_features) - gradient of loss function with respect to output Returns: d_result: np", "loops self.X = X; #if np.any(self.W.init != self.W.value) or np.any(self.B.init != self.B.value): self.W.grad", "self.B.init = self.B.value; return np.dot(self.X, self.W.value) + self.B.value; def backward(self, d_out): \"\"\" Backward", "Returns: d_result: np array (batch_size, n_input) - gradient with respect to input \"\"\"", "def __init__(self): self.X = None def forward(self, X): # TODO: Implement forward pass", "and cross-entropy loss for model predictions, including the gradient Arguments: predictions, np array,", "to use it later in the backward pass self.X = X; return (X", "backward pass # Compute both gradient with respect to input # and gradients", "raise Exception(\"Not implemented!\") class Param: \"\"\" Trainable parameter of the model Captures both", "from the previous assignment # TODO implement softmax with cross-entropy #One-dimension option if", "of weight by l2 loss \"\"\" # TODO: Copy from the previous assignment", "with respect to input # and gradients with respect to W and B", "#print(\"target_index - 1:\", target_index - 1); it = np.nditer(target_index - 1, flags =", "to input # and gradients with respect to W and B # Add", "np.dot(np.ones((1, d_out.shape[0])), d_out); d_input = np.dot(d_out, self.W.value.T); self.W.grad += dW; self.B.grad += dB;", "# It should be pretty similar to linear classifier from # the previous", "TODO implement cross-entropy #print(\"probs:\", probs); return -log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\"", "forward(self, X): # TODO: Implement forward pass # Hint: you'll need to save", "dprediction, np array same shape as predictions - gradient of predictions by loss", "return {} class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W = Param(0.01 * np.random.randn(n_input,", "d_out); dB = np.dot(np.ones((1, d_out.shape[0])), d_out); d_input = np.dot(d_out, self.W.value.T); self.W.grad += dW;", "Exception(\"Not implemented!\") class Param: \"\"\" Trainable parameter of the model Captures both parameter", "X; #if np.any(self.W.init != self.W.value) or np.any(self.B.init != self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad", "= reg_strength*2*W; return loss, grad def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments:", "predictions.ndim == 1: predictions_ = predictions - np.max(predictions); dprediction = np.array(list(map(exp, predictions_))); summ", "np from math import exp, log def l2_regularization(W, reg_strength): \"\"\" Computes L2 regularization", "n_input, n_output): self.W = Param(0.01 * np.random.randn(n_input, n_output)) self.B = Param(0.01 * np.random.randn(1,", "pass Arguments: d_out, np array (batch_size, num_features) - gradient of loss function with", "- index of the true class for given sample(s) Returns: loss, single value", "= np.nditer(target_index - 1, flags = ['c_index'] ) while not it.finished: #print(\"it[0] =", "l2 regularization loss gradient, np.array same shape as W - gradient of weight", "class for given sample(s) Returns: loss, single value - cross-entropy loss dprediction, np", "and B to their `grad` attribute # It should be pretty similar to", "1); it = np.nditer(target_index - 1, flags = ['c_index'] ) while not it.finished:", "both parameter value and the gradient \"\"\" def __init__(self, value): #self.init = value.copy();", "d_out): \"\"\" Backward pass Computes gradient with respect to input and accumulates gradients", "\"\"\" Backward pass Computes gradient with respect to input and accumulates gradients within", "params(self): # ReLU Doesn't have any parameters return {} class FullyConnectedLayer: def __init__(self,", "\", loss); #print(\"target_index - 1:\", target_index - 1); it = np.nditer(target_index - 1,", "= sum(dprediction.T); #print(\"summ: \", summ); dprediction /= summ[:, np.newaxis]; #print(\"dprediction after division: \",", "cross-entropy loss dprediction, np array same shape as predictions - gradient of predictions", "self.W and self.B Arguments: d_out, np array (batch_size, n_output) - gradient of loss", "probabilities for every class target_index: np array of int, shape is (1) or", "value ''' # TODO implement cross-entropy #print(\"probs:\", probs); return -log(probs[target_index - 1]); def", "math import exp, log def l2_regularization(W, reg_strength): \"\"\" Computes L2 regularization loss on", "in the backward pass self.X = X; return (X > 0)*X; def backward(self,", "import exp, log def l2_regularization(W, reg_strength): \"\"\" Computes L2 regularization loss on weights", "and gradients with respect to W and B # Add gradients of W", "backward pass self.X = X; return (X > 0)*X; def backward(self, d_out): \"\"\"", "target_index): \"\"\" Computes softmax and cross-entropy loss for model predictions, including the gradient", "is either (N) or (batch_size, N) - probabilities for every class target_index: np", "X): # TODO: Implement forward pass # Hint: you'll need to save some", "weights and its gradient Arguments: W, np array - weights reg_strength - float", "* np.random.randn(1, n_output)) self.X = None def forward(self, X): # TODO: Implement forward", "given sample(s) Returns: loss: single value ''' # TODO implement cross-entropy #print(\"probs:\", probs);", "# TODO: Copy from the previous assignment # TODO implement softmax with cross-entropy", "value.copy(); self.value = value; self.grad = np.zeros_like(value); class ReLULayer: def __init__(self): self.X =", "ReLULayer: def __init__(self): self.X = None def forward(self, X): # TODO: Implement forward", "None def forward(self, X): # TODO: Implement forward pass # Hint: you'll need", "use it later in the backward pass self.X = X; return (X >", "its gradient Arguments: W, np array - weights reg_strength - float value Returns:", "class Param: \"\"\" Trainable parameter of the model Captures both parameter value and", "+= dW; self.B.grad += dB; return d_input; def params(self): return {'W': self.W, 'B':", "n_input) - gradient with respect to input \"\"\" # TODO: Implement backward pass", "np.any(self.B.init != self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); # self.W.init = self.W.value;", "def l2_regularization(W, reg_strength): \"\"\" Computes L2 regularization loss on weights and its gradient", "(N) or (batch_size, N) - probabilities for every class target_index: np array of", "W, np array - weights reg_strength - float value Returns: loss, single value", "value Returns: loss, single value - l2 regularization loss gradient, np.array same shape", "= reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return loss, grad def cross_entropy_loss(probs, target_index): ''' Computes", "# TODO: Implement backward pass # Your final implementation shouldn't have any loops", "self.X = None def forward(self, X): # TODO: Implement forward pass # Hint:", "x,y in zip(dprediction, target_index)]); #print(\"loss: \", loss); #print(\"target_index - 1:\", target_index - 1);", "gradients with respect to W and B # Add gradients of W and", "-= 1 it.iternext() dprediction /= len(target_index); #print(\"dprediction after subtraction: \", dprediction); return loss.mean(),", "is either (N) or (N, batch_size) - classifier output target_index: np array of", "loss on weights and its gradient Arguments: W, np array - weights reg_strength", "0)*X; def backward(self, d_out): \"\"\" Backward pass Arguments: d_out, np array (batch_size, num_features)", "- index of the true class for given sample(s) Returns: loss: single value", "> 0)*X; def backward(self, d_out): \"\"\" Backward pass Arguments: d_out, np array (batch_size,", "- gradient with respect to input \"\"\" # TODO: Implement backward pass #", "= None def forward(self, X): # TODO: Implement forward pass # Your final", "d_out, np array (batch_size, num_features) - gradient of loss function with respect to", "target_index - 1); it = np.nditer(target_index - 1, flags = ['c_index'] ) while", "array of int, shape is (1) or (batch_size) - index of the true", "implemented!\") class Param: \"\"\" Trainable parameter of the model Captures both parameter value", "-log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax and cross-entropy loss for", "by l2 loss \"\"\" # TODO: Copy from the previous assignment loss =", "weights reg_strength - float value Returns: loss, single value - l2 regularization loss", "self.B.value; def backward(self, d_out): \"\"\" Backward pass Computes gradient with respect to input", "input and accumulates gradients within self.W and self.B Arguments: d_out, np array (batch_size,", "sample(s) Returns: loss, single value - cross-entropy loss dprediction, np array same shape", "(batch_size, n_input) - gradient with respect to input \"\"\" # TODO: Implement backward", "= X; #if np.any(self.W.init != self.W.value) or np.any(self.B.init != self.B.value): self.W.grad = np.zeros_like(self.W.value);", "be pretty similar to linear classifier from # the previous assignment dW =", "reg_strength - float value Returns: loss, single value - l2 regularization loss gradient,", "of the model Captures both parameter value and the gradient \"\"\" def __init__(self,", "- cross-entropy loss dprediction, np array same shape as predictions - gradient of", "np.array same shape as W - gradient of weight by l2 loss \"\"\"", "of the true class for given sample(s) Returns: loss: single value ''' #", "self.B = Param(0.01 * np.random.randn(1, n_output)) self.X = None def forward(self, X): #", "array, shape is either (N) or (batch_size, N) - probabilities for every class", "# Add gradients of W and B to their `grad` attribute # It", "# TODO implement softmax with cross-entropy #One-dimension option if predictions.ndim == 1: predictions_", "d_result: np array (batch_size, num_features) - gradient with respect to input \"\"\" #", "def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax and cross-entropy loss for model predictions, including", "Param(0.01 * np.random.randn(1, n_output)) self.X = None def forward(self, X): # TODO: Implement", "Copy from the previous assignment loss = reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return loss,", "with respect to input \"\"\" # TODO: Implement backward pass # Your final", "gradients within self.W and self.B Arguments: d_out, np array (batch_size, n_output) - gradient", "with respect to input \"\"\" # TODO: Implement backward pass # Compute both", "np.random.randn(n_input, n_output)) self.B = Param(0.01 * np.random.randn(1, n_output)) self.X = None def forward(self,", "(batch_size, n_output) - gradient of loss function with respect to output Returns: d_result:", "- float value Returns: loss, single value - l2 regularization loss gradient, np.array", "respect to input \"\"\" # TODO: Implement backward pass # Your final implementation", "self.B Arguments: d_out, np array (batch_size, n_output) - gradient of loss function with", "!= self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); # self.W.init = self.W.value; #", "assignment # TODO implement softmax with cross-entropy #One-dimension option if predictions.ndim == 1:", "dprediction /= summ[:, np.newaxis]; #print(\"dprediction after division: \", dprediction); loss = np.array([cross_entropy_loss(x,y) for", "implementation shouldn't have any loops return (self.X > 0)*d_out; def params(self): # ReLU", "Arguments: d_out, np array (batch_size, num_features) - gradient of loss function with respect", "shape as W - gradient of weight by l2 loss \"\"\" # TODO:", "for given sample(s) Returns: loss, single value - cross-entropy loss dprediction, np array", "loss = reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return loss, grad def cross_entropy_loss(probs, target_index): '''", "reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return loss, grad def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy", "reg_strength*2*W; return loss, grad def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs,", "class target_index: np array of int, shape is (1) or (batch_size) - index", "and its gradient Arguments: W, np array - weights reg_strength - float value", "implement cross-entropy #print(\"probs:\", probs); return -log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes", "pass # Your final implementation shouldn't have any loops self.X = X; #if", "['c_index'] ) while not it.finished: #print(\"it[0] = \", it[0]); dprediction[it.index, it[0]] -= 1", "pass self.X = X; return (X > 0)*X; def backward(self, d_out): \"\"\" Backward", "loss, grad def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np array,", "similar to linear classifier from # the previous assignment dW = np.dot(self.X.T, d_out);", "of W and B to their `grad` attribute # It should be pretty", "- 1:\", target_index - 1); it = np.nditer(target_index - 1, flags = ['c_index']", "probs, np array, shape is either (N) or (batch_size, N) - probabilities for", "flags = ['c_index'] ) while not it.finished: #print(\"it[0] = \", it[0]); dprediction[it.index, it[0]]", "\"\"\" # TODO: Copy from the previous assignment # TODO implement softmax with", "array (batch_size, num_features) - gradient of loss function with respect to output Returns:", "softmax and cross-entropy loss for model predictions, including the gradient Arguments: predictions, np", "or (batch_size, N) - probabilities for every class target_index: np array of int,", "- gradient of predictions by loss value \"\"\" # TODO: Copy from the", "model Captures both parameter value and the gradient \"\"\" def __init__(self, value): #self.init", "Add gradients of W and B to their `grad` attribute # It should", "Compute both gradient with respect to input # and gradients with respect to", "cross-entropy #print(\"probs:\", probs); return -log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax", "Trainable parameter of the model Captures both parameter value and the gradient \"\"\"", "and B # Add gradients of W and B to their `grad` attribute", "input \"\"\" # TODO: Implement backward pass # Compute both gradient with respect", "return loss, grad def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np", "or np.any(self.B.init != self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); # self.W.init =", "need to save some information about X # to use it later in", "either (N) or (N, batch_size) - classifier output target_index: np array of int,", "predictions - gradient of predictions by loss value \"\"\" # TODO: Copy from", "np.dot(self.X.T, d_out); dB = np.dot(np.ones((1, d_out.shape[0])), d_out); d_input = np.dot(d_out, self.W.value.T); self.W.grad +=", "return (self.X > 0)*d_out; def params(self): # ReLU Doesn't have any parameters return", "d_out): \"\"\" Backward pass Arguments: d_out, np array (batch_size, num_features) - gradient of", "dprediction = np.array(list(map(exp, predictions_))); summ = sum(dprediction); dprediction /= summ; loss = cross_entropy_loss(dprediction,", "array same shape as predictions - gradient of predictions by loss value \"\"\"", "= None def forward(self, X): # TODO: Implement forward pass # Hint: you'll", "with respect to output Returns: d_result: np array (batch_size, num_features) - gradient with", "Backward pass Computes gradient with respect to input and accumulates gradients within self.W", "about X # to use it later in the backward pass self.X =", "N) - probabilities for every class target_index: np array of int, shape is", "#print(\"dprediction before division: \", dprediction); summ = sum(dprediction.T); #print(\"summ: \", summ); dprediction /=", "self.B.value; return np.dot(self.X, self.W.value) + self.B.value; def backward(self, d_out): \"\"\" Backward pass Computes", "- np.max(predictions, axis = 1)[:, np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction =", "loss gradient, np.array same shape as W - gradient of weight by l2", "float value Returns: loss, single value - l2 regularization loss gradient, np.array same", "as np from math import exp, log def l2_regularization(W, reg_strength): \"\"\" Computes L2", "\"\"\" # TODO: Implement backward pass # Compute both gradient with respect to", "grad def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np array, shape", "information about X # to use it later in the backward pass self.X", "of the true class for given sample(s) Returns: loss, single value - cross-entropy", "single value ''' # TODO implement cross-entropy #print(\"probs:\", probs); return -log(probs[target_index - 1]);", "* np.random.randn(n_input, n_output)) self.B = Param(0.01 * np.random.randn(1, n_output)) self.X = None def", "- classifier output target_index: np array of int, shape is (1) or (batch_size)", "np array (batch_size, n_input) - gradient with respect to input \"\"\" # TODO:", "- 1] -= 1; return loss, dprediction; else: predictions_ = predictions - np.max(predictions,", "array - weights reg_strength - float value Returns: loss, single value - l2", "FullyConnectedLayer: def __init__(self, n_input, n_output): self.W = Param(0.01 * np.random.randn(n_input, n_output)) self.B =", "np.dot(self.X, self.W.value) + self.B.value; def backward(self, d_out): \"\"\" Backward pass Computes gradient with", "gradient Arguments: W, np array - weights reg_strength - float value Returns: loss,", "TODO: Copy from the previous assignment loss = reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return", "gradient with respect to input \"\"\" # TODO: Implement backward pass # Your", "TODO implement softmax with cross-entropy #One-dimension option if predictions.ndim == 1: predictions_ =", "with respect to W and B # Add gradients of W and B", "loss, single value - cross-entropy loss dprediction, np array same shape as predictions", "respect to input \"\"\" # TODO: Implement backward pass # Compute both gradient", "- 1, flags = ['c_index'] ) while not it.finished: #print(\"it[0] = \", it[0]);", "n_output)) self.X = None def forward(self, X): # TODO: Implement forward pass #", "backward pass # Your final implementation shouldn't have any loops return (self.X >", "from the previous assignment loss = reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return loss, grad", "Arguments: W, np array - weights reg_strength - float value Returns: loss, single", "def backward(self, d_out): \"\"\" Backward pass Arguments: d_out, np array (batch_size, num_features) -", "np.random.randn(1, n_output)) self.X = None def forward(self, X): # TODO: Implement forward pass", "to input and accumulates gradients within self.W and self.B Arguments: d_out, np array", "dprediction; else: predictions_ = predictions - np.max(predictions, axis = 1)[:, np.newaxis]; exp_vec =", "gradient of predictions by loss value \"\"\" # TODO: Copy from the previous", "Returns: d_result: np array (batch_size, num_features) - gradient with respect to input \"\"\"", "#print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before division: \", dprediction); summ", "on weights and its gradient Arguments: W, np array - weights reg_strength -", "TODO: Implement backward pass # Your final implementation shouldn't have any loops return", "def params(self): # ReLU Doesn't have any parameters return {} class FullyConnectedLayer: def", "(1) or (batch_size) - index of the true class for given sample(s) Returns:", "if predictions.ndim == 1: predictions_ = predictions - np.max(predictions); dprediction = np.array(list(map(exp, predictions_)));", "accumulates gradients within self.W and self.B Arguments: d_out, np array (batch_size, n_output) -", "B to their `grad` attribute # It should be pretty similar to linear", "np array (batch_size, n_output) - gradient of loss function with respect to output", "np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before division: \", dprediction); summ = sum(dprediction.T); #print(\"summ: \",", "self.W.grad += dW; self.B.grad += dB; return d_input; def params(self): return {'W': self.W,", "value - cross-entropy loss dprediction, np array same shape as predictions - gradient", "Param(0.01 * np.random.randn(n_input, n_output)) self.B = Param(0.01 * np.random.randn(1, n_output)) self.X = None", "array (batch_size, num_features) - gradient with respect to input \"\"\" # TODO: Implement", "summ[:, np.newaxis]; #print(\"dprediction after division: \", dprediction); loss = np.array([cross_entropy_loss(x,y) for x,y in", "after division: \", dprediction); loss = np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction, target_index)]); #print(\"loss:", "in zip(dprediction, target_index)]); #print(\"loss: \", loss); #print(\"target_index - 1:\", target_index - 1); it", "# to use it later in the backward pass self.X = X; return", "option if predictions.ndim == 1: predictions_ = predictions - np.max(predictions); dprediction = np.array(list(map(exp,", "self.X = None def forward(self, X): # TODO: Implement forward pass # Your", "= self.B.value; return np.dot(self.X, self.W.value) + self.B.value; def backward(self, d_out): \"\"\" Backward pass", "1, predictions_); #print(\"dprediction before division: \", dprediction); summ = sum(dprediction.T); #print(\"summ: \", summ);", "respect to W and B # Add gradients of W and B to", "Backward pass Arguments: d_out, np array (batch_size, num_features) - gradient of loss function", "the backward pass self.X = X; return (X > 0)*X; def backward(self, d_out):", "\"\"\" Backward pass Arguments: d_out, np array (batch_size, num_features) - gradient of loss", "Your final implementation shouldn't have any loops return (self.X > 0)*d_out; def params(self):", "W - gradient of weight by l2 loss \"\"\" # TODO: Copy from", "Returns: loss, single value - l2 regularization loss gradient, np.array same shape as", "loss: single value ''' # TODO implement cross-entropy #print(\"probs:\", probs); return -log(probs[target_index -", "= np.dot(self.X.T, d_out); dB = np.dot(np.ones((1, d_out.shape[0])), d_out); d_input = np.dot(d_out, self.W.value.T); self.W.grad", "before division: \", dprediction); summ = sum(dprediction.T); #print(\"summ: \", summ); dprediction /= summ[:,", "have any loops self.X = X; #if np.any(self.W.init != self.W.value) or np.any(self.B.init !=", "should be pretty similar to linear classifier from # the previous assignment dW", "index of the true class for given sample(s) Returns: loss, single value -", "the true class for given sample(s) Returns: loss, single value - cross-entropy loss", "\", it[0]); dprediction[it.index, it[0]] -= 1 it.iternext() dprediction /= len(target_index); #print(\"dprediction after subtraction:", "you'll need to save some information about X # to use it later", "by loss value \"\"\" # TODO: Copy from the previous assignment # TODO", "and accumulates gradients within self.W and self.B Arguments: d_out, np array (batch_size, n_output)", "shape is either (N) or (N, batch_size) - classifier output target_index: np array", "self.W.value.T); self.W.grad += dW; self.B.grad += dB; return d_input; def params(self): return {'W':", "to input \"\"\" # TODO: Implement backward pass # Compute both gradient with", "np array, shape is either (N) or (batch_size, N) - probabilities for every", "import numpy as np from math import exp, log def l2_regularization(W, reg_strength): \"\"\"", "shape is either (N) or (batch_size, N) - probabilities for every class target_index:", "it[0]] -= 1 it.iternext() dprediction /= len(target_index); #print(\"dprediction after subtraction: \", dprediction); return", "Param: \"\"\" Trainable parameter of the model Captures both parameter value and the", "classifier output target_index: np array of int, shape is (1) or (batch_size) -", "implementation shouldn't have any loops self.X = X; #if np.any(self.W.init != self.W.value) or", "\", dprediction); return loss.mean(), dprediction; raise Exception(\"Not implemented!\") class Param: \"\"\" Trainable parameter", "def forward(self, X): # TODO: Implement forward pass # Hint: you'll need to", "d_out.shape[0])), d_out); d_input = np.dot(d_out, self.W.value.T); self.W.grad += dW; self.B.grad += dB; return", "Hint: you'll need to save some information about X # to use it", "# self.B.init = self.B.value; return np.dot(self.X, self.W.value) + self.B.value; def backward(self, d_out): \"\"\"", "\", dprediction); loss = np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction, target_index)]); #print(\"loss: \", loss);", "shape as predictions - gradient of predictions by loss value \"\"\" # TODO:", "l2_regularization(W, reg_strength): \"\"\" Computes L2 regularization loss on weights and its gradient Arguments:", "axis = 1)[:, np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec, 1,", "respect to input and accumulates gradients within self.W and self.B Arguments: d_out, np", "num_features) - gradient with respect to input \"\"\" # TODO: Implement backward pass", "loss.mean(), dprediction; raise Exception(\"Not implemented!\") class Param: \"\"\" Trainable parameter of the model", "#print(\"it[0] = \", it[0]); dprediction[it.index, it[0]] -= 1 it.iternext() dprediction /= len(target_index); #print(\"dprediction", "classifier from # the previous assignment dW = np.dot(self.X.T, d_out); dB = np.dot(np.ones((1,", "the previous assignment loss = reg_strength*sum(sum(W**2)); grad = reg_strength*2*W; return loss, grad def", "loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1] -= 1; return loss, dprediction; else:", "= ['c_index'] ) while not it.finished: #print(\"it[0] = \", it[0]); dprediction[it.index, it[0]] -=", "#print(\"dprediction after subtraction: \", dprediction); return loss.mean(), dprediction; raise Exception(\"Not implemented!\") class Param:", "previous assignment dW = np.dot(self.X.T, d_out); dB = np.dot(np.ones((1, d_out.shape[0])), d_out); d_input =", "= 1)[:, np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec, 1, predictions_);", "- gradient of weight by l2 loss \"\"\" # TODO: Copy from the", "exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before division:", "None def forward(self, X): # TODO: Implement forward pass # Your final implementation", "backward(self, d_out): \"\"\" Backward pass Arguments: d_out, np array (batch_size, num_features) - gradient", "= np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before division: \",", "# Hint: you'll need to save some information about X # to use", "single value - l2 regularization loss gradient, np.array same shape as W -", "__init__(self, value): #self.init = value.copy(); self.value = value; self.grad = np.zeros_like(value); class ReLULayer:", "it.iternext() dprediction /= len(target_index); #print(\"dprediction after subtraction: \", dprediction); return loss.mean(), dprediction; raise", "= np.zeros_like(self.B.value); # self.W.init = self.W.value; # self.B.init = self.B.value; return np.dot(self.X, self.W.value)", "np.zeros_like(self.B.value); # self.W.init = self.W.value; # self.B.init = self.B.value; return np.dot(self.X, self.W.value) +", "0)*d_out; def params(self): # ReLU Doesn't have any parameters return {} class FullyConnectedLayer:", "for every class target_index: np array of int, shape is (1) or (batch_size)", "n_output)) self.B = Param(0.01 * np.random.randn(1, n_output)) self.X = None def forward(self, X):", "to linear classifier from # the previous assignment dW = np.dot(self.X.T, d_out); dB", "parameter value and the gradient \"\"\" def __init__(self, value): #self.init = value.copy(); self.value", "batch_size) - classifier output target_index: np array of int, shape is (1) or", "#print(\"probs:\", probs); return -log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax and", "#self.init = value.copy(); self.value = value; self.grad = np.zeros_like(value); class ReLULayer: def __init__(self):", "np array - weights reg_strength - float value Returns: loss, single value -", "array (batch_size, n_input) - gradient with respect to input \"\"\" # TODO: Implement", "TODO: Copy from the previous assignment # TODO implement softmax with cross-entropy #One-dimension", "# TODO: Implement forward pass # Hint: you'll need to save some information", "loss function with respect to output Returns: d_result: np array (batch_size, num_features) -", "both gradient with respect to input # and gradients with respect to W", "cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np array, shape is either", "Returns: loss, single value - cross-entropy loss dprediction, np array same shape as", "the gradient \"\"\" def __init__(self, value): #self.init = value.copy(); self.value = value; self.grad", "dprediction /= summ; loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1] -= 1; return", "self.W.grad = np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); # self.W.init = self.W.value; # self.B.init =", "gradient with respect to input # and gradients with respect to W and", "dprediction = np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before division: \", dprediction); summ = sum(dprediction.T);", "= Param(0.01 * np.random.randn(1, n_output)) self.X = None def forward(self, X): # TODO:", "for x,y in zip(dprediction, target_index)]); #print(\"loss: \", loss); #print(\"target_index - 1:\", target_index -", "else: predictions_ = predictions - np.max(predictions, axis = 1)[:, np.newaxis]; exp_vec = np.vectorize(exp);", "!= self.W.value) or np.any(self.B.init != self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); #", "Copy from the previous assignment # TODO implement softmax with cross-entropy #One-dimension option", "= np.dot(d_out, self.W.value.T); self.W.grad += dW; self.B.grad += dB; return d_input; def params(self):", "predictions_); dprediction = np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before division: \", dprediction); summ =", "any parameters return {} class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W = Param(0.01", "shouldn't have any loops self.X = X; #if np.any(self.W.init != self.W.value) or np.any(self.B.init", "save some information about X # to use it later in the backward", "gradient with respect to input \"\"\" # TODO: Implement backward pass # Compute", "zip(dprediction, target_index)]); #print(\"loss: \", loss); #print(\"target_index - 1:\", target_index - 1); it =", "Implement forward pass # Hint: you'll need to save some information about X", "# Compute both gradient with respect to input # and gradients with respect", "d_out); d_input = np.dot(d_out, self.W.value.T); self.W.grad += dW; self.B.grad += dB; return d_input;", "+ self.B.value; def backward(self, d_out): \"\"\" Backward pass Computes gradient with respect to", "# ReLU Doesn't have any parameters return {} class FullyConnectedLayer: def __init__(self, n_input,", "X): # TODO: Implement forward pass # Your final implementation shouldn't have any", "gradients of W and B to their `grad` attribute # It should be", "predictions by loss value \"\"\" # TODO: Copy from the previous assignment #", "1: predictions_ = predictions - np.max(predictions); dprediction = np.array(list(map(exp, predictions_))); summ = sum(dprediction);", "reg_strength): \"\"\" Computes L2 regularization loss on weights and its gradient Arguments: W,", "summ); dprediction /= summ[:, np.newaxis]; #print(\"dprediction after division: \", dprediction); loss = np.array([cross_entropy_loss(x,y)", "model predictions, including the gradient Arguments: predictions, np array, shape is either (N)", "to W and B # Add gradients of W and B to their", "with respect to output Returns: d_result: np array (batch_size, n_input) - gradient with", "Computes cross-entropy loss Arguments: probs, np array, shape is either (N) or (batch_size,", "including the gradient Arguments: predictions, np array, shape is either (N) or (N,", "np.vectorize(exp); #print(\"predictions_:\", predictions_); dprediction = np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before division: \", dprediction);", "ReLU Doesn't have any parameters return {} class FullyConnectedLayer: def __init__(self, n_input, n_output):", "''' Computes cross-entropy loss Arguments: probs, np array, shape is either (N) or", "for model predictions, including the gradient Arguments: predictions, np array, shape is either", "predictions_))); summ = sum(dprediction); dprediction /= summ; loss = cross_entropy_loss(dprediction, target_index); dprediction[target_index -", "numpy as np from math import exp, log def l2_regularization(W, reg_strength): \"\"\" Computes", "exp, log def l2_regularization(W, reg_strength): \"\"\" Computes L2 regularization loss on weights and", "# the previous assignment dW = np.dot(self.X.T, d_out); dB = np.dot(np.ones((1, d_out.shape[0])), d_out);", "shape is (1) or (batch_size) - index of the true class for given", "#if np.any(self.W.init != self.W.value) or np.any(self.B.init != self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad =", "d_result: np array (batch_size, n_input) - gradient with respect to input \"\"\" #", "target_index)]); #print(\"loss: \", loss); #print(\"target_index - 1:\", target_index - 1); it = np.nditer(target_index", "Arguments: predictions, np array, shape is either (N) or (N, batch_size) - classifier", "/= summ[:, np.newaxis]; #print(\"dprediction after division: \", dprediction); loss = np.array([cross_entropy_loss(x,y) for x,y", "sample(s) Returns: loss: single value ''' # TODO implement cross-entropy #print(\"probs:\", probs); return", "TODO: Implement forward pass # Hint: you'll need to save some information about", "loss, single value - l2 regularization loss gradient, np.array same shape as W", "true class for given sample(s) Returns: loss, single value - cross-entropy loss dprediction,", "gradient of loss function with respect to output Returns: d_result: np array (batch_size,", "either (N) or (batch_size, N) - probabilities for every class target_index: np array", "np array (batch_size, num_features) - gradient of loss function with respect to output", "np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); # self.W.init = self.W.value; # self.B.init = self.B.value; return", "len(target_index); #print(\"dprediction after subtraction: \", dprediction); return loss.mean(), dprediction; raise Exception(\"Not implemented!\") class", "1]); def softmax_with_cross_entropy(predictions, target_index): \"\"\" Computes softmax and cross-entropy loss for model predictions,", "#print(\"summ: \", summ); dprediction /= summ[:, np.newaxis]; #print(\"dprediction after division: \", dprediction); loss", "grad = reg_strength*2*W; return loss, grad def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss", "#print(\"dprediction after division: \", dprediction); loss = np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction, target_index)]);", "for given sample(s) Returns: loss: single value ''' # TODO implement cross-entropy #print(\"probs:\",", "self.X = X; return (X > 0)*X; def backward(self, d_out): \"\"\" Backward pass", "target_index); dprediction[target_index - 1] -= 1; return loss, dprediction; else: predictions_ = predictions", "return np.dot(self.X, self.W.value) + self.B.value; def backward(self, d_out): \"\"\" Backward pass Computes gradient", "division: \", dprediction); summ = sum(dprediction.T); #print(\"summ: \", summ); dprediction /= summ[:, np.newaxis];", "loss, dprediction; else: predictions_ = predictions - np.max(predictions, axis = 1)[:, np.newaxis]; exp_vec", "\"\"\" Computes softmax and cross-entropy loss for model predictions, including the gradient Arguments:", "with respect to input and accumulates gradients within self.W and self.B Arguments: d_out,", "np.dot(d_out, self.W.value.T); self.W.grad += dW; self.B.grad += dB; return d_input; def params(self): return", "# self.W.init = self.W.value; # self.B.init = self.B.value; return np.dot(self.X, self.W.value) + self.B.value;", "\"\"\" # TODO: Copy from the previous assignment loss = reg_strength*sum(sum(W**2)); grad =", "class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W = Param(0.01 * np.random.randn(n_input, n_output)) self.B", "self.W.value) or np.any(self.B.init != self.B.value): self.W.grad = np.zeros_like(self.W.value); self.B.grad = np.zeros_like(self.B.value); # self.W.init", "np array same shape as predictions - gradient of predictions by loss value", "(batch_size, N) - probabilities for every class target_index: np array of int, shape", "loss \"\"\" # TODO: Copy from the previous assignment loss = reg_strength*sum(sum(W**2)); grad", "dprediction); loss = np.array([cross_entropy_loss(x,y) for x,y in zip(dprediction, target_index)]); #print(\"loss: \", loss); #print(\"target_index", "or (batch_size) - index of the true class for given sample(s) Returns: loss,", "cross_entropy_loss(dprediction, target_index); dprediction[target_index - 1] -= 1; return loss, dprediction; else: predictions_ =", "__init__(self, n_input, n_output): self.W = Param(0.01 * np.random.randn(n_input, n_output)) self.B = Param(0.01 *", "= predictions - np.max(predictions, axis = 1)[:, np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\", predictions_);", "after subtraction: \", dprediction); return loss.mean(), dprediction; raise Exception(\"Not implemented!\") class Param: \"\"\"", "the previous assignment dW = np.dot(self.X.T, d_out); dB = np.dot(np.ones((1, d_out.shape[0])), d_out); d_input", "have any parameters return {} class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W =", "return (X > 0)*X; def backward(self, d_out): \"\"\" Backward pass Arguments: d_out, np", "''' # TODO implement cross-entropy #print(\"probs:\", probs); return -log(probs[target_index - 1]); def softmax_with_cross_entropy(predictions,", "self.W.init = self.W.value; # self.B.init = self.B.value; return np.dot(self.X, self.W.value) + self.B.value; def", "= np.apply_along_axis(exp_vec, 1, predictions_); #print(\"dprediction before division: \", dprediction); summ = sum(dprediction.T); #print(\"summ:", "#One-dimension option if predictions.ndim == 1: predictions_ = predictions - np.max(predictions); dprediction =", "> 0)*d_out; def params(self): # ReLU Doesn't have any parameters return {} class", "gradient Arguments: predictions, np array, shape is either (N) or (N, batch_size) -", "value): #self.init = value.copy(); self.value = value; self.grad = np.zeros_like(value); class ReLULayer: def", "subtraction: \", dprediction); return loss.mean(), dprediction; raise Exception(\"Not implemented!\") class Param: \"\"\" Trainable", ") while not it.finished: #print(\"it[0] = \", it[0]); dprediction[it.index, it[0]] -= 1 it.iternext()", "Computes gradient with respect to input and accumulates gradients within self.W and self.B", "predictions_ = predictions - np.max(predictions, axis = 1)[:, np.newaxis]; exp_vec = np.vectorize(exp); #print(\"predictions_:\",", "forward pass # Your final implementation shouldn't have any loops self.X = X;", "it later in the backward pass self.X = X; return (X > 0)*X;", "self.W.value) + self.B.value; def backward(self, d_out): \"\"\" Backward pass Computes gradient with respect", "`grad` attribute # It should be pretty similar to linear classifier from #", "# and gradients with respect to W and B # Add gradients of", "- np.max(predictions); dprediction = np.array(list(map(exp, predictions_))); summ = sum(dprediction); dprediction /= summ; loss", "return loss.mean(), dprediction; raise Exception(\"Not implemented!\") class Param: \"\"\" Trainable parameter of the", "l2 loss \"\"\" # TODO: Copy from the previous assignment loss = reg_strength*sum(sum(W**2));", "the model Captures both parameter value and the gradient \"\"\" def __init__(self, value):", "attribute # It should be pretty similar to linear classifier from # the", "softmax with cross-entropy #One-dimension option if predictions.ndim == 1: predictions_ = predictions -", "pass # Your final implementation shouldn't have any loops return (self.X > 0)*d_out;", "(N) or (N, batch_size) - classifier output target_index: np array of int, shape", "loss for model predictions, including the gradient Arguments: predictions, np array, shape is" ]
[ "Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype,", "\"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Supplier Quotation", "None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc): if frappe.flags.args and frappe.flags.args.default_supplier: #", "parent in ({0}) and default_supplier IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name,", "target_doc) # def select_item(d): # frappe.errprint(d) # return d.ordered_qty < d.stock_qty doclist =", "\"doctype\": \"Purchase Order\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } },", "license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.model.mapper", "[] for d in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from `tabItem Default` where", "target.conversion_factor # target.stock_qty = (target.qty * target.conversion_factor) # if getdate(target.schedule_date) < getdate(nowdate()): #", "frappe.db.sql(\"\"\"select default_supplier from `tabItem Default` where parent in ({0}) and default_supplier IS NOT", "NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc): set_missing_values(source, target_doc)", "frappe.utils import cstr, flt, getdate, new_line_sep, nowdate, add_days, get_link_to_form class FixedAssetRequest(Document): pass def", "getdate, new_line_sep, nowdate, add_days, get_link_to_form class FixedAssetRequest(Document): pass def set_missing_values(source, target_doc): if target_doc.doctype", "[\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ] } }, target_doc, postprocess) return doclist", "target_doc, postprocess) return doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed Asset Request\",", "frappe.flags.args.default_supplier: # items only for given default supplier supplier_items = [] for d", "\"Nos\"] ] } }, target_doc) return doclist # def update_item(obj, target, source_parent): #", "Request Item\": { \"doctype\": \"Supplier Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"],", "@frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc): set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed Asset", "class FixedAssetRequest(Document): pass def set_missing_values(source, target_doc): if target_doc.doctype == \"Purchase Order\" and getdate(target_doc.schedule_date)", "supplier_items set_missing_values(source, target_doc) # def select_item(d): # frappe.errprint(d) # return d.ordered_qty < d.stock_qty", "def make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc): set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed Asset Request\",", "[ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"]", "\"Fixed Asset Request Item\": { \"doctype\": \"Supplier Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"],", "Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ] }", "'.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc): set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed", "= [] for d in target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier ==", "\"Fixed Asset Request\": { \"doctype\": \"Purchase Order\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\":", "and default_supplier IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def postprocess(source,", "For license information, please see license.txt from __future__ import unicode_literals import frappe from", "# def update_item(obj, target, source_parent): # target.conversion_factor = obj.conversion_factor # target.qty = flt(flt(obj.stock_qty)", "target, source_parent): # target.conversion_factor = obj.conversion_factor # target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor", "and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt,", "pass def set_missing_values(source, target_doc): if target_doc.doctype == \"Purchase Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()):", "[\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\": update_item, #", "@frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc): if frappe.flags.args and frappe.flags.args.default_supplier: # items", "\"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Purchase Order Item\", \"field_map\":", "from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from frappe.utils import cstr, flt,", "Item\": { \"doctype\": \"Supplier Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\",", "== default_supplier: supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source, target_doc) # def select_item(d): # frappe.errprint(d)", "\"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": {", "and frappe.flags.args.default_supplier: # items only for given default supplier supplier_items = [] for", "[\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\": update_item, # \"condition\": select_item } }, target_doc, postprocess)", "], # \"postprocess\": update_item, # \"condition\": select_item } }, target_doc, postprocess) return doclist", "frappe.errprint(d) # return d.ordered_qty < d.stock_qty doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, {", "filters.get(\"doc\")) item_list = [] for d in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from", "Asset Request\": { \"doctype\": \"Request for Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\":", "item_list = [] for d in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from `tabItem", "from frappe.model.mapper import get_mapped_doc from frappe.utils import cstr, flt, getdate, new_line_sep, nowdate, add_days,", "d in target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items", "if frappe.flags.args and frappe.flags.args.default_supplier: # items only for given default supplier supplier_items =", "for Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"]", "start, page_len, filters): doc = frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list = [] for", "license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document", "\"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ] } },", "frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source, target_doc) # def select_item(d): #", "for d in target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d)", "[\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Purchase Order Item\",", "Document from frappe.model.mapper import get_mapped_doc from frappe.utils import cstr, flt, getdate, new_line_sep, nowdate,", "{ \"doctype\": \"Request for Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\",", "get_link_to_form class FixedAssetRequest(Document): pass def set_missing_values(source, target_doc): if target_doc.doctype == \"Purchase Order\" and", "= get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Purchase Order\",", "# def select_item(d): # frappe.errprint(d) # return d.ordered_qty < d.stock_qty doclist = get_mapped_doc(\"Fixed", "= get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Request for", "target.stock_qty = (target.qty * target.conversion_factor) # if getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date =", "Default` where parent in ({0}) and default_supplier IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist()", "where parent in ({0}) and default_supplier IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def", "Item\": { \"doctype\": \"Purchase Order Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\",", "(c) 2020, TeamPRO and contributors # For license information, please see license.txt from", "postprocess(source, target_doc): set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset", "getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield,", "target.schedule_date = None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc): if frappe.flags.args and", "# -*- coding: utf-8 -*- # Copyright (c) 2020, TeamPRO and contributors #", "return doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, {", "Order Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\",", "target_doc=None): def postprocess(source, target_doc): set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, {", "{ \"doctype\": \"Purchase Order Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"],", "\"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Request for", "\"Purchase Order\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed", "from `tabItem Default` where parent in ({0}) and default_supplier IS NOT NULL \"\"\".format(',", "target_doc.doctype == \"Purchase Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\")", "coding: utf-8 -*- # Copyright (c) 2020, TeamPRO and contributors # For license", "if target_doc.doctype == \"Purchase Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\")", "doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Purchase", "given default supplier supplier_items = [] for d in target_doc.items: default_supplier = get_item_defaults(d.item_code,", "Request\": { \"doctype\": \"Supplier Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"]", "doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Supplier", "1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Supplier", "target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty = (target.qty * target.conversion_factor) #", "target_doc): if target_doc.doctype == \"Purchase Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date = None", "= get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source, target_doc)", "\"Fixed Asset Request Item\": { \"doctype\": \"Request for Quotation Item\", \"field_map\": [ [\"name\",", "-*- # Copyright (c) 2020, TeamPRO and contributors # For license information, please", "Asset Request\", filters.get(\"doc\")) item_list = [] for d in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select", "[\"uom\", \"stock_uom\"], ] } }, target_doc, postprocess) return doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None):", "<reponame>TridotsTech/senergy # -*- coding: utf-8 -*- # Copyright (c) 2020, TeamPRO and contributors", "only for given default supplier supplier_items = [] for d in target_doc.items: default_supplier", "make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc): if frappe.flags.args and frappe.flags.args.default_supplier: # items only for", "-*- coding: utf-8 -*- # Copyright (c) 2020, TeamPRO and contributors # For", "[ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ] } }, target_doc,", "{ \"doctype\": \"Request for Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"]", "} }, \"Fixed Asset Request Item\": { \"doctype\": \"Request for Quotation Item\", \"field_map\":", "Copyright (c) 2020, TeamPRO and contributors # For license information, please see license.txt", "frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from frappe.utils import cstr, flt, getdate,", "} }, target_doc, postprocess) return doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed", "\"sales_order_item\"] ], # \"postprocess\": update_item, # \"condition\": select_item } }, target_doc, postprocess) return", "Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Purchase Order\", \"validation\": { \"docstatus\":", "target.conversion_factor) # if getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date = None @frappe.whitelist() def make_purchase_order(source_name,", "get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source, target_doc) #", "\"Fixed Asset Request Item\": { \"doctype\": \"Purchase Order Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"],", "{ \"Fixed Asset Request\": { \"doctype\": \"Supplier Quotation\", \"validation\": { \"docstatus\": [\"=\", 1],", "\"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], #", "Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Request for Quotation\", \"validation\":", "IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc): set_missing_values(source,", "1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Purchase", "if getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date = None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def", "\"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Purchase Order", "[] for d in target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier:", "= obj.conversion_factor # target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty = (target.qty", "doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Request", "__future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc", "Asset Request\": { \"doctype\": \"Purchase Order\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\",", "return frappe.db.sql(\"\"\"select default_supplier from `tabItem Default` where parent in ({0}) and default_supplier IS", "set_missing_values(source, target_doc): if target_doc.doctype == \"Purchase Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date =", "# target.schedule_date = None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc): if frappe.flags.args", "\"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request", "\"Purchase Order Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"],", "supplier_items = [] for d in target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier", "target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield, start, page_len, filters):", "\"uom\"], [\"uom\", \"stock_uom\"], ] } }, target_doc, postprocess) return doclist @frappe.whitelist() def make_request_for_quotation(source_name,", "= flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty = (target.qty * target.conversion_factor) # if", "target_doc=None): def postprocess(source, target_doc): if frappe.flags.args and frappe.flags.args.default_supplier: # items only for given", "[\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ] } }, target_doc) return", "[ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ] } }, target_doc)", "Request Item\": { \"doctype\": \"Purchase Order Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"],", "get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Purchase Order\", \"validation\":", "in ({0}) and default_supplier IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None):", "[\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\": update_item, # \"condition\": select_item } },", "flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty = (target.qty * target.conversion_factor) # if getdate(target.schedule_date)", "postprocess(source, target_doc): if frappe.flags.args and frappe.flags.args.default_supplier: # items only for given default supplier", "Request Item\": { \"doctype\": \"Request for Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\",", "[\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\":", "from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.model.mapper import", "{ \"doctype\": \"Supplier Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"],", "get_default_supplier_query(doctype, txt, searchfield, start, page_len, filters): doc = frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list", "= frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list = [] for d in doc.items: item_list.append(d.item_code)", "for Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed", "[\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ] } }, target_doc) return doclist # def update_item(obj,", "{ \"doctype\": \"Purchase Order\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] }", "# Copyright (c) 2020, TeamPRO and contributors # For license information, please see", "source_name, { \"Fixed Asset Request\": { \"doctype\": \"Request for Quotation\", \"validation\": { \"docstatus\":", "Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ]", "cstr, flt, getdate, new_line_sep, nowdate, add_days, get_link_to_form class FixedAssetRequest(Document): pass def set_missing_values(source, target_doc):", "flt, getdate, new_line_sep, nowdate, add_days, get_link_to_form class FixedAssetRequest(Document): pass def set_missing_values(source, target_doc): if", "target_doc) return doclist # def update_item(obj, target, source_parent): # target.conversion_factor = obj.conversion_factor #", "select_item(d): # frappe.errprint(d) # return d.ordered_qty < d.stock_qty doclist = get_mapped_doc(\"Fixed Asset Request\",", "for d in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from `tabItem Default` where parent", "\"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\": update_item, # \"condition\":", "Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Request for Quotation\", \"validation\": {", "information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import", "flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty = (target.qty * target.conversion_factor) # if getdate(target.schedule_date) < getdate(nowdate()):", "in target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items =", "if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source, target_doc) # def select_item(d):", "target_doc): set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\":", "* target.conversion_factor) # if getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date = None @frappe.whitelist() def", "target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source, target_doc) # def", "[\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\": update_item, # \"condition\": select_item", "\"Request for Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\",", "target_doc.items = supplier_items set_missing_values(source, target_doc) # def select_item(d): # frappe.errprint(d) # return d.ordered_qty", "get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Request for Quotation\",", "default supplier supplier_items = [] for d in target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier')", "default_supplier: supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source, target_doc) # def select_item(d): # frappe.errprint(d) #", "TeamPRO and contributors # For license information, please see license.txt from __future__ import", "} }, target_doc) return doclist # def update_item(obj, target, source_parent): # target.conversion_factor =", "}, target_doc, postprocess) return doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed Asset", "in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from `tabItem Default` where parent in ({0})", "[\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Supplier Quotation Item\",", "] } }, target_doc) return doclist # def update_item(obj, target, source_parent): # target.conversion_factor", "\"Supplier Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed", "def set_missing_values(source, target_doc): if target_doc.doctype == \"Purchase Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date", "\"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Request for Quotation Item\",", "def make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc): if frappe.flags.args and frappe.flags.args.default_supplier: # items only", "\"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\",", "target.conversion_factor = obj.conversion_factor # target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty =", "< d.stock_qty doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": {", "source_name, { \"Fixed Asset Request\": { \"doctype\": \"Supplier Quotation\", \"validation\": { \"docstatus\": [\"=\",", "\"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ] } }, target_doc) return doclist # def", "= (target.qty * target.conversion_factor) # if getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date = None", "target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items = supplier_items", "frappe.flags.args and frappe.flags.args.default_supplier: # items only for given default supplier supplier_items = []", "Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Supplier Quotation\", \"validation\": {", "filters): doc = frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list = [] for d in", "supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source, target_doc) # def select_item(d): # frappe.errprint(d) # return", "and contributors # For license information, please see license.txt from __future__ import unicode_literals", "update_item(obj, target, source_parent): # target.conversion_factor = obj.conversion_factor # target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/", "< getdate(nowdate()): # target.schedule_date = None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc):", "unicode_literals import frappe from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from frappe.utils", "set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": {", "}, target_doc) return doclist # def update_item(obj, target, source_parent): # target.conversion_factor = obj.conversion_factor", "frappe from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from frappe.utils import cstr,", "Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ]", "supplier supplier_items = [] for d in target_doc.items: default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if", "Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"],", "contributors # For license information, please see license.txt from __future__ import unicode_literals import", "# For license information, please see license.txt from __future__ import unicode_literals import frappe", "\"Fixed Asset Request\": { \"doctype\": \"Request for Quotation\", \"validation\": { \"docstatus\": [\"=\", 1],", "get_mapped_doc from frappe.utils import cstr, flt, getdate, new_line_sep, nowdate, add_days, get_link_to_form class FixedAssetRequest(Document):", "Asset Request Item\": { \"doctype\": \"Request for Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"],", "item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from `tabItem Default` where parent in ({0}) and default_supplier", "default_supplier from `tabItem Default` where parent in ({0}) and default_supplier IS NOT NULL", "] } }, target_doc, postprocess) return doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist =", "2020, TeamPRO and contributors # For license information, please see license.txt from __future__", "- flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty = (target.qty * target.conversion_factor) # if getdate(target.schedule_date) <", "set_missing_values(source, target_doc) # def select_item(d): # frappe.errprint(d) # return d.ordered_qty < d.stock_qty doclist", "new_line_sep, nowdate, add_days, get_link_to_form class FixedAssetRequest(Document): pass def set_missing_values(source, target_doc): if target_doc.doctype ==", "Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset", "import get_mapped_doc from frappe.utils import cstr, flt, getdate, new_line_sep, nowdate, add_days, get_link_to_form class", "doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from `tabItem Default` where parent in ({0}) and", "add_days, get_link_to_form class FixedAssetRequest(Document): pass def set_missing_values(source, target_doc): if target_doc.doctype == \"Purchase Order\"", "\"doctype\": \"Request for Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] }", "# frappe.errprint(d) # return d.ordered_qty < d.stock_qty doclist = get_mapped_doc(\"Fixed Asset Request\", source_name,", "(target.qty * target.conversion_factor) # if getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date = None @frappe.whitelist()", "}, \"Fixed Asset Request Item\": { \"doctype\": \"Supplier Quotation Item\", \"field_map\": [ [\"name\",", "} }, \"Fixed Asset Request Item\": { \"doctype\": \"Supplier Quotation Item\", \"field_map\": [", "\"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ] } },", "obj.conversion_factor # target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty = (target.qty *", "source_parent): # target.conversion_factor = obj.conversion_factor # target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor #", "Asset Request\": { \"doctype\": \"Supplier Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\",", "d.ordered_qty < d.stock_qty doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\":", "[\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ] } }, target_doc, postprocess)", "== \"Purchase Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist()", "[\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ],", "None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield, start, page_len, filters): doc =", "from frappe.utils import cstr, flt, getdate, new_line_sep, nowdate, add_days, get_link_to_form class FixedAssetRequest(Document): pass", "\"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\": update_item,", "{ \"Fixed Asset Request\": { \"doctype\": \"Request for Quotation\", \"validation\": { \"docstatus\": [\"=\",", "NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc): set_missing_values(source, target_doc) doclist", "page_len, filters): doc = frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list = [] for d", "def select_item(d): # frappe.errprint(d) # return d.ordered_qty < d.stock_qty doclist = get_mapped_doc(\"Fixed Asset", "= None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc): if frappe.flags.args and frappe.flags.args.default_supplier:", "d in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from `tabItem Default` where parent in", "[\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ] } }, target_doc) return doclist #", "# target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty = (target.qty * target.conversion_factor)", "Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Supplier Quotation\", \"validation\": { \"docstatus\":", "# if getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date = None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None):", "}, \"Fixed Asset Request Item\": { \"doctype\": \"Request for Quotation Item\", \"field_map\": [", "# items only for given default supplier supplier_items = [] for d in", "doclist # def update_item(obj, target, source_parent): # target.conversion_factor = obj.conversion_factor # target.qty =", "\"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ] } }, target_doc) return doclist", "< getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield, start,", "target_doc): if frappe.flags.args and frappe.flags.args.default_supplier: # items only for given default supplier supplier_items", "Asset Request Item\": { \"doctype\": \"Purchase Order Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\",", "frappe.model.mapper import get_mapped_doc from frappe.utils import cstr, flt, getdate, new_line_sep, nowdate, add_days, get_link_to_form", "# target.stock_qty = (target.qty * target.conversion_factor) # if getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date", "} }, \"Fixed Asset Request Item\": { \"doctype\": \"Purchase Order Item\", \"field_map\": [", "target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield, start, page_len, filters): doc = frappe.get_doc(\"Fixed Asset", "\"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc): set_missing_values(source, target_doc) doclist =", "see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from", "default_supplier IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc):", "source_name, { \"Fixed Asset Request\": { \"doctype\": \"Purchase Order\", \"validation\": { \"docstatus\": [\"=\",", "nowdate, add_days, get_link_to_form class FixedAssetRequest(Document): pass def set_missing_values(source, target_doc): if target_doc.doctype == \"Purchase", "import unicode_literals import frappe from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from", "= supplier_items set_missing_values(source, target_doc) # def select_item(d): # frappe.errprint(d) # return d.ordered_qty <", "\"Request for Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } },", "@frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset", "= None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield, start, page_len, filters): doc", "items only for given default supplier supplier_items = [] for d in target_doc.items:", "target_doc) doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\":", "\"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\": update_item, # \"condition\": select_item } }, target_doc,", "target_doc=None): doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\":", "\"uom\"], [\"sales_order\", \"sales_order\"], [\"sales_order_item\", \"sales_order_item\"] ], # \"postprocess\": update_item, # \"condition\": select_item }", "def postprocess(source, target_doc): set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed", "1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Request", "\"Supplier Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"],", "\"Purchase Order\" and getdate(target_doc.schedule_date) < getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def", "import frappe from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from frappe.utils import", "[\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ] } }, target_doc, postprocess) return doclist @frappe.whitelist() def", "import Document from frappe.model.mapper import get_mapped_doc from frappe.utils import cstr, flt, getdate, new_line_sep,", "please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document", "\"doctype\": \"Request for Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"],", "def make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\":", "Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Purchase Order\", \"validation\": {", "= [] for d in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier from `tabItem Default`", "doc = frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list = [] for d in doc.items:", "[\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\":", "[\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Request for Quotation", "Request\", filters.get(\"doc\")) item_list = [] for d in doc.items: item_list.append(d.item_code) return frappe.db.sql(\"\"\"select default_supplier", "utf-8 -*- # Copyright (c) 2020, TeamPRO and contributors # For license information,", "Request\": { \"doctype\": \"Request for Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\",", "FixedAssetRequest(Document): pass def set_missing_values(source, target_doc): if target_doc.doctype == \"Purchase Order\" and getdate(target_doc.schedule_date) <", "}, \"Fixed Asset Request Item\": { \"doctype\": \"Purchase Order Item\", \"field_map\": [ [\"name\",", "\"Purchase\"] } }, \"Fixed Asset Request Item\": { \"doctype\": \"Supplier Quotation Item\", \"field_map\":", "\"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ] } }, target_doc, postprocess) return", "def update_item(obj, target, source_parent): # target.conversion_factor = obj.conversion_factor # target.qty = flt(flt(obj.stock_qty) -", "getdate(target.schedule_date) < getdate(nowdate()): # target.schedule_date = None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def postprocess(source,", "txt, searchfield, start, page_len, filters): doc = frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list =", "target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield, start, page_len, filters): doc = frappe.get_doc(\"Fixed", "postprocess) return doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed Asset Request\", source_name,", "getdate(nowdate()): target_doc.schedule_date = None target_doc.run_method(\"set_missing_values\") target_doc.run_method(\"calculate_taxes_and_totals\") @frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield, start, page_len,", "\"doctype\": \"Purchase Order Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\",", "d.stock_qty doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\":", "[\"uom\", \"Nos\"] ] } }, target_doc) return doclist # def update_item(obj, target, source_parent):", "\"stock_uom\"], ] } }, target_doc, postprocess) return doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist", "\"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\", \"stock_uom\"], ] } }, target_doc, postprocess) return doclist @frappe.whitelist()", "make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": {", "Item\": { \"doctype\": \"Request for Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"],", "Asset Request Item\": { \"doctype\": \"Supplier Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\",", "default_supplier = get_item_defaults(d.item_code, target_doc.company).get('default_supplier') if frappe.flags.args.default_supplier == default_supplier: supplier_items.append(d) target_doc.items = supplier_items set_missing_values(source,", "doclist @frappe.whitelist() def make_request_for_quotation(source_name, target_doc=None): doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed", "({0}) and default_supplier IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list)) @frappe.whitelist() def make_supplier_quotation(source_name, target_doc=None): def", "def get_default_supplier_query(doctype, txt, searchfield, start, page_len, filters): doc = frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\"))", "`tabItem Default` where parent in ({0}) and default_supplier IS NOT NULL \"\"\".format(', '.join(['%s']*len(item_list))),tuple(item_list))", "\"doctype\": \"Supplier Quotation Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"uom\"], [\"uom\",", "# target.conversion_factor = obj.conversion_factor # target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty))/ target.conversion_factor # target.stock_qty", "\"doctype\": \"Supplier Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } },", "{ \"Fixed Asset Request\": { \"doctype\": \"Purchase Order\", \"validation\": { \"docstatus\": [\"=\", 1],", "get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Supplier Quotation\", \"validation\":", "return doclist # def update_item(obj, target, source_parent): # target.conversion_factor = obj.conversion_factor # target.qty", "return d.ordered_qty < d.stock_qty doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset", "{ \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset Request Item\":", "frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list = [] for d in doc.items: item_list.append(d.item_code) return", "Item\", \"field_map\": [ [\"name\", \"fixed_asset_request_item\"], [\"parent\", \"fixed_asset_request\"], [\"uom\", \"stock_uom\"], [\"uom\", \"Nos\"] ] }", "Order\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] } }, \"Fixed Asset", "Request\": { \"doctype\": \"Purchase Order\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"]", "def postprocess(source, target_doc): if frappe.flags.args and frappe.flags.args.default_supplier: # items only for given default", "make_supplier_quotation(source_name, target_doc=None): def postprocess(source, target_doc): set_missing_values(source, target_doc) doclist = get_mapped_doc(\"Fixed Asset Request\", source_name,", "searchfield, start, page_len, filters): doc = frappe.get_doc(\"Fixed Asset Request\", filters.get(\"doc\")) item_list = []", "# return d.ordered_qty < d.stock_qty doclist = get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed", "\"Fixed Asset Request\": { \"doctype\": \"Supplier Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\":", "\"stock_uom\"], [\"uom\", \"Nos\"] ] } }, target_doc) return doclist # def update_item(obj, target,", "import cstr, flt, getdate, new_line_sep, nowdate, add_days, get_link_to_form class FixedAssetRequest(Document): pass def set_missing_values(source,", "getdate(nowdate()): # target.schedule_date = None @frappe.whitelist() def make_purchase_order(source_name, target_doc=None): def postprocess(source, target_doc): if", "= get_mapped_doc(\"Fixed Asset Request\", source_name, { \"Fixed Asset Request\": { \"doctype\": \"Supplier Quotation\",", "for given default supplier supplier_items = [] for d in target_doc.items: default_supplier =", "@frappe.whitelist() def get_default_supplier_query(doctype, txt, searchfield, start, page_len, filters): doc = frappe.get_doc(\"Fixed Asset Request\",", "{ \"doctype\": \"Supplier Quotation\", \"validation\": { \"docstatus\": [\"=\", 1], \"material_request_type\": [\"=\", \"Purchase\"] }" ]
[ "current t = threading.current_thread() for n in range(5): # cur print('{0} th excute", "name=None): super().__init__(name=name) # def run(self): # current t = threading.current_thread() for n in", "# t1.start() # block # t1.join() #print('value = {0}'.format(value)) #print('main continue') # thread", "######################################################################### # !/usr/bin/env python3 import time import threading import json import requests def", "print_value(): global x x = 100 print('函数中x = {0}'.format(x)) print_value() print('全局变量x = {0}'.format(x))", "sum(*numbers): total = 0.0 for number in numbers: total += number return total", "t1.start() # active thread t2 # t2.start() class SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name)", "= [n for n in range(100)] def biger50(n): return True if n >", "100 print('函数中x = {0}'.format(x)) print_value() print('全局变量x = {0}'.format(x)) # 输出结果: # 函数中x=100 #", "time import threading import json import requests def sum(*numbers): total = 0.0 for", "time.sleep(2) print('thread {0} Done.'.format(t.name)) # main thread # create th obj 1 t1", "14:58:24 2021 ######################################################################### # !/usr/bin/env python3 import time import threading import json import", "t.name)) # thread sleep time.sleep(2) print('thread {0} Done.'.format(t.name)) # main thread # create", "print(f'{threading.current_thread().name} is working...') # thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its job.') # control", "n > 50 else False print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/') # print(r.status_code) #", "# print(r.status_code) # print(r.content) # print(r.content.decode()) # json.loads(r.content) def thread_body(): # current t", "= 0.0 for number in numbers: total += number return total x =", "False print('control thread done.') # main # crt work thread obj workthread workthread", "job.') # control thread body def controlthread_body(): global isrunning while isrunning: # input", "{0}'.format(value)) #print('main continue') # thread stop isrunning = True # work thread body", "sleep time.sleep(2) print('thread {0} Done.'.format(t.name)) # main thread # create th obj 1", "class SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name) # def run(self): # current t =", "print(f'thread{t.name} done.') # main # crt t1 #t1 = SmallThread(\"t1\") # crt t2", "cur print(\"{0} th excute {1}\".format(n, t.name)) # sleep time.sleep(2) print(f'thread{t.name} done.') # main", "print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1 = threading.Thread(target=thread_body) # t1.start() # block # t1.join()", "print('control thread done.') # main # crt work thread obj workthread workthread =", "t.name)) # sleep time.sleep(2) print(f'thread{t.name} done.') # main # crt t1 #t1 =", "time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1 = threading.Thread(target=thread_body) # t1.start() # block #", "# t2.start() class SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name) # def run(self): # current", "# input stop cmd from standard input(keyboard) command = input('Input Stop Command: ')", "t = threading.current_thread() for n in range(5): # cur print('{0} th excute thread", "#t1 = SmallThread(\"t1\") # crt t2 #t2 = SmallThread(\"t2\") # launch # t1.start()", "# obj 2 t2 = threading.Thread(target=thread_body, name=\"MyThread\") # active thread t1 # t1.start()", "#print('main continue') # thread stop isrunning = True # work thread body def", "Stop Command: ') if command == 'exit': isrunning = False print('control thread done.')", "current t = threading.current_thread() for n in range(5): # cur print(\"{0} th excute", "body def workthread_body(): while isrunning: # thread beginning to work print(f'{threading.current_thread().name} is working...')", "thread_body(): # current t = threading.current_thread() for n in range(5): # cur print('{0}", "print('全局变量x = {0}'.format(x)) # 输出结果: # 函数中x=100 # 全局变量x=100 arr = [n for", "active thread t2 # t2.start() class SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name) # def", "starting...') for n in range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main", "print('{0} th excute thread {1}.'.format(n, t.name)) # thread sleep time.sleep(2) print('thread {0} Done.'.format(t.name))", "SmallThread(\"t1\") # crt t2 #t2 = SmallThread(\"t2\") # launch # t1.start() # t2.start()", "import threading import json import requests def sum(*numbers): total = 0.0 for number", "in numbers: total += number return total x = 200 def print_value(): global", "__init__(self, name=None): super().__init__(name=name) # def run(self): # current t = threading.current_thread() for n", "# 全局变量x=100 arr = [n for n in range(100)] def biger50(n): return True", "print(f'{threading.current_thread().name} starting...') for n in range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.')", "thread sleep time.sleep(2) print('thread {0} Done.'.format(t.name)) # main thread # create th obj", "python3 import time import threading import json import requests def sum(*numbers): total =", "work print(f'{threading.current_thread().name} is working...') # thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its job.') #", "# !/usr/bin/env python3 import time import threading import json import requests def sum(*numbers):", "t2 = threading.Thread(target=thread_body, name=\"MyThread\") # active thread t1 # t1.start() # active thread", "thread {1}.'.format(n, t.name)) # thread sleep time.sleep(2) print('thread {0} Done.'.format(t.name)) # main thread", "######################################################################### # File Name: 1.py # Author: Walker # mail:<EMAIL> # Created Time:", "Created Time: Tue Dec 7 14:58:24 2021 ######################################################################### # !/usr/bin/env python3 import time", "else False print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content) # print(r.content.decode())", "active thread t1 # t1.start() # active thread t2 # t2.start() class SmallThread(threading.Thread):", "SmallThread(\"t2\") # launch # t1.start() # t2.start() value = [] def thread_body(): print(f'{threading.current_thread().name}", "standard input(keyboard) command = input('Input Stop Command: ') if command == 'exit': isrunning", "# thread beginning to work print(f'{threading.current_thread().name} is working...') # thread sleep time.sleep(5) print(f'{threading.current_thread().name}", "print(r.status_code) # print(r.content) # print(r.content.decode()) # json.loads(r.content) def thread_body(): # current t =", "obj 1 t1 = threading.Thread(target=thread_body) # obj 2 t2 = threading.Thread(target=thread_body, name=\"MyThread\") #", "Time: Tue Dec 7 14:58:24 2021 ######################################################################### # !/usr/bin/env python3 import time import", "def controlthread_body(): global isrunning while isrunning: # input stop cmd from standard input(keyboard)", "input(keyboard) command = input('Input Stop Command: ') if command == 'exit': isrunning =", "# sleep time.sleep(2) print(f'thread{t.name} done.') # main # crt t1 #t1 = SmallThread(\"t1\")", "while isrunning: # thread beginning to work print(f'{threading.current_thread().name} is working...') # thread sleep", "value = [] def thread_body(): print(f'{threading.current_thread().name} starting...') for n in range(4): print(f'{n}_th {threading.current_thread().name}", "= {0}'.format(value)) #print('main continue') # thread stop isrunning = True # work thread", "thread obj workthread workthread = threading.Thread(target=workthread_body) # workthread.start() # crt ctrl thread obj", "block # t1.join() #print('value = {0}'.format(value)) #print('main continue') # thread stop isrunning =", "threading.Thread(target=thread_body) # obj 2 t2 = threading.Thread(target=thread_body, name=\"MyThread\") # active thread t1 #", "cur print('{0} th excute thread {1}.'.format(n, t.name)) # thread sleep time.sleep(2) print('thread {0}", "#t1 = threading.Thread(target=thread_body) # t1.start() # block # t1.join() #print('value = {0}'.format(value)) #print('main", "[] def thread_body(): print(f'{threading.current_thread().name} starting...') for n in range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n)", "for n in range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\")", "workthread = threading.Thread(target=workthread_body) # workthread.start() # crt ctrl thread obj controlthread controlthread =", "range(100)] def biger50(n): return True if n > 50 else False print(list(filter(biger50, arr)))", "def biger50(n): return True if n > 50 else False print(list(filter(biger50, arr))) r", "# thread stop isrunning = True # work thread body def workthread_body(): while", "global isrunning while isrunning: # input stop cmd from standard input(keyboard) command =", "= SmallThread(\"t2\") # launch # t1.start() # t2.start() value = [] def thread_body():", "numbers: total += number return total x = 200 def print_value(): global x", "print(\"{0} th excute {1}\".format(n, t.name)) # sleep time.sleep(2) print(f'thread{t.name} done.') # main #", "{0} Done.'.format(t.name)) # main thread # create th obj 1 t1 = threading.Thread(target=thread_body)", "print(r.content) # print(r.content.decode()) # json.loads(r.content) def thread_body(): # current t = threading.current_thread() for", "== 'exit': isrunning = False print('control thread done.') # main # crt work", "#t2 = SmallThread(\"t2\") # launch # t1.start() # t2.start() value = [] def", "Command: ') if command == 'exit': isrunning = False print('control thread done.') #", "work thread obj workthread workthread = threading.Thread(target=workthread_body) # workthread.start() # crt ctrl thread", "= [] def thread_body(): print(f'{threading.current_thread().name} starting...') for n in range(4): print(f'{n}_th {threading.current_thread().name} running...')", "create th obj 1 t1 = threading.Thread(target=thread_body) # obj 2 t2 = threading.Thread(target=thread_body,", "= True # work thread body def workthread_body(): while isrunning: # thread beginning", "threading.Thread(target=thread_body, name=\"MyThread\") # active thread t1 # t1.start() # active thread t2 #", "for n in range(5): # cur print('{0} th excute thread {1}.'.format(n, t.name)) #", "working...') # thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its job.') # control thread body", "{threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1 = threading.Thread(target=thread_body) # t1.start()", "launch # t1.start() # t2.start() value = [] def thread_body(): print(f'{threading.current_thread().name} starting...') for", "print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content) # print(r.content.decode()) # json.loads(r.content)", "# 输出结果: # 函数中x=100 # 全局变量x=100 arr = [n for n in range(100)]", "thread done.') # main # crt work thread obj workthread workthread = threading.Thread(target=workthread_body)", "') if command == 'exit': isrunning = False print('control thread done.') # main", "2021 ######################################################################### # !/usr/bin/env python3 import time import threading import json import requests", "excute {1}\".format(n, t.name)) # sleep time.sleep(2) print(f'thread{t.name} done.') # main # crt t1", "its job.') # control thread body def controlthread_body(): global isrunning while isrunning: #", "crt work thread obj workthread workthread = threading.Thread(target=workthread_body) # workthread.start() # crt ctrl", "# json.loads(r.content) def thread_body(): # current t = threading.current_thread() for n in range(5):", "Walker # mail:<EMAIL> # Created Time: Tue Dec 7 14:58:24 2021 ######################################################################### #", "input('Input Stop Command: ') if command == 'exit': isrunning = False print('control thread", "isrunning while isrunning: # input stop cmd from standard input(keyboard) command = input('Input", "return True if n > 50 else False print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/')", "json import requests def sum(*numbers): total = 0.0 for number in numbers: total", "thread body def controlthread_body(): global isrunning while isrunning: # input stop cmd from", "range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1 = threading.Thread(target=thread_body)", "# def run(self): # current t = threading.current_thread() for n in range(5): #", "obj 2 t2 = threading.Thread(target=thread_body, name=\"MyThread\") # active thread t1 # t1.start() #", "main thread # create th obj 1 t1 = threading.Thread(target=thread_body) # obj 2", "= {0}'.format(x)) print_value() print('全局变量x = {0}'.format(x)) # 输出结果: # 函数中x=100 # 全局变量x=100 arr", "t = threading.current_thread() for n in range(5): # cur print(\"{0} th excute {1}\".format(n,", "n in range(5): # cur print('{0} th excute thread {1}.'.format(n, t.name)) # thread", "controlthread_body(): global isrunning while isrunning: # input stop cmd from standard input(keyboard) command", "th obj 1 t1 = threading.Thread(target=thread_body) # obj 2 t2 = threading.Thread(target=thread_body, name=\"MyThread\")", "beginning to work print(f'{threading.current_thread().name} is working...') # thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its", "# print(r.content) # print(r.content.decode()) # json.loads(r.content) def thread_body(): # current t = threading.current_thread()", "# current t = threading.current_thread() for n in range(5): # cur print(\"{0} th", "函数中x=100 # 全局变量x=100 arr = [n for n in range(100)] def biger50(n): return", "arr))) r = requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content) # print(r.content.decode()) # json.loads(r.content) def", "return total x = 200 def print_value(): global x x = 100 print('函数中x", "if command == 'exit': isrunning = False print('control thread done.') # main #", "# t2.start() value = [] def thread_body(): print(f'{threading.current_thread().name} starting...') for n in range(4):", "workthread_body(): while isrunning: # thread beginning to work print(f'{threading.current_thread().name} is working...') # thread", "threading.Thread(target=thread_body) # t1.start() # block # t1.join() #print('value = {0}'.format(value)) #print('main continue') #", "= threading.current_thread() for n in range(5): # cur print('{0} th excute thread {1}.'.format(n,", "to work print(f'{threading.current_thread().name} is working...') # thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its job.')", "number return total x = 200 def print_value(): global x x = 100", "# t1.join() #print('value = {0}'.format(value)) #print('main continue') # thread stop isrunning = True", "{0}'.format(x)) # 输出结果: # 函数中x=100 # 全局变量x=100 arr = [n for n in", "File Name: 1.py # Author: Walker # mail:<EMAIL> # Created Time: Tue Dec", "time.sleep(5) print(f'{threading.current_thread().name} Finished its job.') # control thread body def controlthread_body(): global isrunning", "n in range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1", "= threading.Thread(target=workthread_body) # workthread.start() # crt ctrl thread obj controlthread controlthread = threading.Thread(target=controlthread_body)", "# Created Time: Tue Dec 7 14:58:24 2021 ######################################################################### # !/usr/bin/env python3 import", "t1.start() # block # t1.join() #print('value = {0}'.format(value)) #print('main continue') # thread stop", "thread t1 # t1.start() # active thread t2 # t2.start() class SmallThread(threading.Thread): def", "th excute {1}\".format(n, t.name)) # sleep time.sleep(2) print(f'thread{t.name} done.') # main # crt", "# Author: Walker # mail:<EMAIL> # Created Time: Tue Dec 7 14:58:24 2021", "total x = 200 def print_value(): global x x = 100 print('函数中x =", "cmd from standard input(keyboard) command = input('Input Stop Command: ') if command ==", "# block # t1.join() #print('value = {0}'.format(value)) #print('main continue') # thread stop isrunning", "# control thread body def controlthread_body(): global isrunning while isrunning: # input stop", "= threading.Thread(target=thread_body, name=\"MyThread\") # active thread t1 # t1.start() # active thread t2", "<reponame>PuddingWalker/py_small_projects ######################################################################### # File Name: 1.py # Author: Walker # mail:<EMAIL> # Created", "print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1 = threading.Thread(target=thread_body) #", "input stop cmd from standard input(keyboard) command = input('Input Stop Command: ') if", "200 def print_value(): global x x = 100 print('函数中x = {0}'.format(x)) print_value() print('全局变量x", "#print('value = {0}'.format(value)) #print('main continue') # thread stop isrunning = True # work", "2 t2 = threading.Thread(target=thread_body, name=\"MyThread\") # active thread t1 # t1.start() # active", "thread stop isrunning = True # work thread body def workthread_body(): while isrunning:", "super().__init__(name=name) # def run(self): # current t = threading.current_thread() for n in range(5):", "def print_value(): global x x = 100 print('函数中x = {0}'.format(x)) print_value() print('全局变量x =", "# t1.start() # active thread t2 # t2.start() class SmallThread(threading.Thread): def __init__(self, name=None):", "obj workthread workthread = threading.Thread(target=workthread_body) # workthread.start() # crt ctrl thread obj controlthread", "in range(100)] def biger50(n): return True if n > 50 else False print(list(filter(biger50,", "# File Name: 1.py # Author: Walker # mail:<EMAIL> # Created Time: Tue", "# mail:<EMAIL> # Created Time: Tue Dec 7 14:58:24 2021 ######################################################################### # !/usr/bin/env", "sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its job.') # control thread body def controlthread_body(): global", "done.') # main # crt work thread obj workthread workthread = threading.Thread(target=workthread_body) #", "range(5): # cur print(\"{0} th excute {1}\".format(n, t.name)) # sleep time.sleep(2) print(f'thread{t.name} done.')", "t1 #t1 = SmallThread(\"t1\") # crt t2 #t2 = SmallThread(\"t2\") # launch #", "from standard input(keyboard) command = input('Input Stop Command: ') if command == 'exit':", "# active thread t1 # t1.start() # active thread t2 # t2.start() class", "{0}'.format(x)) print_value() print('全局变量x = {0}'.format(x)) # 输出结果: # 函数中x=100 # 全局变量x=100 arr =", "def __init__(self, name=None): super().__init__(name=name) # def run(self): # current t = threading.current_thread() for", "t1.join() #print('value = {0}'.format(value)) #print('main continue') # thread stop isrunning = True #", "thread_body(): print(f'{threading.current_thread().name} starting...') for n in range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name}", "# main thread # create th obj 1 t1 = threading.Thread(target=thread_body) # obj", "threading.Thread(target=workthread_body) # workthread.start() # crt ctrl thread obj controlthread controlthread = threading.Thread(target=controlthread_body) controlthread.start()", "Author: Walker # mail:<EMAIL> # Created Time: Tue Dec 7 14:58:24 2021 #########################################################################", "command = input('Input Stop Command: ') if command == 'exit': isrunning = False", "全局变量x=100 arr = [n for n in range(100)] def biger50(n): return True if", "thread t2 # t2.start() class SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name) # def run(self):", "total = 0.0 for number in numbers: total += number return total x", "= threading.Thread(target=thread_body) # t1.start() # block # t1.join() #print('value = {0}'.format(value)) #print('main continue')", "t2 # t2.start() class SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name) # def run(self): #", "Tue Dec 7 14:58:24 2021 ######################################################################### # !/usr/bin/env python3 import time import threading", "# thread sleep time.sleep(2) print('thread {0} Done.'.format(t.name)) # main thread # create th", "= threading.current_thread() for n in range(5): # cur print(\"{0} th excute {1}\".format(n, t.name))", "# cur print(\"{0} th excute {1}\".format(n, t.name)) # sleep time.sleep(2) print(f'thread{t.name} done.') #", "stop isrunning = True # work thread body def workthread_body(): while isrunning: #", "json.loads(r.content) def thread_body(): # current t = threading.current_thread() for n in range(5): #", "t2.start() value = [] def thread_body(): print(f'{threading.current_thread().name} starting...') for n in range(4): print(f'{n}_th", "= input('Input Stop Command: ') if command == 'exit': isrunning = False print('control", "command == 'exit': isrunning = False print('control thread done.') # main # crt", "done.') #print(\"main ....\") #t1 = threading.Thread(target=thread_body) # t1.start() # block # t1.join() #print('value", "#print(\"main ....\") #t1 = threading.Thread(target=thread_body) # t1.start() # block # t1.join() #print('value =", "requests def sum(*numbers): total = 0.0 for number in numbers: total += number", "def sum(*numbers): total = 0.0 for number in numbers: total += number return", "is working...') # thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its job.') # control thread", "# crt t1 #t1 = SmallThread(\"t1\") # crt t2 #t2 = SmallThread(\"t2\") #", "thread body def workthread_body(): while isrunning: # thread beginning to work print(f'{threading.current_thread().name} is", "print(r.content.decode()) # json.loads(r.content) def thread_body(): # current t = threading.current_thread() for n in", "import json import requests def sum(*numbers): total = 0.0 for number in numbers:", "for n in range(100)] def biger50(n): return True if n > 50 else", "main # crt t1 #t1 = SmallThread(\"t1\") # crt t2 #t2 = SmallThread(\"t2\")", "1.py # Author: Walker # mail:<EMAIL> # Created Time: Tue Dec 7 14:58:24", "'exit': isrunning = False print('control thread done.') # main # crt work thread", "print(f'{threading.current_thread().name} Finished its job.') # control thread body def controlthread_body(): global isrunning while", "+= number return total x = 200 def print_value(): global x x =", "while isrunning: # input stop cmd from standard input(keyboard) command = input('Input Stop", "0.0 for number in numbers: total += number return total x = 200", "continue') # thread stop isrunning = True # work thread body def workthread_body():", "time.sleep(2) print(f'thread{t.name} done.') # main # crt t1 #t1 = SmallThread(\"t1\") # crt", "x = 200 def print_value(): global x x = 100 print('函数中x = {0}'.format(x))", "False print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content) # print(r.content.decode()) #", "control thread body def controlthread_body(): global isrunning while isrunning: # input stop cmd", "50 else False print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content) #", "= False print('control thread done.') # main # crt work thread obj workthread", "arr = [n for n in range(100)] def biger50(n): return True if n", "输出结果: # 函数中x=100 # 全局变量x=100 arr = [n for n in range(100)] def", "print_value() print('全局变量x = {0}'.format(x)) # 输出结果: # 函数中x=100 # 全局变量x=100 arr = [n", "True # work thread body def workthread_body(): while isrunning: # thread beginning to", "threading.current_thread() for n in range(5): # cur print('{0} th excute thread {1}.'.format(n, t.name))", "body def controlthread_body(): global isrunning while isrunning: # input stop cmd from standard", "def thread_body(): # current t = threading.current_thread() for n in range(5): # cur", "1 t1 = threading.Thread(target=thread_body) # obj 2 t2 = threading.Thread(target=thread_body, name=\"MyThread\") # active", "crt t1 #t1 = SmallThread(\"t1\") # crt t2 #t2 = SmallThread(\"t2\") # launch", "threading.current_thread() for n in range(5): # cur print(\"{0} th excute {1}\".format(n, t.name)) #", "in range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1 =", "= {0}'.format(x)) # 输出结果: # 函数中x=100 # 全局变量x=100 arr = [n for n", "= threading.Thread(target=thread_body) # obj 2 t2 = threading.Thread(target=thread_body, name=\"MyThread\") # active thread t1", "x = 100 print('函数中x = {0}'.format(x)) print_value() print('全局变量x = {0}'.format(x)) # 输出结果: #", "threading import json import requests def sum(*numbers): total = 0.0 for number in", "thread beginning to work print(f'{threading.current_thread().name} is working...') # thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished", "running...') value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1 = threading.Thread(target=thread_body) # t1.start() #", "name=\"MyThread\") # active thread t1 # t1.start() # active thread t2 # t2.start()", "t2.start() class SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name) # def run(self): # current t", "Done.'.format(t.name)) # main thread # create th obj 1 t1 = threading.Thread(target=thread_body) #", "for n in range(5): # cur print(\"{0} th excute {1}\".format(n, t.name)) # sleep", "isrunning = False print('control thread done.') # main # crt work thread obj", "work thread body def workthread_body(): while isrunning: # thread beginning to work print(f'{threading.current_thread().name}", "def workthread_body(): while isrunning: # thread beginning to work print(f'{threading.current_thread().name} is working...') #", "stop cmd from standard input(keyboard) command = input('Input Stop Command: ') if command", "main # crt work thread obj workthread workthread = threading.Thread(target=workthread_body) # workthread.start() #", "crt t2 #t2 = SmallThread(\"t2\") # launch # t1.start() # t2.start() value =", "t1 # t1.start() # active thread t2 # t2.start() class SmallThread(threading.Thread): def __init__(self,", "in range(5): # cur print(\"{0} th excute {1}\".format(n, t.name)) # sleep time.sleep(2) print(f'thread{t.name}", "# crt work thread obj workthread workthread = threading.Thread(target=workthread_body) # workthread.start() # crt", "isrunning = True # work thread body def workthread_body(): while isrunning: # thread", "workthread workthread = threading.Thread(target=workthread_body) # workthread.start() # crt ctrl thread obj controlthread controlthread", "SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name) # def run(self): # current t = threading.current_thread()", "isrunning: # input stop cmd from standard input(keyboard) command = input('Input Stop Command:", "number in numbers: total += number return total x = 200 def print_value():", "# current t = threading.current_thread() for n in range(5): # cur print('{0} th", "t1 = threading.Thread(target=thread_body) # obj 2 t2 = threading.Thread(target=thread_body, name=\"MyThread\") # active thread", "# print(r.content.decode()) # json.loads(r.content) def thread_body(): # current t = threading.current_thread() for n", "{1}.'.format(n, t.name)) # thread sleep time.sleep(2) print('thread {0} Done.'.format(t.name)) # main thread #", "True if n > 50 else False print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/') #", "= 200 def print_value(): global x x = 100 print('函数中x = {0}'.format(x)) print_value()", "# main # crt t1 #t1 = SmallThread(\"t1\") # crt t2 #t2 =", "# thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its job.') # control thread body def", "# create th obj 1 t1 = threading.Thread(target=thread_body) # obj 2 t2 =", "= SmallThread(\"t1\") # crt t2 #t2 = SmallThread(\"t2\") # launch # t1.start() #", "def run(self): # current t = threading.current_thread() for n in range(5): # cur", "sleep time.sleep(2) print(f'thread{t.name} done.') # main # crt t1 #t1 = SmallThread(\"t1\") #", "th excute thread {1}.'.format(n, t.name)) # thread sleep time.sleep(2) print('thread {0} Done.'.format(t.name)) #", "# t1.start() # t2.start() value = [] def thread_body(): print(f'{threading.current_thread().name} starting...') for n", "print('函数中x = {0}'.format(x)) print_value() print('全局变量x = {0}'.format(x)) # 输出结果: # 函数中x=100 # 全局变量x=100", "# active thread t2 # t2.start() class SmallThread(threading.Thread): def __init__(self, name=None): super().__init__(name=name) #", "....\") #t1 = threading.Thread(target=thread_body) # t1.start() # block # t1.join() #print('value = {0}'.format(value))", "for number in numbers: total += number return total x = 200 def", "# work thread body def workthread_body(): while isrunning: # thread beginning to work", "x x = 100 print('函数中x = {0}'.format(x)) print_value() print('全局变量x = {0}'.format(x)) # 输出结果:", "# 函数中x=100 # 全局变量x=100 arr = [n for n in range(100)] def biger50(n):", "def thread_body(): print(f'{threading.current_thread().name} starting...') for n in range(4): print(f'{n}_th {threading.current_thread().name} running...') value.append(n) time.sleep(2)", "[n for n in range(100)] def biger50(n): return True if n > 50", "range(5): # cur print('{0} th excute thread {1}.'.format(n, t.name)) # thread sleep time.sleep(2)", "Dec 7 14:58:24 2021 ######################################################################### # !/usr/bin/env python3 import time import threading import", "> 50 else False print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content)", "!/usr/bin/env python3 import time import threading import json import requests def sum(*numbers): total", "total += number return total x = 200 def print_value(): global x x", "7 14:58:24 2021 ######################################################################### # !/usr/bin/env python3 import time import threading import json", "if n > 50 else False print(list(filter(biger50, arr))) r = requests.get('https://cn.bing.com/') # print(r.status_code)", "isrunning: # thread beginning to work print(f'{threading.current_thread().name} is working...') # thread sleep time.sleep(5)", "t1.start() # t2.start() value = [] def thread_body(): print(f'{threading.current_thread().name} starting...') for n in", "value.append(n) time.sleep(2) print(f'{threading.current_thread().name} done.') #print(\"main ....\") #t1 = threading.Thread(target=thread_body) # t1.start() # block", "r = requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content) # print(r.content.decode()) # json.loads(r.content) def thread_body():", "import requests def sum(*numbers): total = 0.0 for number in numbers: total +=", "# crt t2 #t2 = SmallThread(\"t2\") # launch # t1.start() # t2.start() value", "# launch # t1.start() # t2.start() value = [] def thread_body(): print(f'{threading.current_thread().name} starting...')", "import time import threading import json import requests def sum(*numbers): total = 0.0", "biger50(n): return True if n > 50 else False print(list(filter(biger50, arr))) r =", "Name: 1.py # Author: Walker # mail:<EMAIL> # Created Time: Tue Dec 7", "= requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content) # print(r.content.decode()) # json.loads(r.content) def thread_body(): #", "# main # crt work thread obj workthread workthread = threading.Thread(target=workthread_body) # workthread.start()", "n in range(100)] def biger50(n): return True if n > 50 else False", "requests.get('https://cn.bing.com/') # print(r.status_code) # print(r.content) # print(r.content.decode()) # json.loads(r.content) def thread_body(): # current", "done.') # main # crt t1 #t1 = SmallThread(\"t1\") # crt t2 #t2", "excute thread {1}.'.format(n, t.name)) # thread sleep time.sleep(2) print('thread {0} Done.'.format(t.name)) # main", "run(self): # current t = threading.current_thread() for n in range(5): # cur print(\"{0}", "thread # create th obj 1 t1 = threading.Thread(target=thread_body) # obj 2 t2", "# cur print('{0} th excute thread {1}.'.format(n, t.name)) # thread sleep time.sleep(2) print('thread", "n in range(5): # cur print(\"{0} th excute {1}\".format(n, t.name)) # sleep time.sleep(2)", "Finished its job.') # control thread body def controlthread_body(): global isrunning while isrunning:", "= 100 print('函数中x = {0}'.format(x)) print_value() print('全局变量x = {0}'.format(x)) # 输出结果: # 函数中x=100", "global x x = 100 print('函数中x = {0}'.format(x)) print_value() print('全局变量x = {0}'.format(x)) #", "print('thread {0} Done.'.format(t.name)) # main thread # create th obj 1 t1 =", "in range(5): # cur print('{0} th excute thread {1}.'.format(n, t.name)) # thread sleep", "{1}\".format(n, t.name)) # sleep time.sleep(2) print(f'thread{t.name} done.') # main # crt t1 #t1", "mail:<EMAIL> # Created Time: Tue Dec 7 14:58:24 2021 ######################################################################### # !/usr/bin/env python3", "t2 #t2 = SmallThread(\"t2\") # launch # t1.start() # t2.start() value = []", "thread sleep time.sleep(5) print(f'{threading.current_thread().name} Finished its job.') # control thread body def controlthread_body():" ]
[ "self.shortterm = stp self.longterm = ltp self.current = current self.reset() @classmethod def configured(cls,", "''' Xd: (delay, batch, pre) X: (batch, post) Vpost: (batch, post) Output: Current", "self.align_signs() def align_signs(self): if not self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad():", "'STDP_frac') else: STDP_frac = None ret = cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current,", "persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False) if ltp is not None: if", "self.W_signed = torch.empty_like(self.W) self.W_signed[signs == -1] = -torch.abs(self.W)[signs == -1] self.W_signed[signs == 0]", "= None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm = stp self.longterm = ltp self.current", "'wmax') wmin = init.expand_to_synapses(projections, nPre, nPost, 'wmin') # Weights bw = 0 if", "not None: Wlong = self.longterm(Xd, X, Vpost) W = self.W_signed * (1-self.STDP_frac) +", "cls(None, None, None) ret.projections = projections return ret nPre = init.get_N(conf_pre) nPost =", "= init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac') else: STDP_frac = None ret = cls(w,", "''' def __init__(self, W, signs_pre, delaymap=None, wmin=None, wmax=None, current=None, stp=None, ltp=None, STDP_frac=None): super().__init__()", "current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs): active = len(projections[0]) > 0 if not active:", "shared_weights=True, train_weight=True, disable_training=False, **kwargs): active = len(projections[0]) > 0 if not active: ret", "as ce class Synapse(ce.Module): ''' Synapse with optional current, short- and long-term plasticity", "= projections return ret nPre = init.get_N(conf_pre) nPost = nPre if conf_post is", "Synapse(ce.Module): ''' Synapse with optional current, short- and long-term plasticity submodules Input: Delayed", "delaymap is None: delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False)", "else: STDP_frac = None ret = cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp,", "nPre = init.get_N(conf_pre) nPost = nPre if conf_post is None else init.get_N(conf_post) delaymap", "None else init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt, conf_pre, conf_post) wmax = init.expand_to_synapses(projections, nPre,", "= cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections", "delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False) if ltp", "= 'beo' else: W = self.W_signed WD = 'eo' if len(self.W.shape) == 2", "nPost, 'wmax') wmin = init.expand_to_synapses(projections, nPre, nPost, 'wmin') # Weights bw = 0", "persistent=False) self.shortterm = stp self.longterm = ltp self.current = current self.reset() @classmethod def", "stp=None, ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs): active = len(projections[0]) > 0 if", "train_weight and not disable_training: w = torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp", "wmax, persistent=False) if ltp is not None: if not torch.any(STDP_frac > 0): ltp", "conf_post) wmax = init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin = init.expand_to_synapses(projections, nPre, nPost, 'wmin')", "* self.STDP_frac WD = 'beo' else: W = self.W_signed WD = 'eo' if", "self.current = current self.reset() @classmethod def configured(cls, projections, conf_pre, conf_post, batch_size, dt, stp=None,", "# dbe # Integrate output = self.internal_forward(WD, W, Xd) # Current filter if", "if not self.active: return torch.zeros_like(Vpost) # LTP if self.longterm is not None: Wlong", "> 0 if not active: ret = cls(None, None, None) ret.projections = projections", "= 0 if shared_weights else batch_size w = init.build_connectivity(projections, nPre, nPost, bw) if", "short- and long-term plasticity submodules Input: Delayed presynaptic spikes; postsynaptic spikes; postsyn voltage", "= W is not None if not self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W),", "init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin = init.expand_to_synapses(projections, nPre, nPost, 'wmin') # Weights bw", "dt, conf_pre, conf_post) wmax = init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin = init.expand_to_synapses(projections, nPre,", "is not None: STDP_frac = init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac') else: STDP_frac =", "None) ret.projections = projections return ret nPre = init.get_N(conf_pre) nPost = nPre if", "*W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False)", "wmin = init.expand_to_synapses(projections, nPre, nPost, 'wmin') # Weights bw = 0 if shared_weights", "+ Wlong * self.STDP_frac WD = 'beo' else: W = self.W_signed WD =", "self.internal_forward(WD, W, Xd) # Current filter if self.current is not None: output =", "'wmin') # Weights bw = 0 if shared_weights else batch_size w = init.build_connectivity(projections,", "X=None, Vpost=None): ''' Xd: (delay, batch, pre) X: (batch, post) Vpost: (batch, post)", "<filename>cantata/elements/synapse.py import torch from cantata import init import cantata.elements as ce class Synapse(ce.Module):", "not None: STDP_frac = init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac') else: STDP_frac = None", "Current filter if self.current is not None: output = self.current(output) return output def", "->bo', W, Xd, self.delaymap) def load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def", "= self.W[signs == 0] self.W_signed[signs == 1] = torch.abs(self.W)[signs == 1] def weight(self):", "-torch.abs(self.W)[signs == -1] self.W_signed[signs == 0] = self.W[signs == 0] self.W_signed[signs == 1]", "> 0): ltp = None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm = stp self.longterm", "None: STDP_frac = init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac') else: STDP_frac = None ret", "ret = cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections =", "disable_training: w = torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is not None:", "nPost, 'STDP_frac') else: STDP_frac = None ret = cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax,", "(batch, post) ''' if not self.active: return torch.zeros_like(Vpost) # LTP if self.longterm is", "if not self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap is None:", "postsyn voltage Output: Synaptic currents ''' def __init__(self, W, signs_pre, delaymap=None, wmin=None, wmax=None,", "if self.current is not None: self.current.reset(keep_values) def forward(self, Xd, X=None, Vpost=None): ''' Xd:", "dbe, deo ->bo', W, Xd, self.delaymap) def load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs)", "cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections return", "not None: self.longterm.reset(self, keep_values) if self.current is not None: self.current.reset(keep_values) def forward(self, Xd,", "output = self.current(output) return output def internal_forward(self, WD, W, Xd): return torch.einsum( f'{WD},", "'eo' if len(self.W.shape) == 2 else 'beo' # STP if self.shortterm is not", "projections, conf_pre, conf_post, batch_size, dt, stp=None, ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs): active", "is not None: Xd = Xd * (self.shortterm(Xd)+1) # dbe # Integrate output", "not active: ret = cls(None, None, None) ret.projections = projections return ret nPre", "== 0] = self.W[signs == 0] self.W_signed[signs == 1] = torch.abs(self.W)[signs == 1]", "nPre, nPost, 'wmax') wmin = init.expand_to_synapses(projections, nPre, nPost, 'wmin') # Weights bw =", "if not active: ret = cls(None, None, None) ret.projections = projections return ret", "= torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is not None: STDP_frac =", "super().__init__() self.active = W is not None if not self.active: return self.register_parabuf('W', W)", "self.register_buffer('wmax', wmax, persistent=False) if ltp is not None: if not torch.any(STDP_frac > 0):", "import init import cantata.elements as ce class Synapse(ce.Module): ''' Synapse with optional current,", "wmax=None, current=None, stp=None, ltp=None, STDP_frac=None): super().__init__() self.active = W is not None if", "= nPre if conf_post is None else init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt, conf_pre,", "ltp is not None: if not torch.any(STDP_frac > 0): ltp = None else:", "deo ->bo', W, Xd, self.delaymap) def load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs()", "self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm = stp self.longterm = ltp self.current = current self.reset()", "== -1] = -torch.abs(self.W)[signs == -1] self.W_signed[signs == 0] = self.W[signs == 0]", "(batch, post) Output: Current (batch, post) ''' if not self.active: return torch.zeros_like(Vpost) #", "keep_values=False): if self.active: self.align_signs() if self.shortterm is not None: self.shortterm.reset(keep_values) if self.longterm is", "import torch from cantata import init import cantata.elements as ce class Synapse(ce.Module): '''", "projections return ret def reset(self, keep_values=False): if self.active: self.align_signs() if self.shortterm is not", "Synaptic currents ''' def __init__(self, W, signs_pre, delaymap=None, wmin=None, wmax=None, current=None, stp=None, ltp=None,", "if ltp is not None: if not torch.any(STDP_frac > 0): ltp = None", "ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections return ret def reset(self, keep_values=False): if self.active: self.align_signs()", "= projections return ret def reset(self, keep_values=False): if self.active: self.align_signs() if self.shortterm is", "None: delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin,", "= stp self.longterm = ltp self.current = current self.reset() @classmethod def configured(cls, projections,", "= init.get_delaymap(projections, dt, conf_pre, conf_post) wmax = init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin =", "init.build_connectivity(projections, nPre, nPost, bw) if train_weight and not disable_training: w = torch.nn.Parameter(w) signs_pre", "w = init.build_connectivity(projections, nPre, nPost, bw) if train_weight and not disable_training: w =", "f'{WD}, dbe, deo ->bo', W, Xd, self.delaymap) def load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args,", "self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap is None: delaymap = torch.ones(1, *W.shape[-2:])", "@classmethod def configured(cls, projections, conf_pre, conf_post, batch_size, dt, stp=None, ltp=None, current=None, shared_weights=True, train_weight=True,", "*args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self): if not self.active: return signs", "else: W = self.W_signed WD = 'eo' if len(self.W.shape) == 2 else 'beo'", "return ret def reset(self, keep_values=False): if self.active: self.align_signs() if self.shortterm is not None:", "W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap is None: delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap',", "wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections return ret def reset(self,", "batch_size, dt, stp=None, ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs): active = len(projections[0]) >", "self.current is not None: output = self.current(output) return output def internal_forward(self, WD, W,", "Xd: (delay, batch, pre) X: (batch, post) Vpost: (batch, post) Output: Current (batch,", "def configured(cls, projections, conf_pre, conf_post, batch_size, dt, stp=None, ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False,", "is None else init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt, conf_pre, conf_post) wmax = init.expand_to_synapses(projections,", "long-term plasticity submodules Input: Delayed presynaptic spikes; postsynaptic spikes; postsyn voltage Output: Synaptic", "ltp = None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm = stp self.longterm = ltp", "align_signs(self): if not self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed =", "persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False) if ltp is", "== -1] self.W_signed[signs == 0] = self.W[signs == 0] self.W_signed[signs == 1] =", "return ret nPre = init.get_N(conf_pre) nPost = nPre if conf_post is None else", "self.W_signed[signs == 0] = self.W[signs == 0] self.W_signed[signs == 1] = torch.abs(self.W)[signs ==", "-1] = -torch.abs(self.W)[signs == -1] self.W_signed[signs == 0] = self.W[signs == 0] self.W_signed[signs", "wmin=None, wmax=None, current=None, stp=None, ltp=None, STDP_frac=None): super().__init__() self.active = W is not None", "= init.get_N(conf_pre) nPost = nPre if conf_post is None else init.get_N(conf_post) delaymap =", "torch.empty_like(W), persistent=False) if delaymap is None: delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False)", "= init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin = init.expand_to_synapses(projections, nPre, nPost, 'wmin') # Weights", "Wlong = self.longterm(Xd, X, Vpost) W = self.W_signed * (1-self.STDP_frac) + Wlong *", "# LTP if self.longterm is not None: Wlong = self.longterm(Xd, X, Vpost) W", "== 2 else 'beo' # STP if self.shortterm is not None: Xd =", "W, Xd, self.delaymap) def load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self):", "WD = 'eo' if len(self.W.shape) == 2 else 'beo' # STP if self.shortterm", "W is not None if not self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False)", "2 else 'beo' # STP if self.shortterm is not None: Xd = Xd", "self.reset() @classmethod def configured(cls, projections, conf_pre, conf_post, batch_size, dt, stp=None, ltp=None, current=None, shared_weights=True,", "persistent=False) if delaymap is None: delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre',", "else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm = stp self.longterm = ltp self.current = current", "Vpost: (batch, post) Output: Current (batch, post) ''' if not self.active: return torch.zeros_like(Vpost)", "torch.empty_like(self.W) self.W_signed[signs == -1] = -torch.abs(self.W)[signs == -1] self.W_signed[signs == 0] = self.W[signs", "batch, pre) X: (batch, post) Vpost: (batch, post) Output: Current (batch, post) '''", "if self.longterm is not None: self.longterm.reset(self, keep_values) if self.current is not None: self.current.reset(keep_values)", "(delay, batch, pre) X: (batch, post) Vpost: (batch, post) Output: Current (batch, post)", "**kwargs) self.align_signs() def align_signs(self): if not self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with", "self.shortterm.reset(keep_values) if self.longterm is not None: self.longterm.reset(self, keep_values) if self.current is not None:", "None: self.longterm.reset(self, keep_values) if self.current is not None: self.current.reset(keep_values) def forward(self, Xd, X=None,", "init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt, conf_pre, conf_post) wmax = init.expand_to_synapses(projections, nPre, nPost, 'wmax')", "None, None) ret.projections = projections return ret nPre = init.get_N(conf_pre) nPost = nPre", "Integrate output = self.internal_forward(WD, W, Xd) # Current filter if self.current is not", "self.current is not None: self.current.reset(keep_values) def forward(self, Xd, X=None, Vpost=None): ''' Xd: (delay,", "projections, nPre, nPost, 'STDP_frac') else: STDP_frac = None ret = cls(w, signs_pre, delaymap=delaymap,", "current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections return ret def reset(self, keep_values=False): if", "signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False) if ltp is not None:", "'beo' # STP if self.shortterm is not None: Xd = Xd * (self.shortterm(Xd)+1)", "= len(projections[0]) > 0 if not active: ret = cls(None, None, None) ret.projections", "# Current filter if self.current is not None: output = self.current(output) return output", "active = len(projections[0]) > 0 if not active: ret = cls(None, None, None)", "None: Wlong = self.longterm(Xd, X, Vpost) W = self.W_signed * (1-self.STDP_frac) + Wlong", "cantata import init import cantata.elements as ce class Synapse(ce.Module): ''' Synapse with optional", "if conf_post is None else init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt, conf_pre, conf_post) wmax", "0): ltp = None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm = stp self.longterm =", "STDP_frac = None ret = cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp,", "self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap is None: delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap,", "keep_values) if self.current is not None: self.current.reset(keep_values) def forward(self, Xd, X=None, Vpost=None): '''", "self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self): if not self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) #", "0 if not active: ret = cls(None, None, None) ret.projections = projections return", "projections return ret nPre = init.get_N(conf_pre) nPost = nPre if conf_post is None", "# Integrate output = self.internal_forward(WD, W, Xd) # Current filter if self.current is", "cantata.elements as ce class Synapse(ce.Module): ''' Synapse with optional current, short- and long-term", "current=None, stp=None, ltp=None, STDP_frac=None): super().__init__() self.active = W is not None if not", "if shared_weights else batch_size w = init.build_connectivity(projections, nPre, nPost, bw) if train_weight and", "Xd) # Current filter if self.current is not None: output = self.current(output) return", "delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False)", "torch.any(STDP_frac > 0): ltp = None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm = stp", "STDP_frac=None): super().__init__() self.active = W is not None if not self.active: return self.register_parabuf('W',", "if self.current is not None: output = self.current(output) return output def internal_forward(self, WD,", "STDP_frac = init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac') else: STDP_frac = None ret =", "len(projections[0]) > 0 if not active: ret = cls(None, None, None) ret.projections =", "None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm = stp self.longterm = ltp self.current =", "persistent=False) if ltp is not None: if not torch.any(STDP_frac > 0): ltp =", "= self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs == -1] = -torch.abs(self.W)[signs", "Delayed presynaptic spikes; postsynaptic spikes; postsyn voltage Output: Synaptic currents ''' def __init__(self,", "nPost = nPre if conf_post is None else init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt,", "else batch_size w = init.build_connectivity(projections, nPre, nPost, bw) if train_weight and not disable_training:", "# STP if self.shortterm is not None: Xd = Xd * (self.shortterm(Xd)+1) #", "if self.longterm is not None: Wlong = self.longterm(Xd, X, Vpost) W = self.W_signed", "bw) if train_weight and not disable_training: w = torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8)", "if ltp is not None: STDP_frac = init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac') else:", "== 0] self.W_signed[signs == 1] = torch.abs(self.W)[signs == 1] def weight(self): return torch.abs(self.W)", "presynaptic spikes; postsynaptic spikes; postsyn voltage Output: Synaptic currents ''' def __init__(self, W,", "Wlong * self.STDP_frac WD = 'beo' else: W = self.W_signed WD = 'eo'", "init import cantata.elements as ce class Synapse(ce.Module): ''' Synapse with optional current, short-", "None if not self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap is", "post) Output: Current (batch, post) ''' if not self.active: return torch.zeros_like(Vpost) # LTP", "super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self): if not self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W)", "torch from cantata import init import cantata.elements as ce class Synapse(ce.Module): ''' Synapse", "len(self.W.shape) == 2 else 'beo' # STP if self.shortterm is not None: Xd", "None: self.current.reset(keep_values) def forward(self, Xd, X=None, Vpost=None): ''' Xd: (delay, batch, pre) X:", "= self.current(output) return output def internal_forward(self, WD, W, Xd): return torch.einsum( f'{WD}, dbe,", "return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs == -1]", "= current self.reset() @classmethod def configured(cls, projections, conf_pre, conf_post, batch_size, dt, stp=None, ltp=None,", "torch.zeros_like(Vpost) # LTP if self.longterm is not None: Wlong = self.longterm(Xd, X, Vpost)", "plasticity submodules Input: Delayed presynaptic spikes; postsynaptic spikes; postsyn voltage Output: Synaptic currents", "Xd, X=None, Vpost=None): ''' Xd: (delay, batch, pre) X: (batch, post) Vpost: (batch,", "''' if not self.active: return torch.zeros_like(Vpost) # LTP if self.longterm is not None:", "not disable_training: w = torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is not", "stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections return ret def reset(self, keep_values=False): if self.active:", "internal_forward(self, WD, W, Xd): return torch.einsum( f'{WD}, dbe, deo ->bo', W, Xd, self.delaymap)", "self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False) if", "delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections return ret def", "is not None: self.longterm.reset(self, keep_values) if self.current is not None: self.current.reset(keep_values) def forward(self,", "= self.longterm(Xd, X, Vpost) W = self.W_signed * (1-self.STDP_frac) + Wlong * self.STDP_frac", "ret = cls(None, None, None) ret.projections = projections return ret nPre = init.get_N(conf_pre)", "-1] self.W_signed[signs == 0] = self.W[signs == 0] self.W_signed[signs == 1] = torch.abs(self.W)[signs", "(1-self.STDP_frac) + Wlong * self.STDP_frac WD = 'beo' else: W = self.W_signed WD", "current self.reset() @classmethod def configured(cls, projections, conf_pre, conf_post, batch_size, dt, stp=None, ltp=None, current=None,", "Current (batch, post) ''' if not self.active: return torch.zeros_like(Vpost) # LTP if self.longterm", "output = self.internal_forward(WD, W, Xd) # Current filter if self.current is not None:", "= self.internal_forward(WD, W, Xd) # Current filter if self.current is not None: output", "def forward(self, Xd, X=None, Vpost=None): ''' Xd: (delay, batch, pre) X: (batch, post)", "= -torch.abs(self.W)[signs == -1] self.W_signed[signs == 0] = self.W[signs == 0] self.W_signed[signs ==", "return output def internal_forward(self, WD, W, Xd): return torch.einsum( f'{WD}, dbe, deo ->bo',", "None: output = self.current(output) return output def internal_forward(self, WD, W, Xd): return torch.einsum(", "self.W_signed WD = 'eo' if len(self.W.shape) == 2 else 'beo' # STP if", "if not torch.any(STDP_frac > 0): ltp = None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm", "self.align_signs() if self.shortterm is not None: self.shortterm.reset(keep_values) if self.longterm is not None: self.longterm.reset(self,", "self.longterm.reset(self, keep_values) if self.current is not None: self.current.reset(keep_values) def forward(self, Xd, X=None, Vpost=None):", "if self.active: self.align_signs() if self.shortterm is not None: self.shortterm.reset(keep_values) if self.longterm is not", "X: (batch, post) Vpost: (batch, post) Output: Current (batch, post) ''' if not", "not self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs", "and not disable_training: w = torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is", "signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is not None: STDP_frac = init.expand_to_synapses( projections,", "init.get_delaymap(projections, dt, conf_pre, conf_post) wmax = init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin = init.expand_to_synapses(projections,", "post) Vpost: (batch, post) Output: Current (batch, post) ''' if not self.active: return", "if delaymap is None: delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre,", "def load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self): if not self.active:", "wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections return ret def reset(self, keep_values=False):", "None: Xd = Xd * (self.shortterm(Xd)+1) # dbe # Integrate output = self.internal_forward(WD,", "nPre, nPost, bw) if train_weight and not disable_training: w = torch.nn.Parameter(w) signs_pre =", "output def internal_forward(self, WD, W, Xd): return torch.einsum( f'{WD}, dbe, deo ->bo', W,", "= torch.empty_like(self.W) self.W_signed[signs == -1] = -torch.abs(self.W)[signs == -1] self.W_signed[signs == 0] =", "stp self.longterm = ltp self.current = current self.reset() @classmethod def configured(cls, projections, conf_pre,", "self.current.reset(keep_values) def forward(self, Xd, X=None, Vpost=None): ''' Xd: (delay, batch, pre) X: (batch,", "**kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self): if not self.active: return signs =", "STP if self.shortterm is not None: Xd = Xd * (self.shortterm(Xd)+1) # dbe", "wmax = init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin = init.expand_to_synapses(projections, nPre, nPost, 'wmin') #", "torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax,", "conf_pre, conf_post, batch_size, dt, stp=None, ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs): active =", "pre) X: (batch, post) Vpost: (batch, post) Output: Current (batch, post) ''' if", "conf_post is None else init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt, conf_pre, conf_post) wmax =", "postsynaptic spikes; postsyn voltage Output: Synaptic currents ''' def __init__(self, W, signs_pre, delaymap=None,", "self.active = W is not None if not self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed',", "delaymap=None, wmin=None, wmax=None, current=None, stp=None, ltp=None, STDP_frac=None): super().__init__() self.active = W is not", "batch_size w = init.build_connectivity(projections, nPre, nPost, bw) if train_weight and not disable_training: w", "forward(self, Xd, X=None, Vpost=None): ''' Xd: (delay, batch, pre) X: (batch, post) Vpost:", "Vpost) W = self.W_signed * (1-self.STDP_frac) + Wlong * self.STDP_frac WD = 'beo'", "W = self.W_signed WD = 'eo' if len(self.W.shape) == 2 else 'beo' #", "* (self.shortterm(Xd)+1) # dbe # Integrate output = self.internal_forward(WD, W, Xd) # Current", "(batch, post) Vpost: (batch, post) Output: Current (batch, post) ''' if not self.active:", "Weights bw = 0 if shared_weights else batch_size w = init.build_connectivity(projections, nPre, nPost,", "self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap is None: delaymap =", "not None if not self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap", "# Weights bw = 0 if shared_weights else batch_size w = init.build_connectivity(projections, nPre,", "conf_pre, conf_post) wmax = init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin = init.expand_to_synapses(projections, nPre, nPost,", "Vpost=None): ''' Xd: (delay, batch, pre) X: (batch, post) Vpost: (batch, post) Output:", "configured(cls, projections, conf_pre, conf_post, batch_size, dt, stp=None, ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs):", "def __init__(self, W, signs_pre, delaymap=None, wmin=None, wmax=None, current=None, stp=None, ltp=None, STDP_frac=None): super().__init__() self.active", "self.longterm is not None: Wlong = self.longterm(Xd, X, Vpost) W = self.W_signed *", "if len(self.W.shape) == 2 else 'beo' # STP if self.shortterm is not None:", "= self.W_signed WD = 'eo' if len(self.W.shape) == 2 else 'beo' # STP", "spikes; postsynaptic spikes; postsyn voltage Output: Synaptic currents ''' def __init__(self, W, signs_pre,", "spikes; postsyn voltage Output: Synaptic currents ''' def __init__(self, W, signs_pre, delaymap=None, wmin=None,", "Xd * (self.shortterm(Xd)+1) # dbe # Integrate output = self.internal_forward(WD, W, Xd) #", "Synapse with optional current, short- and long-term plasticity submodules Input: Delayed presynaptic spikes;", "return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap is None: delaymap = torch.ones(1,", "wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False) if ltp is not None: if not torch.any(STDP_frac", "W, Xd) # Current filter if self.current is not None: output = self.current(output)", "def internal_forward(self, WD, W, Xd): return torch.einsum( f'{WD}, dbe, deo ->bo', W, Xd,", "nPost, bw) if train_weight and not disable_training: w = torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre,", "Xd = Xd * (self.shortterm(Xd)+1) # dbe # Integrate output = self.internal_forward(WD, W,", "voltage Output: Synaptic currents ''' def __init__(self, W, signs_pre, delaymap=None, wmin=None, wmax=None, current=None,", "W, Xd): return torch.einsum( f'{WD}, dbe, deo ->bo', W, Xd, self.delaymap) def load_state_dict(self,", "ltp self.current = current self.reset() @classmethod def configured(cls, projections, conf_pre, conf_post, batch_size, dt,", "Xd, self.delaymap) def load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self): if", "shared_weights else batch_size w = init.build_connectivity(projections, nPre, nPost, bw) if train_weight and not", "= self.W_signed * (1-self.STDP_frac) + Wlong * self.STDP_frac WD = 'beo' else: W", "None: if not torch.any(STDP_frac > 0): ltp = None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False)", "self.STDP_frac WD = 'beo' else: W = self.W_signed WD = 'eo' if len(self.W.shape)", "return torch.einsum( f'{WD}, dbe, deo ->bo', W, Xd, self.delaymap) def load_state_dict(self, *args, **kwargs):", "Input: Delayed presynaptic spikes; postsynaptic spikes; postsyn voltage Output: Synaptic currents ''' def", "persistent=False) self.register_buffer('wmax', wmax, persistent=False) if ltp is not None: if not torch.any(STDP_frac >", "self.W_signed * (1-self.STDP_frac) + Wlong * self.STDP_frac WD = 'beo' else: W =", "Output: Synaptic currents ''' def __init__(self, W, signs_pre, delaymap=None, wmin=None, wmax=None, current=None, stp=None,", "self.delaymap) def load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self): if not", "def reset(self, keep_values=False): if self.active: self.align_signs() if self.shortterm is not None: self.shortterm.reset(keep_values) if", "self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs ==", "init.get_N(conf_pre) nPost = nPre if conf_post is None else init.get_N(conf_post) delaymap = init.get_delaymap(projections,", "not None: self.shortterm.reset(keep_values) if self.longterm is not None: self.longterm.reset(self, keep_values) if self.current is", "W, signs_pre, delaymap=None, wmin=None, wmax=None, current=None, stp=None, ltp=None, STDP_frac=None): super().__init__() self.active = W", "nPre, nPost, 'wmin') # Weights bw = 0 if shared_weights else batch_size w", "torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is not None: STDP_frac = init.expand_to_synapses(", "is not None: output = self.current(output) return output def internal_forward(self, WD, W, Xd):", "submodules Input: Delayed presynaptic spikes; postsynaptic spikes; postsyn voltage Output: Synaptic currents '''", "dt, stp=None, ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs): active = len(projections[0]) > 0", "self.shortterm is not None: Xd = Xd * (self.shortterm(Xd)+1) # dbe # Integrate", "0 if shared_weights else batch_size w = init.build_connectivity(projections, nPre, nPost, bw) if train_weight", "signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs == -1] =", "ret def reset(self, keep_values=False): if self.active: self.align_signs() if self.shortterm is not None: self.shortterm.reset(keep_values)", "**kwargs): active = len(projections[0]) > 0 if not active: ret = cls(None, None,", "ltp is not None: STDP_frac = init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac') else: STDP_frac", "delaymap = init.get_delaymap(projections, dt, conf_pre, conf_post) wmax = init.expand_to_synapses(projections, nPre, nPost, 'wmax') wmin", "(self.shortterm(Xd)+1) # dbe # Integrate output = self.internal_forward(WD, W, Xd) # Current filter", "class Synapse(ce.Module): ''' Synapse with optional current, short- and long-term plasticity submodules Input:", "None ret = cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections", "__init__(self, W, signs_pre, delaymap=None, wmin=None, wmax=None, current=None, stp=None, ltp=None, STDP_frac=None): super().__init__() self.active =", "nPre, nPost, 'STDP_frac') else: STDP_frac = None ret = cls(w, signs_pre, delaymap=delaymap, wmin=wmin,", "filter if self.current is not None: output = self.current(output) return output def internal_forward(self,", "not None: Xd = Xd * (self.shortterm(Xd)+1) # dbe # Integrate output =", "WD, W, Xd): return torch.einsum( f'{WD}, dbe, deo ->bo', W, Xd, self.delaymap) def", "self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs == -1] = -torch.abs(self.W)[signs ==", "init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac') else: STDP_frac = None ret = cls(w, signs_pre,", "self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False) if ltp is not None: if not", "self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax', wmax, persistent=False) if ltp is not", "active: ret = cls(None, None, None) ret.projections = projections return ret nPre =", "train_weight=True, disable_training=False, **kwargs): active = len(projections[0]) > 0 if not active: ret =", "ltp=None, STDP_frac=None): super().__init__() self.active = W is not None if not self.active: return", "WD = 'beo' else: W = self.W_signed WD = 'eo' if len(self.W.shape) ==", "w = torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is not None: STDP_frac", "not self.active: return torch.zeros_like(Vpost) # LTP if self.longterm is not None: Wlong =", "ret.projections = projections return ret def reset(self, keep_values=False): if self.active: self.align_signs() if self.shortterm", "ret.projections = projections return ret nPre = init.get_N(conf_pre) nPost = nPre if conf_post", "self.current(output) return output def internal_forward(self, WD, W, Xd): return torch.einsum( f'{WD}, dbe, deo", "with torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs == -1] = -torch.abs(self.W)[signs == -1] self.W_signed[signs", "self.W_signed[signs == -1] = -torch.abs(self.W)[signs == -1] self.W_signed[signs == 0] = self.W[signs ==", "is not None if not self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if", "if not self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed = torch.empty_like(self.W)", "nPost, 'wmin') # Weights bw = 0 if shared_weights else batch_size w =", "not self.active: return self.register_parabuf('W', W) self.register_buffer('W_signed', torch.empty_like(W), persistent=False) if delaymap is None: delaymap", "optional current, short- and long-term plasticity submodules Input: Delayed presynaptic spikes; postsynaptic spikes;", "conf_post, batch_size, dt, stp=None, ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs): active = len(projections[0])", "# with torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs == -1] = -torch.abs(self.W)[signs == -1]", "def align_signs(self): if not self.active: return signs = self.signs_pre.unsqueeze(1).expand_as(self.W) # with torch.no_grad(): self.W_signed", "ce class Synapse(ce.Module): ''' Synapse with optional current, short- and long-term plasticity submodules", "self.longterm is not None: self.longterm.reset(self, keep_values) if self.current is not None: self.current.reset(keep_values) def", "current, short- and long-term plasticity submodules Input: Delayed presynaptic spikes; postsynaptic spikes; postsyn", "self.active: return torch.zeros_like(Vpost) # LTP if self.longterm is not None: Wlong = self.longterm(Xd,", "STDP_frac=STDP_frac) ret.projections = projections return ret def reset(self, keep_values=False): if self.active: self.align_signs() if", "STDP_frac, persistent=False) self.shortterm = stp self.longterm = ltp self.current = current self.reset() @classmethod", "= init.build_connectivity(projections, nPre, nPost, bw) if train_weight and not disable_training: w = torch.nn.Parameter(w)", "bw = 0 if shared_weights else batch_size w = init.build_connectivity(projections, nPre, nPost, bw)", "is not None: Wlong = self.longterm(Xd, X, Vpost) W = self.W_signed * (1-self.STDP_frac)", "torch.einsum( f'{WD}, dbe, deo ->bo', W, Xd, self.delaymap) def load_state_dict(self, *args, **kwargs): super(Synapse,", "'sign').to(torch.int8) if ltp is not None: STDP_frac = init.expand_to_synapses( projections, nPre, nPost, 'STDP_frac')", "self.active: self.align_signs() if self.shortterm is not None: self.shortterm.reset(keep_values) if self.longterm is not None:", "init.expand_to_synapses(projections, nPre, nPost, 'wmin') # Weights bw = 0 if shared_weights else batch_size", "= Xd * (self.shortterm(Xd)+1) # dbe # Integrate output = self.internal_forward(WD, W, Xd)", "0] = self.W[signs == 0] self.W_signed[signs == 1] = torch.abs(self.W)[signs == 1] def", "from cantata import init import cantata.elements as ce class Synapse(ce.Module): ''' Synapse with", "disable_training=False, **kwargs): active = len(projections[0]) > 0 if not active: ret = cls(None,", "= init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is not None: STDP_frac = init.expand_to_synapses( projections, nPre,", "load_state_dict(self, *args, **kwargs): super(Synapse, self).load_state_dict(*args, **kwargs) self.align_signs() def align_signs(self): if not self.active: return", "is not None: self.current.reset(keep_values) def forward(self, Xd, X=None, Vpost=None): ''' Xd: (delay, batch,", "torch.no_grad(): self.W_signed = torch.empty_like(self.W) self.W_signed[signs == -1] = -torch.abs(self.W)[signs == -1] self.W_signed[signs ==", "ret nPre = init.get_N(conf_pre) nPost = nPre if conf_post is None else init.get_N(conf_post)", "dbe # Integrate output = self.internal_forward(WD, W, Xd) # Current filter if self.current", "with optional current, short- and long-term plasticity submodules Input: Delayed presynaptic spikes; postsynaptic", "= init.expand_to_synapses(projections, nPre, nPost, 'wmin') # Weights bw = 0 if shared_weights else", "not None: output = self.current(output) return output def internal_forward(self, WD, W, Xd): return", "= 'eo' if len(self.W.shape) == 2 else 'beo' # STP if self.shortterm is", "return torch.zeros_like(Vpost) # LTP if self.longterm is not None: Wlong = self.longterm(Xd, X,", "signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac) ret.projections = projections return ret", "W = self.W_signed * (1-self.STDP_frac) + Wlong * self.STDP_frac WD = 'beo' else:", "* (1-self.STDP_frac) + Wlong * self.STDP_frac WD = 'beo' else: W = self.W_signed", "self.longterm = ltp self.current = current self.reset() @classmethod def configured(cls, projections, conf_pre, conf_post,", "Output: Current (batch, post) ''' if not self.active: return torch.zeros_like(Vpost) # LTP if", "not torch.any(STDP_frac > 0): ltp = None else: self.register_buffer('STDP_frac', STDP_frac, persistent=False) self.shortterm =", "nPre if conf_post is None else init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt, conf_pre, conf_post)", "self.shortterm is not None: self.shortterm.reset(keep_values) if self.longterm is not None: self.longterm.reset(self, keep_values) if", "self.W[signs == 0] self.W_signed[signs == 1] = torch.abs(self.W)[signs == 1] def weight(self): return", "post) ''' if not self.active: return torch.zeros_like(Vpost) # LTP if self.longterm is not", "if self.shortterm is not None: Xd = Xd * (self.shortterm(Xd)+1) # dbe #", "if train_weight and not disable_training: w = torch.nn.Parameter(w) signs_pre = init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if", "''' Synapse with optional current, short- and long-term plasticity submodules Input: Delayed presynaptic", "Xd): return torch.einsum( f'{WD}, dbe, deo ->bo', W, Xd, self.delaymap) def load_state_dict(self, *args,", "X, Vpost) W = self.W_signed * (1-self.STDP_frac) + Wlong * self.STDP_frac WD =", "currents ''' def __init__(self, W, signs_pre, delaymap=None, wmin=None, wmax=None, current=None, stp=None, ltp=None, STDP_frac=None):", "is None: delaymap = torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin',", "= None ret = cls(w, signs_pre, delaymap=delaymap, wmin=wmin, wmax=wmax, current=current, stp=stp, ltp=ltp, STDP_frac=STDP_frac)", "else 'beo' # STP if self.shortterm is not None: Xd = Xd *", "= cls(None, None, None) ret.projections = projections return ret nPre = init.get_N(conf_pre) nPost", "init.expand_to_neurons(conf_pre, 'sign').to(torch.int8) if ltp is not None: STDP_frac = init.expand_to_synapses( projections, nPre, nPost,", "if self.shortterm is not None: self.shortterm.reset(keep_values) if self.longterm is not None: self.longterm.reset(self, keep_values)", "else init.get_N(conf_post) delaymap = init.get_delaymap(projections, dt, conf_pre, conf_post) wmax = init.expand_to_synapses(projections, nPre, nPost,", "import cantata.elements as ce class Synapse(ce.Module): ''' Synapse with optional current, short- and", "stp=None, ltp=None, STDP_frac=None): super().__init__() self.active = W is not None if not self.active:", "not None: self.current.reset(keep_values) def forward(self, Xd, X=None, Vpost=None): ''' Xd: (delay, batch, pre)", "LTP if self.longterm is not None: Wlong = self.longterm(Xd, X, Vpost) W =", "signs_pre, delaymap=None, wmin=None, wmax=None, current=None, stp=None, ltp=None, STDP_frac=None): super().__init__() self.active = W is", "and long-term plasticity submodules Input: Delayed presynaptic spikes; postsynaptic spikes; postsyn voltage Output:", "reset(self, keep_values=False): if self.active: self.align_signs() if self.shortterm is not None: self.shortterm.reset(keep_values) if self.longterm", "= torch.ones(1, *W.shape[-2:]) self.register_buffer('delaymap', delaymap, persistent=False) self.register_buffer('signs_pre', signs_pre, persistent=False) self.register_buffer('wmin', wmin, persistent=False) self.register_buffer('wmax',", "is not None: self.shortterm.reset(keep_values) if self.longterm is not None: self.longterm.reset(self, keep_values) if self.current", "not None: if not torch.any(STDP_frac > 0): ltp = None else: self.register_buffer('STDP_frac', STDP_frac,", "is not None: if not torch.any(STDP_frac > 0): ltp = None else: self.register_buffer('STDP_frac',", "self.longterm(Xd, X, Vpost) W = self.W_signed * (1-self.STDP_frac) + Wlong * self.STDP_frac WD", "= ltp self.current = current self.reset() @classmethod def configured(cls, projections, conf_pre, conf_post, batch_size,", "ltp=None, current=None, shared_weights=True, train_weight=True, disable_training=False, **kwargs): active = len(projections[0]) > 0 if not", "'beo' else: W = self.W_signed WD = 'eo' if len(self.W.shape) == 2 else", "None: self.shortterm.reset(keep_values) if self.longterm is not None: self.longterm.reset(self, keep_values) if self.current is not" ]
[ "[ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/',", "'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, }, ], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ],", "settings.configure(**SETTINGS) # app registry setup django.setup() # test runner test_runner = TestRunner(verbosity=1) failures", "import sys import django from django.conf import settings from django.test.runner import DiscoverRunner as", "'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),), } def", "'django.db.backends.sqlite3', 'NAME': 'dev.db', }, # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste',", "'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),),", "setup django.setup() # test runner test_runner = TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste']) if failures:", "'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ],", "} }, 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {", "}, }, ], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ),", "not settings.configured: settings.configure(**SETTINGS) # app registry setup django.setup() # test runner test_runner =", "{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, }, ], 'INSTALLED_APPS': [", "SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', }, #", "= { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', }, # 'default':", "settings if not settings.configured: settings.configure(**SETTINGS) # app registry setup django.setup() # test runner", "import DiscoverRunner as TestRunner SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3',", "from django.conf import settings from django.test.runner import DiscoverRunner as TestRunner SETTINGS = {", "# 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste', # 'USER': 'root', #", "'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE':", "], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/',", "'en', 'LANGUAGES': (('en', 'English'),), } def runtests(*test_args): # Setup settings if not settings.configured:", "# test runner test_runner = TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste']) if failures: sys.exit(failures) if", "test runner test_runner = TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste']) if failures: sys.exit(failures) if __name__", "'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES':", "sys import django from django.conf import settings from django.test.runner import DiscoverRunner as TestRunner", "TestRunner SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', },", "'', # } }, 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True,", "'dpaste.context_processors.dpaste_globals', ], }, }, ], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': (", "'USER': 'root', # 'PASSWORD': '', # } }, 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',", "'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste', # 'USER': 'root', # 'PASSWORD': '', # }", "{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', }, # 'default': { # 'ENGINE': 'django.db.backends.mysql', #", "def runtests(*test_args): # Setup settings if not settings.configured: settings.configure(**SETTINGS) # app registry setup", "import django from django.conf import settings from django.test.runner import DiscoverRunner as TestRunner SETTINGS", "'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, }, ], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES':", "# Setup settings if not settings.configured: settings.configure(**SETTINGS) # app registry setup django.setup() #", "}, 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':", "runtests(*test_args): # Setup settings if not settings.configured: settings.configure(**SETTINGS) # app registry setup django.setup()", "), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),), }", "'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n',", "as TestRunner SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db',", "{ 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', }, # 'default': {", "'django.db.backends.mysql', # 'NAME': 'dpaste', # 'USER': 'root', # 'PASSWORD': '', # } },", "'LANGUAGES': (('en', 'English'),), } def runtests(*test_args): # Setup settings if not settings.configured: settings.configure(**SETTINGS)", "'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),), } def runtests(*test_args): # Setup settings if", "}, # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste', # 'USER': 'root',", "} def runtests(*test_args): # Setup settings if not settings.configured: settings.configure(**SETTINGS) # app registry", "# 'PASSWORD': '', # } }, 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [],", "'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),), } def runtests(*test_args): # Setup settings if not", "# 'NAME': 'dpaste', # 'USER': 'root', # 'PASSWORD': '', # } }, 'TEMPLATES':", "DiscoverRunner as TestRunner SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':", "from django.test.runner import DiscoverRunner as TestRunner SETTINGS = { 'DATABASES': { 'default': {", "}, ], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT':", "'PASSWORD': '', # } }, 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS':", "import settings from django.test.runner import DiscoverRunner as TestRunner SETTINGS = { 'DATABASES': {", "django from django.conf import settings from django.test.runner import DiscoverRunner as TestRunner SETTINGS =", "django.test.runner import DiscoverRunner as TestRunner SETTINGS = { 'DATABASES': { 'default': { 'ENGINE':", "( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en',", "'/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),), } def runtests(*test_args):", "settings from django.test.runner import DiscoverRunner as TestRunner SETTINGS = { 'DATABASES': { 'default':", "'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', }, # 'default': { # 'ENGINE': 'django.db.backends.mysql',", "(('en', 'English'),), } def runtests(*test_args): # Setup settings if not settings.configured: settings.configure(**SETTINGS) #", "'dev.db', }, # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste', # 'USER':", "django.setup() # test runner test_runner = TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste']) if failures: sys.exit(failures)", "python import sys import django from django.conf import settings from django.test.runner import DiscoverRunner", "[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',", "'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),), } def runtests(*test_args): # Setup settings", "'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, }, ], 'INSTALLED_APPS': [ 'django.contrib.sessions',", "'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL':", "[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, }, ], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles',", "if not settings.configured: settings.configure(**SETTINGS) # app registry setup django.setup() # test runner test_runner", "'dpaste', # 'USER': 'root', # 'PASSWORD': '', # } }, 'TEMPLATES': [ {", "= TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste']) if failures: sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])", "'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),), } def runtests(*test_args): #", "app registry setup django.setup() # test runner test_runner = TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste'])", "{ # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste', # 'USER': 'root', # 'PASSWORD': '',", "Setup settings if not settings.configured: settings.configure(**SETTINGS) # app registry setup django.setup() # test", "'NAME': 'dpaste', # 'USER': 'root', # 'PASSWORD': '', # } }, 'TEMPLATES': [", "runner test_runner = TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste']) if failures: sys.exit(failures) if __name__ ==", "'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls',", "# } }, 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS':", "'root', # 'PASSWORD': '', # } }, 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':", "'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals',", "'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste', # 'USER': 'root', # 'PASSWORD':", "# 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste', # 'USER': 'root', # 'PASSWORD': '', #", "[], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], },", "# app registry setup django.setup() # test runner test_runner = TestRunner(verbosity=1) failures =", "# 'USER': 'root', # 'PASSWORD': '', # } }, 'TEMPLATES': [ { 'BACKEND':", "'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, }, ], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste',", "'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', }, # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME':", "], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en',", "#!/usr/bin/env python import sys import django from django.conf import settings from django.test.runner import", "'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [", "settings.configured: settings.configure(**SETTINGS) # app registry setup django.setup() # test runner test_runner = TestRunner(verbosity=1)", "'English'),), } def runtests(*test_args): # Setup settings if not settings.configured: settings.configure(**SETTINGS) # app", "{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',", "'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware', ), 'STATIC_ROOT': '/tmp/dpaste_test_static/', 'STATIC_URL': '/static/', 'ROOT_URLCONF':", "'/static/', 'ROOT_URLCONF': 'dpaste.urls', 'LANGUAGE_CODE': 'en', 'LANGUAGES': (('en', 'English'),), } def runtests(*test_args): # Setup", "test_runner = TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste']) if failures: sys.exit(failures) if __name__ == '__main__':", "registry setup django.setup() # test runner test_runner = TestRunner(verbosity=1) failures = test_runner.run_tests(['dpaste']) if", "True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, }, ],", "django.conf import settings from django.test.runner import DiscoverRunner as TestRunner SETTINGS = { 'DATABASES':", "{ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', }, # 'default': { # 'ENGINE':", "], }, }, ], 'INSTALLED_APPS': [ 'django.contrib.sessions', 'django.contrib.staticfiles', 'dpaste', ], 'MIDDLEWARE_CLASSES': ( 'django.contrib.sessions.middleware.SessionMiddleware',", "'NAME': 'dev.db', }, # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'dpaste', #", "'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', }, # 'default': { #", "'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, },", "'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'dpaste.context_processors.dpaste_globals', ], }, }, ], 'INSTALLED_APPS':" ]
[ "that if you don't first turn the LED on this will error out.", "self.led_dim.start(brightness) except: raise LedError(\"Error while turning the LED on.\") def off(self): \"\"\" Turns", "via a pin given. See the documentation for an example of how to", "you don't first turn the LED on this will error out. \"\"\" if", "except: raise LedError(\"Error during the initiation of the LED class.\") def on(self, brightness=100):", "and setting the PWM up so that the LED can be dimmed. \"\"\"", "during the initiation of the LED class.\") def on(self, brightness=100): \"\"\" Turns the", "making sure it is off, and setting the PWM up so that the", "in mind, that if you don't first turn the LED on this will", "raise LedError(\"Error while turning the LED on.\") def off(self): \"\"\" Turns the defined", "mind, that if you don't first turn the LED on this will error", "self.led_dim = GPIO.PWM(self.pin, 500) except: raise LedError(\"Error during the initiation of the LED", "while turning the LED off.\") def dim(self, brightness): \"\"\" Dims the definied LED.", "\"\"\" This initates the LED on the given pin, setting it into the", "LED off. \"\"\" try: self.led_dim.stop() except: raise LedError(\"Error while turning the LED off.\")", "100 else: pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while dimming the LED. Make", "GPIO.PWM(self.pin, 500) except: raise LedError(\"Error during the initiation of the LED class.\") def", "off, and setting the PWM up so that the LED can be dimmed.", "\"\"\" This is a class used to control LED's directly connected to the", "GPIO from .light_errors import LedError class Led: \"\"\" This is a class used", "except: raise LedError(\"Error while dimming the LED. Make sure you have turned the", "< 0: brightness = 0 elif brightness > 100: brightness = 100 else:", "defined LED on, the brightness is set by default to 100%. \"\"\" try:", "by default to 100%. \"\"\" try: self.led_dim.start(brightness) except: raise LedError(\"Error while turning the", "set by default to 100%. \"\"\" try: self.led_dim.start(brightness) except: raise LedError(\"Error while turning", "initiation of the LED class.\") def on(self, brightness=100): \"\"\" Turns the defined LED", "initates the LED on the given pin, setting it into the output mode,", "raise LedError(\"Error while turning the LED off.\") def dim(self, brightness): \"\"\" Dims the", "pin, setting it into the output mode, making sure it is off, and", "sure it is off, and setting the PWM up so that the LED", "that the LED can be dimmed. \"\"\" try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin,", "turning the LED on.\") def off(self): \"\"\" Turns the defined LED off. \"\"\"", "class.\") def on(self, brightness=100): \"\"\" Turns the defined LED on, the brightness is", "LED can be dimmed. \"\"\" try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin,", "the LED can be dimmed. \"\"\" try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT)", "defined LED off. \"\"\" try: self.led_dim.stop() except: raise LedError(\"Error while turning the LED", "to control LED's directly connected to the GPIO via a pin given. See", "first turn the LED on this will error out. \"\"\" if brightness <", "\"\"\" if brightness < 0: brightness = 0 elif brightness > 100: brightness", "setting the PWM up so that the LED can be dimmed. \"\"\" try:", "100: brightness = 100 else: pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while dimming", "\"\"\" Dims the definied LED. Keep in mind, that if you don't first", "try: self.led_dim.start(brightness) except: raise LedError(\"Error while turning the LED on.\") def off(self): \"\"\"", "turning the LED off.\") def dim(self, brightness): \"\"\" Dims the definied LED. Keep", "can be dimmed. \"\"\" try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW)", "error out. \"\"\" if brightness < 0: brightness = 0 elif brightness >", "control LED's directly connected to the GPIO via a pin given. See the", "LedError(\"Error while dimming the LED. Make sure you have turned the LED on.\")", "a pin given. See the documentation for an example of how to wire", "output mode, making sure it is off, and setting the PWM up so", "the defined LED on, the brightness is set by default to 100%. \"\"\"", "on(self, brightness=100): \"\"\" Turns the defined LED on, the brightness is set by", "import RPi.GPIO as GPIO from .light_errors import LedError class Led: \"\"\" This is", "Turns the defined LED on, the brightness is set by default to 100%.", "default to 100%. \"\"\" try: self.led_dim.start(brightness) except: raise LedError(\"Error while turning the LED", "Keep in mind, that if you don't first turn the LED on this", "definied LED. Keep in mind, that if you don't first turn the LED", "pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while dimming the LED. Make sure you", "= 0 elif brightness > 100: brightness = 100 else: pass try: self.led_dim.ChangeDutyCycle(brightness)", "This is a class used to control LED's directly connected to the GPIO", "GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500) except: raise LedError(\"Error during the initiation", "LED off.\") def dim(self, brightness): \"\"\" Dims the definied LED. Keep in mind,", "__init__(self, pin): \"\"\" This initates the LED on the given pin, setting it", "int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500) except: raise LedError(\"Error", "Led: \"\"\" This is a class used to control LED's directly connected to", "LED on the given pin, setting it into the output mode, making sure", "elif brightness > 100: brightness = 100 else: pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise", "LedError(\"Error while turning the LED off.\") def dim(self, brightness): \"\"\" Dims the definied", "LedError class Led: \"\"\" This is a class used to control LED's directly", "self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while dimming the LED. Make sure you have turned", "raise LedError(\"Error during the initiation of the LED class.\") def on(self, brightness=100): \"\"\"", "GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500) except: raise LedError(\"Error during the initiation of", "brightness): \"\"\" Dims the definied LED. Keep in mind, that if you don't", "from .light_errors import LedError class Led: \"\"\" This is a class used to", "0: brightness = 0 elif brightness > 100: brightness = 100 else: pass", "don't first turn the LED on this will error out. \"\"\" if brightness", "it is off, and setting the PWM up so that the LED can", "> 100: brightness = 100 else: pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while", "to wire the LED. \"\"\" def __init__(self, pin): \"\"\" This initates the LED", "given. See the documentation for an example of how to wire the LED.", "GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500) except: raise LedError(\"Error during", "LED class.\") def on(self, brightness=100): \"\"\" Turns the defined LED on, the brightness", "on, the brightness is set by default to 100%. \"\"\" try: self.led_dim.start(brightness) except:", "the LED on this will error out. \"\"\" if brightness < 0: brightness", "\"\"\" try: self.led_dim.start(brightness) except: raise LedError(\"Error while turning the LED on.\") def off(self):", "connected to the GPIO via a pin given. See the documentation for an", "an example of how to wire the LED. \"\"\" def __init__(self, pin): \"\"\"", "off(self): \"\"\" Turns the defined LED off. \"\"\" try: self.led_dim.stop() except: raise LedError(\"Error", "0 elif brightness > 100: brightness = 100 else: pass try: self.led_dim.ChangeDutyCycle(brightness) except:", "on the given pin, setting it into the output mode, making sure it", "GPIO via a pin given. See the documentation for an example of how", "100%. \"\"\" try: self.led_dim.start(brightness) except: raise LedError(\"Error while turning the LED on.\") def", "on.\") def off(self): \"\"\" Turns the defined LED off. \"\"\" try: self.led_dim.stop() except:", "self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500) except:", "brightness = 100 else: pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while dimming the", "GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500) except: raise LedError(\"Error during the", "\"\"\" try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin,", "def __init__(self, pin): \"\"\" This initates the LED on the given pin, setting", "GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500) except: raise LedError(\"Error during the initiation of the", "Turns the defined LED off. \"\"\" try: self.led_dim.stop() except: raise LedError(\"Error while turning", "as GPIO from .light_errors import LedError class Led: \"\"\" This is a class", "example of how to wire the LED. \"\"\" def __init__(self, pin): \"\"\" This", ".light_errors import LedError class Led: \"\"\" This is a class used to control", "while turning the LED on.\") def off(self): \"\"\" Turns the defined LED off.", "= 100 else: pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while dimming the LED.", "given pin, setting it into the output mode, making sure it is off,", "LedError(\"Error during the initiation of the LED class.\") def on(self, brightness=100): \"\"\" Turns", "\"\"\" try: self.led_dim.stop() except: raise LedError(\"Error while turning the LED off.\") def dim(self,", "to 100%. \"\"\" try: self.led_dim.start(brightness) except: raise LedError(\"Error while turning the LED on.\")", "the PWM up so that the LED can be dimmed. \"\"\" try: self.pin", "= int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500) except: raise", "if you don't first turn the LED on this will error out. \"\"\"", "the LED on.\") def off(self): \"\"\" Turns the defined LED off. \"\"\" try:", "the definied LED. Keep in mind, that if you don't first turn the", "import LedError class Led: \"\"\" This is a class used to control LED's", "will error out. \"\"\" if brightness < 0: brightness = 0 elif brightness", "the LED on the given pin, setting it into the output mode, making", "LED on, the brightness is set by default to 100%. \"\"\" try: self.led_dim.start(brightness)", "500) except: raise LedError(\"Error during the initiation of the LED class.\") def on(self,", "brightness=100): \"\"\" Turns the defined LED on, the brightness is set by default", "used to control LED's directly connected to the GPIO via a pin given.", "the LED class.\") def on(self, brightness=100): \"\"\" Turns the defined LED on, the", "into the output mode, making sure it is off, and setting the PWM", "raise LedError(\"Error while dimming the LED. Make sure you have turned the LED", "a class used to control LED's directly connected to the GPIO via a", "this will error out. \"\"\" if brightness < 0: brightness = 0 elif", "documentation for an example of how to wire the LED. \"\"\" def __init__(self,", "LED on.\") def off(self): \"\"\" Turns the defined LED off. \"\"\" try: self.led_dim.stop()", "def off(self): \"\"\" Turns the defined LED off. \"\"\" try: self.led_dim.stop() except: raise", "it into the output mode, making sure it is off, and setting the", "the defined LED off. \"\"\" try: self.led_dim.stop() except: raise LedError(\"Error while turning the", "try: self.led_dim.stop() except: raise LedError(\"Error while turning the LED off.\") def dim(self, brightness):", "pin given. See the documentation for an example of how to wire the", "else: pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while dimming the LED. Make sure", "to the GPIO via a pin given. See the documentation for an example", "LedError(\"Error while turning the LED on.\") def off(self): \"\"\" Turns the defined LED", "LED. Keep in mind, that if you don't first turn the LED on", "wire the LED. \"\"\" def __init__(self, pin): \"\"\" This initates the LED on", "LED. \"\"\" def __init__(self, pin): \"\"\" This initates the LED on the given", "LED's directly connected to the GPIO via a pin given. See the documentation", "turn the LED on this will error out. \"\"\" if brightness < 0:", "for an example of how to wire the LED. \"\"\" def __init__(self, pin):", "the LED off.\") def dim(self, brightness): \"\"\" Dims the definied LED. Keep in", "the LED. \"\"\" def __init__(self, pin): \"\"\" This initates the LED on the", "= GPIO.PWM(self.pin, 500) except: raise LedError(\"Error during the initiation of the LED class.\")", "LED on this will error out. \"\"\" if brightness < 0: brightness =", "of how to wire the LED. \"\"\" def __init__(self, pin): \"\"\" This initates", "RPi.GPIO as GPIO from .light_errors import LedError class Led: \"\"\" This is a", "the output mode, making sure it is off, and setting the PWM up", "so that the LED can be dimmed. \"\"\" try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD)", "brightness < 0: brightness = 0 elif brightness > 100: brightness = 100", "try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error while dimming the LED. Make sure you have", "This initates the LED on the given pin, setting it into the output", "except: raise LedError(\"Error while turning the LED off.\") def dim(self, brightness): \"\"\" Dims", "if brightness < 0: brightness = 0 elif brightness > 100: brightness =", "directly connected to the GPIO via a pin given. See the documentation for", "brightness is set by default to 100%. \"\"\" try: self.led_dim.start(brightness) except: raise LedError(\"Error", "is set by default to 100%. \"\"\" try: self.led_dim.start(brightness) except: raise LedError(\"Error while", "of the LED class.\") def on(self, brightness=100): \"\"\" Turns the defined LED on,", "off.\") def dim(self, brightness): \"\"\" Dims the definied LED. Keep in mind, that", "\"\"\" def __init__(self, pin): \"\"\" This initates the LED on the given pin,", "the initiation of the LED class.\") def on(self, brightness=100): \"\"\" Turns the defined", "\"\"\" Turns the defined LED off. \"\"\" try: self.led_dim.stop() except: raise LedError(\"Error while", "dim(self, brightness): \"\"\" Dims the definied LED. Keep in mind, that if you", "the documentation for an example of how to wire the LED. \"\"\" def", "Dims the definied LED. Keep in mind, that if you don't first turn", "dimmed. \"\"\" try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim =", "except: raise LedError(\"Error while turning the LED on.\") def off(self): \"\"\" Turns the", "be dimmed. \"\"\" try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim", "def on(self, brightness=100): \"\"\" Turns the defined LED on, the brightness is set", "PWM up so that the LED can be dimmed. \"\"\" try: self.pin =", "See the documentation for an example of how to wire the LED. \"\"\"", "up so that the LED can be dimmed. \"\"\" try: self.pin = int(pin)", "the brightness is set by default to 100%. \"\"\" try: self.led_dim.start(brightness) except: raise", "def dim(self, brightness): \"\"\" Dims the definied LED. Keep in mind, that if", "pin): \"\"\" This initates the LED on the given pin, setting it into", "brightness = 0 elif brightness > 100: brightness = 100 else: pass try:", "is a class used to control LED's directly connected to the GPIO via", "class used to control LED's directly connected to the GPIO via a pin", "out. \"\"\" if brightness < 0: brightness = 0 elif brightness > 100:", "try: self.pin = int(pin) GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, GPIO.LOW) self.led_dim = GPIO.PWM(self.pin, 500)", "the GPIO via a pin given. See the documentation for an example of", "class Led: \"\"\" This is a class used to control LED's directly connected", "setting it into the output mode, making sure it is off, and setting", "is off, and setting the PWM up so that the LED can be", "\"\"\" Turns the defined LED on, the brightness is set by default to", "the given pin, setting it into the output mode, making sure it is", "how to wire the LED. \"\"\" def __init__(self, pin): \"\"\" This initates the", "off. \"\"\" try: self.led_dim.stop() except: raise LedError(\"Error while turning the LED off.\") def", "brightness > 100: brightness = 100 else: pass try: self.led_dim.ChangeDutyCycle(brightness) except: raise LedError(\"Error", "mode, making sure it is off, and setting the PWM up so that", "on this will error out. \"\"\" if brightness < 0: brightness = 0", "self.led_dim.stop() except: raise LedError(\"Error while turning the LED off.\") def dim(self, brightness): \"\"\"" ]
[ "NORMAL_TEST_FILE = 'dataset/normal.csv' def train(): classifier = MyMLPClassifier() classifier.train() def predict(): xss_test_data, xss_test_label", "[l_name for i in range(len(data))] return data, label def run(): train() predict() if", "list(set(f.readlines())) label = [l_name for i in range(len(data))] return data, label def run():", "train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train =", "+ normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label + normal_train_label # loading", "def predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test", "XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def", "as f: data = list(set(f.readlines())) label = [l_name for i in range(len(data))] return", "= data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data + normal_test_data", "= confusion_matrix( pred, y_test, labels=['xss', 'normal'] ) print(\"acc: \\n\", acc_score) print(\"confusion matrix: \\n\",", "= nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label + normal_train_label # loading labels le = LabelEncoder()", "xss_train_label + normal_train_label # loading labels le = LabelEncoder() le.fit(y_train) Y = le.transform(y_train)", "coding: utf-8 -*- # ! /usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas as pd", "labels le = LabelEncoder() le.fit(y_train) Y = le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X,", "pred, y_test, labels=['xss', 'normal'] ) print(\"acc: \\n\", acc_score) print(\"confusion matrix: \\n\", conf_mat) class", "= 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def train(): classifier = MyMLPClassifier()", "= list(set(f.readlines())) label = [l_name for i in range(len(data))] return data, label def", "self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model = model self.classes = le.classes_.tolist()", "def train(): classifier = MyMLPClassifier() classifier.train() def predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss')", "le.fit(y_train) Y = le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save models", "+ normal_test_data y_test = xss_test_label + normal_test_label classifier = MyMLPClassifier() classifier.load_model() pred =", "le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_,", "'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def train(): classifier", "MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE =", "os.path import kimura.nlp_tasks as nlp_tasks from sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics", "data = list(set(f.readlines())) label = [l_name for i in range(len(data))] return data, label", "from sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE =", "data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data + normal_test_data y_test = xss_test_label + normal_test_label classifier", "data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data + normal_train_data X,", "print(\"acc: \\n\", acc_score) print(\"confusion matrix: \\n\", conf_mat) class MyMLPClassifier(): model = None model_name", "joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model = model self.classes = le.classes_.tolist() self.vectorizer", "'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data + normal_test_data y_test =", "from sklearn.preprocessing import LabelEncoder from sklearn.externals import joblib import os.path import kimura.nlp_tasks as", "sklearn.preprocessing import LabelEncoder from sklearn.externals import joblib import os.path import kimura.nlp_tasks as nlp_tasks", "def train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train", "'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data + normal_train_data X, vectorizer", "label = [l_name for i in range(len(data))] return data, label def run(): train()", "in range(len(data))] return data, label def run(): train() predict() if __name__ == '__main__':", "predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test =", "return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss')", "vectorizer def predict(self,query): X = self.vectorizer.transform([query]) key = self.model.predict(X) return self.classes[key[0]] def data_loader(f_name,", "as nlp_tasks from sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score, confusion_matrix", "= le.classes_.tolist() self.vectorizer = vectorizer def predict(self,query): X = self.vectorizer.transform([query]) key = self.model.predict(X)", "self.model = joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def", "train(): classifier = MyMLPClassifier() classifier.train() def predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data,", "confusion_matrix( pred, y_test, labels=['xss', 'normal'] ) print(\"acc: \\n\", acc_score) print(\"confusion matrix: \\n\", conf_mat)", "\"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no model file found!') self.model = joblib.load(self.get_model_path())", "# アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv'", "matrix: \\n\", conf_mat) class MyMLPClassifier(): model = None model_name = \"mlp\" def load_model(self):", "nlp_tasks from sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE", "import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from", "= MyMLPClassifier() classifier.train() def predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label =", "X = self.vectorizer.transform([query]) key = self.model.predict(X) return self.classes[key[0]] def data_loader(f_name, l_name): with open(f_name,", "predict(self,query): X = self.vectorizer.transform([query]) key = self.model.predict(X) return self.classes[key[0]] def data_loader(f_name, l_name): with", "le = LabelEncoder() le.fit(y_train) Y = le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y)", "<reponame>prprhyt/pacman # -*- coding: utf-8 -*- # ! /usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import", "= data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data + normal_train_data", "= le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save models joblib.dump(model, self.get_model_path())", "encoding='utf-8') as f: data = list(set(f.readlines())) label = [l_name for i in range(len(data))]", "range(len(data))] return data, label def run(): train() predict() if __name__ == '__main__': run()", "import kimura.nlp_tasks as nlp_tasks from sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics import", "joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model = model self.classes =", "#参考: https://spjai.com/category-classification/#i-5 import pandas as pd import numpy as np from sklearn.preprocessing import", "raise Exception('no model file found!') self.model = joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer =", "i in range(len(data))] return data, label def run(): train() predict() if __name__ ==", "accuracy_score(y_test, pred) conf_mat = confusion_matrix( pred, y_test, labels=['xss', 'normal'] ) print(\"acc: \\n\", acc_score)", "def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as f: data = list(set(f.readlines())) label", "= model self.classes = le.classes_.tolist() self.vectorizer = vectorizer def predict(self,query): X = self.vectorizer.transform([query])", "MyMLPClassifier(): model = None model_name = \"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no", "'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data,", "MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\"))", "None model_name = \"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no model file found!')", "model_name = \"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no model file found!') self.model", "= LabelEncoder() le.fit(y_train) Y = le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) #", "le.classes_.tolist() self.vectorizer = vectorizer def predict(self,query): X = self.vectorizer.transform([query]) key = self.model.predict(X) return", "normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data + normal_test_data y_test = xss_test_label +", "= 'dataset/normal.csv' def train(): classifier = MyMLPClassifier() classifier.train() def predict(): xss_test_data, xss_test_label =", "pred = classifier.predict(X_test) acc_score = accuracy_score(y_test, pred) conf_mat = confusion_matrix( pred, y_test, labels=['xss',", "'dataset/normal.csv' def train(): classifier = MyMLPClassifier() classifier.train() def predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE,", "+ normal_test_label classifier = MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test) acc_score = accuracy_score(y_test, pred)", "xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data +", ") print(\"acc: \\n\", acc_score) print(\"confusion matrix: \\n\", conf_mat) class MyMLPClassifier(): model = None", "mode='r', encoding='utf-8') as f: data = list(set(f.readlines())) label = [l_name for i in", "f: data = list(set(f.readlines())) label = [l_name for i in range(len(data))] return data,", "file found!') self.model = joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le =", "class MyMLPClassifier(): model = None model_name = \"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False: raise", "sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv'", "normal_test_data y_test = xss_test_label + normal_test_label classifier = MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test)", "y_test, labels=['xss', 'normal'] ) print(\"acc: \\n\", acc_score) print(\"confusion matrix: \\n\", conf_mat) class MyMLPClassifier():", "normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data + normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train)", "joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text):", "xss_test_label + normal_test_label classifier = MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test) acc_score = accuracy_score(y_test,", "'normal') X_train = xss_train_data + normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label", "classifier.load_model() pred = classifier.predict(X_test) acc_score = accuracy_score(y_test, pred) conf_mat = confusion_matrix( pred, y_test,", "# save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model =", "as np from sklearn.preprocessing import LabelEncoder from sklearn.externals import joblib import os.path import", "load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no model file found!') self.model = joblib.load(self.get_model_path()) self.classes =", "print(\"confusion matrix: \\n\", conf_mat) class MyMLPClassifier(): model = None model_name = \"mlp\" def", "y_train = xss_train_label + normal_train_label # loading labels le = LabelEncoder() le.fit(y_train) Y", "normal_test_label classifier = MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test) acc_score = accuracy_score(y_test, pred) conf_mat", "classifier = MyMLPClassifier() classifier.train() def predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label", "Y = le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save models joblib.dump(model,", "classifier.train() def predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal')", "= MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test) acc_score = accuracy_score(y_test, pred) conf_mat = confusion_matrix(", "= data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data + normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train", "models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model = model self.classes", "from sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE =", "! /usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas as pd import numpy as np", "# -*- coding: utf-8 -*- # ! /usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas", "LabelEncoder from sklearn.externals import joblib import os.path import kimura.nlp_tasks as nlp_tasks from sklearn.neural_network", "np from sklearn.preprocessing import LabelEncoder from sklearn.externals import joblib import os.path import kimura.nlp_tasks", "-*- coding: utf-8 -*- # ! /usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas as", "self.vectorizer = joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return", "numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.externals import joblib import os.path", "xss_test_data + normal_test_data y_test = xss_test_label + normal_test_label classifier = MyMLPClassifier() classifier.load_model() pred", "joblib import os.path import kimura.nlp_tasks as nlp_tasks from sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用", "import joblib import os.path import kimura.nlp_tasks as nlp_tasks from sklearn.neural_network import MLPClassifier #", "-*- # ! /usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas as pd import numpy", "= xss_train_data + normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label + normal_train_label", "confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv'", "model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\"))", "normal_train_label # loading labels le = LabelEncoder() le.fit(y_train) Y = le.transform(y_train) model =", "= [l_name for i in range(len(data))] return data, label def run(): train() predict()", "https://spjai.com/category-classification/#i-5 import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder", "XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def train(): classifier =", "joblib.dump(le, self.get_model_path(\"le\")) self.model = model self.classes = le.classes_.tolist() self.vectorizer = vectorizer def predict(self,query):", "= joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def", "LabelEncoder() le.fit(y_train) Y = le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save", "xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data +", "/usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas as pd import numpy as np from", "hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le,", "def predict(self,query): X = self.vectorizer.transform([query]) key = self.model.predict(X) return self.classes[key[0]] def data_loader(f_name, l_name):", "joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model = model self.classes = le.classes_.tolist() self.vectorizer = vectorizer", "\\n\", conf_mat) class MyMLPClassifier(): model = None model_name = \"mlp\" def load_model(self): if", "with open(f_name, mode='r', encoding='utf-8') as f: data = list(set(f.readlines())) label = [l_name for", "self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model = model self.classes = le.classes_.tolist() self.vectorizer =", "Exception('no model file found!') self.model = joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect'))", "joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return", "os.path.exists(self.get_model_path())==False: raise Exception('no model file found!') self.model = joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer", "classifier.predict(X_test) acc_score = accuracy_score(y_test, pred) conf_mat = confusion_matrix( pred, y_test, labels=['xss', 'normal'] )", "from sklearn.externals import joblib import os.path import kimura.nlp_tasks as nlp_tasks from sklearn.neural_network import", "X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label + normal_train_label # loading labels le", "vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label + normal_train_label # loading labels le =", "normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data + normal_test_data y_test = xss_test_label", "import LabelEncoder from sklearn.externals import joblib import os.path import kimura.nlp_tasks as nlp_tasks from", "= \"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no model file found!') self.model =", "model = None model_name = \"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no model", "model.fit(X, Y) # save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\"))", "def load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no model file found!') self.model = joblib.load(self.get_model_path()) self.classes", "self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal')", "joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label", "= MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,) model.fit(X, Y) # save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer,", "import os.path import kimura.nlp_tasks as nlp_tasks from sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用 from", "self.model = model self.classes = le.classes_.tolist() self.vectorizer = vectorizer def predict(self,query): X =", "= self.model.predict(X) return self.classes[key[0]] def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as f:", "MyMLPClassifier() classifier.train() def predict(): xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE,", "= joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text]) def train(self): xss_train_data,", "sklearn.externals import joblib import os.path import kimura.nlp_tasks as nlp_tasks from sklearn.neural_network import MLPClassifier", "if os.path.exists(self.get_model_path())==False: raise Exception('no model file found!') self.model = joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist()", "= 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def train(): classifier = MyMLPClassifier() classifier.train() def predict():", "model file found!') self.model = joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le", "conf_mat) class MyMLPClassifier(): model = None model_name = \"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False:", "'normal') X_test = xss_test_data + normal_test_data y_test = xss_test_label + normal_test_label classifier =", "normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data + normal_train_data X, vectorizer =", "pred) conf_mat = confusion_matrix( pred, y_test, labels=['xss', 'normal'] ) print(\"acc: \\n\", acc_score) print(\"confusion", "normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label + normal_train_label # loading labels", "acc_score = accuracy_score(y_test, pred) conf_mat = confusion_matrix( pred, y_test, labels=['xss', 'normal'] ) print(\"acc:", "loading labels le = LabelEncoder() le.fit(y_train) Y = le.transform(y_train) model = MLPClassifier(max_iter=300, hidden_layer_sizes=(100,),verbose=10,)", "= 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def train():", "acc_score) print(\"confusion matrix: \\n\", conf_mat) class MyMLPClassifier(): model = None model_name = \"mlp\"", "save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model = model", "pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.externals import joblib", "'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def train(): classifier = MyMLPClassifier() classifier.train()", "\\n\", acc_score) print(\"confusion matrix: \\n\", conf_mat) class MyMLPClassifier(): model = None model_name =", "found!') self.model = joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le'))", "= xss_train_label + normal_train_label # loading labels le = LabelEncoder() le.fit(y_train) Y =", "= self.vectorizer.transform([query]) key = self.model.predict(X) return self.classes[key[0]] def data_loader(f_name, l_name): with open(f_name, mode='r',", "self.vectorizer.transform([query]) key = self.model.predict(X) return self.classes[key[0]] def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8')", "labels=['xss', 'normal'] ) print(\"acc: \\n\", acc_score) print(\"confusion matrix: \\n\", conf_mat) class MyMLPClassifier(): model", "self.classes[key[0]] def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as f: data = list(set(f.readlines()))", "self.model.predict(X) return self.classes[key[0]] def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as f: data", "# ! /usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas as pd import numpy as", "= data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data + normal_test_data y_test = xss_test_label + normal_test_label", "utf-8 -*- # ! /usr/bin/python #NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas as pd import", "data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data + normal_test_data y_test", "return self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE,", "l_name): with open(f_name, mode='r', encoding='utf-8') as f: data = list(set(f.readlines())) label = [l_name", "y_test = xss_test_label + normal_test_label classifier = MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test) acc_score", "data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data + normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train =", "Y) # save models joblib.dump(model, self.get_model_path()) joblib.dump(le.classes_, self.get_model_path(\"class\")) joblib.dump(vectorizer, self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model", "data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as f: data = list(set(f.readlines())) label =", "アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE", "self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl'", "= joblib.load(self.get_model_path()) self.classes = joblib.load(self.get_model_path('class')).tolist() self.vectorizer = joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'):", "'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def train(): classifier = MyMLPClassifier() classifier.train() def predict(): xss_test_data,", "as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.externals import", "pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.externals", "#NLPでやってみた #参考: https://spjai.com/category-classification/#i-5 import pandas as pd import numpy as np from sklearn.preprocessing", "+ normal_train_label # loading labels le = LabelEncoder() le.fit(y_train) Y = le.transform(y_train) model", "accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE =", "xss_test_data, xss_test_label = data_loader(XSS_TEST_FILE, 'xss') normal_test_data, normal_test_label = data_loader(NORMAL_TEST_FILE, 'normal') X_test = xss_test_data", "self.get_model_path(\"vect\")) joblib.dump(le, self.get_model_path(\"le\")) self.model = model self.classes = le.classes_.tolist() self.vectorizer = vectorizer def", "classifier = MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test) acc_score = accuracy_score(y_test, pred) conf_mat =", "self.classes = le.classes_.tolist() self.vectorizer = vectorizer def predict(self,query): X = self.vectorizer.transform([query]) key =", "import MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE", "= xss_test_label + normal_test_label classifier = MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test) acc_score =", "get_vector(self,text): return self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label =", "sklearn.metrics import accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv'", "get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE,", "def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label =", "# loading labels le = LabelEncoder() le.fit(y_train) Y = le.transform(y_train) model = MLPClassifier(max_iter=300,", "= vectorizer def predict(self,query): X = self.vectorizer.transform([query]) key = self.model.predict(X) return self.classes[key[0]] def", "self.get_model_path(\"le\")) self.model = model self.classes = le.classes_.tolist() self.vectorizer = vectorizer def predict(self,query): X", "'normal'] ) print(\"acc: \\n\", acc_score) print(\"confusion matrix: \\n\", conf_mat) class MyMLPClassifier(): model =", "return self.classes[key[0]] def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as f: data =", "self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text]) def train(self):", "xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label = data_loader(NORMAL_TRAIN_FILE, 'normal') X_train = xss_train_data", "for i in range(len(data))] return data, label def run(): train() predict() if __name__", "= None model_name = \"mlp\" def load_model(self): if os.path.exists(self.get_model_path())==False: raise Exception('no model file", "xss_train_data + normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label + normal_train_label #", "X_train = xss_train_data + normal_train_data X, vectorizer = nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label +", "self.vectorizer = vectorizer def predict(self,query): X = self.vectorizer.transform([query]) key = self.model.predict(X) return self.classes[key[0]]", "kimura.nlp_tasks as nlp_tasks from sklearn.neural_network import MLPClassifier # アルゴリズムとしてmlpを使用 from sklearn.metrics import accuracy_score,", "= accuracy_score(y_test, pred) conf_mat = confusion_matrix( pred, y_test, labels=['xss', 'normal'] ) print(\"acc: \\n\",", "nlp_tasks.get_vector_by_text_list(X_train) y_train = xss_train_label + normal_train_label # loading labels le = LabelEncoder() le.fit(y_train)", "= xss_test_data + normal_test_data y_test = xss_test_label + normal_test_label classifier = MyMLPClassifier() classifier.load_model()", "X_test = xss_test_data + normal_test_data y_test = xss_test_label + normal_test_label classifier = MyMLPClassifier()", "joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text]) def", "def get_vector(self,text): return self.vectorizer.transform([text]) def train(self): xss_train_data, xss_train_label = data_loader(XSS_TRAIN_FILE, 'xss') normal_train_data, normal_train_label", "model self.classes = le.classes_.tolist() self.vectorizer = vectorizer def predict(self,query): X = self.vectorizer.transform([query]) key", "NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE = 'dataset/normal.csv' def train(): classifier = MyMLPClassifier() classifier.train() def", "import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.externals import joblib import", "= joblib.load(self.get_model_path('vect')) self.le = joblib.load(self.get_model_path('le')) def get_model_path(self,type='model'): return 'kimura/models/'+self.model_name+\"_\"+type+'.pkl' def get_vector(self,text): return self.vectorizer.transform([text])", "= classifier.predict(X_test) acc_score = accuracy_score(y_test, pred) conf_mat = confusion_matrix( pred, y_test, labels=['xss', 'normal']", "import accuracy_score, confusion_matrix XSS_TRAIN_FILE = 'dataset/train_level_1.csv' XSS_TEST_FILE = 'dataset/test_level_1.csv' NORMAL_TRAIN_FILE = 'dataset/normal.csv' NORMAL_TEST_FILE", "MyMLPClassifier() classifier.load_model() pred = classifier.predict(X_test) acc_score = accuracy_score(y_test, pred) conf_mat = confusion_matrix( pred,", "key = self.model.predict(X) return self.classes[key[0]] def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as", "conf_mat = confusion_matrix( pred, y_test, labels=['xss', 'normal'] ) print(\"acc: \\n\", acc_score) print(\"confusion matrix:", "open(f_name, mode='r', encoding='utf-8') as f: data = list(set(f.readlines())) label = [l_name for i" ]
[ "configuration as well', action='store_true') if __name__ == '__main__': args = parser.parse_args() model, cls,", "copy import argparse import torch from pynn.util import load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path',", "= [s for s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states = args.states.split(',') states", "parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path', default='model') parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states',", "default='model.cfg') parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all', help='save configuration as well', action='store_true') if __name__", "states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters()) for state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams", "= args.states.split(',') states = [\"%s/epoch-%s.pt\" % (args.model_path, s) for s in states] state", "config', default='model.cfg') parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all', help='save configuration as well', action='store_true') if", "\"License\") import os, glob import copy import argparse import torch from pynn.util import", "'ALL': states = [s for s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states =", "Copyright 2019 <NAME> # Licensed under the Apache License, Version 2.0 (the \"License\")", "load_object_param(args.model_path + '/' + args.config) ext = copy.deepcopy(model) if args.states == 'ALL': states", "for i in range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0 / len(states) for p in", "for p in params: p.data.mul_(scale) state = model.state_dict() if not args.save_all: model_file =", "help='model states', default='ALL') parser.add_argument('--save-all', help='save configuration as well', action='store_true') if __name__ == '__main__':", "default='ALL') parser.add_argument('--save-all', help='save configuration as well', action='store_true') if __name__ == '__main__': args =", "from pynn.util import load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path', default='model') parser.add_argument('--config',", "parser.parse_args() model, cls, module, m_params = load_object_param(args.model_path + '/' + args.config) ext =", "__name__ == '__main__': args = parser.parse_args() model, cls, module, m_params = load_object_param(args.model_path +", "if args.states == 'ALL': states = [s for s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)]", "#!/usr/bin/env python3 # encoding: utf-8 # Copyright 2019 <NAME> # Licensed under the", "map_location='cpu')) params = list(model.parameters()) for state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters())", "(the \"License\") import os, glob import copy import argparse import torch from pynn.util", "1.0 / len(states) for p in params: p.data.mul_(scale) state = model.state_dict() if not", "state = model.state_dict() if not args.save_all: model_file = '%s/epoch-avg.pt' % args.model_path torch.save(state, model_file)", "= argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path', default='model') parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states', help='model", "= list(model.parameters()) for state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters()) for i", "copy.deepcopy(model) if args.states == 'ALL': states = [s for s in glob.glob(\"%s/epoch-*.pt\" %", "list(ext.parameters()) for i in range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0 / len(states) for p", "state = states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters()) for state in states[1:]: ext.load_state_dict(torch.load(state,", "state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters()) for i in range(len(params)): params[i].data.add_(eparams[i].data)", "states = [\"%s/epoch-%s.pt\" % (args.model_path, s) for s in states] state = states[0]", "dic = {'params': m_params, 'class': cls, 'module': module, 'state': state} torch.save(dic, '%s/epoch-avg.dic' %", "2.0 (the \"License\") import os, glob import copy import argparse import torch from", "for s in states] state = states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters()) for", "args = parser.parse_args() model, cls, module, m_params = load_object_param(args.model_path + '/' + args.config)", "args.states == 'ALL': states = [s for s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else:", "% (args.model_path, s) for s in states] state = states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params", "import copy import argparse import torch from pynn.util import load_object_param parser = argparse.ArgumentParser(description='pynn')", "# encoding: utf-8 # Copyright 2019 <NAME> # Licensed under the Apache License,", "utf-8 # Copyright 2019 <NAME> # Licensed under the Apache License, Version 2.0", "len(states) for p in params: p.data.mul_(scale) state = model.state_dict() if not args.save_all: model_file", "= '%s/epoch-avg.pt' % args.model_path torch.save(state, model_file) else: dic = {'params': m_params, 'class': cls,", "states] state = states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters()) for state in states[1:]:", "parser.add_argument('--model-path', help='model saving path', default='model') parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states', help='model states', default='ALL')", "'__main__': args = parser.parse_args() model, cls, module, m_params = load_object_param(args.model_path + '/' +", "glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states = args.states.split(',') states = [\"%s/epoch-%s.pt\" % (args.model_path, s)", "as well', action='store_true') if __name__ == '__main__': args = parser.parse_args() model, cls, module,", "args.states.split(',') states = [\"%s/epoch-%s.pt\" % (args.model_path, s) for s in states] state =", "= copy.deepcopy(model) if args.states == 'ALL': states = [s for s in glob.glob(\"%s/epoch-*.pt\"", "help='save configuration as well', action='store_true') if __name__ == '__main__': args = parser.parse_args() model,", "scale = 1.0 / len(states) for p in params: p.data.mul_(scale) state = model.state_dict()", "params = list(model.parameters()) for state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters()) for", "else: states = args.states.split(',') states = [\"%s/epoch-%s.pt\" % (args.model_path, s) for s in", "in range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0 / len(states) for p in params: p.data.mul_(scale)", "import load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path', default='model') parser.add_argument('--config', help='model config',", "pynn.util import load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path', default='model') parser.add_argument('--config', help='model", "in params: p.data.mul_(scale) state = model.state_dict() if not args.save_all: model_file = '%s/epoch-avg.pt' %", "glob import copy import argparse import torch from pynn.util import load_object_param parser =", "torch from pynn.util import load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path', default='model')", "python3 # encoding: utf-8 # Copyright 2019 <NAME> # Licensed under the Apache", "argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path', default='model') parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states', help='model states',", "states = args.states.split(',') states = [\"%s/epoch-%s.pt\" % (args.model_path, s) for s in states]", "= model.state_dict() if not args.save_all: model_file = '%s/epoch-avg.pt' % args.model_path torch.save(state, model_file) else:", "% args.model_path)] else: states = args.states.split(',') states = [\"%s/epoch-%s.pt\" % (args.model_path, s) for", "p.data.mul_(scale) state = model.state_dict() if not args.save_all: model_file = '%s/epoch-avg.pt' % args.model_path torch.save(state,", "torch.save(state, model_file) else: dic = {'params': m_params, 'class': cls, 'module': module, 'state': state}", "/ len(states) for p in params: p.data.mul_(scale) state = model.state_dict() if not args.save_all:", "if __name__ == '__main__': args = parser.parse_args() model, cls, module, m_params = load_object_param(args.model_path", "well', action='store_true') if __name__ == '__main__': args = parser.parse_args() model, cls, module, m_params", "load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path', default='model') parser.add_argument('--config', help='model config', default='model.cfg')", "= {'params': m_params, 'class': cls, 'module': module, 'state': state} torch.save(dic, '%s/epoch-avg.dic' % args.model_path)", "map_location='cpu')) eparams = list(ext.parameters()) for i in range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0 /", "parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all', help='save configuration as well', action='store_true') if __name__ ==", "s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states = args.states.split(',') states = [\"%s/epoch-%s.pt\" %", "= load_object_param(args.model_path + '/' + args.config) ext = copy.deepcopy(model) if args.states == 'ALL':", "encoding: utf-8 # Copyright 2019 <NAME> # Licensed under the Apache License, Version", "import torch from pynn.util import load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving path',", "states = [s for s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states = args.states.split(',')", "parser.add_argument('--save-all', help='save configuration as well', action='store_true') if __name__ == '__main__': args = parser.parse_args()", "states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters()) for i in range(len(params)): params[i].data.add_(eparams[i].data) scale =", "ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters()) for i in range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0", "% args.model_path torch.save(state, model_file) else: dic = {'params': m_params, 'class': cls, 'module': module,", "<NAME> # Licensed under the Apache License, Version 2.0 (the \"License\") import os,", "2019 <NAME> # Licensed under the Apache License, Version 2.0 (the \"License\") import", "for s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states = args.states.split(',') states = [\"%s/epoch-%s.pt\"", "else: dic = {'params': m_params, 'class': cls, 'module': module, 'state': state} torch.save(dic, '%s/epoch-avg.dic'", "+ '/' + args.config) ext = copy.deepcopy(model) if args.states == 'ALL': states =", "= list(ext.parameters()) for i in range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0 / len(states) for", "args.model_path torch.save(state, model_file) else: dic = {'params': m_params, 'class': cls, 'module': module, 'state':", "model_file) else: dic = {'params': m_params, 'class': cls, 'module': module, 'state': state} torch.save(dic,", "list(model.parameters()) for state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters()) for i in", "the Apache License, Version 2.0 (the \"License\") import os, glob import copy import", "help='model config', default='model.cfg') parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all', help='save configuration as well', action='store_true')", "range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0 / len(states) for p in params: p.data.mul_(scale) state", "# Licensed under the Apache License, Version 2.0 (the \"License\") import os, glob", "License, Version 2.0 (the \"License\") import os, glob import copy import argparse import", "p in params: p.data.mul_(scale) state = model.state_dict() if not args.save_all: model_file = '%s/epoch-avg.pt'", "== '__main__': args = parser.parse_args() model, cls, module, m_params = load_object_param(args.model_path + '/'", "in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states = args.states.split(',') states = [\"%s/epoch-%s.pt\" % (args.model_path,", "action='store_true') if __name__ == '__main__': args = parser.parse_args() model, cls, module, m_params =", "= states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters()) for state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu'))", "Licensed under the Apache License, Version 2.0 (the \"License\") import os, glob import", "argparse import torch from pynn.util import load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model saving", "params: p.data.mul_(scale) state = model.state_dict() if not args.save_all: model_file = '%s/epoch-avg.pt' % args.model_path", "i in range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0 / len(states) for p in params:", "path', default='model') parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all', help='save configuration", "[s for s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states = args.states.split(',') states =", "'/' + args.config) ext = copy.deepcopy(model) if args.states == 'ALL': states = [s", "import os, glob import copy import argparse import torch from pynn.util import load_object_param", "args.model_path)] else: states = args.states.split(',') states = [\"%s/epoch-%s.pt\" % (args.model_path, s) for s", "= [\"%s/epoch-%s.pt\" % (args.model_path, s) for s in states] state = states[0] model.load_state_dict(torch.load(state,", "(args.model_path, s) for s in states] state = states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params =", "model, cls, module, m_params = load_object_param(args.model_path + '/' + args.config) ext = copy.deepcopy(model)", "s) for s in states] state = states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters())", "module, m_params = load_object_param(args.model_path + '/' + args.config) ext = copy.deepcopy(model) if args.states", "[\"%s/epoch-%s.pt\" % (args.model_path, s) for s in states] state = states[0] model.load_state_dict(torch.load(state, map_location='cpu'))", "s in states] state = states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters()) for state", "= 1.0 / len(states) for p in params: p.data.mul_(scale) state = model.state_dict() if", "+ args.config) ext = copy.deepcopy(model) if args.states == 'ALL': states = [s for", "model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters()) for state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams =", "Apache License, Version 2.0 (the \"License\") import os, glob import copy import argparse", "params[i].data.add_(eparams[i].data) scale = 1.0 / len(states) for p in params: p.data.mul_(scale) state =", "eparams = list(ext.parameters()) for i in range(len(params)): params[i].data.add_(eparams[i].data) scale = 1.0 / len(states)", "os, glob import copy import argparse import torch from pynn.util import load_object_param parser", "import argparse import torch from pynn.util import load_object_param parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--model-path', help='model", "Version 2.0 (the \"License\") import os, glob import copy import argparse import torch", "states', default='ALL') parser.add_argument('--save-all', help='save configuration as well', action='store_true') if __name__ == '__main__': args", "args.config) ext = copy.deepcopy(model) if args.states == 'ALL': states = [s for s", "parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all', help='save configuration as well',", "in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters()) for i in range(len(params)): params[i].data.add_(eparams[i].data) scale", "'%s/epoch-avg.pt' % args.model_path torch.save(state, model_file) else: dic = {'params': m_params, 'class': cls, 'module':", "<reponame>enesyugan/yapay-nn<gh_stars>0 #!/usr/bin/env python3 # encoding: utf-8 # Copyright 2019 <NAME> # Licensed under", "== 'ALL': states = [s for s in glob.glob(\"%s/epoch-*.pt\" % args.model_path)] else: states", "saving path', default='model') parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all', help='save", "in states] state = states[0] model.load_state_dict(torch.load(state, map_location='cpu')) params = list(model.parameters()) for state in", "# Copyright 2019 <NAME> # Licensed under the Apache License, Version 2.0 (the", "default='model') parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all', help='save configuration as", "m_params = load_object_param(args.model_path + '/' + args.config) ext = copy.deepcopy(model) if args.states ==", "for state in states[1:]: ext.load_state_dict(torch.load(state, map_location='cpu')) eparams = list(ext.parameters()) for i in range(len(params)):", "args.save_all: model_file = '%s/epoch-avg.pt' % args.model_path torch.save(state, model_file) else: dic = {'params': m_params,", "if not args.save_all: model_file = '%s/epoch-avg.pt' % args.model_path torch.save(state, model_file) else: dic =", "model_file = '%s/epoch-avg.pt' % args.model_path torch.save(state, model_file) else: dic = {'params': m_params, 'class':", "cls, module, m_params = load_object_param(args.model_path + '/' + args.config) ext = copy.deepcopy(model) if", "not args.save_all: model_file = '%s/epoch-avg.pt' % args.model_path torch.save(state, model_file) else: dic = {'params':", "help='model saving path', default='model') parser.add_argument('--config', help='model config', default='model.cfg') parser.add_argument('--states', help='model states', default='ALL') parser.add_argument('--save-all',", "= parser.parse_args() model, cls, module, m_params = load_object_param(args.model_path + '/' + args.config) ext", "model.state_dict() if not args.save_all: model_file = '%s/epoch-avg.pt' % args.model_path torch.save(state, model_file) else: dic", "ext = copy.deepcopy(model) if args.states == 'ALL': states = [s for s in", "under the Apache License, Version 2.0 (the \"License\") import os, glob import copy" ]
[ "numpy as np import tensorflow as tf from tensorflow.python.ops import math_ops from tensorflow.python.ops", "super().__init__(model) def forward(self,x0,ts): Nt = x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for i in range(Nt):", "time_delta_grid = time_grid[1:] - time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0') scan_func", "= tf.float64 class Integrator(ABC): \"\"\" Base class for integrators \"\"\" def __init__(self,model): self.model=", "math_ops.cast(dt, y.dtype) k1 = f(y, t) k2 = f(y + dt*k1/2, t+dt/2) k3", "dt = t_dt dy = self._step_func(f, dt, t, y) dy = math_ops.cast(dy, dtype=y.dtype)", "y0 = ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys", "SDEs dx = f(x)*dt + g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model) self.s = s", "\"\"\" Base class for integrators \"\"\" def __init__(self,model): self.model= model @abstractmethod def forward(self):", "ODEs \"\"\" def __init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt = x0.shape[0] Xs = np.zeros(Nt,dtype=np.object)", "ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0],", "t_dt dy = self._step_func(f, dt, t, y) dy = math_ops.cast(dy, dtype=y.dtype) return y", "- time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0],", "dy = math_ops.cast(dy, dtype=y.dtype) return y + dy return scan_func class SDEEM(Integrator): \"\"\"", "= np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1])", "import tensorflow as tf from tensorflow.python.ops import math_ops from tensorflow.python.ops import functional_ops from", "ABC, abstractmethod float_type = tf.float64 class Integrator(ABC): \"\"\" Base class for integrators \"\"\"", "\"\"\" def __init__(self,model,s=1): super().__init__(model) self.s = s def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for", "self.s = s def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for i in range(len(ts)): t", "tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt)", "math_ops.cast(dt, x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt =", "for solving ODEs \"\"\" def __init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt = x0.shape[0] Xs", "t_dt): t,dt = t_dt dy = self._step_func(f,g,t,dt,y) dy = math_ops.cast(dy, dtype=y.dtype) return y", "t = np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:] - time_grid[:-1]", "name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:] - time_grid[:-1] scan_func = self._make_scan_func(self.model.f)", "in range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid =", "= array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y): dt =", "def __init__(self,model,s=1): super().__init__(model) self.s = s def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for i", "for i in range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0')", "tensorflow.python.ops import array_ops from tensorflow.python.framework import ops from abc import ABC, abstractmethod float_type", "x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for i in range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t')", "time_grid[1:] - time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s =", "range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i]) )[0] t", "t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i]) )[0] t =", "= time_grid[1:] - time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s", "from tensorflow.python.framework import ops from abc import ABC, abstractmethod float_type = tf.float64 class", "dt*k3, t+dt) return math_ops.add_n([k1, 2*k2, 2*k3, k4]) * (dt / 6) def _make_scan_func(self,f):", "= f(x)*dt + g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model) self.s = s def forward(self,x0,ts,Nw=1):", "t+dt) return math_ops.add_n([k1, 2*k2, 2*k3, k4]) * (dt / 6) def _make_scan_func(self,f): def", "time_grid[1:] - time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g)", "(time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def", "from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops from abc import ABC, abstractmethod", "from abc import ABC, abstractmethod float_type = tf.float64 class Integrator(ABC): \"\"\" Base class", "= ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:] - time_grid[:-1]", "self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0], y_grid], axis=0) Xs[i] =", "dtype=y.dtype) return y + dy return scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for", "forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for i in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t =", "y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D])", "(dt / 6) def _make_scan_func(self,f): def scan_func(y, t_dt): t, dt = t_dt dy", "np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:]", "ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:] - time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func,", "@abstractmethod def forward(self): pass @abstractmethod def _step_func(self): pass @abstractmethod def _make_scan_func(self): pass class", "forward(self): pass @abstractmethod def _step_func(self): pass @abstractmethod def _make_scan_func(self): pass class ODERK4(Integrator): \"\"\"", "Base class for integrators \"\"\" def __init__(self,model): self.model= model @abstractmethod def forward(self): pass", "return Xs def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype) k1 = f(y, t) k2", "class for integrators \"\"\" def __init__(self,model): self.model= model @abstractmethod def forward(self): pass @abstractmethod", "= f(y, t) k2 = f(y + dt*k1/2, t+dt/2) k3 = f(y +", "t, y) dy = math_ops.cast(dy, dtype=y.dtype) return y + dy return scan_func class", "= math_ops.cast(dt, y.dtype) k1 = f(y, t) k2 = f(y + dt*k1/2, t+dt/2)", "array_ops from tensorflow.python.framework import ops from abc import ABC, abstractmethod float_type = tf.float64", "np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1]) time_grid", "+ dt*k1/2, t+dt/2) k3 = f(y + dt*k2/2, t+dt/2) k4 = f(y +", "def _step_func(self): pass @abstractmethod def _make_scan_func(self): pass class ODERK4(Integrator): \"\"\" Runge-Kutta implementation for", "Runge-Kutta implementation for solving ODEs \"\"\" def __init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt =", "f(y, t) k2 = f(y + dt*k1/2, t+dt/2) k3 = f(y + dt*k2/2,", "time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid =", "def forward(self): pass @abstractmethod def _step_func(self): pass @abstractmethod def _make_scan_func(self): pass class ODERK4(Integrator):", "def __init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt = x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for i", "= x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for i in range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type,", "implementation for solving SDEs dx = f(x)*dt + g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model)", "= tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype) return f(x,t)*dt +", "from tensorflow.python.ops import functional_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops from", "= f(y + dt*k2/2, t+dt/2) k4 = f(y + dt*k3, t+dt) return math_ops.add_n([k1,", "= np.zeros(Nt,dtype=np.object) for i in range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 =", "dt*k2/2, t+dt/2) k4 = f(y + dt*k3, t+dt) return math_ops.add_n([k1, 2*k2, 2*k3, k4])", "y0) ys = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x):", "preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:] - time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0,", "return math_ops.add_n([k1, 2*k2, 2*k3, k4]) * (dt / 6) def _make_scan_func(self,f): def scan_func(y,", "y) dy = math_ops.cast(dy, dtype=y.dtype) return y + dy return scan_func class SDEEM(Integrator):", "np import tensorflow as tf from tensorflow.python.ops import math_ops from tensorflow.python.ops import functional_ops", "import functional_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops from abc import", "np.zeros(len(ts),dtype=np.object) for i in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx =", "ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:] - time_grid[:-1] scan_func", "np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type,", "ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:] - time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 =", "__init__(self,model): self.model= model @abstractmethod def forward(self): pass @abstractmethod def _step_func(self): pass @abstractmethod def", "import numpy as np import tensorflow as tf from tensorflow.python.ops import math_ops from", "t_dt): t, dt = t_dt dy = self._step_func(f, dt, t, y) dy =", "s def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for i in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1)", "axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype) return", "from tensorflow.python.ops import math_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import array_ops from", "tensorflow.python.ops import functional_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops from abc", "_step_func(self): pass @abstractmethod def _make_scan_func(self): pass class ODERK4(Integrator): \"\"\" Runge-Kutta implementation for solving", "abstractmethod float_type = tf.float64 class Integrator(ABC): \"\"\" Base class for integrators \"\"\" def", "Euler-Maruyama implementation for solving SDEs dx = f(x)*dt + g*sqrt(dt) \"\"\" def __init__(self,model,s=1):", "name='t') time_delta_grid = time_grid[1:] - time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0')", "scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0], y_grid], axis=0)", "dt = math_ops.cast(dt, x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y, t_dt):", "def _make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt = t_dt dy = self._step_func(f,g,t,dt,y) dy =", "functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs", "range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:]", "_make_scan_func(self): pass class ODERK4(Integrator): \"\"\" Runge-Kutta implementation for solving ODEs \"\"\" def __init__(self,model):", "= t_dt dy = self._step_func(f, dt, t, y) dy = math_ops.cast(dy, dtype=y.dtype) return", "import math_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import", "= self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0], y_grid], axis=0) Xs[i]", "/ 6) def _make_scan_func(self,f): def scan_func(y, t_dt): t, dt = t_dt dy =", "y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:] - time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid", "k2 = f(y + dt*k1/2, t+dt/2) k3 = f(y + dt*k2/2, t+dt/2) k4", "__init__(self,model,s=1): super().__init__(model) self.s = s def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for i in", "y0) y_s = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y):", "= f(y + dt*k1/2, t+dt/2) k3 = f(y + dt*k2/2, t+dt/2) k4 =", "= functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return", "= np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t,", "float_type = tf.float64 class Integrator(ABC): \"\"\" Base class for integrators \"\"\" def __init__(self,model):", "= np.zeros(len(ts),dtype=np.object) for i in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx", "= array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x): dt =", "time_delta_grid = time_grid[1:] - time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0)", "def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype) k1 = f(y, t) k2 = f(y", "= s def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for i in range(len(ts)): t =", "g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt = t_dt dy = self._step_func(f,g,t,dt,y) dy", "k3 = f(y + dt*k2/2, t+dt/2) k4 = f(y + dt*k3, t+dt) return", "math_ops.cast(dy, dtype=y.dtype) return y + dy return scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation", "dx = f(x)*dt + g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model) self.s = s def", "def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def", "t,dt = t_dt dy = self._step_func(f,g,t,dt,y) dy = math_ops.cast(dy, dtype=y.dtype) return y +", "np.zeros(Nt,dtype=np.object) for i in range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)),", "+ dy return scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for solving SDEs dx", "Xs def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype) k1 = f(y, t) k2 =", "\"\"\" def __init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt = x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for", "array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt,", "np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0)", "_make_scan_func(self,f): def scan_func(y, t_dt): t, dt = t_dt dy = self._step_func(f, dt, t,", "dy return scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for solving SDEs dx =", "def __init__(self,model): self.model= model @abstractmethod def forward(self): pass @abstractmethod def _step_func(self): pass @abstractmethod", "Integrator(ABC): \"\"\" Base class for integrators \"\"\" def __init__(self,model): self.model= model @abstractmethod def", "k4 = f(y + dt*k3, t+dt) return math_ops.add_n([k1, 2*k2, 2*k3, k4]) * (dt", "name='y0') time_delta_grid = time_grid[1:] - time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid),", "+ dt*k3, t+dt) return math_ops.add_n([k1, 2*k2, 2*k3, k4]) * (dt / 6) def", "= ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:] - time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid =", "2*k2, 2*k3, k4]) * (dt / 6) def _make_scan_func(self,f): def scan_func(y, t_dt): t,", "f(y + dt*k3, t+dt) return math_ops.add_n([k1, 2*k2, 2*k3, k4]) * (dt / 6)", "= math_ops.cast(dt, x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt", "* (dt / 6) def _make_scan_func(self,f): def scan_func(y, t_dt): t, dt = t_dt", "f(x)*dt + g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model) self.s = s def forward(self,x0,ts,Nw=1): Xs", "def _make_scan_func(self): pass class ODERK4(Integrator): \"\"\" Runge-Kutta implementation for solving ODEs \"\"\" def", "+ dt*k2/2, t+dt/2) k4 = f(y + dt*k3, t+dt) return math_ops.add_n([k1, 2*k2, 2*k3,", "idx = np.where( np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t')", "time_grid[:-1] scan_func = self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0], y_grid],", "self.model= model @abstractmethod def forward(self): pass @abstractmethod def _step_func(self): pass @abstractmethod def _make_scan_func(self):", "= self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0], y_grid], axis=0) Xs[i]", ")[0] t = np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:] -", "dt*k1/2, t+dt/2) k3 = f(y + dt*k2/2, t+dt/2) k4 = f(y + dt*k3,", "solving ODEs \"\"\" def __init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt = x0.shape[0] Xs =", "\"\"\" def __init__(self,model): self.model= model @abstractmethod def forward(self): pass @abstractmethod def _step_func(self): pass", "math_ops.add_n([k1, 2*k2, 2*k3, k4]) * (dt / 6) def _make_scan_func(self,f): def scan_func(y, t_dt):", "= np.where( np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid", "= np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:] - time_grid[:-1] y0", "tf.float64 class Integrator(ABC): \"\"\" Base class for integrators \"\"\" def __init__(self,model): self.model= model", "y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2])", "def scan_func(y, t_dt): t,dt = t_dt dy = self._step_func(f,g,t,dt,y) dy = math_ops.cast(dy, dtype=y.dtype)", "SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for solving SDEs dx = f(x)*dt + g*sqrt(dt) \"\"\"", "dt = math_ops.cast(dt, y.dtype) k1 = f(y, t) k2 = f(y + dt*k1/2,", "2*k3, k4]) * (dt / 6) def _make_scan_func(self,f): def scan_func(y, t_dt): t, dt", "tensorflow as tf from tensorflow.python.ops import math_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops", "return y + dy return scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for solving", "y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype)", "def _make_scan_func(self,f): def scan_func(y, t_dt): t, dt = t_dt dy = self._step_func(f, dt,", "y_s = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y): dt", "math_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops", "f(y + dt*k2/2, t+dt/2) k4 = f(y + dt*k3, t+dt) return math_ops.add_n([k1, 2*k2,", "time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:] - time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0)", "+ g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model) self.s = s def forward(self,x0,ts,Nw=1): Xs =", "Xs = np.zeros(Nt,dtype=np.object) for i in range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0", "return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt = t_dt dy", "scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for solving SDEs dx = f(x)*dt +", "y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func,", "return Xs def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def", "= np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid),", "f(y + dt*k1/2, t+dt/2) k3 = f(y + dt*k2/2, t+dt/2) k4 = f(y", "scan_func(y, t_dt): t,dt = t_dt dy = self._step_func(f,g,t,dt,y) dy = math_ops.cast(dy, dtype=y.dtype) return", "def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for i in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t", "<reponame>marghetis/npde import numpy as np import tensorflow as tf from tensorflow.python.ops import math_ops", "g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model) self.s = s def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object)", "= time_grid[1:] - time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0') scan_func =", "Xs def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g):", "import ABC, abstractmethod float_type = tf.float64 class Integrator(ABC): \"\"\" Base class for integrators", "@abstractmethod def _step_func(self): pass @abstractmethod def _make_scan_func(self): pass class ODERK4(Integrator): \"\"\" Runge-Kutta implementation", "t_dt dy = self._step_func(f,g,t,dt,y) dy = math_ops.cast(dy, dtype=y.dtype) return y + dy return", "scan_func = self._make_scan_func(self.model.f) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0], y_grid], axis=0)", "Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype) k1 =", "return scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for solving SDEs dx = f(x)*dt", "__init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt = x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for i in", "pass @abstractmethod def _make_scan_func(self): pass class ODERK4(Integrator): \"\"\" Runge-Kutta implementation for solving ODEs", "dy = self._step_func(f, dt, t, y) dy = math_ops.cast(dy, dtype=y.dtype) return y +", "import array_ops from tensorflow.python.framework import ops from abc import ABC, abstractmethod float_type =", "ODERK4(Integrator): \"\"\" Runge-Kutta implementation for solving ODEs \"\"\" def __init__(self,model): super().__init__(model) def forward(self,x0,ts):", "+ g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt = t_dt dy = self._step_func(f,g,t,dt,y)", "for integrators \"\"\" def __init__(self,model): self.model= model @abstractmethod def forward(self): pass @abstractmethod def", "ops from abc import ABC, abstractmethod float_type = tf.float64 class Integrator(ABC): \"\"\" Base", "= math_ops.cast(dy, dtype=y.dtype) return y + dy return scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama", "super().__init__(model) self.s = s def forward(self,x0,ts,Nw=1): Xs = np.zeros(len(ts),dtype=np.object) for i in range(len(ts)):", "model @abstractmethod def forward(self): pass @abstractmethod def _step_func(self): pass @abstractmethod def _make_scan_func(self): pass", "x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt = t_dt", "forward(self,x0,ts): Nt = x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for i in range(Nt): time_grid =", "(time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def", "k4]) * (dt / 6) def _make_scan_func(self,f): def scan_func(y, t_dt): t, dt =", "y + dy return scan_func class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for solving SDEs", "class ODERK4(Integrator): \"\"\" Runge-Kutta implementation for solving ODEs \"\"\" def __init__(self,model): super().__init__(model) def", "f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt = t_dt dy =", "t) k2 = f(y + dt*k1/2, t+dt/2) k3 = f(y + dt*k2/2, t+dt/2)", "dy = self._step_func(f,g,t,dt,y) dy = math_ops.cast(dy, dtype=y.dtype) return y + dy return scan_func", "as tf from tensorflow.python.ops import math_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import", "tf from tensorflow.python.ops import math_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import array_ops", "array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt,", "class SDEEM(Integrator): \"\"\" Euler-Maruyama implementation for solving SDEs dx = f(x)*dt + g*sqrt(dt)", "tensorflow.python.framework import ops from abc import ABC, abstractmethod float_type = tf.float64 class Integrator(ABC):", "k1 = f(y, t) k2 = f(y + dt*k1/2, t+dt/2) k3 = f(y", "functional_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops from abc import ABC,", "pass class ODERK4(Integrator): \"\"\" Runge-Kutta implementation for solving ODEs \"\"\" def __init__(self,model): super().__init__(model)", "tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype) k1 = f(y, t)", "solving SDEs dx = f(x)*dt + g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model) self.s =", "y.dtype) k1 = f(y, t) k2 = f(y + dt*k1/2, t+dt/2) k3 =", "= functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return", "@abstractmethod def _make_scan_func(self): pass class ODERK4(Integrator): \"\"\" Runge-Kutta implementation for solving ODEs \"\"\"", "= tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype) k1 = f(y,", "def forward(self,x0,ts): Nt = x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for i in range(Nt): time_grid", "6) def _make_scan_func(self,f): def scan_func(y, t_dt): t, dt = t_dt dy = self._step_func(f,", "scan_func(y, t_dt): t, dt = t_dt dy = self._step_func(f, dt, t, y) dy", "dt, t, y) dy = math_ops.cast(dy, dtype=y.dtype) return y + dy return scan_func", "in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i]) )[0]", "= ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:] - time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0", "y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype)", "- time_grid[:-1] y0 = np.repeat(x0[i,:].reshape((1,-1)),Nw,axis=0) y0 = ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid", "= ops.convert_to_tensor(y0, name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys =", "name='y0') scan_func = self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0], y_grid],", "t, dt = t_dt dy = self._step_func(f, dt, t, y) dy = math_ops.cast(dy,", "implementation for solving ODEs \"\"\" def __init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt = x0.shape[0]", "Nt = x0.shape[0] Xs = np.zeros(Nt,dtype=np.object) for i in range(Nt): time_grid = ops.convert_to_tensor(ts[i],", "t = np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1]) time_grid =", "time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:] -", "t+dt/2) k4 = f(y + dt*k3, t+dt) return math_ops.add_n([k1, 2*k2, 2*k3, k4]) *", "t+dt/2) k3 = f(y + dt*k2/2, t+dt/2) k4 = f(y + dt*k3, t+dt)", "as np import tensorflow as tf from tensorflow.python.ops import math_ops from tensorflow.python.ops import", "\"\"\" Euler-Maruyama implementation for solving SDEs dx = f(x)*dt + g*sqrt(dt) \"\"\" def", "np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid = time_grid[1:] - time_grid[:-1] y0 =", "ys = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x): dt", "integrators \"\"\" def __init__(self,model): self.model= model @abstractmethod def forward(self): pass @abstractmethod def _step_func(self):", "Xs = np.zeros(len(ts),dtype=np.object) for i in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i]))))", "self._make_scan_func(self.model.f,self.model.diffus.g) y_grid = functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) ys = array_ops.concat([[y0], y_grid], axis=0) Xs[i] =", "pass @abstractmethod def _step_func(self): pass @abstractmethod def _make_scan_func(self): pass class ODERK4(Integrator): \"\"\" Runge-Kutta", "class Integrator(ABC): \"\"\" Base class for integrators \"\"\" def __init__(self,model): self.model= model @abstractmethod", "= self._step_func(f, dt, t, y) dy = math_ops.cast(dy, dtype=y.dtype) return y + dy", "for solving SDEs dx = f(x)*dt + g*sqrt(dt) \"\"\" def __init__(self,model,s=1): super().__init__(model) self.s", "def scan_func(y, t_dt): t, dt = t_dt dy = self._step_func(f, dt, t, y)", "self._step_func(f, dt, t, y) dy = math_ops.cast(dy, dtype=y.dtype) return y + dy return", "np.where( np.isin(t,ts[i]) )[0] t = np.reshape(t,[-1,1]) time_grid = ops.convert_to_tensor(t, preferred_dtype=float_type, name='t') time_delta_grid =", "_make_scan_func(self,f,g): def scan_func(y, t_dt): t,dt = t_dt dy = self._step_func(f,g,t,dt,y) dy = math_ops.cast(dy,", "tensorflow.python.ops import math_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework", "i in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where( np.isin(t,ts[i])", "abc import ABC, abstractmethod float_type = tf.float64 class Integrator(ABC): \"\"\" Base class for", "= f(y + dt*k3, t+dt) return math_ops.add_n([k1, 2*k2, 2*k3, k4]) * (dt /", "= t_dt dy = self._step_func(f,g,t,dt,y) dy = math_ops.cast(dy, dtype=y.dtype) return y + dy", "import ops from abc import ABC, abstractmethod float_type = tf.float64 class Integrator(ABC): \"\"\"", "axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs def _step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype) k1", "i in range(Nt): time_grid = ops.convert_to_tensor(ts[i], preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid", "for i in range(len(ts)): t = np.linspace(0,np.max(ts[i]),(len(ts[i])-1)*self.s+1) t = np.unique(np.sort(np.hstack((t,ts[i])))) idx = np.where(", "\"\"\" Runge-Kutta implementation for solving ODEs \"\"\" def __init__(self,model): super().__init__(model) def forward(self,x0,ts): Nt", "_step_func(self,f,dt,t,y): dt = math_ops.cast(dt, y.dtype) k1 = f(y, t) k2 = f(y +", "functional_ops.scan(scan_func, (time_grid[:-1],time_delta_grid), y0) y_s = array_ops.concat([[y0], y_grid], axis=0) Xs[i] = tf.reshape(tf.squeeze(y_s),[len(ts[i]),self.model.D]) return Xs", "Xs[i] = tf.transpose(tf.gather(ys,idx,axis=0),[1,0,2]) return Xs def _step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype) return f(x,t)*dt", "_step_func(self,f,g,t,dt,x): dt = math_ops.cast(dt, x.dtype) return f(x,t)*dt + g(x,t)*tf.sqrt(dt) def _make_scan_func(self,f,g): def scan_func(y,", "preferred_dtype=float_type, name='t') y0 = ops.convert_to_tensor(x0[i,:].reshape((1,-1)), name='y0') time_delta_grid = time_grid[1:] - time_grid[:-1] scan_func =" ]
[ "r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0])", "self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\",", "sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5)", "[self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero = self.get_selected_hero(lst) if hero is not None: self.update_stats_listbox(hero)", "ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"), ) self.stats_scl =", "lambda event: self.search(event)) # hero list self.heroes = dict() self.hero_frm = ttk.Frame(self, borderwidth=0)", "\"wb\") as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if ( event.widget.winfo_class() ==", "hero in hero list, fetching stats if necessary def get_selected_hero(self, lst: SearchListbox) ->", "ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda:", "= self.get_selected_hero(lst) if hero is not None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self,", "self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe cached stats and fetch fresh stats for", "team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently selected hero in hero list, fetching stats if", "): if isinstance(hero_or_team, Hero) or hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0)", "idx = lst.curselection() hero: Hero = None # use Optional? do something different?", "doable by deleting heroes.dat before run def refresh_heroes(self): self.init_heroes() self.wipe_stats() # button action", "def add_hero(self, team: Team, team_lst): hero: Hero = self.get_selected_hero(self.hero_lst) if hero is not", "column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW)", "hero is not None and team.add_hero(hero): team_lst.append(hero.name) # button action def remove_hero(self, team,", "= Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has no button; doable by deleting heroes.dat", "# hero list self.heroes = dict() self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm,", "self.get_selected_hero(self.hero_lst) if hero is not None and team.add_hero(hero): team_lst.append(hero.name) # button action def", "column=1) self.clear_stats_btn.grid(row=1, column=2) # team 1 selected by default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset()", "ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3,", "in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS)", "ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0)", "self.init_heroes() self.wipe_stats() # button action def add_hero(self, team: Team, team_lst): hero: Hero =", "rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def", "borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"),", "different? if idx: hero = self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats() return hero #", "team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def", "self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\",", "self.stats_lst = SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list()", "hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed on window close", "teams def wipe_stats(self): for hero in self.heroes.values(): hero.stats = dict() for hero in", "or teams for lst in [self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero = self.get_selected_hero(lst) if", "self.team1_lst), ) self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn =", "import ttk from Hero import Hero from SearchListbox import SearchListbox from Team import", "in self.heroes.values(): hero.stats = dict() for hero in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0,", "self.team2_lst]: hero: Hero = self.get_selected_hero(lst) if hero is not None: self.update_stats_listbox(hero) break else:", "lists self.team1 = Team() self.team2 = Team() self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst =", "pickle import re import requests import tkinter from tkinter import ttk from Hero", "= ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() # stats list self.stats_frm", "item: item[1], reverse=True, ): if isinstance(hero_or_team, Hero) or hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20}", "height=5) self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0)", "# initialize hero dict and SearchListbox def init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\":", "ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, )", "text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb", "self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def", "list or teams for lst in [self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero = self.get_selected_hero(lst)", "self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() # stats list self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl =", "hero # button action def show_stats(self): if self.show_rb_var.get() == \"hero\": # can select", "ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\",", "f: self.heroes = pickle.load(f) else: self.init_heroes() for name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview)", "column=2) # team 1 selected by default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0,", "SearchListbox def init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes", "= ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\",", ") self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() # stats", "not hero.stats: hero.fetch_stats() return hero # button action def show_stats(self): if self.show_rb_var.get() ==", ") self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn = ttk.Button(", "init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0,", "self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl =", "initialize hero dict and SearchListbox def init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"}", "hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed on window close def write_stats(self): with", "# unused, has no button; doable by deleting heroes.dat before run def refresh_heroes(self):", "hero, stat in sorted( hero_or_team.stats.items(), key=lambda item: item[1], reverse=True, ): if isinstance(hero_or_team, Hero)", "dict() for hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(),", "\"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes = dict() for hero_info in re.findall(", "\"<space>\") # how to rebind action to Enter? self.root.bind(\"<Key>\", lambda event: self.search(event)) #", "if not hero.stats: hero.fetch_stats() return hero # button action def show_stats(self): if self.show_rb_var.get()", "def __init__(self, root=None): super().__init__(root) self.root = root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how", "text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3)", "button; doable by deleting heroes.dat before run def refresh_heroes(self): self.init_heroes() self.wipe_stats() # button", "init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0,", "self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0)", "self.search(event)) # hero list self.heroes = dict() self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst =", "button action def add_hero(self, team: Team, team_lst): hero: Hero = self.get_selected_hero(self.hero_lst) if hero", "for hero in self.heroes.values(): hero.stats = dict() for hero in self.team1.heroes + self.team2.heroes:", "stats list self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox(", "self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2,", "command=self.wipe_stats, ) self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as f: self.heroes", "column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl", "as f: self.heroes = pickle.load(f) else: self.init_heroes() for name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set)", "value=\"hero\", ) self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn = ttk.Button( self.controls_lfrm,", "self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0)", "Hero = self.get_selected_hero(lst) if hero is not None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def", "text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst),", "self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): # better way to handle hero", "run def refresh_heroes(self): self.init_heroes() self.wipe_stats() # button action def add_hero(self, team: Team, team_lst):", "team, team_lst): idx = team_lst.curselection() if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get", "minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS)", "tkinter from tkinter import ttk from Hero import Hero from SearchListbox import SearchListbox", "= ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists self.team1 = Team() self.team2 = Team() self.team_frm", "self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1,", "= None # use Optional? do something different? if idx: hero = self.heroes[lst.get(idx[0])]", "import SearchListbox from Team import Team class Window(ttk.Frame): def __init__(self, root=None): super().__init__(root) self.root", "= ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\",", "hero: Hero = self.get_selected_hero(lst) if hero is not None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\"))", "to handle hero or team? self.stats_lst.delete(0, tkinter.END) for hero, stat in sorted( hero_or_team.stats.items(),", "column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) # team 1 selected", "weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1)", "for hero in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize hero dict", "column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self):", "in [self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero = self.get_selected_hero(lst) if hero is not None:", "write_stats(self): with open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if", ") self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn = ttk.Button(", "self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists self.team1 =", "stats if necessary def get_selected_hero(self, lst: SearchListbox) -> Hero: idx = lst.curselection() hero:", "= SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove buttons self.add_rem_frm =", "team_lst): idx = team_lst.curselection() if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently", "self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", )", "Hero = self.get_selected_hero(self.hero_lst) if hero is not None and team.add_hero(hero): team_lst.append(hero.name) # button", "= requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes = dict() for hero_info", "close def write_stats(self): with open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def", "necessary def get_selected_hero(self, lst: SearchListbox) -> Hero: idx = lst.curselection() hero: Hero =", "if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as f: self.heroes = pickle.load(f) else: self.init_heroes() for", "self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8,", "self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) # team 1 selected by default self.show_team1_rb.invoke() def clear_teams(self):", "self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe cached stats", "self.init_hero_list() # team lists self.team1 = Team() self.team2 = Team() self.team_frm = ttk.Frame(self,", "team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1)", "remove_hero(self, team, team_lst): idx = team_lst.curselection() if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) #", "if isinstance(hero_or_team, Hero) or hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) #", "value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn = ttk.Button(", "requests import tkinter from tkinter import ttk from Hero import Hero from SearchListbox", "to rebind action to Enter? self.root.bind(\"<Key>\", lambda event: self.search(event)) # hero list self.heroes", "event: self.search(event)) # hero list self.heroes = dict() self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst", "fetch fresh stats for heroes on teams def wipe_stats(self): for hero in self.heroes.values():", "sorted( hero_or_team.stats.items(), key=lambda item: item[1], reverse=True, ): if isinstance(hero_or_team, Hero) or hero not", "self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1,", "init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes = dict()", "font=(\"Courier\", \"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\")", "re import requests import tkinter from tkinter import ttk from Hero import Hero", "column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0,", "__init__(self, root=None): super().__init__(root) self.root = root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how to", "requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes = dict() for hero_info in", "command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), )", "# wipe cached stats and fetch fresh stats for heroes on teams def", "self.init_team_lists() # add/remove buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\",", "self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed on window close def write_stats(self): with open(\"heroes.dat\",", "SearchListbox from Team import Team class Window(ttk.Frame): def __init__(self, root=None): super().__init__(root) self.root =", "SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove buttons self.add_rem_frm = ttk.Frame(self,", "tkinter import ttk from Hero import Hero from SearchListbox import SearchListbox from Team", "self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1,", "1 selected by default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END)", "is not None and team.add_hero(hero): team_lst.append(hero.name) # button action def remove_hero(self, team, team_lst):", "hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS)", "sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1,", "\"rb\") as f: self.heroes = pickle.load(f) else: self.init_heroes() for name in self.heroes.keys(): self.hero_lst.append(name)", "ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists self.team1 = Team() self.team2 = Team() self.team_frm =", "action to Enter? self.root.bind(\"<Key>\", lambda event: self.search(event)) # hero list self.heroes = dict()", "column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2,", "os import pickle import re import requests import tkinter from tkinter import ttk", "= dict() for hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text", "page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes = dict() for", "from tkinter import ttk from Hero import Hero from SearchListbox import SearchListbox from", "rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1)", "def write_stats(self): with open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event):", "hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0,", "command=self.clear_teams, ) self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def init_hero_list(self): if", "@staticmethod def search(event): if ( event.widget.winfo_class() == \"Listbox\" and (event.char.isalpha() or event.char ==", "self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) # team 1 selected by", "column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1)", "self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats,", "import os import pickle import re import requests import tkinter from tkinter import", "= ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, )", "= tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton(", "text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn =", "class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) #", "+ self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize hero dict and SearchListbox def init_heroes(self):", "self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as f: self.heroes = pickle.load(f)", "controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\",", "self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): # better way to handle hero or team? self.stats_lst.delete(0,", "idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently selected hero in hero list, fetching", "column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) # team", "deleting heroes.dat before run def refresh_heroes(self): self.init_heroes() self.wipe_stats() # button action def add_hero(self,", "item[1], reverse=True, ): if isinstance(hero_or_team, Hero) or hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\")", "action def add_hero(self, team: Team, team_lst): hero: Hero = self.get_selected_hero(self.hero_lst) if hero is", "self.team2_lst), ) self.init_add_rem_buttons() # stats list self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm,", ") self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn = ttk.Button( self.controls_lfrm,", "import tkinter from tkinter import ttk from Hero import Hero from SearchListbox import", "to Enter? self.root.bind(\"<Key>\", lambda event: self.search(event)) # hero list self.heroes = dict() self.hero_frm", "open(\"heroes.dat\", \"rb\") as f: self.heroes = pickle.load(f) else: self.init_heroes() for name in self.heroes.keys():", "team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3)", "f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if ( event.widget.winfo_class() == \"Listbox\" and (event.char.isalpha() or", "buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst),", "\"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var", "team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6,", "self.init_heroes() for name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0,", "= ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var,", "self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn = ttk.Button( self.add_rem_frm,", "ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\")", "self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0,", "self.clear_stats_btn.grid(row=1, column=2) # team 1 selected by default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset()", "import Team class Window(ttk.Frame): def __init__(self, root=None): super().__init__(root) self.root = root self.root.title(\"teamcomp\") self.grid()", "clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe cached stats and fetch", "self.wipe_stats() # button action def add_hero(self, team: Team, team_lst): hero: Hero = self.get_selected_hero(self.hero_lst)", "hero.stats: hero.fetch_stats() return hero # button action def show_stats(self): if self.show_rb_var.get() == \"hero\":", "hero.fetch_stats() return hero # button action def show_stats(self): if self.show_rb_var.get() == \"hero\": #", "hero from full list or teams for lst in [self.hero_lst, self.team1_lst, self.team2_lst]: hero:", "full list or teams for lst in [self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero =", "team lists self.team1 = Team() self.team2 = Team() self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst", "column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0,", "dict() self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list()", "self.team2_lst), ) self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() #", "default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe cached", "show_stats(self): if self.show_rb_var.get() == \"hero\": # can select a hero from full list", "= ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0,", "hero: Hero = self.get_selected_hero(self.hero_lst) if hero is not None and team.add_hero(hero): team_lst.append(hero.name) #", "None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): # better way to handle", "SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists self.team1 = Team() self.team2", "self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats() return hero # button action def show_stats(self): if", "if idx: hero = self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats() return hero # button", "def init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes =", "sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3,", "= ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\",", "self.stats_lst.delete(0, tkinter.END) for hero, stat in sorted( hero_or_team.stats.items(), key=lambda item: item[1], reverse=True, ):", "= ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var,", ") self.init_add_rem_buttons() # stats list self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\")", "def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0,", "== \"hero\": # can select a hero from full list or teams for", "command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), )", "self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize hero dict and SearchListbox def", "rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl =", "if necessary def get_selected_hero(self, lst: SearchListbox) -> Hero: idx = lst.curselection() hero: Hero", "lst.curselection() hero: Hero = None # use Optional? do something different? if idx:", "def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe cached stats and", "unused, has no button; doable by deleting heroes.dat before run def refresh_heroes(self): self.init_heroes()", "SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls", "def get_selected_hero(self, lst: SearchListbox) -> Hero: idx = lst.curselection() hero: Hero = None", ") self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var =", "= ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team", "self.hero_lst.delete(0, tkinter.END) self.heroes = dict() for hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search(", "def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as f: self.heroes = pickle.load(f) else:", "column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm,", "column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1,", "re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused,", "# use Optional? do something different? if idx: hero = self.heroes[lst.get(idx[0])] if not", "wipe cached stats and fetch fresh stats for heroes on teams def wipe_stats(self):", "def update_stats_listbox(self, hero_or_team): # better way to handle hero or team? self.stats_lst.delete(0, tkinter.END)", "Hero from SearchListbox import SearchListbox from Team import Team class Window(ttk.Frame): def __init__(self,", ") self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"):", "ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\",", "Enter? self.root.bind(\"<Key>\", lambda event: self.search(event)) # hero list self.heroes = dict() self.hero_frm =", "self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def", "team_lst.curselection() if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently selected hero in", "stats for heroes on teams def wipe_stats(self): for hero in self.heroes.values(): hero.stats =", "heroes.dat before run def refresh_heroes(self): self.init_heroes() self.wipe_stats() # button action def add_hero(self, team:", "team 1 selected by default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0,", "self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn = ttk.Button( self.add_rem_frm,", "in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize hero dict and SearchListbox", "how to rebind action to Enter? self.root.bind(\"<Key>\", lambda event: self.search(event)) # hero list", "\"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes = dict() for hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div", "self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0,", "with open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if (", "button action def remove_hero(self, team, team_lst): idx = team_lst.curselection() if not idx: return", "self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1)", "self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", )", "r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has", "teams for lst in [self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero = self.get_selected_hero(lst) if hero", "self.hero_lst.append(hero_info[1]) # unused, has no button; doable by deleting heroes.dat before run def", "for hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ):", "tkinter.END) # wipe cached stats and fetch fresh stats for heroes on teams", "rebind action to Enter? self.root.bind(\"<Key>\", lambda event: self.search(event)) # hero list self.heroes =", "hero in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize hero dict and", "in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed on window close def write_stats(self):", "self.team2 = Team() self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst =", "rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N)", "width=26, font=(\"Courier\", \"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm = ttk.LabelFrame(self,", "command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() # stats list self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl", "self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1,", "self.get_selected_hero(lst) if hero is not None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team):", "not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed on window close def", "sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\")", "os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as f: self.heroes = pickle.load(f) else: self.init_heroes() for name", "# how to rebind action to Enter? self.root.bind(\"<Key>\", lambda event: self.search(event)) # hero", "ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7,", "self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams,", "on window close def write_stats(self): with open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL)", "selected by default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) #", "init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set)", "= SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists self.team1 = Team()", "team_lst.delete(idx[0]) # get currently selected hero in hero list, fetching stats if necessary", "if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently selected hero in hero", "minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40)", "not None and team.add_hero(hero): team_lst.append(hero.name) # button action def remove_hero(self, team, team_lst): idx", "before run def refresh_heroes(self): self.init_heroes() self.wipe_stats() # button action def add_hero(self, team: Team,", "lst in [self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero = self.get_selected_hero(lst) if hero is not", "action def remove_hero(self, team, team_lst): idx = team_lst.curselection() if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])])", ") self.hero_lst.delete(0, tkinter.END) self.heroes = dict() for hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>',", "tkinter.END) self.heroes = dict() for hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div", "for heroes on teams def wipe_stats(self): for hero in self.heroes.values(): hero.stats = dict()", "team? self.stats_lst.delete(0, tkinter.END) for hero, stat in sorted( hero_or_team.stats.items(), key=lambda item: item[1], reverse=True,", "# stats list self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst =", "self.heroes = pickle.load(f) else: self.init_heroes() for name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl", "team_lst.append(hero.name) # button action def remove_hero(self, team, team_lst): idx = team_lst.curselection() if not", "self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3)", "self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm", "window close def write_stats(self): with open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod", "command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), )", "if ( event.widget.winfo_class() == \"Listbox\" and (event.char.isalpha() or event.char == \" \") ):", "self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with", "with open(\"heroes.dat\", \"rb\") as f: self.heroes = pickle.load(f) else: self.init_heroes() for name in", "column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1,", "= pickle.load(f) else: self.init_heroes() for name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl =", "= root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how to rebind action to Enter?", "self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) # team 1 selected by default self.show_team1_rb.invoke()", "page.text ).group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has no button;", "hero = self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats() return hero # button action def", "hero is not None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): # better", "self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1,", "# get currently selected hero in hero list, fetching stats if necessary def", "text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst),", "else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): # better way to handle hero or team?", "reverse=True, ): if isinstance(hero_or_team, Hero) or hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1,", "-> Hero: idx = lst.curselection() hero: Hero = None # use Optional? do", "Team() self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm, height=5)", "def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N)", "def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self):", "= team_lst.curselection() if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently selected hero", "self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn = ttk.Button( self.add_rem_frm,", "Hero: idx = lst.curselection() hero: Hero = None # use Optional? do something", "text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def", "= ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\",", "and SearchListbox def init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END)", "list self.heroes = dict() self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl", "self.stats_lst.grid(row=1, column=0) # performed on window close def write_stats(self): with open(\"heroes.dat\", \"wb\") as", "None and team.add_hero(hero): team_lst.append(hero.name) # button action def remove_hero(self, team, team_lst): idx =", "Hero import Hero from SearchListbox import SearchListbox from Team import Team class Window(ttk.Frame):", "from Team import Team class Window(ttk.Frame): def __init__(self, root=None): super().__init__(root) self.root = root", "= ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, )", "text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5)", "pickle.load(f) else: self.init_heroes() for name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm,", "height=20, width=26, font=(\"Courier\", \"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm =", "fetching stats if necessary def get_selected_hero(self, lst: SearchListbox) -> Hero: idx = lst.curselection()", "column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3,", "key=lambda item: item[1], reverse=True, ): if isinstance(hero_or_team, Hero) or hero not in hero_or_team.heroes:", "get_selected_hero(self, lst: SearchListbox) -> Hero: idx = lst.curselection() hero: Hero = None #", "self.root = root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how to rebind action to", "idx: hero = self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats() return hero # button action", "class Window(ttk.Frame): def __init__(self, root=None): super().__init__(root) self.root = root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\")", "self.root.unbind_class(\"Listbox\", \"<space>\") # how to rebind action to Enter? self.root.bind(\"<Key>\", lambda event: self.search(event))", "Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has no button; doable by deleting heroes.dat before", "search(event): if ( event.widget.winfo_class() == \"Listbox\" and (event.char.isalpha() or event.char == \" \")", "and fetch fresh stats for heroes on teams def wipe_stats(self): for hero in", "tkinter.END) for hero, stat in sorted( hero_or_team.stats.items(), key=lambda item: item[1], reverse=True, ): if", "borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn = ttk.Button(", "Hero = None # use Optional? do something different? if idx: hero =", "# button action def show_stats(self): if self.show_rb_var.get() == \"hero\": # can select a", "and team.add_hero(hero): team_lst.append(hero.name) # button action def remove_hero(self, team, team_lst): idx = team_lst.curselection()", "in hero list, fetching stats if necessary def get_selected_hero(self, lst: SearchListbox) -> Hero:", "do something different? if idx: hero = self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats() return", "def show_stats(self): if self.show_rb_var.get() == \"hero\": # can select a hero from full", "self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1,", "or hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed on window", "= ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20)", "column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2)", "root=None): super().__init__(root) self.root = root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how to rebind", "self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how to rebind action to Enter? self.root.bind(\"<Key>\", lambda", "button action def show_stats(self): if self.show_rb_var.get() == \"hero\": # can select a hero", "init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as f: self.heroes = pickle.load(f) else: self.init_heroes()", "stat in sorted( hero_or_team.stats.items(), key=lambda item: item[1], reverse=True, ): if isinstance(hero_or_team, Hero) or", "f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if ( event.widget.winfo_class() == \"Listbox\" and", "): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has no button; doable by", "name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2,", "from full list or teams for lst in [self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero", "self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1,", ") self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as f: self.heroes =", "re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1],", "= ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats,", "ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda:", "self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var,", "self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview)", "self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists self.team1 = Team() self.team2 = Team()", "or team? self.stats_lst.delete(0, tkinter.END) for hero, stat in sorted( hero_or_team.stats.items(), key=lambda item: item[1],", "ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists", "ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls()", "# better way to handle hero or team? self.stats_lst.delete(0, tkinter.END) for hero, stat", "init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0)", "weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2)", "dict() for hero in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize hero", "list self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm,", ") self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\",", "# performed on window close def write_stats(self): with open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes,", "# team 1 selected by default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END)", "hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has no button; doable by deleting heroes.dat before run", "handle hero or team? self.stats_lst.delete(0, tkinter.END) for hero, stat in sorted( hero_or_team.stats.items(), key=lambda", "= SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn =", "weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0)", "idx = team_lst.curselection() if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently selected", "Team() self.team2 = Team() self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst", "self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\")", "= ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn", "self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn", "self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how to rebind action to Enter? self.root.bind(\"<Key>\", lambda event:", "= self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats() return hero # button action def show_stats(self):", "self.team2_lst.delete(0, tkinter.END) # wipe cached stats and fetch fresh stats for heroes on", "Hero) or hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed on", "value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton(", "tkinter.END) # initialize hero dict and SearchListbox def init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\",", "ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", )", "Optional? do something different? if idx: hero = self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats()", "import Hero from SearchListbox import SearchListbox from Team import Team class Window(ttk.Frame): def", "= SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() #", "= ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists() #", "= Team() self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm,", "def search(event): if ( event.widget.winfo_class() == \"Listbox\" and (event.char.isalpha() or event.char == \"", "= Team() self.team2 = Team() self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5)", "self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() #", ") self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\",", "# can select a hero from full list or teams for lst in", "hero_or_team.stats.items(), key=lambda item: item[1], reverse=True, ): if isinstance(hero_or_team, Hero) or hero not in", "in sorted( hero_or_team.stats.items(), key=lambda item: item[1], reverse=True, ): if isinstance(hero_or_team, Hero) or hero", "borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists self.team1", "self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm, height=20,", "self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\",", "column=0) # performed on window close def write_stats(self): with open(\"heroes.dat\", \"wb\") as f:", "def wipe_stats(self): for hero in self.heroes.values(): hero.stats = dict() for hero in self.team1.heroes", "self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2,", "self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe cached stats and fetch fresh", "column=0) def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2,", "ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\",", "column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl", "self.team1_lst, self.team2_lst]: hero: Hero = self.get_selected_hero(lst) if hero is not None: self.update_stats_listbox(hero) break", "in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]] =", "= ttk.Label(self.team_frm, text=\"Radiant\") team2_lbl = ttk.Label(self.team_frm, text=\"Dire\") self.team_frm.grid(row=0, column=2, sticky=tkinter.N) team1_lbl.grid(row=0, column=3) self.team1_lst.grid(row=1,", "self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn", "variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn =", "self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize hero dict and SearchListbox def init_heroes(self): page =", "sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2)", "self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"), )", "self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1,", "self.show_rb_var = tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb =", "column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0, column=1, sticky=tkinter.N) self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4)", "self.team1 = Team() self.team2 = Team() self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm,", "self.heroes = dict() self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl =", "text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() # stats list self.stats_frm = ttk.Frame(self, borderwidth=0)", "import requests import tkinter from tkinter import ttk from Hero import Hero from", "ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda:", "column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) # team 1 selected by default self.show_team1_rb.invoke() def", "self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() # stats list", "self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0)", "performed on window close def write_stats(self): with open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes, f,", "fresh stats for heroes on teams def wipe_stats(self): for hero in self.heroes.values(): hero.stats", "self.init_stats_list() # controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton(", "self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as", "root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how to rebind action to Enter? self.root.bind(\"<Key>\",", "sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self): team1_lbl = ttk.Label(self.team_frm,", "a hero from full list or teams for lst in [self.hero_lst, self.team1_lst, self.team2_lst]:", "for lst in [self.hero_lst, self.team1_lst, self.team2_lst]: hero: Hero = self.get_selected_hero(lst) if hero is", ").group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has no button; doable", "= dict() self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm)", "Team, team_lst): hero: Hero = self.get_selected_hero(self.hero_lst) if hero is not None and team.add_hero(hero):", "self.team_frm = ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists()", "self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) # team 1", "heroes on teams def wipe_stats(self): for hero in self.heroes.values(): hero.stats = dict() for", "hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]]", "if self.show_rb_var.get() == \"hero\": # can select a hero from full list or", "from SearchListbox import SearchListbox from Team import Team class Window(ttk.Frame): def __init__(self, root=None):", "protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if ( event.widget.winfo_class() == \"Listbox\" and (event.char.isalpha() or event.char", "self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1,", "text=\"Show\", command=self.show_stats, ) self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn = ttk.Button(", "stats and fetch fresh stats for heroes on teams def wipe_stats(self): for hero", "add_hero(self, team: Team, team_lst): hero: Hero = self.get_selected_hero(self.hero_lst) if hero is not None", "href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1])", "by deleting heroes.dat before run def refresh_heroes(self): self.init_heroes() self.wipe_stats() # button action def", "ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn", "self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove buttons self.add_rem_frm", "hero_or_team): # better way to handle hero or team? self.stats_lst.delete(0, tkinter.END) for hero,", "pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if ( event.widget.winfo_class() == \"Listbox\" and (event.char.isalpha()", "hero list self.heroes = dict() self.hero_frm = ttk.Frame(self, borderwidth=0) self.hero_lst = SearchListbox(self.hero_frm, height=20)", "sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1,", "variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn = ttk.Button(", "self.heroes.values(): hero.stats = dict() for hero in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END)", "team.add_hero(hero): team_lst.append(hero.name) # button action def remove_hero(self, team, team_lst): idx = team_lst.curselection() if", "if hero is not None and team.add_hero(hero): team_lst.append(hero.name) # button action def remove_hero(self,", "hero dict and SearchListbox def init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} )", "def remove_hero(self, team, team_lst): idx = team_lst.curselection() if not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0])", "self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2,", "text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn", "self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) #", "by default self.show_team1_rb.invoke() def clear_teams(self): self.team1.reset() self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe", "None # use Optional? do something different? if idx: hero = self.heroes[lst.get(idx[0])] if", "= ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm, height=20, width=26,", "team: Team, team_lst): hero: Hero = self.get_selected_hero(self.hero_lst) if hero is not None and", "text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb", "lst: SearchListbox) -> Hero: idx = lst.curselection() hero: Hero = None # use", "= lst.curselection() hero: Hero = None # use Optional? do something different? if", "# button action def add_hero(self, team: Team, team_lst): hero: Hero = self.get_selected_hero(self.hero_lst) if", "Team import Team class Window(ttk.Frame): def __init__(self, root=None): super().__init__(root) self.root = root self.root.title(\"teamcomp\")", "ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb =", "self.team1_lst), ) self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn =", "self.team1_lst.grid(row=1, column=3, rowspan=5) self.team_frm.grid_rowconfigure(6, minsize=20) team2_lbl.grid(row=7, column=3) self.team2_lst.grid(row=8, column=3, rowspan=5) def init_add_rem_buttons(self): self.add_rem_frm.grid(row=0,", "super().__init__(root) self.root = root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") # how to rebind action", "no button; doable by deleting heroes.dat before run def refresh_heroes(self): self.init_heroes() self.wipe_stats() #", "team_lst): hero: Hero = self.get_selected_hero(self.hero_lst) if hero is not None and team.add_hero(hero): team_lst.append(hero.name)", "headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0, tkinter.END) self.heroes = dict() for hero_info in re.findall( r'<a", "text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn = ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def init_hero_list(self):", "ttk.Frame(self, borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove", "hero list, fetching stats if necessary def get_selected_hero(self, lst: SearchListbox) -> Hero: idx", "select a hero from full list or teams for lst in [self.hero_lst, self.team1_lst,", "# button action def remove_hero(self, team, team_lst): idx = team_lst.curselection() if not idx:", "# controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm,", "ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() # stats list self.stats_frm =", "# add/remove buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda:", "hero in self.heroes.values(): hero.stats = dict() for hero in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats()", "on teams def wipe_stats(self): for hero in self.heroes.values(): hero.stats = dict() for hero", "self.add_rem_frm.grid_rowconfigure(0, minsize=40) self.team1_add_btn.grid(row=1) self.team1_rem_btn.grid(row=2) self.team2_add_btn.grid(row=3) self.team2_rem_btn.grid(row=4) def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2,", "if hero is not None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): #", "text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\", \"rb\") as f:", "action def show_stats(self): if self.show_rb_var.get() == \"hero\": # can select a hero from", "SearchListbox import SearchListbox from Team import Team class Window(ttk.Frame): def __init__(self, root=None): super().__init__(root)", "self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn", "self.add_hero(self.team2, self.team2_lst), ) self.team2_rem_btn = ttk.Button( self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons()", "self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1) self.controls_lfrm.grid(row=1, column=1, columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0,", "ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), ) self.team1_rem_btn =", "tkinter.StringVar() self.show_team1_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Radiant\", variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm,", "self.team2.reset() self.team1_lst.delete(0, tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe cached stats and fetch fresh stats", "cached stats and fetch fresh stats for heroes on teams def wipe_stats(self): for", "self.stats_lst.delete(0, tkinter.END) # initialize hero dict and SearchListbox def init_heroes(self): page = requests.get(", "hero: Hero = None # use Optional? do something different? if idx: hero", "def refresh_heroes(self): self.init_heroes() self.wipe_stats() # button action def add_hero(self, team: Team, team_lst): hero:", "else: self.init_heroes() for name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\")", "return hero # button action def show_stats(self): if self.show_rb_var.get() == \"hero\": # can", "has no button; doable by deleting heroes.dat before run def refresh_heroes(self): self.init_heroes() self.wipe_stats()", "break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): # better way to handle hero or", "SearchListbox) -> Hero: idx = lst.curselection() hero: Hero = None # use Optional?", "= ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"), ) self.stats_scl", "for hero, stat in sorted( hero_or_team.stats.items(), key=lambda item: item[1], reverse=True, ): if isinstance(hero_or_team,", "get currently selected hero in hero list, fetching stats if necessary def get_selected_hero(self,", "open(\"heroes.dat\", \"wb\") as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if ( event.widget.winfo_class()", "not None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): # better way to", "( event.widget.winfo_class() == \"Listbox\" and (event.char.isalpha() or event.char == \" \") ): event.widget.search(event.char)", "dict and SearchListbox def init_heroes(self): page = requests.get( \"https://www.dotabuff.com/heroes\", headers={\"user-agent\": \"Mozilla/5.0\"} ) self.hero_lst.delete(0,", "class=\"hero-grid\">[\\s\\S]+</div></footer></section>', page.text ).group(), ): self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has no", "Team class Window(ttk.Frame): def __init__(self, root=None): super().__init__(root) self.root = root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\",", "way to handle hero or team? self.stats_lst.delete(0, tkinter.END) for hero, stat in sorted(", "self.init_add_rem_buttons() # stats list self.stats_frm = ttk.Frame(self, borderwidth=0) self.stats_lbl = ttk.Label(self.stats_frm, text=\"Counters\") self.stats_lst", "self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self): self.controls_lfrm.grid_columnconfigure(0, weight=1) self.controls_lfrm.grid_columnconfigure(1, weight=1) self.controls_lfrm.grid_columnconfigure(2, weight=1)", "return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently selected hero in hero list, fetching stats", "def init_stats_list(self): self.stats_lst.config(yscrollcommand=self.stats_scl.set) self.stats_scl.config(command=self.stats_lst.yview) self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS)", "text=\"<--\", command=lambda: self.remove_hero(self.team1, self.team1_lst), ) self.team2_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team2, self.team2_lst),", "wipe_stats(self): for hero in self.heroes.values(): hero.stats = dict() for hero in self.team1.heroes +", "self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize hero dict and SearchListbox def init_heroes(self): page", "self.heroes[hero_info[1]] = Hero(hero_info[1], hero_info[0]) self.hero_lst.append(hero_info[1]) # unused, has no button; doable by deleting", "isinstance(hero_or_team, Hero) or hero not in hero_or_team.heroes: self.stats_lst.append_stat(f\"{hero:20} {stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed", "import pickle import re import requests import tkinter from tkinter import ttk from", ") self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb = ttk.Radiobutton( self.controls_lfrm,", "can select a hero from full list or teams for lst in [self.hero_lst,", "height=5) self.init_team_lists() # add/remove buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm,", "hero.stats = dict() for hero in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) #", "tkinter.END) self.team2_lst.delete(0, tkinter.END) # wipe cached stats and fetch fresh stats for heroes", "use Optional? do something different? if idx: hero = self.heroes[lst.get(idx[0])] if not hero.stats:", "add/remove buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1,", "hero or team? self.stats_lst.delete(0, tkinter.END) for hero, stat in sorted( hero_or_team.stats.items(), key=lambda item:", "= self.get_selected_hero(self.hero_lst) if hero is not None and team.add_hero(hero): team_lst.append(hero.name) # button action", "better way to handle hero or team? self.stats_lst.delete(0, tkinter.END) for hero, stat in", "self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button( self.add_rem_frm, text=\"-->\", command=lambda: self.add_hero(self.team1, self.team1_lst), )", "\"hero\": # can select a hero from full list or teams for lst", "borderwidth=0) self.team1_lst = SearchListbox(self.team_frm, height=5) self.team2_lst = SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove buttons", "{stat:+.2f}\") self.stats_lst.grid(row=1, column=0) # performed on window close def write_stats(self): with open(\"heroes.dat\", \"wb\")", "Window(ttk.Frame): def __init__(self, root=None): super().__init__(root) self.root = root self.root.title(\"teamcomp\") self.grid() self.root.unbind_class(\"Listbox\", \"<space>\") #", "= dict() for hero in self.team1.heroes + self.team2.heroes: self.heroes[hero.name].fetch_stats() self.stats_lst.delete(0, tkinter.END) # initialize", "from Hero import Hero from SearchListbox import SearchListbox from Team import Team class", "# team lists self.team1 = Team() self.team2 = Team() self.team_frm = ttk.Frame(self, borderwidth=0)", "= ttk.Button( self.controls_lfrm, text=\"Wipe\", command=self.wipe_stats, ) self.init_controls() def init_hero_list(self): if os.path.isfile(\"heroes.dat\"): with open(\"heroes.dat\",", "= ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar() self.show_team1_rb", "for name in self.heroes.keys(): self.hero_lst.append(name) self.hero_lst.config(yscrollcommand=self.hero_scl.set) self.hero_scl.config(command=self.hero_lst.yview) hero_lbl = ttk.Label(self.hero_frm, text=\"Heroes\") self.hero_frm.grid(row=0, column=0,", "currently selected hero in hero list, fetching stats if necessary def get_selected_hero(self, lst:", "columnspan=2, sticky=tkinter.NSEW) self.show_team1_rb.grid(row=0, column=0) self.show_team2_rb.grid(row=0, column=1) self.show_hero_rb.grid(row=0, column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1,", "self.stats_scl = ttk.Scrollbar(self.stats_frm) self.init_stats_list() # controls self.controls_lfrm = ttk.LabelFrame(self, text=\"Controls\") self.show_rb_var = tkinter.StringVar()", "variable=self.show_rb_var, value=\"team1\", ) self.show_team2_rb = ttk.Radiobutton( self.controls_lfrm, text=\"Dire\", variable=self.show_rb_var, value=\"team2\", ) self.show_hero_rb =", "selected hero in hero list, fetching stats if necessary def get_selected_hero(self, lst: SearchListbox)", "self.controls_lfrm, text=\"Hero\", variable=self.show_rb_var, value=\"hero\", ) self.show_stats_btn = ttk.Button( self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn", "self.root.bind(\"<Key>\", lambda event: self.search(event)) # hero list self.heroes = dict() self.hero_frm = ttk.Frame(self,", "column=2) self.show_stats_btn.grid(row=1, column=0) self.reset_teams_btn.grid(row=1, column=1) self.clear_stats_btn.grid(row=1, column=2) # team 1 selected by default", "is not None: self.update_stats_listbox(hero) break else: self.update_stats_listbox(eval(f\"self.{self.show_rb_var.get()}\")) def update_stats_listbox(self, hero_or_team): # better way", "something different? if idx: hero = self.heroes[lst.get(idx[0])] if not hero.stats: hero.fetch_stats() return hero", "self.add_rem_frm, text=\"<--\", command=lambda: self.remove_hero(self.team2, self.team2_lst), ) self.init_add_rem_buttons() # stats list self.stats_frm = ttk.Frame(self,", "not idx: return team.remove_hero(self.heroes[team_lst.get(idx[0])]) team_lst.delete(idx[0]) # get currently selected hero in hero list,", "update_stats_listbox(self, hero_or_team): # better way to handle hero or team? self.stats_lst.delete(0, tkinter.END) for", "command=self.show_stats, ) self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn = ttk.Button( self.controls_lfrm,", "import re import requests import tkinter from tkinter import ttk from Hero import", "as f: pickle.dump(self.heroes, f, protocol=pickle.HIGHEST_PROTOCOL) @staticmethod def search(event): if ( event.widget.winfo_class() == \"Listbox\"", "ttk from Hero import Hero from SearchListbox import SearchListbox from Team import Team", "height=20) self.hero_scl = ttk.Scrollbar(self.hero_frm) self.init_hero_list() # team lists self.team1 = Team() self.team2 =", "self.hero_frm.grid(row=0, column=0, rowspan=2, sticky=tkinter.NS) self.hero_lst.grid(row=1, column=0) self.hero_scl.grid(row=1, column=1, sticky=tkinter.NS) hero_lbl.grid(row=0, column=0) def init_team_lists(self):", "self.show_rb_var.get() == \"hero\": # can select a hero from full list or teams", "SearchListbox(self.team_frm, height=5) self.init_team_lists() # add/remove buttons self.add_rem_frm = ttk.Frame(self, borderwidth=0) self.team1_add_btn = ttk.Button(", "self.heroes = dict() for hero_info in re.findall( r'<a href=\"/heroes/(.+?)\">.+?<div class=\"name\">(.+?)</div>', re.search( r'<div class=\"hero-grid\">[\\s\\S]+</div></footer></section>',", "refresh_heroes(self): self.init_heroes() self.wipe_stats() # button action def add_hero(self, team: Team, team_lst): hero: Hero", "list, fetching stats if necessary def get_selected_hero(self, lst: SearchListbox) -> Hero: idx =", "text=\"Counters\") self.stats_lst = SearchListbox( self.stats_frm, height=20, width=26, font=(\"Courier\", \"10\"), ) self.stats_scl = ttk.Scrollbar(self.stats_frm)", "self.controls_lfrm, text=\"Show\", command=self.show_stats, ) self.reset_teams_btn = ttk.Button( self.controls_lfrm, text=\"Clear\", command=self.clear_teams, ) self.clear_stats_btn =", "self.stats_frm.grid(row=0, column=3, rowspan=2, sticky=tkinter.NS) self.stats_lst.grid(row=1, column=0) self.stats_scl.grid(row=1, column=1, sticky=tkinter.NS) self.stats_lbl.grid(row=0, column=0) def init_controls(self):" ]
[ "networks=[network_cloud_user], scale=5) topology = Topology(nodes=[ *nodes_camera_1, node_detector_1, *nodes_camera_2, node_detector_2, node_historian, node_user ]) return", "num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources,", "network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources,", "NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker)", "<gh_stars>1-10 import json from docker.types import RestartPolicy from wotemu.enums import NetworkConditions from wotemu.topology.models", "NodeResources, Service, Topology) _ID_1 = \"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN", "user_app = NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\":", "import NetworkConditions from wotemu.topology.models import (Broker, BuiltinApps, Network, Node, NodeApp, NodeResources, Service, Topology)", "broker_network=network_edge) return nodes_camera, node_detector def topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 =", "cam_name} for cam_name in camera_hostnames ]) app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True)", "app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\":", "_THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN,", "import (Broker, BuiltinApps, Network, Node, NodeApp, NodeResources, Service, Topology) _ID_1 = \"loc1\" _ID_2", "]) app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector,", "= Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources(", "app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for idx in range(num_cameras) ] camera_hostnames = [ f\"{item.name}.{network.name}\"", "nodes_camera ] param_cameras = json.dumps([ {\"servient_host\": cam_name} for cam_name in camera_hostnames ]) app_detector", "in camera_hostnames ]) app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector = Node(", "\"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian = Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user])", "= [ f\"{item.name}.{network.name}\" for item in nodes_camera ] param_cameras = json.dumps([ {\"servient_host\": cam_name}", "import json from docker.types import RestartPolicy from wotemu.enums import NetworkConditions from wotemu.topology.models import", "node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster(", "\"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge, num_cameras, broker, camera_resources=None, detector_resources=None): network = Network( name=f\"field_{cluster_id}\",", "Service, Topology) _ID_1 = \"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN =", "for idx in range(num_cameras) ] camera_hostnames = [ f\"{item.name}.{network.name}\" for item in nodes_camera", "= NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources,", "= Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources(", "NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources,", "= _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo = Service( name=\"mongo\", image=\"mongo:4\",", "= \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge, num_cameras,", "= \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge, num_cameras, broker, camera_resources=None, detector_resources=None):", "item in nodes_camera ] param_cameras = json.dumps([ {\"servient_host\": cam_name} for cam_name in camera_hostnames", "networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1,", "\"params\": json.dumps({\"write\": None, \"list\": None}), \"lambd\": 5 }) node_user = Node( name=\"user\", app=user_app,", "NetworkConditions from wotemu.topology.models import (Broker, BuiltinApps, Network, Node, NodeApp, NodeResources, Service, Topology) _ID_1", "path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker,", "}, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True,", "docker.types import RestartPolicy from wotemu.enums import NetworkConditions from wotemu.topology.models import (Broker, BuiltinApps, Network,", "_build_detector_cluster( cluster_id, network_edge, num_cameras, broker, camera_resources=None, detector_resources=None): network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera", "Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200,", "broker=broker, broker_network=network_edge) return nodes_camera, node_detector def topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2", "\"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ] historian_app", "num_cameras, broker, camera_resources=None, detector_resources=None): network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [ Node(", "Topology) _ID_1 = \"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\"", "Network, Node, NodeApp, NodeResources, Service, Topology) _ID_1 = \"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR", "params={\"cameras\": param_cameras}, mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge)", "= Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR", "] camera_hostnames = [ f\"{item.name}.{network.name}\" for item in nodes_camera ] param_cameras = json.dumps([", "import RestartPolicy from wotemu.enums import NetworkConditions from wotemu.topology.models import (Broker, BuiltinApps, Network, Node,", "Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\", networks=[network_edge_1,", "detector_resources=None): network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True),", "= Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources)", "f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\",", "node_user = Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology = Topology(nodes=[ *nodes_camera_1, node_detector_1, *nodes_camera_2,", "networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN,", "name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for idx", "cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6,", "= Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology = Topology(nodes=[ *nodes_camera_1, node_detector_1, *nodes_camera_2, node_detector_2,", "= NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster(", "network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1", "Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for idx in range(num_cameras) ] camera_hostnames =", "= Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera, node_detector def", "def topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user", "http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian = Node( name=\"cloud\", app=historian_app, networks=[network_edge_1,", "json.dumps(historian_observed_things) }) node_historian = Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app =", "network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources =", "json from docker.types import RestartPolicy from wotemu.enums import NetworkConditions from wotemu.topology.models import (Broker,", "from docker.types import RestartPolicy from wotemu.enums import NetworkConditions from wotemu.topology.models import (Broker, BuiltinApps,", "_THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge, num_cameras, broker, camera_resources=None,", "cluster_id, network_edge, num_cameras, broker, camera_resources=None, detector_resources=None): network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera =", "\"thing_id\": _THING_ID_DETECTOR } ] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\":", "{ \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={", "name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\")", "= [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for idx in range(num_cameras) ]", "in range(num_cameras) ] camera_hostnames = [ f\"{item.name}.{network.name}\" for item in nodes_camera ] param_cameras", "name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\",", "json.dumps({\"write\": None, \"list\": None}), \"lambd\": 5 }) node_user = Node( name=\"user\", app=user_app, networks=[network_cloud_user],", "[ f\"{item.name}.{network.name}\" for item in nodes_camera ] param_cameras = json.dumps([ {\"servient_host\": cam_name} for", "f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\": None}), \"lambd\": 5 }) node_user =", "camera_hostnames ]) app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\",", "conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker =", "name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\")", "network_edge, num_cameras, broker, camera_resources=None, detector_resources=None): network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [", "for item in nodes_camera ] param_cameras = json.dumps([ {\"servient_host\": cam_name} for cam_name in", "camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker)", "detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo", "Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera, node_detector def topology():", "[ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for idx in range(num_cameras) ] camera_hostnames", "node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo = Service( name=\"mongo\",", "}) node_historian = Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp(", "wotemu.enums import NetworkConditions from wotemu.topology.models import (Broker, BuiltinApps, Network, Node, NodeApp, NodeResources, Service,", "def _build_detector_cluster( cluster_id, network_edge, num_cameras, broker, camera_resources=None, detector_resources=None): network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI)", "_THING_ID_DETECTOR } ] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things)", "\"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge, num_cameras, broker, camera_resources=None, detector_resources=None): network", "= NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian = Node(", "nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 =", "param_cameras = json.dumps([ {\"servient_host\": cam_name} for cam_name in camera_hostnames ]) app_detector = NodeApp(", "= NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\": None}),", "num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo = Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [", "historian_observed_things = [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\":", "mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2", "\"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge, num_cameras, broker,", "camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo = Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ {", "name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, {", "from wotemu.enums import NetworkConditions from wotemu.topology.models import (Broker, BuiltinApps, Network, Node, NodeApp, NodeResources,", "mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2,", "mongo = Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\":", "= \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge, num_cameras, broker, camera_resources=None, detector_resources=None): network = Network(", "\"list\": None}), \"lambd\": 5 }) node_user = Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology", "target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2,", "for cam_name in camera_hostnames ]) app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector", "conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources", "path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian = Node( name=\"cloud\", app=historian_app,", "broker = Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources =", "conditions=NetworkConditions.WIFI) nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for idx in", "None}), \"lambd\": 5 }) node_user = Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology =", "networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera, node_detector def topology(): network_edge_1 = Network(", "network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera, node_detector def topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\",", "Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for", "\"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\":", "name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology = Topology(nodes=[ *nodes_camera_1, node_detector_1, *nodes_camera_2, node_detector_2, node_historian, node_user", "target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1,", "] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian", "detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources,", "= json.dumps([ {\"servient_host\": cam_name} for cam_name in camera_hostnames ]) app_detector = NodeApp( path=BuiltinApps.DETECTOR,", "mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera,", "\"observed_things\": json.dumps(historian_observed_things) }) node_historian = Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app", "range(num_cameras) ] camera_hostnames = [ f\"{item.name}.{network.name}\" for item in nodes_camera ] param_cameras =", "node_historian = Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER,", "NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\": None}), \"lambd\":", "app=user_app, networks=[network_cloud_user], scale=5) topology = Topology(nodes=[ *nodes_camera_1, node_detector_1, *nodes_camera_2, node_detector_2, node_historian, node_user ])", "NodeApp, NodeResources, Service, Topology) _ID_1 = \"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\"", "detector_resources=detector_resources, broker=broker) mongo = Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ { \"servient_host\":", "network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker(", "= Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\",", "topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user =", "node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera, node_detector", "None, \"list\": None}), \"lambd\": 5 }) node_user = Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5)", "RestartPolicy from wotemu.enums import NetworkConditions from wotemu.topology.models import (Broker, BuiltinApps, Network, Node, NodeApp,", "network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\":", "broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo =", "params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian = Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2,", "BuiltinApps, Network, Node, NodeApp, NodeResources, Service, Topology) _ID_1 = \"loc1\" _ID_2 = \"loc2\"", "}) node_user = Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology = Topology(nodes=[ *nodes_camera_1, node_detector_1,", "NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian = Node( name=\"cloud\",", "cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo = Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things", "param_cameras}, mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return", "wotemu.topology.models import (Broker, BuiltinApps, Network, Node, NodeApp, NodeResources, Service, Topology) _ID_1 = \"loc1\"", "name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera, node_detector def topology(): network_edge_1", "5 }) node_user = Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology = Topology(nodes=[ *nodes_camera_1,", "\"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ] historian_app = NodeApp(", "nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo = Service(", "_build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo = Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\"))", "node_detector def topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G)", "nodes_camera, node_detector def topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\",", "\"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id,", "network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network(", "in nodes_camera ] param_cameras = json.dumps([ {\"servient_host\": cam_name} for cam_name in camera_hostnames ])", "_THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge, num_cameras, broker, camera_resources=None, detector_resources=None): network =", "idx in range(num_cameras) ] camera_hostnames = [ f\"{item.name}.{network.name}\" for item in nodes_camera ]", "camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 =", "network_edge=network_edge_2, num_cameras=6, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) mongo = Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things =", "= _build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2,", "broker=broker) mongo = Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\",", "http=True), networks=[network], resources=camera_resources) for idx in range(num_cameras) ] camera_hostnames = [ f\"{item.name}.{network.name}\" for", "app=app_detector, networks=[network, network_edge], resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera, node_detector def topology(): network_edge_1 =", "= \"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster(", "return nodes_camera, node_detector def topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network(", "} ] historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) })", "\"lambd\": 5 }) node_user = Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology = Topology(nodes=[", "cam_name in camera_hostnames ]) app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector =", "json.dumps([ {\"servient_host\": cam_name} for cam_name in camera_hostnames ]) app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\":", "nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for idx in range(num_cameras)", "f\"{item.name}.{network.name}\" for item in nodes_camera ] param_cameras = json.dumps([ {\"servient_host\": cam_name} for cam_name", "image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\":", "from wotemu.topology.models import (Broker, BuiltinApps, Network, Node, NodeApp, NodeResources, Service, Topology) _ID_1 =", "camera_resources=None, detector_resources=None): network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA,", "node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None,", "\"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\": None}), \"lambd\": 5 }) node_user = Node(", "{\"servient_host\": cam_name} for cam_name in camera_hostnames ]) app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras},", "broker, camera_resources=None, detector_resources=None): network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\",", "Node( name=\"user\", app=user_app, networks=[network_cloud_user], scale=5) topology = Topology(nodes=[ *nodes_camera_1, node_detector_1, *nodes_camera_2, node_detector_2, node_historian,", "f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ] historian_app =", "] param_cameras = json.dumps([ {\"servient_host\": cam_name} for cam_name in camera_hostnames ]) app_detector =", "[ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR }", "app_detector = NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network,", "path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\": None}), \"lambd\": 5", "= Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER, params={", "Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE)", "{ \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR } ]", "Node, NodeApp, NodeResources, Service, Topology) _ID_1 = \"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR =", "= NodeApp( path=BuiltinApps.DETECTOR, params={\"cameras\": param_cameras}, mqtt=True) node_detector = Node( name=f\"detector_{cluster_id}\", app=app_detector, networks=[network, network_edge],", "_THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\": None}), \"lambd\": 5 }) node_user = Node( name=\"user\",", "NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600, mem_limit=\"1G\") nodes_camera_1, node_detector_1 = _build_detector_cluster( cluster_id=_ID_1,", "restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\",", "network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\":", "params={ \"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\": None}), \"lambd\": 5 })", "_ID_2 = \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def _build_detector_cluster( cluster_id, network_edge,", "Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo) user_app = NodeApp( path=BuiltinApps.CALLER, params={ \"servient_host\":", "\"servient_host\": f\"{node_historian.name}.{network_cloud_user.name}\", \"thing_id\": _THING_ID_HISTORIAN, \"params\": json.dumps({\"write\": None, \"list\": None}), \"lambd\": 5 }) node_user", "name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS) network_edge_2 = Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker", "Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources = NodeResources( target_cpu_speed=600,", "historian_app = NodeApp( path=BuiltinApps.MONGO_HISTORIAN, http=True, params={ \"mongo_uri\": \"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian =", "scale=5) topology = Topology(nodes=[ *nodes_camera_1, node_detector_1, *nodes_camera_2, node_detector_2, node_historian, node_user ]) return topology", "network = Network( name=f\"field_{cluster_id}\", conditions=NetworkConditions.WIFI) nodes_camera = [ Node( name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network],", "name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2])", "_ID_1 = \"loc1\" _ID_2 = \"loc2\" _THING_ID_DETECTOR = \"urn:org:fundacionctic:thing:wotemu:detector\" _THING_ID_HISTORIAN = \"urn:org:fundacionctic:thing:historian\" def", "networks=[network], resources=camera_resources) for idx in range(num_cameras) ] camera_hostnames = [ f\"{item.name}.{network.name}\" for item", "conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\", networks=[network_edge_1, network_edge_2]) camera_resources = NodeResources( target_cpu_speed=200, mem_limit=\"256M\") detector_resources", "name=f\"camera_{cluster_id}_{idx}\", app=NodeApp(path=BuiltinApps.CAMERA, http=True), networks=[network], resources=camera_resources) for idx in range(num_cameras) ] camera_hostnames = [", "_build_detector_cluster( cluster_id=_ID_1, network_edge=network_edge_1, num_cameras=2, camera_resources=camera_resources, detector_resources=detector_resources, broker=broker) nodes_camera_2, node_detector_2 = _build_detector_cluster( cluster_id=_ID_2, network_edge=network_edge_2,", "= Network( name=f\"edge_3g_{_ID_2}\", conditions=NetworkConditions.REGULAR_3G) network_cloud_user = Network( name=\"cloud_user\", conditions=NetworkConditions.CABLE) broker = Broker( name=f\"broker\",", "Service( name=\"mongo\", image=\"mongo:4\", restart_policy=RestartPolicy(condition=\"on-failure\")) historian_observed_things = [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR },", "(Broker, BuiltinApps, Network, Node, NodeApp, NodeResources, Service, Topology) _ID_1 = \"loc1\" _ID_2 =", "resources=detector_resources, broker=broker, broker_network=network_edge) return nodes_camera, node_detector def topology(): network_edge_1 = Network( name=f\"edge_2g_{_ID_1}\", conditions=NetworkConditions.GPRS)", "= [ { \"servient_host\": f\"{node_detector_1.name}.{network_edge_1.name}\", \"thing_id\": _THING_ID_DETECTOR }, { \"servient_host\": f\"{node_detector_2.name}.{network_edge_2.name}\", \"thing_id\": _THING_ID_DETECTOR", "\"mongodb://mongo\", \"observed_things\": json.dumps(historian_observed_things) }) node_historian = Node( name=\"cloud\", app=historian_app, networks=[network_edge_1, network_edge_2, network_cloud_user]) node_historian.link_service(mongo)", "camera_hostnames = [ f\"{item.name}.{network.name}\" for item in nodes_camera ] param_cameras = json.dumps([ {\"servient_host\":", "resources=camera_resources) for idx in range(num_cameras) ] camera_hostnames = [ f\"{item.name}.{network.name}\" for item in" ]
[ "from bulletin.api import permissions from bulletin.api.views import PostList, PostDetail import serializers from bulletin.tools.plugins.models", "PostDetail import serializers from bulletin.tools.plugins.models import Job class JobList(PostList): queryset = Job.objects.all() serializer_class", "from bulletin.tools.plugins.models import Job class JobList(PostList): queryset = Job.objects.all() serializer_class = serializers.JobSerializer permission_classes", "= serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,) class JobDetail(PostDetail): serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,)", "bulletin.tools.plugins.models import Job class JobList(PostList): queryset = Job.objects.all() serializer_class = serializers.JobSerializer permission_classes =", "import Job class JobList(PostList): queryset = Job.objects.all() serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,)", "from bulletin.api.views import PostList, PostDetail import serializers from bulletin.tools.plugins.models import Job class JobList(PostList):", "permissions from bulletin.api.views import PostList, PostDetail import serializers from bulletin.tools.plugins.models import Job class", "serializers from bulletin.tools.plugins.models import Job class JobList(PostList): queryset = Job.objects.all() serializer_class = serializers.JobSerializer", "Job class JobList(PostList): queryset = Job.objects.all() serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,) class", "bulletin.api.views import PostList, PostDetail import serializers from bulletin.tools.plugins.models import Job class JobList(PostList): queryset", "<gh_stars>1-10 from bulletin.api import permissions from bulletin.api.views import PostList, PostDetail import serializers from", "Job.objects.all() serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,) class JobDetail(PostDetail): serializer_class = serializers.JobSerializer permission_classes", "class JobList(PostList): queryset = Job.objects.all() serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,) class JobDetail(PostDetail):", "import permissions from bulletin.api.views import PostList, PostDetail import serializers from bulletin.tools.plugins.models import Job", "PostList, PostDetail import serializers from bulletin.tools.plugins.models import Job class JobList(PostList): queryset = Job.objects.all()", "JobList(PostList): queryset = Job.objects.all() serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,) class JobDetail(PostDetail): serializer_class", "= Job.objects.all() serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,) class JobDetail(PostDetail): serializer_class = serializers.JobSerializer", "import serializers from bulletin.tools.plugins.models import Job class JobList(PostList): queryset = Job.objects.all() serializer_class =", "serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,) class JobDetail(PostDetail): serializer_class = serializers.JobSerializer permission_classes =", "queryset = Job.objects.all() serializer_class = serializers.JobSerializer permission_classes = (permissions.IsAdminUserOrReadOnly,) class JobDetail(PostDetail): serializer_class =", "bulletin.api import permissions from bulletin.api.views import PostList, PostDetail import serializers from bulletin.tools.plugins.models import", "import PostList, PostDetail import serializers from bulletin.tools.plugins.models import Job class JobList(PostList): queryset =" ]
[ ">>> C = [ # ... [2, 5], # ... [6, 7], #", "[ [10, 20], ] assert multiply(a, b) == [ [10, 20], [20, 40],", "1], # ... [0, 1, 0], # ... ] # >>> multiply(C, D)", ">>> D = [ # ... [1, 2, 1], # ... [0, 1,", "второй матрицей. В результате операции умножения матрицы размера M×N # на матрицу размером", "[10, 20], [20, 40], ] a = [ [1, 2, 1], [0, 1,", "операции умножения матрицы размера M×N # на матрицу размером N×K является матрица размером", "и # возвращает новую матрицу — результат их произведения. # # Примеры #", "range(len(matrix1))] for i in range(len(matrix1)): for j in range(len(t_matrix2)): for k in range(len(matrix1[0])):", "for j in range(len(t_matrix2)): for k in range(len(matrix1[0])): result[i][j] += matrix1[i][k] * t_matrix2[j][k]", "размером M×K. # # src/solution.py # Реализуйте функцию multiply, которая принимает две матрицы", "# >>> # >>> C = [ # ... [2, 5], # ...", "[6, 7], # ... [1, 8], # ... ] # >>> D =", "с количеством строк во второй матрице. # Это значит, что первая матрица обязательно", "0], [2, 3, 4], ] b = [ [2, 5], [6, 7], [1,", "Две матрицы можно перемножать только в том случае, если количество столбцов # в", "размером N×K является матрица размером M×K. # # src/solution.py # Реализуйте функцию multiply,", "[ # ... [2, 5], # ... [6, 7], # ... [1, 8],", "1]] def multiply(matrix1, matrix2): t_matrix2 = list(map(list, zip(*matrix2))) result = [[0 for _", "7], [1, 8], ] assert multiply(a, b) == [ [15, 27], [6, 7],", "b = [ [10, 20], ] assert multiply(a, b) == [ [10, 20],", "А и В представляет собой вычисление # результирующей матрицы С, где каждый элемент", "# в столбце второй матрицы B(kj). # # Две матрицы можно перемножать только", "первой матрицы A(ik) и элементов # в столбце второй матрицы B(kj). # #", "range(len(matrix1[0])): result[i][j] += matrix1[i][k] * t_matrix2[j][k] return result C = [ [2, 5],", "и элементов # в столбце второй матрицы B(kj). # # Две матрицы можно", "В представляет собой вычисление # результирующей матрицы С, где каждый элемент C(ij) равен", "[2, 5], [6, 7], [1, 8], ] assert multiply(a, b) == [ [15,", "второй матрицы B(kj). # # Две матрицы можно перемножать только в том случае,", "матрица размером M×K. # # src/solution.py # Реализуйте функцию multiply, которая принимает две", "[1, 10, 1]] def multiply(matrix1, matrix2): t_matrix2 = list(map(list, zip(*matrix2))) result = [[0", "[2, 5], # ... [6, 7], # ... [1, 8], # ... ]", "t_matrix2 = list(map(list, zip(*matrix2))) result = [[0 for _ in range(len(t_matrix2))] for _", "является матрица размером M×K. # # src/solution.py # Реализуйте функцию multiply, которая принимает", "result = [[0 for _ in range(len(t_matrix2))] for _ in range(len(matrix1))] for i", "если количество столбцов # в первой матрице совпадает с количеством строк во второй", "[10, 20], ] assert multiply(a, b) == [ [10, 20], [20, 40], ]", "элементов # в столбце второй матрицы B(kj). # # Две матрицы можно перемножать", "только в том случае, если количество столбцов # в первой матрице совпадает с", "[[2]], [[3]], ) == [[6]] a = [ [1], [2], ] b =", "t_matrix2[j][k] return result C = [ [2, 5], [6, 7], [1, 8], ]", "[2, 5], [6, 7], [1, 8], ] D = [ [1, 2, 1],", "] a = [ [1, 2, 1], [0, 1, 0], [2, 3, 4],", "# Это значит, что первая матрица обязательно должна быть согласованной # со второй", "for _ in range(len(t_matrix2))] for _ in range(len(matrix1))] for i in range(len(matrix1)): for", "# ... ] # >>> multiply(C, D) # [[2, 9, 2], [6, 19,", "6], [1, 10, 1]] def multiply(matrix1, matrix2): t_matrix2 = list(map(list, zip(*matrix2))) result =", "функцию multiply, которая принимает две матрицы и # возвращает новую матрицу — результат", "for _ in range(len(matrix1))] for i in range(len(matrix1)): for j in range(len(t_matrix2)): for", "результат их произведения. # # Примеры # >>> from solution import multiply #", "8], # ... ] # >>> D = [ # ... [1, 2,", "матриц А и В представляет собой вычисление # результирующей матрицы С, где каждый", "равен сумме произведений # элементов в соответствующей строке первой матрицы A(ik) и элементов", "# ... [2, 5], # ... [6, 7], # ... [1, 8], #", "[[3, 2], [1, 1]] # >>> multiply(A, B) # [[5, 4], [11, 8]]", "матрицы A(ik) и элементов # в столбце второй матрицы B(kj). # # Две", "[ [1, 2, 1], [0, 1, 0], [2, 3, 4], ] b =", "... ] # >>> multiply(C, D) # [[2, 9, 2], [6, 19, 6],", "multiply(A, B) # [[5, 4], [11, 8]] # >>> # >>> C =", "result[i][j] += matrix1[i][k] * t_matrix2[j][k] return result C = [ [2, 5], [6,", "in range(len(matrix1)): for j in range(len(t_matrix2)): for k in range(len(matrix1[0])): result[i][j] += matrix1[i][k]", "[1, 2, 1], [0, 1, 0], [2, 3, 4], ] b = [", "[1, 8], # ... ] # >>> D = [ # ... [1,", "и В представляет собой вычисление # результирующей матрицы С, где каждый элемент C(ij)", "a = [ [1], [2], ] b = [ [10, 20], ] assert", "0], ] print(multiply(C, D)) def test_multiply(): assert multiply( [[2]], [[3]], ) == [[6]]", "элемент C(ij) равен сумме произведений # элементов в соответствующей строке первой матрицы A(ik)", "N×K является матрица размером M×K. # # src/solution.py # Реализуйте функцию multiply, которая", "[1, 1]] # >>> multiply(A, B) # [[5, 4], [11, 8]] # >>>", "5], [6, 7], [1, 8], ] assert multiply(a, b) == [ [15, 27],", "7], # ... [1, 8], # ... ] # >>> D = [", "быть согласованной # со второй матрицей. В результате операции умножения матрицы размера M×N", "4], [11, 8]] # >>> # >>> C = [ # ... [2,", "первая матрица обязательно должна быть согласованной # со второй матрицей. В результате операции", "[ [2, 5], [6, 7], [1, 8], ] D = [ [1, 2,", "их произведения. # # Примеры # >>> from solution import multiply # >>>", "... [6, 7], # ... [1, 8], # ... ] # >>> D", "[0, 1, 0], ] print(multiply(C, D)) def test_multiply(): assert multiply( [[2]], [[3]], )", "return result C = [ [2, 5], [6, 7], [1, 8], ] D", "первой матрице совпадает с количеством строк во второй матрице. # Это значит, что", "# в первой матрице совпадает с количеством строк во второй матрице. # Это", "+= matrix1[i][k] * t_matrix2[j][k] return result C = [ [2, 5], [6, 7],", "В результате операции умножения матрицы размера M×N # на матрицу размером N×K является", "k in range(len(matrix1[0])): result[i][j] += matrix1[i][k] * t_matrix2[j][k] return result C = [", "] assert multiply(a, b) == [ [15, 27], [6, 7], [26, 63], ]", "10, 1]] def multiply(matrix1, matrix2): t_matrix2 = list(map(list, zip(*matrix2))) result = [[0 for", "сумме произведений # элементов в соответствующей строке первой матрицы A(ik) и элементов #", "количеством строк во второй матрице. # Это значит, что первая матрица обязательно должна", "матрицу — результат их произведения. # # Примеры # >>> from solution import", "A = [[1, 2], [3, 2]] # >>> B = [[3, 2], [1,", "_ in range(len(t_matrix2))] for _ in range(len(matrix1))] for i in range(len(matrix1)): for j", "D = [ [1, 2, 1], [0, 1, 0], ] print(multiply(C, D)) def", "assert multiply(a, b) == [ [15, 27], [6, 7], [26, 63], ] test_multiply()", "1]] # >>> multiply(A, B) # [[5, 4], [11, 8]] # >>> #", "* t_matrix2[j][k] return result C = [ [2, 5], [6, 7], [1, 8],", "# ... [6, 7], # ... [1, 8], # ... ] # >>>", "# Операция умножения двух матриц А и В представляет собой вычисление # результирующей", "C = [ [2, 5], [6, 7], [1, 8], ] D = [", "[ [1], [2], ] b = [ [10, 20], ] assert multiply(a, b)", "8], ] assert multiply(a, b) == [ [15, 27], [6, 7], [26, 63],", "multiply(a, b) == [ [10, 20], [20, 40], ] a = [ [1,", "где каждый элемент C(ij) равен сумме произведений # элементов в соответствующей строке первой", "B) # [[5, 4], [11, 8]] # >>> # >>> C = [", "B(kj). # # Две матрицы можно перемножать только в том случае, если количество", "= [ [2, 5], [6, 7], [1, 8], ] assert multiply(a, b) ==", "assert multiply( [[2]], [[3]], ) == [[6]] a = [ [1], [2], ]", "9, 2], [6, 19, 6], [1, 10, 1]] def multiply(matrix1, matrix2): t_matrix2 =", "в соответствующей строке первой матрицы A(ik) и элементов # в столбце второй матрицы", "— результат их произведения. # # Примеры # >>> from solution import multiply", "= [ [2, 5], [6, 7], [1, 8], ] D = [ [1,", "соответствующей строке первой матрицы A(ik) и элементов # в столбце второй матрицы B(kj).", "matrix1[i][k] * t_matrix2[j][k] return result C = [ [2, 5], [6, 7], [1,", "range(len(t_matrix2))] for _ in range(len(matrix1))] for i in range(len(matrix1)): for j in range(len(t_matrix2)):", ">>> from solution import multiply # >>> A = [[1, 2], [3, 2]]", "5], [6, 7], [1, 8], ] D = [ [1, 2, 1], [0,", "] D = [ [1, 2, 1], [0, 1, 0], ] print(multiply(C, D))", "# Реализуйте функцию multiply, которая принимает две матрицы и # возвращает новую матрицу", "<reponame>PavliukKonstantin/learn-python # Операция умножения двух матриц А и В представляет собой вычисление #", "] b = [ [2, 5], [6, 7], [1, 8], ] assert multiply(a,", "[11, 8]] # >>> # >>> C = [ # ... [2, 5],", "... [1, 8], # ... ] # >>> D = [ # ...", "... [0, 1, 0], # ... ] # >>> multiply(C, D) # [[2,", "перемножать только в том случае, если количество столбцов # в первой матрице совпадает", "2], [3, 2]] # >>> B = [[3, 2], [1, 1]] # >>>", "zip(*matrix2))) result = [[0 for _ in range(len(t_matrix2))] for _ in range(len(matrix1))] for", "# результирующей матрицы С, где каждый элемент C(ij) равен сумме произведений # элементов", "from solution import multiply # >>> A = [[1, 2], [3, 2]] #", "[ [2, 5], [6, 7], [1, 8], ] assert multiply(a, b) == [", "матрицы размера M×N # на матрицу размером N×K является матрица размером M×K. #", "должна быть согласованной # со второй матрицей. В результате операции умножения матрицы размера", "D)) def test_multiply(): assert multiply( [[2]], [[3]], ) == [[6]] a = [", "можно перемножать только в том случае, если количество столбцов # в первой матрице", "матрице совпадает с количеством строк во второй матрице. # Это значит, что первая", "# >>> B = [[3, 2], [1, 1]] # >>> multiply(A, B) #", "# ... [0, 1, 0], # ... ] # >>> multiply(C, D) #", "[[3]], ) == [[6]] a = [ [1], [2], ] b = [", "1, 0], ] print(multiply(C, D)) def test_multiply(): assert multiply( [[2]], [[3]], ) ==", "1, 0], # ... ] # >>> multiply(C, D) # [[2, 9, 2],", "2, 1], [0, 1, 0], ] print(multiply(C, D)) def test_multiply(): assert multiply( [[2]],", "возвращает новую матрицу — результат их произведения. # # Примеры # >>> from", "j in range(len(t_matrix2)): for k in range(len(matrix1[0])): result[i][j] += matrix1[i][k] * t_matrix2[j][k] return", "столбце второй матрицы B(kj). # # Две матрицы можно перемножать только в том", ">>> # >>> C = [ # ... [2, 5], # ... [6,", "значит, что первая матрица обязательно должна быть согласованной # со второй матрицей. В", "import multiply # >>> A = [[1, 2], [3, 2]] # >>> B", "# элементов в соответствующей строке первой матрицы A(ik) и элементов # в столбце", "solution import multiply # >>> A = [[1, 2], [3, 2]] # >>>", "M×N # на матрицу размером N×K является матрица размером M×K. # # src/solution.py", "две матрицы и # возвращает новую матрицу — результат их произведения. # #", "[6, 19, 6], [1, 10, 1]] def multiply(matrix1, matrix2): t_matrix2 = list(map(list, zip(*matrix2)))", "обязательно должна быть согласованной # со второй матрицей. В результате операции умножения матрицы", "in range(len(t_matrix2))] for _ in range(len(matrix1))] for i in range(len(matrix1)): for j in", "20], [20, 40], ] a = [ [1, 2, 1], [0, 1, 0],", "матрице. # Это значит, что первая матрица обязательно должна быть согласованной # со", "[3, 2]] # >>> B = [[3, 2], [1, 1]] # >>> multiply(A,", "== [ [10, 20], [20, 40], ] a = [ [1, 2, 1],", "multiply # >>> A = [[1, 2], [3, 2]] # >>> B =", "D) # [[2, 9, 2], [6, 19, 6], [1, 10, 1]] def multiply(matrix1,", "Реализуйте функцию multiply, которая принимает две матрицы и # возвращает новую матрицу —", "= [ [1, 2, 1], [0, 1, 0], [2, 3, 4], ] b", "19, 6], [1, 10, 1]] def multiply(matrix1, matrix2): t_matrix2 = list(map(list, zip(*matrix2))) result", "] assert multiply(a, b) == [ [10, 20], [20, 40], ] a =", "assert multiply(a, b) == [ [10, 20], [20, 40], ] a = [", "2, 1], [0, 1, 0], [2, 3, 4], ] b = [ [2,", "[[1, 2], [3, 2]] # >>> B = [[3, 2], [1, 1]] #", "[0, 1, 0], [2, 3, 4], ] b = [ [2, 5], [6,", "] # >>> multiply(C, D) # [[2, 9, 2], [6, 19, 6], [1,", "[2], ] b = [ [10, 20], ] assert multiply(a, b) == [", "4], ] b = [ [2, 5], [6, 7], [1, 8], ] assert", "def multiply(matrix1, matrix2): t_matrix2 = list(map(list, zip(*matrix2))) result = [[0 for _ in", "столбцов # в первой матрице совпадает с количеством строк во второй матрице. #", "матрицы и # возвращает новую матрицу — результат их произведения. # # Примеры", "range(len(t_matrix2)): for k in range(len(matrix1[0])): result[i][j] += matrix1[i][k] * t_matrix2[j][k] return result C", "8]] # >>> # >>> C = [ # ... [2, 5], #", "совпадает с количеством строк во второй матрице. # Это значит, что первая матрица", "[[0 for _ in range(len(t_matrix2))] for _ in range(len(matrix1))] for i in range(len(matrix1)):", "i in range(len(matrix1)): for j in range(len(t_matrix2)): for k in range(len(matrix1[0])): result[i][j] +=", "# [[2, 9, 2], [6, 19, 6], [1, 10, 1]] def multiply(matrix1, matrix2):", "умножения двух матриц А и В представляет собой вычисление # результирующей матрицы С,", "C(ij) равен сумме произведений # элементов в соответствующей строке первой матрицы A(ik) и", "строке первой матрицы A(ik) и элементов # в столбце второй матрицы B(kj). #", "2], [6, 19, 6], [1, 10, 1]] def multiply(matrix1, matrix2): t_matrix2 = list(map(list,", "умножения матрицы размера M×N # на матрицу размером N×K является матрица размером M×K.", "элементов в соответствующей строке первой матрицы A(ik) и элементов # в столбце второй", "test_multiply(): assert multiply( [[2]], [[3]], ) == [[6]] a = [ [1], [2],", "# # Две матрицы можно перемножать только в том случае, если количество столбцов", "# >>> multiply(A, B) # [[5, 4], [11, 8]] # >>> # >>>", "случае, если количество столбцов # в первой матрице совпадает с количеством строк во", "= [[0 for _ in range(len(t_matrix2))] for _ in range(len(matrix1))] for i in", "[ [10, 20], [20, 40], ] a = [ [1, 2, 1], [0,", "a = [ [1, 2, 1], [0, 1, 0], [2, 3, 4], ]", "# ... ] # >>> D = [ # ... [1, 2, 1],", "# [[5, 4], [11, 8]] # >>> # >>> C = [ #", "[ # ... [1, 2, 1], # ... [0, 1, 0], # ...", "С, где каждый элемент C(ij) равен сумме произведений # элементов в соответствующей строке", "for k in range(len(matrix1[0])): result[i][j] += matrix1[i][k] * t_matrix2[j][k] return result C =", "multiply(C, D) # [[2, 9, 2], [6, 19, 6], [1, 10, 1]] def", "# со второй матрицей. В результате операции умножения матрицы размера M×N # на", "result C = [ [2, 5], [6, 7], [1, 8], ] D =", "[[2, 9, 2], [6, 19, 6], [1, 10, 1]] def multiply(matrix1, matrix2): t_matrix2", "что первая матрица обязательно должна быть согласованной # со второй матрицей. В результате", "[1, 8], ] D = [ [1, 2, 1], [0, 1, 0], ]", "list(map(list, zip(*matrix2))) result = [[0 for _ in range(len(t_matrix2))] for _ in range(len(matrix1))]", "src/solution.py # Реализуйте функцию multiply, которая принимает две матрицы и # возвращает новую", "2]] # >>> B = [[3, 2], [1, 1]] # >>> multiply(A, B)", "[1, 8], ] assert multiply(a, b) == [ [15, 27], [6, 7], [26,", "принимает две матрицы и # возвращает новую матрицу — результат их произведения. #", ") == [[6]] a = [ [1], [2], ] b = [ [10,", "[2, 3, 4], ] b = [ [2, 5], [6, 7], [1, 8],", "# Две матрицы можно перемножать только в том случае, если количество столбцов #", "# # Примеры # >>> from solution import multiply # >>> A =", "] b = [ [10, 20], ] assert multiply(a, b) == [ [10,", "# Примеры # >>> from solution import multiply # >>> A = [[1,", "# на матрицу размером N×K является матрица размером M×K. # # src/solution.py #", "# >>> D = [ # ... [1, 2, 1], # ... [0,", "результирующей матрицы С, где каждый элемент C(ij) равен сумме произведений # элементов в", "8], ] D = [ [1, 2, 1], [0, 1, 0], ] print(multiply(C,", "= [ # ... [2, 5], # ... [6, 7], # ... [1,", "# ... [1, 2, 1], # ... [0, 1, 0], # ... ]", "# >>> multiply(C, D) # [[2, 9, 2], [6, 19, 6], [1, 10,", "[[5, 4], [11, 8]] # >>> # >>> C = [ # ...", "... [1, 2, 1], # ... [0, 1, 0], # ... ] #", "[[6]] a = [ [1], [2], ] b = [ [10, 20], ]", "= [ [1, 2, 1], [0, 1, 0], ] print(multiply(C, D)) def test_multiply():", "= [ # ... [1, 2, 1], # ... [0, 1, 0], #", "строк во второй матрице. # Это значит, что первая матрица обязательно должна быть", "[0, 1, 0], # ... ] # >>> multiply(C, D) # [[2, 9,", "== [[6]] a = [ [1], [2], ] b = [ [10, 20],", "# >>> C = [ # ... [2, 5], # ... [6, 7],", "[6, 7], [1, 8], ] assert multiply(a, b) == [ [15, 27], [6,", "том случае, если количество столбцов # в первой матрице совпадает с количеством строк", "со второй матрицей. В результате операции умножения матрицы размера M×N # на матрицу", "= list(map(list, zip(*matrix2))) result = [[0 for _ in range(len(t_matrix2))] for _ in", "] print(multiply(C, D)) def test_multiply(): assert multiply( [[2]], [[3]], ) == [[6]] a", "# ... [1, 8], # ... ] # >>> D = [ #", "представляет собой вычисление # результирующей матрицы С, где каждый элемент C(ij) равен сумме", "D = [ # ... [1, 2, 1], # ... [0, 1, 0],", "# # src/solution.py # Реализуйте функцию multiply, которая принимает две матрицы и #", ">>> B = [[3, 2], [1, 1]] # >>> multiply(A, B) # [[5,", "2], [1, 1]] # >>> multiply(A, B) # [[5, 4], [11, 8]] #", "= [[1, 2], [3, 2]] # >>> B = [[3, 2], [1, 1]]", "b) == [ [10, 20], [20, 40], ] a = [ [1, 2,", "[1, 2, 1], [0, 1, 0], ] print(multiply(C, D)) def test_multiply(): assert multiply(", "[20, 40], ] a = [ [1, 2, 1], [0, 1, 0], [2,", "каждый элемент C(ij) равен сумме произведений # элементов в соответствующей строке первой матрицы", "[ [1, 2, 1], [0, 1, 0], ] print(multiply(C, D)) def test_multiply(): assert", ">>> multiply(A, B) # [[5, 4], [11, 8]] # >>> # >>> C", "второй матрице. # Это значит, что первая матрица обязательно должна быть согласованной #", "# возвращает новую матрицу — результат их произведения. # # Примеры # >>>", "матрица обязательно должна быть согласованной # со второй матрицей. В результате операции умножения", "в том случае, если количество столбцов # в первой матрице совпадает с количеством", "b = [ [2, 5], [6, 7], [1, 8], ] assert multiply(a, b)", "in range(len(matrix1))] for i in range(len(matrix1)): for j in range(len(t_matrix2)): for k in", "# src/solution.py # Реализуйте функцию multiply, которая принимает две матрицы и # возвращает", "[1], [2], ] b = [ [10, 20], ] assert multiply(a, b) ==", "= [ [1], [2], ] b = [ [10, 20], ] assert multiply(a,", "7], [1, 8], ] D = [ [1, 2, 1], [0, 1, 0],", "Операция умножения двух матриц А и В представляет собой вычисление # результирующей матрицы", "произведения. # # Примеры # >>> from solution import multiply # >>> A", "собой вычисление # результирующей матрицы С, где каждый элемент C(ij) равен сумме произведений", "на матрицу размером N×K является матрица размером M×K. # # src/solution.py # Реализуйте", "1], [0, 1, 0], ] print(multiply(C, D)) def test_multiply(): assert multiply( [[2]], [[3]],", "# >>> A = [[1, 2], [3, 2]] # >>> B = [[3,", "= [ [10, 20], ] assert multiply(a, b) == [ [10, 20], [20,", "multiply, которая принимает две матрицы и # возвращает новую матрицу — результат их", "40], ] a = [ [1, 2, 1], [0, 1, 0], [2, 3,", "результате операции умножения матрицы размера M×N # на матрицу размером N×K является матрица", "matrix2): t_matrix2 = list(map(list, zip(*matrix2))) result = [[0 for _ in range(len(t_matrix2))] for", ">>> multiply(C, D) # [[2, 9, 2], [6, 19, 6], [1, 10, 1]]", "5], # ... [6, 7], # ... [1, 8], # ... ] #", "матрицы можно перемножать только в том случае, если количество столбцов # в первой", "M×K. # # src/solution.py # Реализуйте функцию multiply, которая принимает две матрицы и", "матрицы С, где каждый элемент C(ij) равен сумме произведений # элементов в соответствующей", "[6, 7], [1, 8], ] D = [ [1, 2, 1], [0, 1,", "матрицей. В результате операции умножения матрицы размера M×N # на матрицу размером N×K", "вычисление # результирующей матрицы С, где каждый элемент C(ij) равен сумме произведений #", "матрицы B(kj). # # Две матрицы можно перемножать только в том случае, если", "for i in range(len(matrix1)): for j in range(len(t_matrix2)): for k in range(len(matrix1[0])): result[i][j]", "C = [ # ... [2, 5], # ... [6, 7], # ...", "in range(len(matrix1[0])): result[i][j] += matrix1[i][k] * t_matrix2[j][k] return result C = [ [2,", "# >>> from solution import multiply # >>> A = [[1, 2], [3,", "в первой матрице совпадает с количеством строк во второй матрице. # Это значит,", "3, 4], ] b = [ [2, 5], [6, 7], [1, 8], ]", "_ in range(len(matrix1))] for i in range(len(matrix1)): for j in range(len(t_matrix2)): for k", "multiply(matrix1, matrix2): t_matrix2 = list(map(list, zip(*matrix2))) result = [[0 for _ in range(len(t_matrix2))]", "1], [0, 1, 0], [2, 3, 4], ] b = [ [2, 5],", "согласованной # со второй матрицей. В результате операции умножения матрицы размера M×N #", "количество столбцов # в первой матрице совпадает с количеством строк во второй матрице.", "= [[3, 2], [1, 1]] # >>> multiply(A, B) # [[5, 4], [11,", "range(len(matrix1)): for j in range(len(t_matrix2)): for k in range(len(matrix1[0])): result[i][j] += matrix1[i][k] *", "2, 1], # ... [0, 1, 0], # ... ] # >>> multiply(C,", "print(multiply(C, D)) def test_multiply(): assert multiply( [[2]], [[3]], ) == [[6]] a =", "1, 0], [2, 3, 4], ] b = [ [2, 5], [6, 7],", "в столбце второй матрицы B(kj). # # Две матрицы можно перемножать только в", "... [2, 5], # ... [6, 7], # ... [1, 8], # ...", "произведений # элементов в соответствующей строке первой матрицы A(ik) и элементов # в", "новую матрицу — результат их произведения. # # Примеры # >>> from solution", "размера M×N # на матрицу размером N×K является матрица размером M×K. # #", "B = [[3, 2], [1, 1]] # >>> multiply(A, B) # [[5, 4],", "multiply( [[2]], [[3]], ) == [[6]] a = [ [1], [2], ] b", "во второй матрице. # Это значит, что первая матрица обязательно должна быть согласованной", "двух матриц А и В представляет собой вычисление # результирующей матрицы С, где", "0], # ... ] # >>> multiply(C, D) # [[2, 9, 2], [6,", "[1, 2, 1], # ... [0, 1, 0], # ... ] # >>>", "Это значит, что первая матрица обязательно должна быть согласованной # со второй матрицей.", "матрицу размером N×K является матрица размером M×K. # # src/solution.py # Реализуйте функцию", "которая принимает две матрицы и # возвращает новую матрицу — результат их произведения.", "in range(len(t_matrix2)): for k in range(len(matrix1[0])): result[i][j] += matrix1[i][k] * t_matrix2[j][k] return result", "Примеры # >>> from solution import multiply # >>> A = [[1, 2],", "... ] # >>> D = [ # ... [1, 2, 1], #", "A(ik) и элементов # в столбце второй матрицы B(kj). # # Две матрицы", "def test_multiply(): assert multiply( [[2]], [[3]], ) == [[6]] a = [ [1],", "20], ] assert multiply(a, b) == [ [10, 20], [20, 40], ] a", ">>> A = [[1, 2], [3, 2]] # >>> B = [[3, 2],", "] # >>> D = [ # ... [1, 2, 1], # ..." ]
[ "= Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors])) explorer = SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples,", "sketches\") parser.add_argument('--image_path', type=str, help='path to image file') parser.add_argument('--distract_dir', type=str, help='directory to distractor image", "to distractor image files') parser.add_argument('--sketch_dir', type=str, help='directory to store sketches') parser.add_argument('--n_samples', type=int, default=5,", "default=1.0, help='hyperparameter for line rendering') args = parser.parse_args() # prep images natural =", "wait N epochs before quitting') parser.add_argument('--beam_width', type=int, default=2, help='number of particles to preserve", "in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([", "help='standard deviation for Gaussian when sampling') parser.add_argument('--patience', type=int, default=5, help='once the informativity measure", "Gaussian when sampling') parser.add_argument('--patience', type=int, default=5, help='once the informativity measure stops improving, wait", "import argparse from PIL import Image import torch import torchvision.transforms as transforms from", "from __future__ import print_function from __future__ import absolute_import if __name__ == '__main__': import", "sketches') parser.add_argument('--n_samples', type=int, default=5, help='number of samples per iteration') parser.add_argument('--n_iters', type=int, default=20, help='number", "help='directory to store sketches') parser.add_argument('--n_samples', type=int, default=5, help='number of samples per iteration') parser.add_argument('--n_iters',", "embeddings for the natural & distractor images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0)", "i) distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456,", "embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for i in range(args.n_iters): sketch =", "i in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing =", "os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485,", "Image import torch import torchvision.transforms as transforms from torch.autograd import Variable from beamsearch", "of samples per iteration') parser.add_argument('--n_iters', type=int, default=20, help='number of iterations') parser.add_argument('--stdev', type=float, default=15.0,", "when sampling') parser.add_argument('--patience', type=int, default=5, help='once the informativity measure stops improving, wait N", "at each timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str,", "transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # grab embeddings for the natural &", "from beamsearch import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path to image", "beamsearch import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path to image file')", "line rendering') args = parser.parse_args() # prep images natural = Image.open(args.image_path) distractors =", "# grab embeddings for the natural & distractor images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors", "default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for line rendering') args = parser.parse_args() #", "[0.229, 0.224, 0.225])]) # grab embeddings for the natural & distractor images natural", "embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for i in range(args.n_iters): sketch", "__future__ import absolute_import if __name__ == '__main__': import os import argparse from PIL", "help='number of particles to preserve at each timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net',", "transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # grab embeddings for the natural", "distractor image files') parser.add_argument('--sketch_dir', type=str, help='directory to store sketches') parser.add_argument('--n_samples', type=int, default=5, help='number", "quitting') parser.add_argument('--beam_width', type=int, default=2, help='number of particles to preserve at each timestep') parser.add_argument('--embedding_layer',", "Variable from beamsearch import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path to", "= [] for i in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path)", "transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # grab embeddings for", "distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])", "import print_function from __future__ import absolute_import if __name__ == '__main__': import os import", "as transforms from torch.autograd import Variable from beamsearch import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate", "parser.add_argument('--image_path', type=str, help='path to image file') parser.add_argument('--distract_dir', type=str, help='directory to distractor image files')", "argparse from PIL import Image import torch import torchvision.transforms as transforms from torch.autograd", "default=5, help='number of samples per iteration') parser.add_argument('--n_iters', type=int, default=20, help='number of iterations') parser.add_argument('--stdev',", "preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) #", "help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for line rendering') args", "help='once the informativity measure stops improving, wait N epochs before quitting') parser.add_argument('--beam_width', type=int,", "division from __future__ import print_function from __future__ import absolute_import if __name__ == '__main__':", "to store sketches') parser.add_argument('--n_samples', type=int, default=5, help='number of samples per iteration') parser.add_argument('--n_iters', type=int,", "default=20, help='number of iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation for Gaussian when sampling')", "parser.parse_args() # prep images natural = Image.open(args.image_path) distractors = [] for i in", "= Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229,", "== '__main__': import os import argparse from PIL import Image import torch import", "parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for line rendering') args =", "parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for line rendering') args = parser.parse_args() # prep images", "import os import argparse from PIL import Image import torch import torchvision.transforms as", "for line rendering') args = parser.parse_args() # prep images natural = Image.open(args.image_path) distractors", "= os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(),", "beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors)", "= explorer.vgg19(distractors) for i in range(args.n_iters): sketch = explorer.train(i, natural_emb, distractor_items=distractor_embs) im =", "distractors = [] for i in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i) distractor =", "0.406], [0.229, 0.224, 0.225])]) # grab embeddings for the natural & distractor images", "image in distractors])) explorer = SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0,", "explorer.vgg19(distractors) for i in range(args.n_iters): sketch = explorer.train(i, natural_emb, distractor_items=distractor_embs) im = Image.fromarray(sketch)", "help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for line rendering') args = parser.parse_args() # prep", "type=str, help='directory to distractor image files') parser.add_argument('--sketch_dir', type=str, help='directory to store sketches') parser.add_argument('--n_samples',", "default=15.0, help='standard deviation for Gaussian when sampling') parser.add_argument('--patience', type=int, default=5, help='once the informativity", "type=float, default=1.0, help='hyperparameter for line rendering') args = parser.parse_args() # prep images natural", "= Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors])) explorer = SemanticBeamSearch(112, 112,", "argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path to image file') parser.add_argument('--distract_dir', type=str, help='directory to distractor", "print_function from __future__ import absolute_import if __name__ == '__main__': import os import argparse", "per iteration') parser.add_argument('--n_iters', type=int, default=20, help='number of iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation", "SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural)", "of iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation for Gaussian when sampling') parser.add_argument('--patience', type=int,", "type=str, help='directory to store sketches') parser.add_argument('--n_samples', type=int, default=5, help='number of samples per iteration')", "distractor_embs = explorer.vgg19(distractors) for i in range(args.n_iters): sketch = explorer.train(i, natural_emb, distractor_items=distractor_embs) im", "parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path to image file') parser.add_argument('--distract_dir', type=str, help='directory", "parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz',", "preserve at each timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn',", "= explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for i in range(args.n_iters): sketch = explorer.train(i, natural_emb,", "import absolute_import if __name__ == '__main__': import os import argparse from PIL import", "for image in distractors])) explorer = SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev,", "112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs", "import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path to image file') parser.add_argument('--distract_dir',", "torch import torchvision.transforms as transforms from torch.autograd import Variable from beamsearch import SemanticBeamSearch", "prep images natural = Image.open(args.image_path) distractors = [] for i in os.listdir(args.distract_dir): distractor_path", "samples per iteration') parser.add_argument('--n_iters', type=int, default=20, help='number of iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard", "os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256),", "os import argparse from PIL import Image import torch import torchvision.transforms as transforms", "type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float,", "help='hyperparameter for line rendering') args = parser.parse_args() # prep images natural = Image.open(args.image_path)", "natural & distractor images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in", "images natural = Image.open(args.image_path) distractors = [] for i in os.listdir(args.distract_dir): distractor_path =", "Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors])) explorer = SemanticBeamSearch(112, 112, 224,", "image file') parser.add_argument('--distract_dir', type=str, help='directory to distractor image files') parser.add_argument('--sketch_dir', type=str, help='directory to", "[] for i in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path) distractors.append(distractor)", "parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation for Gaussian when sampling') parser.add_argument('--patience', type=int, default=5, help='once", "explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for i in range(args.n_iters): sketch = explorer.train(i, natural_emb, distractor_items=distractor_embs)", "for i in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing", "N epochs before quitting') parser.add_argument('--beam_width', type=int, default=2, help='number of particles to preserve at", "# prep images natural = Image.open(args.image_path) distractors = [] for i in os.listdir(args.distract_dir):", "= argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path to image file') parser.add_argument('--distract_dir', type=str, help='directory to", "transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # grab embeddings", "= transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # grab", "Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors])) explorer = SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters,", "PIL import Image import torch import torchvision.transforms as transforms from torch.autograd import Variable", "store sketches') parser.add_argument('--n_samples', type=int, default=5, help='number of samples per iteration') parser.add_argument('--n_iters', type=int, default=20,", "n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for i", "from torch.autograd import Variable from beamsearch import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path',", "type=str, help='path to image file') parser.add_argument('--distract_dir', type=str, help='directory to distractor image files') parser.add_argument('--sketch_dir',", "stops improving, wait N epochs before quitting') parser.add_argument('--beam_width', type=int, default=2, help='number of particles", "for the natural & distractor images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for", "type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for line rendering') args = parser.parse_args()", "type=int, default=2, help='number of particles to preserve at each timestep') parser.add_argument('--embedding_layer', type=int, default=-1,", "in distractors])) explorer = SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net,", "distractor_path = os.path.join(args.distract_dir, i) distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224),", "of particles to preserve at each timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str,", "distractor = Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406],", "natural = Image.open(args.image_path) distractors = [] for i in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir,", "Image.open(distractor_path) distractors.append(distractor) preprocessing = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224,", "timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2')", "measure stops improving, wait N epochs before quitting') parser.add_argument('--beam_width', type=int, default=2, help='number of", "help='number of samples per iteration') parser.add_argument('--n_iters', type=int, default=20, help='number of iterations') parser.add_argument('--stdev', type=float,", "parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for", "image files') parser.add_argument('--sketch_dir', type=str, help='directory to store sketches') parser.add_argument('--n_samples', type=int, default=5, help='number of", "__name__ == '__main__': import os import argparse from PIL import Image import torch", "args = parser.parse_args() # prep images natural = Image.open(args.image_path) distractors = [] for", "help='directory to distractor image files') parser.add_argument('--sketch_dir', type=str, help='directory to store sketches') parser.add_argument('--n_samples', type=int,", "parser.add_argument('--n_iters', type=int, default=20, help='number of iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation for Gaussian", "i in range(args.n_iters): sketch = explorer.train(i, natural_emb, distractor_items=distractor_embs) im = Image.fromarray(sketch) im.save(os.path.join(args.sketch_dir, 'sketch.png'))", "0.456, 0.406], [0.229, 0.224, 0.225])]) # grab embeddings for the natural & distractor", "torchvision.transforms as transforms from torch.autograd import Variable from beamsearch import SemanticBeamSearch parser =", "type=int, default=5, help='once the informativity measure stops improving, wait N epochs before quitting')", "type=float, default=15.0, help='standard deviation for Gaussian when sampling') parser.add_argument('--patience', type=int, default=5, help='once the", "Image.open(args.image_path) distractors = [] for i in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i) distractor", "default=2, help='number of particles to preserve at each timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8')", "import Variable from beamsearch import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path", "rendering') args = parser.parse_args() # prep images natural = Image.open(args.image_path) distractors = []", "to image file') parser.add_argument('--distract_dir', type=str, help='directory to distractor image files') parser.add_argument('--sketch_dir', type=str, help='directory", "__future__ import print_function from __future__ import absolute_import if __name__ == '__main__': import os", "distractor images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors])) explorer", "improving, wait N epochs before quitting') parser.add_argument('--beam_width', type=int, default=2, help='number of particles to", "parser.add_argument('--n_samples', type=int, default=5, help='number of samples per iteration') parser.add_argument('--n_iters', type=int, default=20, help='number of", "parser.add_argument('--distract_dir', type=str, help='directory to distractor image files') parser.add_argument('--sketch_dir', type=str, help='directory to store sketches')", "default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0,", "particles to preserve at each timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19',", "to preserve at each timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152')", "type=int, default=20, help='number of iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation for Gaussian when", "__future__ import division from __future__ import print_function from __future__ import absolute_import if __name__", "the informativity measure stops improving, wait N epochs before quitting') parser.add_argument('--beam_width', type=int, default=2,", "0.224, 0.225])]) # grab embeddings for the natural & distractor images natural =", "help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter", "deviation for Gaussian when sampling') parser.add_argument('--patience', type=int, default=5, help='once the informativity measure stops", "grab embeddings for the natural & distractor images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors =", "default=5, help='once the informativity measure stops improving, wait N epochs before quitting') parser.add_argument('--beam_width',", "for Gaussian when sampling') parser.add_argument('--patience', type=int, default=5, help='once the informativity measure stops improving,", "import Image import torch import torchvision.transforms as transforms from torch.autograd import Variable from", "from PIL import Image import torch import torchvision.transforms as transforms from torch.autograd import", "file') parser.add_argument('--distract_dir', type=str, help='directory to distractor image files') parser.add_argument('--sketch_dir', type=str, help='directory to store", "if __name__ == '__main__': import os import argparse from PIL import Image import", "the natural & distractor images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image", "default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for line rendering')", "each timestep') parser.add_argument('--embedding_layer', type=int, default=-1, help='-1|0|1|...|7|8') parser.add_argument('--embedding_net', type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine',", "type=int, default=5, help='number of samples per iteration') parser.add_argument('--n_iters', type=int, default=20, help='number of iterations')", "import division from __future__ import print_function from __future__ import absolute_import if __name__ ==", "parser.add_argument('--sketch_dir', type=str, help='directory to store sketches') parser.add_argument('--n_samples', type=int, default=5, help='number of samples per", "epochs before quitting') parser.add_argument('--beam_width', type=int, default=2, help='number of particles to preserve at each", "parser.add_argument('--patience', type=int, default=5, help='once the informativity measure stops improving, wait N epochs before", "distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors])) explorer = SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width,", "help='number of iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation for Gaussian when sampling') parser.add_argument('--patience',", "stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for i in", "absolute_import if __name__ == '__main__': import os import argparse from PIL import Image", "import torchvision.transforms as transforms from torch.autograd import Variable from beamsearch import SemanticBeamSearch parser", "type=str, default='vgg19', help='vgg19|resnet152') parser.add_argument('--distance_fn', type=str, default='cosine', help='cosine|l1|l2') parser.add_argument('--fuzz', type=float, default=1.0, help='hyperparameter for line", "distractors])) explorer = SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer)", "iteration') parser.add_argument('--n_iters', type=int, default=20, help='number of iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation for", "= Image.open(args.image_path) distractors = [] for i in os.listdir(args.distract_dir): distractor_path = os.path.join(args.distract_dir, i)", "0.225])]) # grab embeddings for the natural & distractor images natural = Variable(preprocessing(natural).unsqueeze(0))", "torch.autograd import Variable from beamsearch import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str,", "sampling') parser.add_argument('--patience', type=int, default=5, help='once the informativity measure stops improving, wait N epochs", "before quitting') parser.add_argument('--beam_width', type=int, default=2, help='number of particles to preserve at each timestep')", "iterations') parser.add_argument('--stdev', type=float, default=15.0, help='standard deviation for Gaussian when sampling') parser.add_argument('--patience', type=int, default=5,", "= parser.parse_args() # prep images natural = Image.open(args.image_path) distractors = [] for i", "224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs =", "transforms from torch.autograd import Variable from beamsearch import SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\")", "explorer = SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb", "n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for", "'__main__': import os import argparse from PIL import Image import torch import torchvision.transforms", "help='path to image file') parser.add_argument('--distract_dir', type=str, help='directory to distractor image files') parser.add_argument('--sketch_dir', type=str,", "from __future__ import absolute_import if __name__ == '__main__': import os import argparse from", "natural = Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors])) explorer = SemanticBeamSearch(112,", "for i in range(args.n_iters): sketch = explorer.train(i, natural_emb, distractor_items=distractor_embs) im = Image.fromarray(sketch) im.save(os.path.join(args.sketch_dir,", "& distractor images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors]))", "files') parser.add_argument('--sketch_dir', type=str, help='directory to store sketches') parser.add_argument('--n_samples', type=int, default=5, help='number of samples", "informativity measure stops improving, wait N epochs before quitting') parser.add_argument('--beam_width', type=int, default=2, help='number", "from __future__ import division from __future__ import print_function from __future__ import absolute_import if", "transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # grab embeddings for the", "= SemanticBeamSearch(112, 112, 224, beam_width=args.beam_width, n_samples=args.n_samples, n_iters=args.n_iters, stdev=args.stdev, fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb =", "import torch import torchvision.transforms as transforms from torch.autograd import Variable from beamsearch import", "fuzz=1.0, embedding_net=args.embedding_net, embedding_layer=args.embedding_layer) natural_emb = explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for i in range(args.n_iters):", "SemanticBeamSearch parser = argparse.ArgumentParser(description=\"generate sketches\") parser.add_argument('--image_path', type=str, help='path to image file') parser.add_argument('--distract_dir', type=str,", "parser.add_argument('--beam_width', type=int, default=2, help='number of particles to preserve at each timestep') parser.add_argument('--embedding_layer', type=int,", "natural_emb = explorer.vgg19(natural) distractor_embs = explorer.vgg19(distractors) for i in range(args.n_iters): sketch = explorer.train(i,", "images natural = Variable(preprocessing(natural).unsqueeze(0)) distractors = Variable(torch.cat([preprocessing(image).unsqueeze(0) for image in distractors])) explorer =" ]
[ "b for i in range(max_v, multiple): if i % a == 0 and", "if i % a == 0 and i % b == 0: return", "a if b > a: max_v = b for i in range(max_v, multiple):", "0 and i % b == 0: return i return multiple print(get_lcm(6, 8))", "i % a == 0 and i % b == 0: return i", "b > a: max_v = b for i in range(max_v, multiple): if i", "i in range(max_v, multiple): if i % a == 0 and i %", "b max_v = a if b > a: max_v = b for i", "> a: max_v = b for i in range(max_v, multiple): if i %", "a: max_v = b for i in range(max_v, multiple): if i % a", "i % b == 0: return i return multiple print(get_lcm(6, 8)) print(get_lcm(12, 15))", "and i % b == 0: return i return multiple print(get_lcm(6, 8)) print(get_lcm(12,", "a * b max_v = a if b > a: max_v = b", "if b > a: max_v = b for i in range(max_v, multiple): if", "* b max_v = a if b > a: max_v = b for", "for i in range(max_v, multiple): if i % a == 0 and i", "max_v = b for i in range(max_v, multiple): if i % a ==", "= b for i in range(max_v, multiple): if i % a == 0", "def get_lcm(a, b): multiple = a * b max_v = a if b", "b): multiple = a * b max_v = a if b > a:", "= a if b > a: max_v = b for i in range(max_v,", "max_v = a if b > a: max_v = b for i in", "multiple): if i % a == 0 and i % b == 0:", "== 0 and i % b == 0: return i return multiple print(get_lcm(6,", "multiple = a * b max_v = a if b > a: max_v", "a == 0 and i % b == 0: return i return multiple", "in range(max_v, multiple): if i % a == 0 and i % b", "get_lcm(a, b): multiple = a * b max_v = a if b >", "% a == 0 and i % b == 0: return i return", "range(max_v, multiple): if i % a == 0 and i % b ==", "= a * b max_v = a if b > a: max_v =" ]