prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def <|fim_middle|>(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
__init__
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def <|fim_middle|>(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
setup_network
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def <|fim_middle|>(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
run_test
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow<|fim▁hole|>from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding)<|fim▁end|>
from grr.lib import rdfvalue from grr.lib.checks import checks
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): <|fim_middle|> class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
protobuf = flows_pb2.CheckFlowArgs
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): <|fim_middle|> <|fim▁end|>
"""This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding)
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): <|fim_middle|> @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
""".""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData")
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): <|fim_middle|> @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
"""Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks")
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): <|fim_middle|> @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses)
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): <|fim_middle|> <|fim▁end|>
if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding)
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: <|fim_middle|> # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
raise RuntimeError("Checks did not run successfully.")
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: <|fim_middle|> self.SendReply(finding) <|fim▁end|>
self.state.checks_with_findings.append(finding.check_id)
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def <|fim_middle|>(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
Start
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def <|fim_middle|>(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
MapArtifactData
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def <|fim_middle|>(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def RunChecks(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
AddResponses
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """ friendly_name = "Run Checks" category = "/Checks/" behaviours = flow.GRRFlow.behaviours + "BASIC" @flow.StateHandler(next_state=["MapArtifactData"]) def Start(self): """.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register("knowledge_base", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register("labels", client.GetLabels()) self.state.Register("artifacts_wanted", set()) self.state.Register("artifacts_fetched", set()) self.state.Register("checks_run", []) self.state.Register("checks_with_findings", []) self.state.Register("results_store", None) self.state.Register("host_data", {}) self.CallState(next_state="MapArtifactData") @flow.StateHandler(next_state=["AddResponses", "RunChecks"]) def MapArtifactData(self, responses): """Get processed data, mapped to artifacts.""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_id], request_data={"artifact_id": artifact_id}, next_state="AddResponses") self.CallState(next_state="RunChecks") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data["artifact_id"] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=["Done"]) def <|fim_middle|>(self, responses): if not responses.success: raise RuntimeError("Checks did not run successfully.") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) <|fim▁end|>
RunChecks
<|file_name|>helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals<|fim▁hole|>import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type)<|fim▁end|>
<|file_name|>helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): <|fim_middle|> <|fim▁end|>
def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type)
<|file_name|>helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): <|fim_middle|> @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type) <|fim▁end|>
self.config = config
<|file_name|>helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): <|fim_middle|> @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type) <|fim▁end|>
allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type)
<|file_name|>helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): <|fim_middle|> <|fim▁end|>
allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type)
<|file_name|>helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def <|fim_middle|>(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type) <|fim▁end|>
__init__
<|file_name|>helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def <|fim_middle|>(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type) <|fim▁end|>
decorate_as_label
<|file_name|>helper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def <|fim_middle|>(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type) <|fim▁end|>
decorate_as_link
<|file_name|>models.py<|end_file_name|><|fim▁begin|>""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value fields<|fim▁hole|> float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value = SerializableField(blank=True, null=True) def __unicode__(self): return 'KVModel instance: ' + self.key + ' = ' + unicode(self.value) @classmethod def get_by_key(cls, key): """ A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found. """ return cls.objects.get(key=key) class Meta: abstract = True<|fim▁end|>
key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int,
<|file_name|>models.py<|end_file_name|><|fim▁begin|>""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): <|fim_middle|> <|fim▁end|>
""" An Abstract model that has key and value fields key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int, float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value = SerializableField(blank=True, null=True) def __unicode__(self): return 'KVModel instance: ' + self.key + ' = ' + unicode(self.value) @classmethod def get_by_key(cls, key): """ A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found. """ return cls.objects.get(key=key) class Meta: abstract = True
<|file_name|>models.py<|end_file_name|><|fim▁begin|>""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value fields key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int, float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value = SerializableField(blank=True, null=True) def __unicode__(self): <|fim_middle|> @classmethod def get_by_key(cls, key): """ A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found. """ return cls.objects.get(key=key) class Meta: abstract = True <|fim▁end|>
return 'KVModel instance: ' + self.key + ' = ' + unicode(self.value)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value fields key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int, float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value = SerializableField(blank=True, null=True) def __unicode__(self): return 'KVModel instance: ' + self.key + ' = ' + unicode(self.value) @classmethod def get_by_key(cls, key): <|fim_middle|> class Meta: abstract = True <|fim▁end|>
""" A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found. """ return cls.objects.get(key=key)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value fields key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int, float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value = SerializableField(blank=True, null=True) def __unicode__(self): return 'KVModel instance: ' + self.key + ' = ' + unicode(self.value) @classmethod def get_by_key(cls, key): """ A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found. """ return cls.objects.get(key=key) class Meta: <|fim_middle|> <|fim▁end|>
abstract = True
<|file_name|>models.py<|end_file_name|><|fim▁begin|>""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value fields key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int, float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value = SerializableField(blank=True, null=True) def <|fim_middle|>(self): return 'KVModel instance: ' + self.key + ' = ' + unicode(self.value) @classmethod def get_by_key(cls, key): """ A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found. """ return cls.objects.get(key=key) class Meta: abstract = True <|fim▁end|>
__unicode__
<|file_name|>models.py<|end_file_name|><|fim▁begin|>""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value fields key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int, float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value = SerializableField(blank=True, null=True) def __unicode__(self): return 'KVModel instance: ' + self.key + ' = ' + unicode(self.value) @classmethod def <|fim_middle|>(cls, key): """ A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found. """ return cls.objects.get(key=key) class Meta: abstract = True <|fim▁end|>
get_by_key
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation."""<|fim▁hole|> return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms)<|fim▁end|>
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): <|fim_middle|> rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): <|fim_middle|> class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): <|fim_middle|> @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Return a printable representation.""" return self.date.strftime('%B %d, %Y')
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): <|fim_middle|> def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all()
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): <|fim_middle|> class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): <|fim_middle|> times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): <|fim_middle|> class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): <|fim_middle|> class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Return a printable representation.""" return self.name
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): <|fim_middle|> class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): <|fim_middle|> @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): <|fim_middle|> class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): <|fim_middle|> <|fim▁end|>
"""Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): <|fim_middle|> def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Return a printable representation.""" return str(self.talk)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): <|fim_middle|> @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
"""Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): <|fim_middle|> <|fim▁end|>
"""Return the number of rooms for the instance.""" return len(self.slot.rooms)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: <|fim_middle|> def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
raise StopIteration
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: <|fim_middle|> if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: <|fim_middle|> row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first()
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: <|fim_middle|> class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
yield row
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def <|fim_middle|>(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
pairwise
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def <|fim_middle|>(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
__str__
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def <|fim_middle|>(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
rooms
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def <|fim_middle|>(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
__iter__
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def <|fim_middle|>(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
rowspan
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def <|fim_middle|>(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
__str__
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def <|fim_middle|>(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
__str__
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def <|fim_middle|>(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
duration
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def <|fim_middle|>(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
__str__
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def <|fim_middle|>(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
is_in_all_rooms
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def <|fim_middle|>(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms) <|fim▁end|>
number_of_rooms
<|file_name|>context_managers.py<|end_file_name|><|fim▁begin|>"""useful context managers""" from contextlib import suppress with suppress(ModuleNotFoundError): from lag import * import os import contextlib def clog(*args, condition=True, log_func=print, **kwargs): if condition: return log_func(*args, **kwargs) @contextlib.contextmanager def cd(newdir, verbose=True): """Change your working directory, do stuff, and change back to the original""" _clog = partial(clog, condition=verbose, log_func=print) prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: _clog(f'cd {newdir}') yield finally: _clog(f'cd {prevdir}') os.chdir(prevdir) # from pathlib import Path<|fim▁hole|> # _clog("Called after cd and same as before", Path().absolute())<|fim▁end|>
# _clog("Called before cd", Path().absolute()) # with cd(Path.home()): # if verbose: print("Called under cd", Path().absolute())
<|file_name|>context_managers.py<|end_file_name|><|fim▁begin|>"""useful context managers""" from contextlib import suppress with suppress(ModuleNotFoundError): from lag import * import os import contextlib def clog(*args, condition=True, log_func=print, **kwargs): <|fim_middle|> @contextlib.contextmanager def cd(newdir, verbose=True): """Change your working directory, do stuff, and change back to the original""" _clog = partial(clog, condition=verbose, log_func=print) prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: _clog(f'cd {newdir}') yield finally: _clog(f'cd {prevdir}') os.chdir(prevdir) # from pathlib import Path # _clog("Called before cd", Path().absolute()) # with cd(Path.home()): # if verbose: print("Called under cd", Path().absolute()) # _clog("Called after cd and same as before", Path().absolute()) <|fim▁end|>
if condition: return log_func(*args, **kwargs)
<|file_name|>context_managers.py<|end_file_name|><|fim▁begin|>"""useful context managers""" from contextlib import suppress with suppress(ModuleNotFoundError): from lag import * import os import contextlib def clog(*args, condition=True, log_func=print, **kwargs): if condition: return log_func(*args, **kwargs) @contextlib.contextmanager def cd(newdir, verbose=True): <|fim_middle|> <|fim▁end|>
"""Change your working directory, do stuff, and change back to the original""" _clog = partial(clog, condition=verbose, log_func=print) prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: _clog(f'cd {newdir}') yield finally: _clog(f'cd {prevdir}') os.chdir(prevdir) # from pathlib import Path # _clog("Called before cd", Path().absolute()) # with cd(Path.home()): # if verbose: print("Called under cd", Path().absolute()) # _clog("Called after cd and same as before", Path().absolute())
<|file_name|>context_managers.py<|end_file_name|><|fim▁begin|>"""useful context managers""" from contextlib import suppress with suppress(ModuleNotFoundError): from lag import * import os import contextlib def clog(*args, condition=True, log_func=print, **kwargs): if condition: <|fim_middle|> @contextlib.contextmanager def cd(newdir, verbose=True): """Change your working directory, do stuff, and change back to the original""" _clog = partial(clog, condition=verbose, log_func=print) prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: _clog(f'cd {newdir}') yield finally: _clog(f'cd {prevdir}') os.chdir(prevdir) # from pathlib import Path # _clog("Called before cd", Path().absolute()) # with cd(Path.home()): # if verbose: print("Called under cd", Path().absolute()) # _clog("Called after cd and same as before", Path().absolute()) <|fim▁end|>
return log_func(*args, **kwargs)
<|file_name|>context_managers.py<|end_file_name|><|fim▁begin|>"""useful context managers""" from contextlib import suppress with suppress(ModuleNotFoundError): from lag import * import os import contextlib def <|fim_middle|>(*args, condition=True, log_func=print, **kwargs): if condition: return log_func(*args, **kwargs) @contextlib.contextmanager def cd(newdir, verbose=True): """Change your working directory, do stuff, and change back to the original""" _clog = partial(clog, condition=verbose, log_func=print) prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: _clog(f'cd {newdir}') yield finally: _clog(f'cd {prevdir}') os.chdir(prevdir) # from pathlib import Path # _clog("Called before cd", Path().absolute()) # with cd(Path.home()): # if verbose: print("Called under cd", Path().absolute()) # _clog("Called after cd and same as before", Path().absolute()) <|fim▁end|>
clog
<|file_name|>context_managers.py<|end_file_name|><|fim▁begin|>"""useful context managers""" from contextlib import suppress with suppress(ModuleNotFoundError): from lag import * import os import contextlib def clog(*args, condition=True, log_func=print, **kwargs): if condition: return log_func(*args, **kwargs) @contextlib.contextmanager def <|fim_middle|>(newdir, verbose=True): """Change your working directory, do stuff, and change back to the original""" _clog = partial(clog, condition=verbose, log_func=print) prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: _clog(f'cd {newdir}') yield finally: _clog(f'cd {prevdir}') os.chdir(prevdir) # from pathlib import Path # _clog("Called before cd", Path().absolute()) # with cd(Path.home()): # if verbose: print("Called under cd", Path().absolute()) # _clog("Called after cd and same as before", Path().absolute()) <|fim▁end|>
cd
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*- """ Verion: 1.0 Author: zhangjian Site: http://iliangqunru.com File: __init__.py.py Time: 2017/7/22 2:19<|fim▁hole|><|fim▁end|>
"""
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try:<|fim▁hole|> return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True<|fim▁end|>
self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex)
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: <|fim_middle|> class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
"""Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): <|fim_middle|> <|fim▁end|>
"""This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): <|fim_middle|> def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
"""Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized")
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): <|fim_middle|> def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
"""Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices]
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: <|fim_middle|> def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
"""Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): <|fim_middle|> def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
"""Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): <|fim_middle|> <|fim▁end|>
"""Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: <|fim_middle|> self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
self.client.http.disable_https_verify()
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: <|fim_middle|> for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
return filtered_attributes
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: <|fim_middle|> attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
continue
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: <|fim_middle|> return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
return filter_named[0]
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def <|fim_middle|>(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
get_scanner
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def <|fim_middle|>(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
__init__
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def <|fim_middle|>(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
scan_devices
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def <|fim_middle|>(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
get_extra_attributes
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def <|fim_middle|>(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def _update_info(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
get_device_name
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Device tracker for Synology SRM routers.""" from __future__ import annotations import logging import synology_srm import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_USERNAME = "admin" DEFAULT_PORT = 8001 DEFAULT_SSL = True DEFAULT_VERIFY_SSL = False PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) ATTRIBUTE_ALIAS = { "band": None, "connection": None, "current_rate": None, "dev_type": None, "hostname": None, "ip6_addr": None, "ip_addr": None, "is_baned": "is_banned", "is_beamforming_on": None, "is_guest": None, "is_high_qos": None, "is_low_qos": None, "is_manual_dev_type": None, "is_manual_hostname": None, "is_online": None, "is_parental_controled": "is_parental_controlled", "is_qos": None, "is_wireless": None, "mac": None, "max_rate": None, "mesh_node_id": None, "rate_quality": None, "signalstrength": "signal_strength", "transferRXRate": "transfer_rx_rate", "transferTXRate": "transfer_tx_rate", } def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return Synology SRM scanner.""" scanner = SynologySrmDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class SynologySrmDeviceScanner(DeviceScanner): """This class scans for devices connected to a Synology SRM router.""" def __init__(self, config): """Initialize the scanner.""" self.client = synology_srm.Client( host=config[CONF_HOST], port=config[CONF_PORT], username=config[CONF_USERNAME], password=config[CONF_PASSWORD], https=config[CONF_SSL], ) if not config[CONF_VERIFY_SSL]: self.client.http.disable_https_verify() self.devices = [] self.success_init = self._update_info() _LOGGER.info("Synology SRM scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device["mac"] for device in self.devices] def get_extra_attributes(self, device) -> dict: """Get the extra attributes of a device.""" device = next( (result for result in self.devices if result["mac"] == device), None ) filtered_attributes: dict[str, str] = {} if not device: return filtered_attributes for attribute, alias in ATTRIBUTE_ALIAS.items(): if (value := device.get(attribute)) is None: continue attr = alias or attribute filtered_attributes[attr] = value return filtered_attributes def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" filter_named = [ result["hostname"] for result in self.devices if result["mac"] == device ] if filter_named: return filter_named[0] return None def <|fim_middle|>(self): """Check the router for connected devices.""" _LOGGER.debug("Scanning for connected devices") try: self.devices = self.client.core.get_network_nsm_device({"is_online": True}) except synology_srm.http.SynologyException as ex: _LOGGER.error("Error with the Synology SRM: %s", ex) return False _LOGGER.debug("Found %d device(s) connected to the router", len(self.devices)) return True <|fim▁end|>
_update_info
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys<|fim▁hole|> if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wellspring.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)<|fim▁end|>
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wellspring.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. #<|fim▁hole|># (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] )<|fim▁end|>
# ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): <|fim_middle|> if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] ) <|fim▁end|>
def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup)
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): <|fim_middle|> if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] ) <|fim▁end|>
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup)
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): <|fim_middle|> <|fim▁end|>
pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] )
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): <|fim_middle|> if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] ) <|fim▁end|>
if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup)
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): <|fim_middle|> else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] ) <|fim▁end|>
cxxinit(self, integrator_CapForce, system, capForce)
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: <|fim_middle|> if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] ) <|fim▁end|>
cxxinit(self, integrator_CapForce, system, capForce, particleGroup)
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : <|fim_middle|> <|fim▁end|>
class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] )
<|file_name|>CapForce.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def <|fim_middle|>(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] ) <|fim▁end|>
__init__
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys <|fim▁hole|> from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)<|fim▁end|>
if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.prod')
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.prod') from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)